One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.5.0
Toby Kalkman91d13b3336f8
diff --cc .gitignoreindex 3814199,c9e23ff..2360b23--- a/.gitignore+++ b/.gitignore@@@ -17,5 -17,5 +17,12 @@@ mac_app/buildmac_app/dist/-# Rendered on demand from docs/*.html; reaches the other machine via Syncthing+# Rendered documents, never committeddocs/pdf/++++# Linux bundles, OSTree build repositories and flatpak-builder's cache.++/dist/++/.flatpak-builder/++++# Offscreen audit fixtures, measurements and renders.++/renders/diff --cc CONTRIBUTING.mdindex e1b17ea,8814de0..5e086b1--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@@ -5,16 -5,15 +5,17 @@@ reply is not guaranteed## Bug reports--Use the bug report form, and attach both machines' logs where you can:++Use the bug report form, and attach the logs from both machines where you can:`~/Library/Logs/Beamer/Beamer.log` on the Mac and `%LOCALAPPDATA%\Beamer\Beamer.log` on Windows.--They hold your machines' names and local network addresses, so look them over first.++They hold your machines' names and local network addresses, so look them over first. On Linux, use++Open log folder from Beamer's menu.## Feature requestsUse the feature request form, or add a reaction to an existing request rather than a "+1"- comment. There is no roadmap and no promise that anything gets built. Linux, Intel Macs, two Macs- or two PCs, and three machines at once are being built for 1.5.0; test builds appear on the- releases page as pre-releases.-comment. There is no roadmap and no promise that anything gets built. Some things are out of scope-by design: Beamer is one Mac and one Windows PC, so a third machine and Linux are not planned.++comment. There is no roadmap and no promise that anything gets built. Beamer 1.5.0 supports Intel++Macs, experimental Linux on GNOME Wayland or X11, Mac-to-Mac and Windows-to-Windows pairs, and three machines++at once. Test builds appear on the releases page as pre-releases.## Pull requests@@@ -25,4 -24,4 +26,5 @@@ we agree the approach before you write## Building it--The README's "Building from source" and "Development checks" sections cover both platforms.++The README's "Building from source" and "Development checks" sections cover macOS and Windows.++For the Linux Flatpak build, see `docs/flatpak-build.md`.diff --cc README.mdindex c091690,5afb69d..7b7d711--- a/README.md+++ b/README.md@@@ -1,10 -1,10 +1,10 @@@<p align="center"><img src="Beamer.svg" width="96" height="96" alt=""></p><h1 align="center">Beamer</h1>--<p align="center">One keyboard and one mouse or trackpad for a Mac and a Windows PC on the same network, in either direction.</p>++<p align="center">One keyboard and one mouse or trackpad for Macs, Windows PCs and Linux machines on the same network, in either direction.</p><p align="center"><a href="https://github.com/kalkman-code/beamer/releases/latest"><img src="https://img.shields.io/github/v/release/kalkman-code/beamer" alt="Latest release"></a><a href="LICENSE"><img src="https://img.shields.io/github/license/kalkman-code/beamer" alt="Licence"></a>-- <img src="https://img.shields.io/badge/platforms-macOS%20%7C%20Windows-lightgrey" alt="Platforms: macOS and Windows">++ <img src="https://img.shields.io/badge/platforms-macOS%20%7C%20Windows%20%7C%20Linux-lightgrey" alt="Platforms: macOS, Windows and Linux"><a href="https://github.com/kalkman-code/beamer/releases"><img src="https://img.shields.io/github/downloads/kalkman-code/beamer/total" alt="Downloads"></a></p>@@@ -16,33 -16,33 +16,30 @@@ still work, and what you type never lea## Download--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 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 |--| Windows, through winget | `winget install KalkmanCode.Beamer` | The same installer, without the warning |++| 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 |## Quick start--1. **Install on both machines.** On the Mac, drag Beamer to Applications, open it, and press the++1. **Install on every machine.** On the Mac, drag Beamer to Applications, open it, and press thetwo Grant buttons on the Permissions page (Accessibility, then Input Monitoring), then RelaunchBeamer on the same page: macOS only passes keys to an app started after the grant, so until thenthe 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.-- 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. For Linux,++ follow [the Flatpak build and install 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.@@@ -63,40 -63,40 +60,52 @@@ In your own appearance: light if your G- **Push through the edge.** Off the edge that faces the other machine, only along the parts of ityou pick, through a corner, or up through the MacBook's notch. The pointer arrives at the samepoint along the border, on the right display however your monitors are stacked or staggered. The-- edge lights up as you push, and the trackpad ticks as the push builds.++ edge lights up as you push, and the trackpad ticks as the push builds. If Windows or macOS briefly++ cannot report the pointer position, Beamer skips that moment and keeps crossing (GitHub #9).- **See where you land.** A switch by the key or a menu plays a short arrival around the pointer onthe machine that takes over, so you never hunt for it.- **Or press a key.** Double-tap or hold a trigger key to switch without moving the pointer. RightOption on the Mac and Right Ctrl on the PC to start with; on either machine it can be any keythat types nothing, recorded by pressing it.- **Either way round.** The Mac drives the PC and the PC drives the Mac. Each machine has a switch-- per direction, so you can turn one way off and keep the other.++ per direction, so you can turn one way off and keep the other. Macs can drive Macs, and Windows++ PCs can drive Windows PCs, too.++- **Pair them clearly.** Pair a machine is at the top of Overview, and the six digits are centred.++- **Three machines.** Pair each machine with the others in the group. A chain needs a direct++ pairing between every pair of machines in it.- **The clipboard comes with you.** Text and images, both ways, at the moment you switch. Filesstay where they are.--- **Your shortcuts still work.** Cmd becomes Ctrl and Option becomes Alt on Windows, so Cmd+C-- copies there too. The PC gets the reverse: its Ctrl+C arrives on the Mac as Cmd+C. Either-- machine can switch to Positional instead, where each key arrives as the key in its place.--- **Media keys follow you to the PC.** While the Mac drives the PC, play, pause, skip, mute and-- volume act on the PC. Brightness stays with the Mac. The PC's own media keys do not reach the Mac-- yet.++- **Your shortcuts still work.** Between a Mac and Windows, Cmd becomes Ctrl and Option becomes++ Alt, so Cmd+C copies there too. The PC gets the reverse. Between two Macs or two PCs, each key++ arrives as the same physical key. On Windows, you can also choose a Mac keyboard layout, where++ Alt acts as Command and the Windows key acts as Option.++- **Media keys follow you.** Play, pause, skip, mute and volume cross between supported machines.++ Brightness and keyboard-backlight keys stay on the Mac.- **Keys and buttons that stay put.** Each machine keeps a list of keys and mouse buttons that keepworking where they were pressed while its input is on the other one: a mouse's back button forthis machine's browser, a volume key for its speakers. Add one by pressing it. The back andforward side buttons cross in both directions otherwise.- **Mac gestures on Windows.** Three or four fingers up for Task View, down for the desktop, leftand right to change virtual desktop, all from the Mac's trackpad.--- **Make it yours.** Glow and Beam, or nine other effects in three families (Membrane, Sparks-- and Instrument), each with colour packs of its own and any colour with any effect. The-- notch as an outline or an island with a meter, how hard you push before it crosses, and settings-- windows that follow the system's light or dark appearance or keep your own choice.++- **Make it yours.** Glow, Beam and Aperture, or effects in Membrane, Sparks, Instrument, Folio and++ Selvedge, each with colour packs of its own. Set the effect's Size and Length, the MacBook notch++ as an outline or an island with a meter, how hard you push before it crosses, and whether settings++ windows follow the system's light or dark appearance. Beam fades softly inward from the edge.- **Feels like your own.** Each machine sets how the other's pointer moves and scrolls on it, from25% to 400%, and can reverse its scrolling, so a Mac trackpad and a PC mouse each feel right onthe other screen.--- **Out of the way when it should be.** A full-screen app holds the edges, so a game or a film never-- loses the pointer; the trigger key still works. Pause crossing does the same by hand. A drag-- that reaches the edge stays a drag. Switch to a machine that is asleep and Beamer wakes it, where-- that machine answers wake-on-LAN: a PC usually does, a MacBook on Wi-Fi usually does not.--- **Your network, nobody else's.** No server in the middle. The two machines talk to each other++- **Out of the way when it should be.** On macOS and Windows, you can choose whether a full-screen++ app on each machine holds its edges; it is off by default, and shortcuts still work. A drag that++ reaches the edge stays a drag. Switch to a machine that is asleep and Beamer wakes it, where that++ machine answers wake-on-LAN: a PC usually does, a MacBook on Wi-Fi usually does not.++- **Keep settings in step.** Same on all machines shares resistance, drag protection, Shortcut,++ effect style, colour, length, size and landing animation with compatible paired machines. Zones,++ jump keys, full-screen hold, whether effects animate, and window appearance stay local.++- **Match design.** Follow one paired machine's style, colour, length, size and landing animation.++ Changing one of those here stops following. Animation enable and window appearance stay local.++- **A more responsive settings window.** Mac resizing and scrolling stay smooth, the Design grid++ fills the window, and Windows and Linux settings layouts use their space more clearly.++- **Your network, nobody else's.** No server in the middle. Paired machines talk to each otherdirectly, encrypted, and you pair them once with a six-digit code. The only thing that ever goesfurther is a once-a-day check of GitHub's public releases for a newer version, which you canswitch off on Overview. More in [SECURITY.md](SECURITY.md).@@@ -110,15 -110,15 +119,15 @@@ About Beamer| Page | Mac | Windows ||---|---|---|--| Overview | Pairing (first, until it is done), where input is, the link and its round trip, Send input and Pause crossing, a switch per direction, start at login, the update check | Pairing (first, until it is done), where input is, the link and its round trip, Send input and Pause crossing, a switch per direction, start at sign-in, the update check |++| Overview | Paired machines, where input is, the links and their round trips, Send input and Pause crossing, a switch per direction, Same on all machines, start at login, the update check | Paired machines, where input is, the links and their round trips, Send input and Pause crossing, a switch per direction, Same on all machines, start at sign-in, the update check || Permissions | Accessibility and Input Monitoring, with Relaunch Beamer | None; the firewall check is on Connection |--| Crossing | A drawing of the arrangement, the ways in (edge, part of the edge, corner, notch), where the PC is, never while dragging, resistance, the shortcut | A drawing of the arrangement, the ways in (edge, part of the edge, corner), where your Mac is, never while dragging, resistance, the shortcut |--| Keyboard | Same shortcuts or same positions, what stays on this Mac, the PC's pointer and scroll speed here | Same shortcuts or same positions, what stays on this PC, the Mac's pointer and scroll speed here |--| Design | Crossing and switch styles, each playing as you point at it, colours, show where the pointer lands, notch style, trackpad ticks, the window's appearance (System, Light or Dark) | Crossing and switch styles, each playing as you point at it, at the edge or a corner, colours, show where the pointer lands, the window's appearance (System, Light or Dark) |--| Connection | Hide addresses, the PC's address, port and token | Whether Windows Firewall lets the Mac in, with a one-button fix; hide addresses; this PC's address, port and token |++| Crossing | A drawing of the arrangement, the ways in for each machine (edge, part of the edge, corner, notch), the full-screen hold, resistance, the shortcut and jump keys | A drawing of the arrangement, the ways in for each machine (edge, part of the edge, corner), the full-screen hold, resistance, the shortcut and jump keys |++| Keyboard | Key mapping, what stays on this Mac, each peer's pointer and scroll speed | Key mapping, including a Mac layout, what stays on this PC, each peer's pointer and scroll speed |++| Design | Crossing and switch styles, colours, Size and Length, landing animation, Match design, notch and trackpad controls, window appearance (System, Light or Dark) | Crossing and switch styles, colours, Size and Length, landing animation, Match design, window appearance (System, Light or Dark) |++| Connection | Hide addresses, a peer's address, port and pairing details | Whether Windows Firewall lets a peer in, with a one-button fix; hide addresses; this PC's address, port and pairing details |--Which edge of the Mac leads to the PC is one setting either machine can change; the two keep it in--step, so the border is always the same one seen from both ends.++Each machine sets its own zones and the machine beyond each one. These settings stay local even++when Same on all machines is on.## Known limits@@@ -127,43 -127,43 +136,34 @@@keyboard 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.++- **The Windows installer is unsigned.** SmartScreen may warn when you first run it; choose More++ info, then Run anyway.## In detail<details><summary><strong>Connection states</strong></summary>--Written from the Mac, which connects to the PC. The PC's link to the Mac reports the mirror of--them, naming the Mac.++These examples use a Mac connected to a Windows PC. Beamer names the other machine in each status,++and reports the mirror status at the other end.| Status | Meaning ||---|---|--| `Connected to <address>:<port>` | The encrypted link is up: the PC decrypted the Mac's first frame, so both hold the same token, and the protocol versions match. Reads `Connected to Windows via secure macOS 27 fallback` when the tunnel is carrying it. |--| `Windows is reachable, but Beamer is not listening on this port.` | The PC answered but nothing accepted the TCP port. |--| `Windows could not be authenticated — check the shared token matches on both sides` | The two derived different keys. The tokens differ. |--| `Windows is unreachable from this Mac` | Nothing got as far as Beamer or the firewall. Check Wi-Fi client isolation, the PC's network, and that the Mac can resolve its address. |--| `Windows did not answer the handshake — it is probably running an older Beamer; update it` | A PC that has never completed a handshake this run is silent, as a Beamer from before encryption is. |--| `Windows receiver speaks Beamer protocol vN, this Mac vM — update both apps` | The wire versions differ. The version travels in cleartext at the start of the connection, so a mismatch says so rather than hanging. |--| `Windows stopped responding` | No ping or acknowledgement for about two seconds. |----Both ends notice a dead link within a few seconds. The PC enforces a 2.5-second read timeout and--the Mac pings at least once a second while idle, so the PC is back to waiting for the Mac within--about three seconds; the Mac notices in about two and takes its input back.----The Mac always fails open. A dropped connection, a missing acknowledgement, a crashed capture--worker or a full event queue returns input to the Mac at once. A watchdog runs for as long as a--socket exists, so a half-open connection is caught and the Mac reconnects even if you never--switched. Trying to switch while the link is down beeps and posts a notification.++| `Connected to <address>:<port>` | The encrypted link is up and the protocol versions match. |++| `<machine> is reachable, but Beamer is not listening on this port.` | The other machine answered but nothing accepted the TCP port. |++| `<machine> could not be authenticated — check the shared token matches on both sides` | The two derived different keys. The tokens differ. |++| `<machine> is unreachable from this Mac` | Nothing got as far as Beamer or the firewall. Check Wi-Fi client isolation, the other machine's network, and that the Mac can resolve its address. |++| `<machine> did not answer the handshake — it is probably running an older Beamer; update it` | An older Beamer may not understand the current connection. |++| `<machine> speaks Beamer protocol vN, this machine vM — update both apps` | The wire versions differ. The version travels in cleartext at the start of the connection, so a mismatch says so rather than hanging. |++| `<machine> stopped responding` | No ping or acknowledgement for about two seconds. |++++Both ends notice a dead link within a few seconds. The receiver enforces a read timeout and the++sender pings while idle; the machine holding input takes it back when the link is lost.++++A dropped connection, a missing acknowledgement, a crashed capture worker or a full event queue++returns input to the machine at once. A watchdog catches a half-open connection and retries it.</details>@@@ -175,7 -175,7 +175,7 @@@ lights up, the trackpad ticks at each qgives. The resistance is the point. An edge that switches the instant you touch it does so everytime you overshoot a close button. The default is 120 points; zero switches on contact.--| Way in | Where it triggers | Mac | PC |++| Way in | Where it triggers | Mac | Windows ||---|---|---|---|| Shortcut | Double-tap the trigger key, or hold it | Yes | Yes || Edge | The whole of one outer edge | Yes | Yes |@@@ -184,7 -184,7 +184,8 @@@| Notch | The top edge, only within the notch's width | Yes | No |Any combination can be on, except Edge and Part of the edge, which exclude each other. On the Mac,--shortcut and the right-hand edge are on to start with.++Shortcut and the right-hand edge are on to start with. On Linux under Wayland, the shortcut only++brings input back; the desktop only lets it go to another machine at an edge.- The notch has no pixels to light, so a push there draws on the notch itself. Outline, the default,runs a comet of light round a small tab under the notch that brightens and speeds up with the@@@ -195,28 -195,28 +196,28 @@@still crosses.- The pointer arrives where it left: 42% of the way down the Mac's right edge is 42% of the waydown the PC's left edge, on whichever monitor owns it.--- Crossing never fires while a mouse button is held, because a drag that reaches the edge is a drag.--- It suspends itself while a full-screen app has focus. Pause crossing in the Mac's menu bar puts it-- away until you resume it or restart Beamer.--- Only one machine's input is on the other at a time. While the Mac drives the PC, pushing the PC's-- own mouse through the edge sends the Mac's input home and takes the PC's mouse across behind it.--- Either machine's own switch, the menu item or the trigger key, sends the other's input home, so a-- way back never depends on the edge alone. The PC's edge facing the Mac leads home even when the-- Mac has only its shortcut on.--- Switching to a PC that is asleep sends wake-on-LAN. The PC's hardware address is read from the-- Mac's ARP table after a successful connection, never typed.----Each machine's menu has one tick per direction: This Mac drives Windows and Windows drives this--Mac on the Mac, Mac drives this PC and This PC drives the Mac in the Windows tray. Turning one off--stops that direction only.++- On macOS and Windows, crossing does not fire while a mouse button is held, so a drag that reaches++ the edge stays a drag. On Wayland, the desktop can capture a drag at the edge.++- The full-screen hold is off by default. When enabled on macOS or Windows, a full-screen app on++ that screen holds pointer crossings; it does not apply to Beamer's own window. Shortcuts and jump++ keys still work. Wayland cannot detect a full-screen app.++- Only one machine's input is on another at a time. The receiving machine can send it home or pass++ it on through one of its own configured zones.++- A machine's own switch, menu or shortcut sends input home. On Wayland, the shortcut only brings++ input back.++- Switching to a sleeping PC sends wake-on-LAN when that PC supports it.++++Each machine's menu lists its peers and the directions it can drive. Turning one direction off++leaves the other direction alone.</details><details><summary><strong>Keys, buttons and media keys</strong></summary>--Mac modifiers map to Windows by meaning, so the shortcuts your fingers know keep working. The--Mac's Keyboard page can switch this to positional, where Cmd sends the Windows key.++For a Mac-to-Windows pair, Mac modifiers map to Windows by meaning, so the shortcuts your fingers++know keep working. The Mac's Keyboard page can switch this to positional, where Cmd sends the++Windows key. Mac-to-Mac and Windows-to-Windows pairs keep each physical key in place.| Mac key | Sends on Windows ||---|---|@@@ -234,8 -234,8 +235,8 @@@ on English, a letter types what the reckeyboard would, and shortcuts keep working. The `key_map` object in each app's config JSON canstill override single keys.--The trigger key is never forwarded. On both machines it is recorded by pressing it: Right Option on--the Mac and Right Ctrl on the PC to start with. Either can double-tap or hold.++The trigger key is never forwarded on macOS and Windows. It is recorded by pressing it: Right++Option on the Mac and Right Ctrl on Windows to start with. Either can double-tap or hold.The stays-here list is per machine, because a Mac keycode and a Windows virtual key are differentnumbers for the same key. It takes keys, the right, middle, back and forward mouse buttons, and on@@@ -243,10 -243,10 +244,9 @@@ the Mac its media keys. A listed pressits release goes wherever its press went, so nothing is ever left held down on the far side. Thetrigger key cannot be added.--The Mac's F7–F12 media row and volume keys forward to the PC as play/pause, next, previous, mute and volume.++The Mac's F7–F12 media row and volume keys cross as play/pause, next, previous, mute and volume.On the Mac they arrive as system events rather than key events and are captured separately--(`mac_app/media_keys.py`). Brightness and keyboard-backlight keys stay with macOS, since Windows has--no equivalent.++(`mac_app/media_keys.py`). Brightness and keyboard-backlight keys stay with macOS.Ctrl+Alt+Del is the Secure Attention Sequence, trapped by the kernel before any app sees it.`SendInput` cannot produce it, and `SendSAS()` needs a Windows service or a signed `uiAccess` app@@@ -257,7 -257,7 +257,7 @@@ installed under Program Files, which Be<details><summary><strong>Gestures</strong></summary>--Trackpad scrolling is smooth and horizontal scrolling works on Windows. While input is on the PC,++Trackpad scrolling is smooth and horizontal scrolling works on Windows. While input is on Windows,the Mac's system gestures do the equivalent thing there and nothing on the Mac:| Mac gesture | On Windows |@@@ -282,8 -282,8 +282,8 @@@ horizontal sign has flipped between rel<details><summary><strong>Clipboard</strong></summary>--The clipboard moves at the moment of a switch, ahead of the switch itself: switching from the Mac--carries the Mac's clipboard to the PC, and switching back carries the PC's to the Mac. Where it++The clipboard moves at the moment of a switch, ahead of the switch itself: switching to another++machine carries the current machine's clipboard, and switching back carries the other machine's. Where itholds both an image and text, both cross and the pasting app picks. The caps keep the switchprompt: 256KB of text and an 8MB image as PNG. Over a cap, that half is left alone rather thantruncated. The PC converts to and from the Windows clipboard's DIB format itself, using the Qt it@@@ -295,23 -295,23 +295,22 @@@ large image is not re-sent every time<details><summary><strong>Latency</strong></summary>--If both machines are on Wi-Fi, every event crosses the air twice, Mac to access point to PC.++If both machines are on Wi-Fi, every event crosses the air twice, through the access point.Ethernet on either machine removes a hop. Where Wi-Fi is unavoidable, 5GHz or 6GHz and turning offpower saving on the PC's adapter both help.Beamer sends every event at once (TCP_NODELAY). Acknowledgements are coalesced over 15ms so a--100Hz stream of moves cannot double the packet count, with an idle heartbeat every 400ms. The Mac's--settings show the measured round trip while input is on the PC.++100Hz stream of moves cannot double the packet count, with an idle heartbeat every 400ms. Settings++show the measured round trip while input is on another machine.</details><details><summary><strong>Security</strong></summary>--Both apps derive a key from the shared token with HKDF-SHA256 and seal every frame with--ChaCha20-Poly1305. The token is never sent. Pairing agrees a token with CPace, a--password-authenticated key exchange over X25519, from the six-digit code, so nothing sent while--pairing can be tested against a list of codes. What that does and does not protect against is in++Wire version 6 combines each paired token with a fresh X25519 exchange to derive directional keys++with HKDF-SHA256. Frames are sealed with ChaCha20-Poly1305. Pairing agrees a token with CPace, a++password-authenticated key exchange, from the six-digit code. What that does and does not protect against is in[SECURITY.md](SECURITY.md).</details>@@@ -321,7 -321,7 +320,7 @@@Once a day, and at start, Beamer asks GitHub's public releases API for the latest release of thisrepository and compares its version with its own. A new minor or major version is always offered;--a patch release (1.4.0 to 1.4.1) only when its release notes ask for it, so a run of small fixes++a patch release (1.5.0 to 1.5.1) only when its release notes ask for it, so a run of small fixesdoes not nag. Drafts and pre-releases never count and nothing is downloaded. When a newer one is out, the menu says Beamer X is available and Overview offers aDownload button that opens the release page. The request is an ordinary HTTPS request, so GitHubsees the address it came from, as it would for a browser. Switch it off with Check for updates on@@@ -357,6 -357,6 +356,29 @@@ 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++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>@@@ -395,10 -395,9 +417,11 @@@ A local Mac build is signed with the rereach it, so privacy grants carry between local builds and releases, and ad-hoc otherwise (overSSH), under the hardened runtime either way. It is not notarised.-Files shared by both apps (`receiver.py`, `return_edge.py`, `pairing.py`, `ignored.py`, `tokens.py`-and others) are byte-identical copies, because each app bundles only what sits under it; a test-fails if a pair drifts. `Beamer.svg` is the master of the mark, and `Beamer.ico`, `Beamer.png` and+What both apps run the same way (`protocol.py`, `pairing.py`, `receiver.py`, `return_edge.py`, the+crossing effects and others) lives once in `core/`, which both apps import and both packagers- bundle; `core/tests` runs inside each app's suite. `tokens.py` is still copied into `win_app`, and a++bundle; `core/tests` runs inside each app's suite. Linux uses the Windows app's Qt shell and its++Linux back ends, packaged as a Flatpak. `tokens.py` is still copied into `win_app`, and a+test fails if the two drift. `Beamer.svg` is the master of the mark, and `Beamer.ico`, `Beamer.png` and`Beamer.icns` are rendered from it.</details>diff --cc SECURITY.mdindex 930fa49,930fa49..84075f4--- a/SECURITY.md+++ b/SECURITY.md@@@ -1,77 -1,77 +1,55 @@@# Security--Beamer sends your keystrokes, pointer and clipboard between two machines, so the link between--them matters. This is what it protects, what it does not, and how to report a problem.++Beamer sends your keystrokes, pointer and clipboard between machines, so the link between them++matters. This is what it protects, what it does not, and how to report a problem.## What the link protects--- **Every frame is encrypted and authenticated.** Each connection opens with both machines sending-- a fresh random prefix. Each direction of that connection then gets its own key, derived with-- HKDF-SHA256 from the shared token and both prefixes, and every frame is sealed with-- ChaCha20-Poly1305. A peer that cannot decrypt the first frame does not hold the token, and the-- connection goes no further.--- **The token is never sent.** Not when connecting, and not when pairing.--- **Recorded traffic cannot be played back.** Within a connection, each frame carries a counter the-- receiver requires to advance by one, so a frame sent twice, dropped or reordered ends the-- connection. A whole recorded connection sent again as a new one fails too: the receiver's fresh-- prefix is part of the key, so frames recorded under an earlier one do not decrypt. Before 1.4.1-- the key was the same for every connection, and that whole-connection replay worked: someone on-- your network who recorded a session could send it again, and the keystrokes, clicks and clipboard-- in it would be repeated. Update both machines to 1.4.1 or later.--- **Pairing is a six-digit code that lasts a minute and works once.** The two machines run CPace,-- a password-authenticated key exchange, with the code as the password, and the token comes out-- of it. The code never crosses the network, and neither does anything a list of codes could be-- tested against: someone listening, or answering in either machine's place, learns only whether-- their one guess was right. The PC answers the first machine to try a code and no other, and the-- Mac judges one answer to a code and no other, so a code allows at most one guess against each-- machine, two chances in a million, and a new code needs someone at the PC to press Pair a Mac-- again. The exchange is written out in [PAIRING.md](PAIRING.md). Before 1.4.3 each machine-- proved it knew the code with an HMAC keyed from it, and someone on your network during that-- minute could capture the Mac's proof, try every code against it offline given enough hardware,-- and pair with the PC as the Mac. Update both machines to 1.4.3 or later, and pair again if you-- last paired on a network you do not trust.--- **Traffic stays on your network.** The two machines talk to each other directly. There is no-- server, no account and no telemetry. On Windows, the firewall rules Beamer adds apply to Private-- networks only. The one request that leaves your network is the update check: once a day, an-- ordinary HTTPS request to GitHub's public releases API, carrying nothing about you or your-- machines beyond the address any request comes from. Check for updates on Overview turns it off.--- **Strangers cannot tie it up cheaply.** A connection must authenticate within a deadline and-- within 4KB, and only a handful of unauthenticated connections are held at once.++- **Every frame is encrypted and authenticated.** Beamer 1.5.0 uses wire version 6. Each connection++ exchanges fresh X25519 public keys and random nonce prefixes. The two directions get separate++ keys, derived with HKDF-SHA256 from the shared token and the X25519 result. PyNaCl provides++ X25519 and ChaCha20-Poly1305 through libsodium; HKDF-SHA256 uses Python's standard library.++ Frames are sealed with ChaCha20-Poly1305.++- **A later token leak does not decrypt a recorded 1.5.0 connection.** The connection key also++ depends on each side's fresh X25519 secret, which is discarded after key setup. A token is still++ sensitive: someone who gets it can act as that paired machine while they have it.++- **The token is never sent.** It is used locally to identify the pair and derive connection keys.++- **Frames cannot be replayed or reordered within a connection.** Each frame carries a counter the++ receiver requires to advance by one. A repeated, dropped or reordered frame ends the connection.++ A recorded connection also fails when sent again because a new connection has fresh keys.++- **Pairing uses a short-lived six-digit code.** The machines run CPace, a password-authenticated++ key exchange, to agree a token. The code is not sent over the network, and a recorded exchange++ cannot be checked against a list of possible codes offline. A code is accepted once and expires++ after a minute. The exchange is written out in [PAIRING.md](PAIRING.md).++- **Traffic stays on your network.** Paired machines talk directly. There is no account, relay++ server or telemetry. The update check makes an ordinary HTTPS request to GitHub's public releases++ API once a day; it sends no Beamer data, though GitHub sees the address the request comes from.++ Check for updates on Overview turns it off. Windows firewall rules apply to Private networks++ only.++- **Unauthenticated connections are limited.** A peer has five seconds and a 4KB first frame to++ authenticate, and Beamer holds only a small number of unauthenticated connections at once.## What it does not protect against--- **Anyone on your network can see that Beamer is running.** The PC broadcasts a small beacon every-- two seconds with its name and Beamer's port, and both machines listen on TCP 24820. Anyone can-- send to the pairing port on UDP 24821 while a code is on screen.--- **Someone on your network while you pair can interfere.** A junk message uses up the code and-- stops that pairing, and so does answering the Mac in the PC's place. That is a nuisance, not a-- way in: whoever does it gets one guess at the code against the PC and one against the Mac, two-- chances in a million for each code you show. The PC answers one machine per code, and the Mac-- will not send a code a second time once an answer to it has failed.--- **The step that mixes the code into pairing is not constant-time arithmetic.** How long it-- takes varies by a few millionths of a second with the code. The PC sends its answer a fixed-- time after the request arrives, so that duration cannot be read off the network, and the code-- is used once and gone in a minute; someone who can time code inside your machine has already-- got further than this protects against.--- **The PC's address is not proved by pairing.** The Mac takes the PC's address and port from the-- PC's announcement, which anything on your network can imitate. That can point the Mac at the-- wrong address and stop it connecting; it cannot read or forge the link, whose keys come from-- the token.--- **A machine that holds the token is trusted completely.** It can type and click anything on the-- other machine. On Windows that includes admin windows, because Beamer runs elevated so it can-- reach them. Treat the token like a password.--- **The token is stored in each app's settings file**, in the user's own profile: under-- `~/Library/Application Support/Beamer` on the Mac, readable only by that user, and under-- `%LOCALAPPDATA%\Beamer` on Windows. Anyone who can read that file can act as the paired machine.-- Pairing again replaces it.--- **Malware on either machine.** Anything that can read your keyboard or the settings file on one-- machine already has what Beamer would protect.--- **A token that leaks later.** The keys come from the token and the prefixes, and the prefixes-- are sent in the clear, so anyone who records your traffic and later learns the token can decrypt-- the recording. Pairing again gives a new token.--- **Traffic analysis.** Encryption hides what you type, not when. Someone watching the network can-- see that the two machines are talking and the size and timing of frames. The protocol version-- byte at the start of each connection is sent in the clear.++- **Someone on your network can see that Beamer is running.** Machines announce their name and++ connection port on the local network. Anyone on that network can try to reach the pairing++ service while a code is on screen.++- **Someone on your network can interrupt pairing.** A failed attempt can use up the displayed++ code, so you may need to show a new one. The attempt does not reveal the code or let the person++ join the pair.++- **Pairing does not prove a machine's network address.** The address comes from local discovery,++ which another machine on the network can imitate. That can stop a connection or point Beamer at++ the wrong address, but the encrypted link still requires the paired token.++- **A machine with the token is trusted.** It can type and click in applications that accept++ synthetic input on the paired machine. On Windows, Beamer runs elevated so it can reach elevated++ windows; it cannot control the secure desktop. Treat the token like a password.++- **Malware on either machine.** Software that can read your keyboard or Beamer's local settings++ can already act as you or the paired machine.++- **Traffic analysis.** Encryption hides the contents, not when machines talk or the size and timing++ of frames. The protocol version and a stable key identifier for the pair are sent in the clear,++ so a network observer can recognise connections between the same pair of machines.++- **Old Beamer versions cannot connect to 1.5.0.** Version 1.5.0 uses wire version 6; Beamer 1.4.x++ uses version 5. Update both ends and pair the machines again.## Reporting a vulnerabilitydiff --cc VERSIONindex 2002824,1c99cf0..bc80560--- a/VERSION+++ b/VERSION@@@ -1,1 -1,1 +1,1 @@@- 1.5.0-beta.6-1.4.4++1.5.0diff --cc WIRE.mdindex 92d1cd5,0000000..9c6a02bmode 100644,000000..100644--- a/WIRE.md+++ b/WIRE.md@@@ -1,1452 -1,0 +1,1458 @@@+# 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".+ - 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`.++ `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+ 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": "signal", "effect_length": "normal",++ "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. A machine that does not advertise `design_sync` is- shown unavailable with “Needs beta.6 or later”.++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":"signal","effect_length":"normal",++ "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.+- Editing any Design control on a follower turns following off and the page says so. Turning off++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 colour-measurements.jsonindex 0000000,0000000..d4938fbnew file mode 100644--- /dev/null+++ b/colour-measurements.json@@@ -1,0 -1,0 +1,242 @@@++[++ {++ "group": "Light",++ "id": "aurora",++ "hue": 147.15328467153284,++ "spacing": 45.73262136873561,++ "delta_e": 22.350650360526046,++ "raw": [++ 5.043364959929626,++ 1.7479684852431845++ ],++ "rendered": [++ 4.591380267931528,++ 3.3008133216687487++ ]++ },++ {++ "group": "Membrane",++ "id": "opal",++ "hue": 221.47058823529414,++ "spacing": 39.09120951751487,++ "delta_e": 13.47583986767184,++ "raw": [++ 4.503200599673889,++ 2.348752711197958++ ],++ "rendered": [++ 4.099625258166648,++ 3.292861247420863++ ]++ },++ {++ "group": "Membrane",++ "id": "sea_glass",++ "hue": 167.14285714285714,++ "spacing": 54.327731092437006,++ "delta_e": 6.786014204806454,++ "raw": [++ 4.718993982799734,++ 1.4869732636316562++ ],++ "rendered": [++ 5.467636781429369,++ 3.2951060903273124++ ]++ },++ {++ "group": "Sparks",++ "id": "arc",++ "hue": 202.00000000000003,++ "spacing": 70.06896551724131,++ "delta_e": 7.225655121350313,++ "raw": [++ 3.6214957472971396,++ 1.3447336029557277++ ],++ "rendered": [++ 3.296938501704237,++ 3.3007818290060307++ ]++ },++ {++ "group": "Sparks",++ "id": "magnesium",++ "hue": 272.06896551724134,++ "spacing": 70.06896551724131,++ "delta_e": 19.340654084553176,++ "raw": [++ 3.8859176087668916,++ 1.3851217243611782++ ],++ "rendered": [++ 3.537662963806001,++ 3.3023725012372394++ ]++ },++ {++ "group": "Instrument",++ "id": "ruby",++ "hue": 344.2105263157895,++ "spacing": 51.68233082706769,++ "delta_e": 9.005679271215719,++ "raw": [++ 3.6147065359480544,++ 1.9921302033438837++ ],++ "rendered": [++ 3.29075773722047,++ 3.2943063975431026++ ]++ },++ {++ "group": "Instrument",++ "id": "cobalt",++ "hue": 215.8620689655172,++ "spacing": 75.4496978314966,++ "delta_e": 6.484460954210651,++ "raw": [++ 3.622408344297309,++ 1.6839452117904303++ ],++ "rendered": [++ 3.297769312064471,++ 3.3150334915974233++ ]++ },++ {++ "group": "Folio",++ "id": "moss",++ "hue": 96.61016949152543,++ "spacing": 62.492522432701904,++ "delta_e": 21.356851529013838,++ "raw": [++ 2.506613881761881,++ 1.6476744296866368++ ],++ "rendered": [++ 4.331593790919604,++ 3.3125702137988347++ ]++ },++ {++ "group": "Folio",++ "id": "plum",++ "hue": 296.4705882352941,++ "spacing": 73.03436225975543,++ "delta_e": 25.909102795906854,++ "raw": [++ 3.603890309336324,++ 1.8681407065802291++ ],++ "rendered": [++ 3.2809108572438785,++ 3.2987427892334766++ ]++ },++ {++ "group": "Selvedge",++ "id": "woad",++ "hue": 251.00000000000003,++ "spacing": 75.44444444444449,++ "delta_e": 20.69283806135547,++ "raw": [++ 3.6268145001099463,++ 1.8542149486409873++ ],++ "rendered": [++ 3.301780589657171,++ 3.299276849447542++ ]++ },++ {++ "group": "Selvedge",++ "id": "saffron",++ "hue": 28.461538461538456,++ "spacing": 12.889812889812884,++ "delta_e": 11.30830116967902,++ "raw": [++ 3.4417316754882106,++ 1.6580964426878013++ ],++ "rendered": [++ 4.385399656474698,++ 3.301935225087352++ ]++ },++ {++ "group": "Bright",++ "id": "citron",++ "hue": 69.88235294117646,++ "spacing": 93.08707937323399,++ "delta_e": 29.95096186700717,++ "raw": [++ 13.482919889713846,++ 1.1273785608928346++ ],++ "rendered": [++ 12.274585089038945,++ 3.3055940408603224++ ]++ },++ {++ "group": "Bright",++ "id": "laser",++ "hue": 162.96943231441045,++ "spacing": 40.08733624454152,++ "delta_e": 31.30072368867452,++ "raw": [++ 11.929910911449213,++ 1.2768702570134498++ ],++ "rendered": [++ 10.8607562594029,++ 3.2938897725148206++ ]++ },++ {++ "group": "Bright",++ "id": "electric",++ "hue": 203.05676855895197,++ "spacing": 40.08733624454152,++ "delta_e": 20.554339371550306,++ "raw": [++ 5.784792966250709,++ 2.2205656468402233++ ],++ "rendered": [++ 5.266361742673331,++ 3.293484991915326++ ]++ },++ {++ "group": "Bright",++ "id": "fuchsia",++ "hue": 329.80392156862746,++ "spacing": 60.04014204106841,++ "delta_e": 18.30416232231641,++ "raw": [++ 5.883044145482397,++ 2.309726338664428++ ],++ "rendered": [++ 5.3558076838672575,++ 3.3049458449488545++ ]++ },++ {++ "group": "Bright",++ "id": "ultraviolet",++ "hue": 269.76377952755905,++ "spacing": 60.04014204106841,++ "delta_e": 25.686520480566607,++ "raw": [++ 5.764969868115669,++ 2.1883387990660177++ ],++ "rendered": [++ 5.248315184006721,++ 3.2975341232599393++ ]++ }++]diff --cc core/effects.pyindex 7f6624f,ab4ac74..2f6ea8a--- a/core/effects.py+++ b/core/effects.py@@@ -93,6 -95,6 +93,8 @@@ def legible(palette, dark, fx=None)ends on a deep red, and effects that drew those, additively on dark most of all, all butvanished. On a light one the effects that draw a pack's colours as given have every colourlighter than LIGHT_CEILING brought down to it, as Mono, Pearl and Contrast all but vanished."""++ if not dark and tuple(palette) in NEW_LIGHT_PACKS:++ return list(NEW_LIGHT_PACKS[tuple(palette)])if dark:low, high = DARK_FLOOR, 1.0elif getattr(fx, "id", None) in LIGHT_AS_GIVEN:@@@ -405,19 -406,12 +407,19 @@@ class Effectself.arrive_seconds = min(0.8, float(arrive_seconds))+def _light_aperture(pen, state, departing):+ from .fx_light import _aperture+ _aperture(pen, state, departing)++# Every direction built, in the order the Design pages list them: each direction's quiet, medium--# and showpiece effect, and its three colour packs. Ids are the settings values, so never rename one.++# and showpiece effect, and its colour packs. Ids are settings values, so never rename one.ALL_DIRECTIONS = (-- ("fx_membrane", "Membrane", ("skin", "film", "rupture"), ("oil_slick", "soap_bubble", "pearl")),-- ("fx_sparks", "Sparks", ("flint", "filings", "discharge"), ("ember", "forge", "sparkler_gold")),-- ("fx_instrument", "Instrument", ("rule", "gauge", "rangefinder"), ("phosphor", "sodium", "contrast")),- ("fx_folio", "Folio", ("crease", "pleat", "concertina"), ("vellum", "carbon_copy", "marbled")),- ("fx_selvedge", "Selvedge", ("thread", "weave", "jacquard"), ("flax", "madder", "tide")),++ ("fx_membrane", "Membrane", ("skin", "film", "rupture"), ("oil_slick", "soap_bubble", "pearl", "opal", "sea_glass")),++ ("fx_sparks", "Sparks", ("flint", "filings", "discharge"), ("ember", "forge", "sparkler_gold", "arc", "magnesium")),++ ("fx_instrument", "Instrument", ("rule", "gauge", "rangefinder"), ("phosphor", "sodium", "contrast", "ruby", "cobalt")),++ ("fx_folio", "Folio", ("crease", "pleat", "concertina"), ("vellum", "carbon_copy", "marbled", "moss", "plum")),++ ("fx_selvedge", "Selvedge", ("thread", "weave", "jacquard"), ("flax", "madder", "tide", "woad", "saffron")),("fx_ink", "Ink", ("capillary", "viscous_drop", "sumi_bloom"), ("indigo_ink", "matcha", "terracotta")),("fx_warp", "Warp", ("light_slit", "hyperdrive", "wormhole"), ("neon", "vaporwave", "cyber")),)@@@ -430,14 -424,12 +432,59 @@@ STAND_INS = {"capillary": "glow", "visc"light_slit": "beam", "hyperdrive": "glow", "wormhole": "glow","neon": "colourful", "vaporwave": "colourful", "cyber": "colourful"}DIRECTIONS = tuple(direction for direction in ALL_DIRECTIONS if direction[0] not in HIDDEN)-EFFECT_IDS = tuple(effect for _module, _name, effects, _packs in DIRECTIONS for effect in effects)+EFFECT_IDS = ("aperture",) + tuple(effect for _module, _name, effects, _packs in DIRECTIONS for effect in effects)# The effects whose designs draw a pack's colours as given on a light wallpaper; the others shade# them for light themselves.-LIGHT_AS_GIVEN = tuple(effect for module, _name, effects, _packs in ALL_DIRECTIONS if module in ("fx_ink", "fx_warp")- for effect in effects)-PACK_IDS = tuple(pack for _module, _name, _effects, packs in DIRECTIONS for pack in packs)+LIGHT_AS_GIVEN = ("aperture", "crease", "pleat", "concertina", "thread", "weave", "jacquard") + tuple(+ effect for module, _name, effects, _packs in ALL_DIRECTIONS if module in ("fx_ink", "fx_warp")+ for effect in effects+)- PACK_IDS = tuple(pack for _module, _name, _effects, packs in DIRECTIONS for pack in packs)++MONO_PACKS = {++ 'mono': ('White', ['#ebebeb', '#969696', '#ebebeb']),++ 'mono_silver': ('Silver', ['#c9ced2', '#a8afb6', '#e1e5e8']),++ 'mono_graphite': ('Graphite', ['#65696f', '#4a4f55', '#868c94']),++ 'mono_ink': ('Ink', ['#25282c', '#101215', '#41464d']),++ 'mono_warm': ('Warm grey', ['#b7ada0', '#8a8074', '#d8cfc2']),++}++BRIGHT_PACKS = {++ 'citron': ('Citron', ['#d5ff00', '#c1f000', '#e3ff38']),++ 'laser': ('Laser', ['#1affbe', '#00efa9', '#42ffd0']),++ 'electric': ('Electric', ['#1aa7ff', '#0098f0', '#36b8ff']),++ 'fuchsia': ('Fuchsia', ['#ff66b3', '#ff4da6', '#ff80bf']),++ 'ultraviolet': ('Ultraviolet', ['#bf80ff', '#b570ff', '#cd99ff']),++}++# Same hue and saturation, luminance capped at .20 (over 3:1 on preview wells).++# Authored stops avoid doing colour-space searches in the animation frame loop.++NEW_LIGHT_PACKS = {++ ('#53dc91', '#9572eb', '#43c5b4'): ('#1d8d50', '#8962e9', '#2a897d'),++ ('#527cda', '#ac8cd2', '#d985b0', '#7eade0'): ('#4c78d9', '#9268c4', '#c8508e', '#337dce'),++ ('#48b8a0', '#8bd6b5', '#388f91', '#b4dfb0'): ('#358977', '#318a63', '#358789', '#408b39'),++ ('#69c8ff', '#269de8', '#b5e5ff', '#456ad0'): ('#0080cb', '#1581c6', '#0081c8', '#456ad0'),++ ('#c98bff', '#9255da', '#ead2ff', '#b064e8'): ('#a945ff', '#9255da', '#a846ff', '#a752e5'),++ ('#ef4471', '#d32859', '#ff9ab5'): ('#ec265b', '#d32859', '#f60042'),++ ('#478df5', '#2a6dd3', '#a4caff'): ('#2376f3', '#2a6dd3', '#1174ff'),++ ('#72965b', '#bfd0a0', '#465e3b'): ('#658450', '#6c8341', '#465e3b'),++ ('#9b6b9e', '#d2b5ce', '#8b6095'): ('#9b6b9e', '#a3679b', '#8b6095'),++ ('#8277b3', '#7268a4', '#c3b9df'): ('#7f73b1', '#7268a4', '#846fbd'),++ ('#d48238', '#976025', '#efc18a'): ('#b36927', '#976025', '#b16b18'),++ tuple(BRIGHT_PACKS['citron'][1]): ('#6f8400', '#6b8500', '#718300'),++ tuple(BRIGHT_PACKS['laser'][1]): ('#008d65', '#008d64', '#008c6a'),++ tuple(BRIGHT_PACKS['electric'][1]): ('#0080d0', '#0080cb', '#0081c8'),++ tuple(BRIGHT_PACKS['fuchsia'][1]): ('#f00079', '#f00078', '#f00077'),++ tuple(BRIGHT_PACKS['ultraviolet'][1]): ('#a449ff', '#a24bff', '#a648ff'),++}++PACK_IDS = tuple(pack for _module, _name, _effects, packs in DIRECTIONS for pack in packs) + tuple(BRIGHT_PACKS) + tuple(MONO_PACKS)++++++def colour_groups(light_choices, with_effects=True):++ """Shared colour catalogue; Mono is independent of every effect family."""++ groups = [('Light', [(value, name) for value, name in light_choices if value != 'mono']),++ ('Mono', [(value, name) for value, (name, _stops) in MONO_PACKS.items()])]++ if with_effects:++ groups.extend((title, [(value, pack(value)[0]) for value in values])++ for _module, title, _effects, values in DIRECTIONS)++ groups.append(('Bright', [(value, name) for value, (name, _stops) in BRIGHT_PACKS.items()]))++ return groups_loaded = None@@@ -457,6 -448,6 +504,8 @@@ def _load()effects[effect_id] = by_id[effect_id]for pack_id in pack_ids:packs[pack_id] = module.PACKS[pack_id]++ packs.update(BRIGHT_PACKS)++ packs.update(MONO_PACKS)_loaded = (effects, packs)return _loadeddiff --cc core/feature_flags.pyindex 0000000,0000000..9981fa1new file mode 100644--- /dev/null+++ b/core/feature_flags.py@@@ -1,0 -1,0 +1,1 @@@++PAIRING_QR_VISIBLE = Falsediff --cc core/fx_folio.pyindex 0020e06,0000000..6e161famode 100644,000000..100644--- a/core/fx_folio.py+++ b/core/fx_folio.py@@@ -1,104 -1,0 +1,106 @@@+"""Folio: a scored edge lifts into paper folds and lays itself flat on arrival."""++import math++from .effects import Effect, clamp, ease_out, effect_depth_scale, lerp+from .fx_material import stroke, surface+++def _sheet(pen, s, level, departing):+ duration = (0.48, 0.62, 0.78)[level]+ t = s.since+ if t is not None and t >= duration:+ return+ pushing = departing and t is None+ p = clamp(s.pressure) if pushing else 1.0+ u = 0.0 if pushing else clamp(t / duration)+ size = effect_depth_scale(s)+ alpha = clamp(p * 5) if pushing else 1 - clamp((u - 0.58) / 0.42)+ motion = 0.65 if s.reduced else p+ at = surface(pen, s, departing)+ span = (48, 90, 144)[level]+ count = (2, 6, 12)[level]+ depth = (12, 28, 46)[level] * size+ base = 3 * size+ wall = 2 * size+ gap = 0.0+ if not pushing and not s.reduced:+ if departing:+ gap = span * ease_out(clamp(u / 0.8))+ motion = 1 - ease_out(u)+ else:+ gap = span * (1 - ease_out(clamp(u / 0.55))) * 0.5+ motion = (1 - ease_out(u)) + 0.22 * math.sin(math.pi * u)+ if s.reduced and not pushing:+ alpha = 1 - u+ step = 2 * span / count+ palette = s.palette+ facets = []+ for i in range(count):+ a, b = -span + i * step, -span + (i + 1) * step+ side = -1 if (a + b) < 0 else 1+ a, b = a + side * gap, b + side * gap+ def ridge(j):+ envelope = math.sin(math.pi * j / count) ** 0.7+ return base + depth * motion * envelope * (1 if j % 2 else 0.64)+ ra, rb = ridge(i), ridge(i + 1)+ facets.append((i, a, b, ra, rb))+ # Batch by pigment: the native replayers otherwise rebuild dozens of identical brushes.+ for pigment, colour in enumerate(palette):+ pen.beginPath()+ for i, a, b, ra, rb in facets:+ if i % len(palette) == pigment:+ pen.moveTo(*at(a, wall))+ pen.lineTo(*at(a, ra))+ pen.lineTo(*at(b, rb))+ pen.lineTo(*at(b, wall))+ pen.closePath()+ pen.fillStyle, pen.globalAlpha = colour, alpha * 0.9+ pen.fill()+ pen.beginPath()+ for i, a, b, ra, rb in facets:+ if i % 2:+ pen.moveTo(*at(a, wall))+ pen.lineTo(*at(a, ra))+ pen.lineTo(*at(b, rb))+ pen.lineTo(*at(b, wall))+ pen.closePath()+ pen.fillStyle, pen.globalAlpha = "#000000", alpha * 0.18+ pen.fill()+ for pigment, colour in enumerate(palette):+ pen.beginPath()+ for i, a, b, ra, rb in facets:+ if (i + 1) % len(palette) == pigment:+ pen.moveTo(*at(a, wall))+ pen.lineTo(*at(a, ra))+ pen.lineTo(*at(b, rb))+ stroke(pen, colour, 1.0, alpha * 0.9, s.dark)+ if level == 2:+ pen.beginPath()+ for i, a, b, ra, rb in facets:+ for k in (0.34, 0.67):+ pen.moveTo(*at(a, lerp(wall, ra, k)))+ pen.lineTo(*at(b, lerp(wall, rb, k)))+ stroke(pen, palette[-1], 0.65, alpha * 0.45, s.dark)+++def _make(id_, name, level, blurb):+ return Effect(id_, name, ("quiet", "medium", "showpiece")[level], blurb,+ lambda pen, s: _sheet(pen, s, level, True),+ lambda pen, s: _sheet(pen, s, level, False),+ (0.48, 0.62, 0.78)[level], (0.48, 0.62, 0.78)[level])+++EFFECTS = [+ _make("crease", "Crease", 0, "A small paper crease lifts under pressure, parts, then settles flat where you arrive."),+ _make("pleat", "Pleat", 1, "Six alternating folds gather at the edge, slide apart and unfold on the other screen."),+ _make("concertina", "Concertina", 2, "A scored paper fan rises along the boundary, opens a passage and folds itself away behind you."),+]++PACKS = {++ "moss": ("Moss", ["#72965b", "#bfd0a0", "#465e3b"]),++ "plum": ("Plum", ["#9b6b9e", "#d2b5ce", "#8b6095"]),+ "vellum": ("Vellum", ["#c69a60", "#f0ddac", "#88674c"]),+ "carbon_copy": ("Carbon copy", ["#6688ae", "#bbcad9", "#344d72"]),+ "marbled": ("Marbled", ["#bd6858", "#6c9691", "#e1bb78"]),+}diff --cc core/fx_instrument.pyindex 5a2eb12,84bbc5a..5ea4691--- a/core/fx_instrument.py+++ b/core/fx_instrument.py@@@ -727,6 -727,6 +727,8 @@@ EFFECTS =]PACKS = {++ "ruby": ("Ruby", ["#ef4471", "#d32859", "#ff9ab5"]),++ "cobalt": ("Cobalt", ["#478df5", "#2a6dd3", "#a4caff"]),"phosphor": ("Phosphor", ["#3dff7f", "#1f9e52", "#caffdc"]),"sodium": ("Sodium", ["#ffa51f", "#c46a12", "#ffe0a3"]),"contrast": ("Contrast", ["#f0e442", "#56b4e9", "#ffffff"]),diff --cc core/fx_membrane.pyindex b348601,8f2c89b..dbefab7--- a/core/fx_membrane.py+++ b/core/fx_membrane.py@@@ -540,6 -540,6 +540,8 @@@ EFFECTS =]PACKS = {++ "opal": ("Opal", ["#527cda", "#ac8cd2", "#d985b0", "#7eade0"]),++ "sea_glass": ("Sea glass", ["#48b8a0", "#8bd6b5", "#388f91", "#b4dfb0"]),"oil_slick": ("Oil slick", ["#8a4dff", "#2f7dff", "#16c6b0", "#9fdc4a", "#f0c23c", "#e8477f"]),"soap_bubble": ("Soap bubble", ["#ffd98e", "#ff9cc2", "#c3a6ff", "#8fcfff", "#9ef2cf"]),"pearl": ("Pearl", ["#fbf4e8", "#f2c9d6", "#c6dcf2", "#d9f0dc", "#ffffff"]),diff --cc core/fx_selvedge.pyindex f9db669,0000000..d24509fmode 100644,000000..100644--- a/core/fx_selvedge.py+++ b/core/fx_selvedge.py@@@ -1,94 -1,0 +1,96 @@@+"""Selvedge: tension opens a woven seam; the threads stay continuous and mend behind you."""++import math++from .effects import Effect, clamp, ease_out, effect_depth_scale+from .fx_material import stroke, surface+++def _cloth(pen, s, level, departing):+ duration = (0.48, 0.64, 0.78)[level]+ t = s.since+ if t is not None and t >= duration:+ return+ pushing = departing and t is None+ p = clamp(s.pressure) if pushing else 1.0+ u = 0.0 if pushing else clamp(t / duration)+ size = effect_depth_scale(s)+ alpha = clamp(p * 5) if pushing else 1 - clamp((u - 0.55) / 0.45)+ tension = 0.55 if s.reduced else p+ opening = 0.0+ if not pushing:+ if s.reduced:+ alpha = 1 - u+ elif departing:+ opening = math.sin(math.pi * ease_out(u)) * 29 * size+ tension = 1 - ease_out(u)+ else:+ opening = 24 * size * (1 - ease_out(clamp(u / 0.65)))+ tension = 0.65 * (1 - ease_out(u))+ at = surface(pen, s, departing)+ span = (48, 88, 132)[level]+ rows = (2, 4, 6)[level]+ samples = (8, 10, 12)[level]+ palette = s.palette+ # The warp stays anchored at the wall while the weft tightens across it.+ if level:+ pen.beginPath()+ for i in range(-8 if level == 2 else -5, 9 if level == 2 else 6):+ x = i * 14+ envelope = max(0, 1 - abs(x) / span)+ y = (5 + (rows - 1) * 4 + 13 * tension * envelope) * size+ pen.moveTo(*at(x, 2 * size))+ pen.lineTo(*at(x + math.copysign(opening * envelope, x or 1), y))+ stroke(pen, palette[1 % len(palette)], 1.0, alpha * 0.62, s.dark)+ for pigment, colour in enumerate(palette):+ pen.beginPath()+ for row in range(rows):+ if row % len(palette) != pigment:+ continue+ def yarn(x):+ envelope = max(0, 1 - (x / span) ** 2)+ lift = (10 + level * 5) * tension * envelope * size+ split = opening * envelope * (1 if row % 2 else -0.12)+ return max(2 * size, 7 * size + row * 4 * size + lift + split)+ pen.moveTo(*at(-span, yarn(-span)))+ step = 2 * span / samples+ for j in range(samples):+ a, b = -span + j * step, -span + (j + 1) * step+ # One cubic per half weave replaces a polyline's dense sampled geometry.+ weave = (3 if level < 2 else 7) * (1 - 0.65 * tension) * size * (-1 if (j + row) % 2 else 1)+ c1, c2 = a + step / 3, b - step / 3+ pen.bezierCurveTo(*at(c1, max(2, yarn(c1) + weave)),+ *at(c2, max(2, yarn(c2) + weave)), *at(b, yarn(b)))+ stroke(pen, colour, 1.8 if level == 0 else 1.6, alpha, s.dark)+ if level:+ # Short overpasses hide the warp at alternating crossings, making an actual weave.+ pen.beginPath()+ for i in range(-4, 5):+ x = i * 14+ envelope = max(0, 1 - (x / span) ** 2)+ y = (9 + (10 + level * 5) * tension * envelope) * size + opening * envelope+ pen.moveTo(*at(x - 2, y - size))+ pen.lineTo(*at(x + 2, y + size))+ stroke(pen, palette[-1], 2.1, alpha * 0.85, s.dark)+++def _make(id_, name, level, blurb):+ return Effect(id_, name, ("quiet", "medium", "showpiece")[level], blurb,+ lambda pen, s: _cloth(pen, s, level, True),+ lambda pen, s: _cloth(pen, s, level, False),+ (0.48, 0.64, 0.78)[level], (0.48, 0.64, 0.78)[level])+++EFFECTS = [+ _make("thread", "Thread", 0, "Two fine yarns tighten, part for the pointer and stitch the seam closed behind it."),+ _make("weave", "Weave", 1, "A woven border gathers tension, opens between its strands and gently mends on arrival."),+ _make("jacquard", "Jacquard", 2, "A diamond-patterned textile tightens across the edge, opens its weave and settles behind you."),+]++PACKS = {++ "woad": ("Woad", ["#8277b3", "#7268a4", "#c3b9df"]),++ "saffron": ("Saffron", ["#d48238", "#976025", "#efc18a"]),+ "flax": ("Flax", ["#cfb885", "#8a9c84", "#efdfb8"]),+ "madder": ("Madder", ["#c45b68", "#873d57", "#e5b09b"]),+ "tide": ("Tide", ["#58a9a3", "#547498", "#b1d1c1"]),+}diff --cc core/fx_sparks.pyindex 2cc7df0,b60128f..46408b7--- a/core/fx_sparks.py+++ b/core/fx_sparks.py@@@ -478,6 -478,6 +478,8 @@@ EFFECTS =]PACKS = {++ "arc": ("Arc", ["#69c8ff", "#269de8", "#b5e5ff", "#456ad0"]),++ "magnesium": ("Magnesium", ["#c98bff", "#9255da", "#ead2ff", "#b064e8"]),"ember": ("Ember", ["#ffe4ad", "#ffb04a", "#ff6a24", "#d8321a", "#8e1a10"]),"forge": ("Forge", ["#fff4dc", "#ffc15e", "#ff7f2a", "#b8c4d2", "#5d7896"]),"sparkler_gold": ("Sparkler gold", ["#ffffff", "#fff1bf", "#ffd35c", "#f0a531"]),diff --cc core/ignored.pyindex b7135a4,5bc01a5..7f9f8e9--- a/core/ignored.py+++ b/core/ignored.py@@@ -47,8 -47,8 +47,8 @@@ class Gatelist says by then: a key sent across and put on the list while still held would otherwise haveits release kept here and stay down on the far side, and one kept here and taken off the listwould stay down here. `keeps` runs on the one thread that reads input on each platform; `reset`-- is for when input comes home, since the far side lets go of everything it was holding then, and-- is called from other threads, hence the lock."""++ forgets remote presses when input comes home, while locally kept presses remain until their++ physical releases arrive. It is called from other threads, hence the lock."""def __init__(self, entries=()):self.entries = frozenset(entries)@@@ -80,6 -80,6 +80,3 @@@def reset(self):with self._lock:self._sent.clear()-- # A release that arrives once input is home is never asked about, so what was kept-- # here is forgotten too.-- self._kept.clear()diff --cc core/link.pyindex ca4a1ef,0000000..b7c532cmode 100644,000000..100644--- a/core/link.py+++ b/core/link.py@@@ -1,816 -1,0 +1,814 @@@+"""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+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- MAX_TEXT_SIZE = 4096-+_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",+ # "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):+ 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]+ try:+ self._connect(entry, host, port, direct=tried is not 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)+ if ended.stop_dialling:+ self._blocked_for = shape+ except Exception:+ 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.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/locale.pyindex 0000000,0000000..6bda3f1new file mode 100644--- /dev/null+++ b/core/locale.py@@@ -1,0 -1,0 +1,84 @@@++"""Choose the display spelling from the operating system's user region."""++++from __future__ import annotations++++import ctypes++import os++import re++import sys++++++_WORDS = {++ "colourful": "colorful", "colours": "colors", "colour": "color",++ "behaviour": "behavior",++ "centred": "centered", "centring": "centering", "centres": "centers", "centre": "center",++ "favourites": "favorites", "favourite": "favorite",++ "organisations": "organizations", "organisation": "organization",++ "organisers": "organizers", "organiser": "organizer",++ "organises": "organizes", "organised": "organized", "organising": "organizing", "organise": "organize",++ "licences": "licenses", "licence": "license",++ "minimises": "minimizes", "minimised": "minimized", "minimising": "minimizing", "minimise": "minimize",++ "initialises": "initializes", "initialised": "initialized", "initialising": "initializing", "initialise": "initialize",++ "authorisations": "authorizations", "authorisation": "authorization",++ "authorises": "authorizes", "authorised": "authorized", "authorising": "authorizing", "authorise": "authorize",++ "cancelled": "canceled", "cancelling": "canceling",++}++_WORD_PATTERN = re.compile(r"\b(" + "|".join(sorted(_WORDS, key=len, reverse=True)) + r")\b", re.IGNORECASE)++++++def _linux_locale() -> str:++ for key in ("LC_ALL", "LC_MESSAGES", "LANG"):++ value = os.environ.get(key)++ if value:++ return value++ return ""++++++def _country_in_locale(locale_name: str) -> str:++ match = re.search(r"(?:^|[-_])[A-Za-z]{2}[-_]([A-Za-z]{2})(?=$|[_.@])", locale_name)++ return match.group(1).upper() if match else ""++++++def _windows_locale() -> str:++ name = ctypes.create_unicode_buffer(85)++ if not ctypes.windll.kernel32.GetUserDefaultLocaleName(name, len(name)):++ return ""++ return name.value++++++def _mac_country() -> str:++ from Foundation import NSLocale, NSLocaleCountryCode++++ locale = NSLocale.currentLocale()++ return str(locale.objectForKey_(NSLocaleCountryCode) or "")++++++def is_us_region() -> bool:++ """Return whether the current user's operating-system region is the United States."""++ try:++ if sys.platform == "darwin":++ return _mac_country().upper() == "US"++ if sys.platform == "win32":++ return _country_in_locale(_windows_locale()) == "US"++ if sys.platform.startswith("linux"):++ return _country_in_locale(_linux_locale()) == "US"++ except (AttributeError, OSError, ImportError, ValueError):++ pass++ return False++++++def americanise(text: str) -> str:++ """Convert British spellings in text intended for display on a US system."""++ if not is_us_region() or not isinstance(text, str):++ return text++++ def replace(match: re.Match) -> str:++ source = match.group(0)++ target = _WORDS[source.casefold()]++ if source.isupper():++ return target.upper()++ if source[0].isupper():++ return target.capitalize()++ return target++++ return _WORD_PATTERN.sub(replace, text)diff --cc core/pairing.pyindex 59330af,0000000..466707bmode 100644,000000..100644--- a/core/pairing.py+++ b/core/pairing.py@@@ -1,2231 -1,0 +1,2252 @@@+"""LAN discovery and pairing, shared by both apps.++The host (the PC) broadcasts a small UDP beacon -- hostname, Beamer TCP port, and a random+pairing id while a code is on screen -- and the requester (the Mac) lists what it hears. Pairing+is then a PAKE with the six-digit code as its password: CPace, draft-irtf-cfrg-cpace-21, suite+CPACE-X25519-SHA512 with initiator and responder roles, followed by the explicit key+confirmation of the draft's section 10.4. Four datagrams:++ requester -> host pair_start {pair, v, nonce, share: Ya, name, id}+ host -> requester pair_answer {pair, ok, share: Yb, tag: Tb, name, id}+ requester -> host pair_confirm {pair, tag: Ta}+ host -> requester pair_done {pair, ok, tag: Td}++Both shares are X25519 public values over a generator derived from the code, so neither says+anything about the code to someone who does not already know it. The shared token is HKDF over+CPace's session key. The full specification is PAIRING.md at the repository root;+tests/pairing_vectors.json holds vectors for every step.++Where no broadcast reaches the Mac (another subnet, a VPN), the Mac asks a typed address for its+beacon with a `find` datagram, and pairing continues exactly as above.++What this protects against, and what it does not:++- The token never crosses the wire, and neither does the code. The beacon carries nothing a+ token or key could be derived from.+- Nothing on the wire can be tested against a list of codes offline, recorded or live. Whoever+ takes part without the code gets one guess against each side: a host answers only the first+ pair_start a code receives, a requester judges only the first pair_answer to its share, and+ it does not send a code again once an answer to it has failed. These rules are what keep an+ attacker to a guess a side, two chances in a million for a code, so none may be relaxed.+- A wrong code fails closed. The requester checks the host's tag before it sends its own, and+ the host stores a token only after the requester's tag checks out. A fresh code needs a person+ at the PC to press Pair a Mac again, and that is the rate limit. Codes expire after+ CODE_LIFETIME_SECONDS.+- Anyone on the LAN can still stop a pairing: a junk pair_start uses up the code. That is a+ denial, not a compromise.+- The host's address and port still come from the beacon, which nothing authenticates. That+ can point the Mac at the wrong address; it cannot read or forge the link.+- The generator is mapped to the curve in Python integers, which are not constant time. The+ code it depends on is single-use and lives a minute, so there is one computation to time per+ code on the PC and one per attempt on the Mac, and the PC's answer leaves a fixed time after+ the request whatever that computation took.++Pairing version 3 (1.5.0, WIRE.md section 6) sits beside version 2 until the apps' windows move to+it (milestone 2, steps 6a and 6b), when PairingHost's and PairingClient's version 2 path,+Announcer and Discovery's own pair() go. In version 3 each side's identity is its 16-byte machine+id, platform and port are bound in beside the name, a machine already paired is refused as+`known`, the host writes the peer entry before pair_done so Td proves it saved the token, and a+code shown as a QR carries a second secret. PairingService is version 3's socket side: every+desktop announces and discovers on one UDP socket, and hosts over UDP and TCP with one+PairingHost, so a code answers one pair_start whichever way it came.+"""++from __future__ import annotations++import base64+import contextlib+import ctypes+import ctypes.util+import hashlib+import hmac+import ipaddress+import json+import logging+import os+import queue+import secrets+import socket+import struct+import sys+import threading+import time++from nacl.bindings import crypto_scalarmult+from nacl.exceptions import CryptoError++from . import protocol++# One home for the port, in the module both apps share byte-for-byte.+PAIRING_PORT = protocol.PAIRING_PORT+BEACON_VERSION = 1+# The pairing exchange's own version, in every beacon and every pair_start. 1 was the+# scrypt-keyed HMAC proof of 1.4.2 and earlier, which carried no number. There is no fallback+# to it: a version that does not match ends the attempt with ERROR_VERSION.+PAIRING_VERSION = 2+BEACON_INTERVAL_SECONDS = 2.0+# Three missed beacons: long enough to ride out Wi-Fi hiccups, short enough that a PC that+# went to sleep leaves the list before anyone tries it.+BEACON_STALE_SECONDS = 7.0+# More PCs than any one network shows, and a ceiling on what forged beacons can make a Mac hold.+MAX_SEEN_HOSTS = 64+# A good pair_answer leaves this long after its pair_start arrived, however long it took to+# make. The generator's arithmetic is not constant time, and this keeps its duration out of+# the one thing a stranger can time: the answer.+PAIR_ANSWER_SECONDS = 0.05+CODE_LIFETIME_SECONDS = 60.0+# How long a requester will not send a code again after an answer to it failed: past the code's+# own life, after which a guess at it is worth nothing.+FAILED_CODE_SECONDS = 2 * CODE_LIFETIME_SECONDS+CODE_DIGITS = 6+MAX_DATAGRAM_BYTES = 1024+PAIR_REPLY_TIMEOUT_SECONDS = 1.5+PAIR_ATTEMPTS = 3+# How many replies already waiting are read for one from the address asked before a held one decides.+MAX_HELD_SWEEP = 64+NONCE_BYTES = 16+SHARE_BYTES = 32+TAG_BYTES = 64+# A name is bound into the exchange as sent, so it is cut before it is sent, never after. 48+# characters keep the largest datagram under MAX_DATAGRAM_BYTES even when JSON escapes each one.+MAX_NAME_CHARS = 48+MAX_IDENTITY_BYTES = 32+# A pairing id is 32 hex characters; 1.4.2's was 8. Anything longer or not ASCII is not one.+MAX_PAIR_ID_CHARS = 64++MSG_BEACON = "beacon"+MSG_PAIR_START = "pair_start"+MSG_PAIR_ANSWER = "pair_answer"+MSG_PAIR_CONFIRM = "pair_confirm"+MSG_PAIR_DONE = "pair_done"+# The 1.4.2 exchange's two datagrams. A host still answers the request, with a refusal, so an+# older Mac is told something rather than left to time out.+MSG_PAIR_REQUEST = "pair_request"+MSG_PAIR_REPLY = "pair_reply"+# The Mac asking one address for its beacon, for a PC that no broadcast reaches (another subnet,+# a VPN). The answer is the beacon every listener already hears, so it discloses nothing new.+MSG_FIND = "find"++ERROR_NOT_PAIRING = "not_pairing"+ERROR_REFUSED = "refused"+ERROR_VERSION = "version"+# Version 3's: the other side's id is already a peer's or this machine's own, and the host+# reached MAX_PEERS while its code was up.+ERROR_KNOWN = "known"+ERROR_FULL = "full"+_ERRORS = (ERROR_NOT_PAIRING, ERROR_REFUSED, ERROR_VERSION, ERROR_KNOWN, ERROR_FULL)+# What read_qr raises for any text that is not exactly the pairing QR's.+ERROR_BAD_QR = "bad_qr"++PAIRING_V3 = 3+CHANNEL_V3 = b"beamer-pair-v3"+TOKEN_INFO_V3 = b"beamer-pair-token-v3"+ID_BYTES = 16+QR_SECRET_BYTES = 16+MAX_PEERS = 32+MAX_PLATFORM_CHARS = 16+_PLATFORM_CHARS = frozenset("abcdefghijklmnopqrstuvwxyz0123456789_")+# A peer entry that never linked and was made this recently, under the name and platform the new+# pairing proves, is taken to be that pairing's lost pair_done and replaced rather than refused.+REPLACE_UNLINKED_SECONDS = 600+# Pairing over TCP, for a host no broadcast reaches and for the phones. The framing's limit is+# the datagram's, so a message means the same on either transport.+TCP_EXCHANGE_SECONDS = 10.0+TCP_CONNECT_SECONDS = 3.0+TCP_MAX_CONNECTIONS = 4+QR_PREFIX = "beamer://pair?"+_QR_KEYS = ("host", "port", "code", "k")+_PRIVATE_NETWORKS = tuple(ipaddress.ip_network(net) for net in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"))++# What the exchange binds besides the code. The two roles are fixed by who shows the code; the+# identities are parameters, empty until machines have ids of their own (wire v6), so a later+# version changes what is fed in and nothing else.+ROLE_REQUESTER = b"requester"+ROLE_HOST = b"host"+CHANNEL = b"beamer-pair-v2"+TOKEN_INFO = b"beamer-pair-token-v2"+DONE_LABEL = b"beamer-pair-done"++_DSI = b"CPace255"+_FIELD_PRIME = 2**255 - 19+_CURVE_A = 486662+_SHA512_BLOCK_BYTES = 128+++class PairingError(Exception):+ pass+++class AlreadyPaired(PairingError):+ """Version 3's `known`: the other machine's id is one of this machine's peers', or its own.+ `entry` is that peer's entry, for the window to name it and when it was paired; None when the+ id was this machine's own."""++ def __init__(self, entry):+ super().__init__(ERROR_KNOWN)+ self.entry = entry+++def new_code() -> str:+ return "".join(secrets.choice("0123456789") for _ in range(CODE_DIGITS))+++def _b64(data: bytes) -> str:+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")+++def _unb64(text: str) -> bytes:+ if not isinstance(text, str):+ raise PairingError("expected base64 text")+ try:+ data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))+ except ValueError as exc:+ raise PairingError("bad base64") from exc+ # The decoder skips what it does not know, so several spellings give the same bytes. Only+ # the one _b64 writes is taken: a field then has one form on the wire on every platform.+ if _b64(data) != text:+ raise PairingError("bad base64")+ return data+++def _prepend_len(data: bytes) -> bytes:+ """The draft's prepend_len: the length as LEB128, then the bytes."""+ length = len(data)+ encoded = bytearray()+ while True:+ encoded.append(length & 0x7F if length < 128 else (length & 0x7F) | 0x80)+ length >>= 7+ if length == 0:+ return bytes(encoded) + data+++def _lv_cat(*parts: bytes) -> bytes:+ return b"".join(_prepend_len(part) for part in parts)+++def _elligator2(r: int) -> int:+ """The u coordinate Elligator 2 maps a field element to on Curve25519 (RFC 9380 6.7.1 with+ Z = 2, as the draft's appendix A.5 repeats it)."""+ p = _FIELD_PRIME+ v = -_CURVE_A * pow(1 + 2 * r * r, p - 2, p) % p+ square = pow((v * v * v + _CURVE_A * v * v + v) % p, (p - 1) // 2, p) == 1+ return v if square else (-v - _CURVE_A) % p+++def _generator(prs: bytes, channel: bytes, sid: bytes) -> bytes:+ """The draft's calculate_generator for G_X25519 with SHA-512 (sections 8.1 and 8.2)."""+ padding = bytes(max(0, _SHA512_BLOCK_BYTES - 1 - len(_prepend_len(prs)) - len(_prepend_len(_DSI))))+ digest = hashlib.sha512(_lv_cat(_DSI, prs, padding, channel, sid)).digest()[:SHARE_BYTES]+ r = int.from_bytes(digest, "little") & ((1 << 255) - 1)+ return _elligator2(r).to_bytes(SHARE_BYTES, "little")+++def _x25519(scalar: bytes, point: bytes) -> bytes:+ """X25519 (RFC 7748), refusing a point that lands on the neutral element: the draft's+ scalar_mult_vfy, which MUST abort there. libsodium reports exactly that case as an error."""+ try:+ product = crypto_scalarmult(scalar, point)+ except CryptoError as exc:+ raise PairingError(ERROR_REFUSED) from exc+ if product == bytes(SHARE_BYTES):+ raise PairingError(ERROR_REFUSED)+ return product+++def _session_id(pair_id: str, nonce: bytes) -> bytes:+ # Random bytes from both ends, as the draft recommends for sid: the host's in the pairing+ # id, the requester's in its nonce.+ return _lv_cat(pair_id.encode("utf-8"), nonce)+++def _party(role: bytes, identity: bytes, name: str, platform: str = None, port: int = None) -> bytes:+ """One side's associated data: CPace's ADa or ADb. The role comes first, so the two sides'+ can never be equal, which is what stops a tag being reflected back at its sender. Version 3+ adds the platform and the link port, so the exchange proves everything pairing saves about+ the other machine but its address."""+ if platform is None:+ return _lv_cat(role, identity, name.encode("utf-8"))+ return _lv_cat(role, identity, name.encode("utf-8"), platform.encode("ascii"), port.to_bytes(2, "big"))+++def _share(code: str, sid: bytes, scalar: bytes, channel: bytes = CHANNEL, secret: bytes = b"") -> bytes:+ # A code read from a QR is followed by the QR's secret, 22 bytes of password in all; the+ # generator's padding follows its length.+ return _x25519(scalar, _generator(code.encode("utf-8") + secret, channel, sid))+++def _keys(sid: bytes, shared: bytes, ya: bytes, ada: bytes, yb: bytes, adb: bytes, token_info: bytes = TOKEN_INFO) -> tuple:+ """(token, Ta, Tb, Td) for one exchange, from the secret the two shares agree. Ta and Tb are+ the draft's tags over each side's own message; Td is the host's receipt."""+ isk = hashlib.sha512(_lv_cat(_DSI + b"_ISK", sid, shared) + _lv_cat(ya, ada) + _lv_cat(yb, adb)).digest()+ mac_key = hashlib.sha512(b"CPaceMac" + sid + isk).digest()++ def tag(message: bytes) -> bytes:+ return hmac.new(mac_key, message, hashlib.sha512).digest()++ return _b64(protocol.hkdf_sha256(isk, sid, token_info)), tag(_lv_cat(ya, ada)), tag(_lv_cat(yb, adb)), tag(_lv_cat(DONE_LABEL))+++def _is_int(value) -> bool:+ # JSON's 1.0 and true both compare equal to 1 in Python; an integer field takes neither.+ return type(value) is int+++def _platform_ok(platform) -> bool:+ return isinstance(platform, str) and 0 < len(platform) <= MAX_PLATFORM_CHARS and set(platform) <= _PLATFORM_CHARS+++def _port_ok(port) -> bool:+ return _is_int(port) and 0 <= port <= 65535+++def _name_ok(name) -> bool:+ if not isinstance(name, str) or not 0 < len(name) <= MAX_NAME_CHARS:+ return False+ try:+ name.encode("utf-8")+ except UnicodeError:+ return False+ return True+++def _machine_id_ok(identity: bytes) -> bool:+ return len(identity) == ID_BYTES and any(identity)+++def _check_own(identity: bytes, platform: str, port: int) -> None:+ if not _machine_id_ok(identity) or not _platform_ok(platform) or not _port_ok(port):+ raise ValueError("a version 3 side needs its 16-byte machine id, its platform and its link port")+++def _key_id(token):+ """The link's key id (WIRE.md section 2), or None for a typed token, which has none."""+ return protocol.key_id(token) if protocol.is_paired_token(token) else None+++def peer_entry(identity: bytes, name: str, platform: str, port: int, token: str, host: str, paired_at: int) -> dict:+ """The peer entry pairing saves (WIRE.md sections 1 and 6). A machine that gives port 0 is a+ phone: it is never dialled and this machine's input never goes to it."""+ phone = port == 0+ return {+ "id": _b64(identity), "name": name, "platform": platform, "token": token,+ "host": "" if phone else host, "port": port, "hw": "", "send": not phone, "allow_drive": True,+ "in_use": True,+ "side": "", "side_set_at": 0, "side_by": "", "paired_with": [], "paired_at": int(paired_at),+ "linked": False, "from_1_4": False,+ }+++def _find_known(peers: list, own: bytes, theirs: bytes, name: str, platform: str, now: float) -> tuple:+ """(refused, replaced) for a pairing that proved `theirs`, `name` and `platform`. `refused` is+ True when the id is this machine's own and otherwise the entry already holding it, None when+ there is none; `replaced` is the entry this pairing replaces: the one left by a lost pair_done,+ or one migrated from 1.4.x that an earlier beta linked and so knows the id of. A migrated entry+ never links, so replacing it takes nothing that works."""+ if theirs == own:+ return True, None+ wanted = _b64(theirs)+ for known in peers:+ if known.get("id") != wanted:+ continue+ if known.get("from_1_4") is True:+ return None, known+ paired_at = known.get("paired_at")+ lost_done = (+ known.get("linked") is False+ and _is_int(paired_at) and paired_at > 0 and 0 <= now - paired_at < REPLACE_UNLINKED_SECONDS+ and known.get("name") == name and known.get("platform") == platform+ )+ return (None, known) if lost_done else (known, None)+ return None, None+++def _migrated_for(peers: list, address: str, name: str, platform: str):+ """The entry migrated from 1.4.x (`id: ""`) that a fresh pairing with the machine at `address`,+ proving `name` and `platform`, replaces, or None: its saved host is `address`, or (its address+ having changed) its name and platform are the ones proved. A name is anyone's to claim, which+ is safe only because a migrated entry never links and a match by name carries nothing over+ (peerlist.add_peer gives its side and zones only to the machine at its host on its platform):+ taking it loses nothing that works, and left, it would ask to be paired again beside this pairing."""+ for known in peers:+ if known.get("id") == "" and known.get("from_1_4") is True and (+ (address and known.get("host") == address)+ or (known.get("name") == name and known.get("platform") == platform)):+ return known+ return None+++def _clashes(peers: list, token: str, replaced) -> bool:+ """Whether the new token's key id is already an entry's, bar the entry it replaces. With a+ fresh 256-bit token that never happens; the check keeps key ids unique whatever the entries+ hold."""+ new = _key_id(token)+ skip = replaced.get("id") if replaced else None+ return any(_key_id(known.get("token")) == new for known in peers if skip is None or known.get("id") != skip)+++def _failure(kind: str, pair_id: str, error: str) -> dict:+ return {"type": kind, "pair": pair_id, "ok": False, "error": error}+++def _error_of(reply: dict) -> str:+ error = reply.get("error")+ return error if error in _ERRORS else ERROR_REFUSED+++def encode(message: dict) -> bytes:+ # The "beamy" key is a wire constant, deliberately kept as the pre-rename name: changing it+ # would break an existing pairing and a mixed-version pair for no gain.+ return json.dumps({"beamy": BEACON_VERSION, **message}, separators=(",", ":")).encode("utf-8")+++def decode(data: bytes):+ """The dict a Beamer datagram carries, or None for anything else on the port."""+ if len(data) > MAX_DATAGRAM_BYTES:+ return None+ try:+ message = json.loads(data.decode("utf-8"))+ except (UnicodeDecodeError, ValueError, RecursionError):+ # RecursionError is what a datagram of nothing but brackets raises on some Pythons, and+ # left uncaught it would end the socket loop that called this.+ return None+ if not isinstance(message, dict) or message.get("beamy") != BEACON_VERSION:+ return None+ return message+++def beacon_msg(name: str, port: int, pair_id: str = None) -> dict:+ message = {"type": MSG_BEACON, "name": name, "port": int(port), "pairing": PAIRING_VERSION}+ if pair_id:+ message["pair"] = pair_id+ return message+++def qr_text(host: str, port: int, code: str, secret: bytes) -> str:+ """What the pairing sheet's QR code holds (WIRE.md section 6). The sheet never shows `k` as+ text."""+ return f"{QR_PREFIX}host={host}&port={port}&code={code}&k={_b64(secret)}"+++def _decimal(text: str) -> bool:+ # str.isdigit() also takes full-width and superscript digits; the QR takes ASCII only, and+ # no leading zero, so a number has one spelling.+ return text.isascii() and text.isdigit() and (text == "0" or not text.startswith("0"))+++def read_qr(text) -> dict:+ """The host, port, code and secret a pairing QR carries, or PairingError(ERROR_BAD_QR) for+ any other text: the four keys in order, lower case, each once, and nothing else."""+ if not isinstance(text, str) or not text.startswith(QR_PREFIX):+ raise PairingError(ERROR_BAD_QR)+ fields = [field.split("=", 1) for field in text[len(QR_PREFIX):].split("&")]+ if [field[0] for field in fields] != list(_QR_KEYS) or any(len(field) != 2 for field in fields):+ raise PairingError(ERROR_BAD_QR)+ host, port, code, k = (field[1] for field in fields)+ octets = host.split(".")+ if len(octets) != 4 or not all(_decimal(octet) and int(octet) <= 255 for octet in octets):+ raise PairingError(ERROR_BAD_QR)+ if not _decimal(port) or not 0 < int(port) <= 65535:+ raise PairingError(ERROR_BAD_QR)+ if len(code) != CODE_DIGITS or not (code.isascii() and code.isdigit()):+ raise PairingError(ERROR_BAD_QR)+ try:+ secret = _unb64(k)+ except PairingError as exc:+ raise PairingError(ERROR_BAD_QR) from exc+ if len(secret) != QR_SECRET_BYTES:+ raise PairingError(ERROR_BAD_QR)+ return {"host": host, "port": int(port), "code": code, "secret": secret}+++def _private(address: str) -> bool:+ try:+ return any(ipaddress.ip_address(address) in network for network in _PRIVATE_NETWORKS)+ except ValueError:+ return False+++def pairing_address():+ """The address the pairing sheet shows and the QR carries: this machine's address in a+ private range, preferring the default route's interface, else the default route's own+ address. None when the machine has no IPv4 address at all."""+ try:+ # A TEST-NET address: nothing is sent, and only the default route reaches it.+ default = local_address_towards("192.0.2.1")+ except OSError:+ default = None+ if default and _private(default):+ return default+ return next((address for address in _local_ipv4_addresses() if _private(address)), default)+++class PairingHost:+ """The host's half: holds at most one live code and answers the exchange. Pure -- the+ Announcer or PairingService owns the socket, and the clock and the randomness are injected+ for the tests and the vectors.++ Version 3 also takes this machine's platform and link port, `peers` (a callable giving the+ peer entries as they stand) and `store(entry, replaced)`, which writes the new entry, and+ drops `replaced` when it is not None, before pair_done is sent, raising if the write fails.+ `wall` gives unix seconds for `paired_at`."""++ def __init__(self, clock=time.monotonic, name: str = "", identity: bytes = b"", entropy=secrets.token_bytes,+ *, version: int = PAIRING_VERSION, platform: str = "", port: int = 0, peers=None, store=None, wall=time.time):+ if version == PAIRING_V3:+ _check_own(identity, platform, port)+ self.clock = clock+ self.name = name[:MAX_NAME_CHARS]+ self.identity = identity+ self._entropy = entropy+ self.version = version+ self.platform = platform+ self.port = port+ self._peers = peers or list+ self.store = store+ self.wall = wall+ self.code = None+ self.pair_id = None+ self.expires_at = 0.0+ # Version 3: the 16 bytes a QR carries beside the code, drawn with it and dropped with it.+ self.qr_secret = None+ # The one pair_start this code answered, as a dict; None until it arrives.+ self._bound = None+ self._last = None+ # True once a pair_answer has just been worked out from the code, until the caller that+ # sends it takes note. A retransmit's answer comes from memory and leaves it False.+ self.fresh_answer = False+ # The pairing just made: (token, requester_name) in version 2, the stored entry in 3.+ self.paired = None+ # How the last code ended -- "paired", "refused", "version" or "expired", and in version+ # 3 "known" (this machine has the requester already), "known_there" (the requester has+ # this one), "full" and "not_saved" -- for the window to say so; None while a code is+ # live or after a deliberate cancel.+ self.outcome = None+ # The entry that made the last code end "known", for the window to name; None when the+ # requester claimed this machine's own id.+ self.known = None++ @property+ def active(self) -> bool:+ if self.code is None:+ return False+ if self.clock() >= self.expires_at:+ self.cancel()+ self.outcome = "expired"+ return False+ return True++ @property+ def seconds_left(self) -> int:+ return max(0, int(self.expires_at - self.clock())) if self.active else 0++ @property+ def v3(self) -> bool:+ return self.version == PAIRING_V3++ def begin(self) -> str:+ if self.v3 and len(self._peers()) >= MAX_PEERS:+ # A host with 32 peers shows no code: the pairing could not be kept.+ raise PairingError(ERROR_FULL)+ self.code = new_code()+ self.pair_id = self._entropy(16).hex()+ self.qr_secret = self._entropy(QR_SECRET_BYTES) if self.v3 else None+ self.expires_at = self.clock() + CODE_LIFETIME_SECONDS+ self._bound = None+ self._last = None+ self.fresh_answer = False+ self.outcome = None+ self.known = None+ return self.code++ def cancel(self) -> None:+ self.code = None+ self.pair_id = None+ self.qr_secret = None+ self.expires_at = 0.0+ self._bound = None+ self.outcome = None++ def beacon(self, port: int) -> dict:+ """Version 3's beacon. The pairing id and this machine's id travel only while a code is+ up, so a machine does not broadcast a stable id on every network it joins."""+ message = {"type": MSG_BEACON, "name": self.name, "port": int(port), "pairing": PAIRING_V3, "platform": self.platform}+ if self.active:+ message["pair"] = self.pair_id+ message["id"] = _b64(self.identity)+ return message++ def handle(self, message: dict, address: str = "", via=None):+ """The reply to one message, or None when it deserves no answer. A successful pairing+ leaves `self.paired` set: (token, requester_name) in version 2, for the caller to store;+ in version 3 the entry `store` has already written. `address` is where the pair_start+ came from, which version 3 saves as the requester's host. `via` is the transport it came+ on (a TCP connection, or the UDP socket): version 3 takes a pair_confirm only on the channel+ whose pair_start bound the code."""+ kind = message.get("type")+ pair_id = message.get("pair")+ # Every reply echoes the pairing id, so one that is not shaped like an id gets none: a+ # reply is then never much larger than the datagram that drew it.+ if not isinstance(pair_id, str) or not pair_id.isascii() or not 0 < len(pair_id) <= MAX_PAIR_ID_CHARS:+ return None+ if kind == MSG_PAIR_START:+ return self._start(message, pair_id, address, via)+ if kind == MSG_PAIR_CONFIRM:+ return self._confirm(message, pair_id, address, via)+ if kind == MSG_PAIR_REQUEST:+ return self._outdated(pair_id)+ return None++ def _start(self, message: dict, pair_id: str, address: str, via=None) -> dict:+ fields = ("pair", "v", "nonce", "share", "name", "id") + (("platform", "port", "qr") if self.v3 else ())+ # "qr" absent and "qr": null are different messages; the sentinel keeps them apart.+ sent = [message.get(field, KeyError) for field in fields]+ if self._last is not None and self._last[0] == sent:+ # A lost reply makes the requester send the same datagram again; answer it the same+ # way, so a retransmit is not read as a second attempt.+ return self._last[1]+ if not self.active or pair_id != self.pair_id:+ return _failure(MSG_PAIR_ANSWER, pair_id, ERROR_NOT_PAIRING)+ if self._bound is not None:+ if self._bound["sent"] == sent:+ return self._bound["answer"]+ # One code answers one share. A second answer would hand whoever sent it a second+ # guess at the code, so it is refused, and the exchange already under way is left+ # alone rather than cancelled by a stranger's datagram.+ return _failure(MSG_PAIR_ANSWER, pair_id, ERROR_REFUSED)+ version = message.get("v")+ if not _is_int(version) or version != self.version:+ return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_VERSION, "version")+ if self.v3 and len(self._peers()) >= MAX_PEERS:+ return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_FULL, "full")+ try:+ nonce = _unb64(message.get("nonce"))+ share = _unb64(message.get("share"))+ identity = _unb64(message.get("id"))+ name = message.get("name")+ platform = message.get("platform")+ port = message.get("port")+ secret = b""+ if (+ len(nonce) != NONCE_BYTES+ or len(share) != SHARE_BYTES+ or len(identity) > MAX_IDENTITY_BYTES+ or not isinstance(name, str)+ or len(name) > MAX_NAME_CHARS+ ):+ raise PairingError(ERROR_REFUSED)+ if self.v3:+ if not (_machine_id_ok(identity) and _name_ok(name) and _platform_ok(platform) and _port_ok(port)):+ raise PairingError(ERROR_REFUSED)+ if "qr" in message:+ if not _is_int(message["qr"]) or message["qr"] != 1:+ raise PairingError(ERROR_REFUSED)+ secret = self.qr_secret+ requester = _party(ROLE_REQUESTER, identity, name, platform, port)+ host = _party(ROLE_HOST, self.identity, self.name, self.platform, self.port)+ else:+ requester = _party(ROLE_REQUESTER, identity, name)+ host = _party(ROLE_HOST, self.identity, self.name)+ sid = _session_id(pair_id, nonce)+ scalar = self._entropy(SHARE_BYTES)+ # Everything that can refuse this datagram is settled before the code is touched:+ # a refusal goes back at once, and must not carry the time the generator took.+ shared = _x25519(scalar, share)+ except (PairingError, UnicodeError):+ return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_REFUSED, "refused")+ try:+ own = _share(self.code, sid, scalar, CHANNEL_V3 if self.v3 else CHANNEL, secret)+ except PairingError:+ return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_REFUSED, "refused")+ token, requester_tag, host_tag, done_tag = _keys(sid, shared, share, requester, own, host, TOKEN_INFO_V3 if self.v3 else TOKEN_INFO)+ self.fresh_answer = True+ answer = {+ "type": MSG_PAIR_ANSWER,+ "pair": pair_id,+ "ok": True,+ "share": _b64(own),+ "tag": _b64(host_tag),+ "name": self.name,+ "id": _b64(self.identity),+ }+ if self.v3:+ answer["platform"] = self.platform+ answer["port"] = self.port+ self._bound = {+ "sent": sent,+ "answer": answer,+ "requester_tag": requester_tag,+ "done_tag": done_tag,+ "token": token,+ "name": name,+ "identity": identity,+ "platform": platform,+ "port": port,+ "address": address,+ "via": via,+ }+ return answer++ def _confirm(self, message: dict, pair_id: str, address: str, via=None) -> dict:+ sent = [pair_id, message.get("tag"), message.get("error")]+ if self._last is not None and self._last[0] == sent:+ return self._last[1]+ if not self.active or pair_id != self.pair_id or self._bound is None:+ return _failure(MSG_PAIR_DONE, pair_id, ERROR_NOT_PAIRING)+ bound = self._bound+ if self.v3 and (address != bound["address"] or via != bound["via"]):+ # Only the address and transport whose pair_start bound the code may end it. A+ # stranger's confirmation, a forged-source datagram or a second connection included, is+ # not answered and leaves the exchange alone.+ return None+ try:+ tag = _unb64(message.get("tag"))+ except PairingError:+ tag = b""+ if not hmac.compare_digest(tag, bound["requester_tag"]):+ # An `error: known` is unauthenticated, like every refusal: the window only says the+ # other machine may already have this one paired.+ there = self.v3 and message.get("error") == ERROR_KNOWN+ return self._end(MSG_PAIR_DONE, sent, pair_id, ERROR_REFUSED, "known_there" if there else "refused")+ if self.v3:+ return self._keep(bound, sent, pair_id)+ self.paired = (bound["token"], bound["name"])+ return self._done(sent, pair_id, bound)++ def _keep(self, bound: dict, sent: list, pair_id: str) -> dict:+ """Version 3, once Ta has proved the requester's id: refuse a machine already paired,+ keep key ids unique, and write the entry before pair_done says it was written."""+ peers = self._peers()+ known, replaced = _find_known(peers, self.identity, bound["identity"], bound["name"], bound["platform"], self.wall())+ if known is not None:+ reply = self._end(MSG_PAIR_DONE, sent, pair_id, ERROR_KNOWN, "known")+ self.known = None if known is True else known+ return reply+ replaced = replaced or _migrated_for(peers, bound["address"], bound["name"], bound["platform"])+ if _clashes(peers, bound["token"], replaced):+ return self._end(MSG_PAIR_DONE, sent, pair_id, ERROR_REFUSED, "refused")+ if replaced is None and len(peers) >= MAX_PEERS:+ # Filled by a pairing this machine requested while the code was up.+ return self._end(MSG_PAIR_DONE, sent, pair_id, ERROR_REFUSED, "full")+ requester_port = bound["port"]+ entry = peer_entry(bound["identity"], bound["name"], bound["platform"], requester_port, bound["token"], bound["address"], self.wall())+ try:+ self.store(entry, replaced)+ except Exception as exc:+ logging.getLogger("Beamer").warning("the new peer entry could not be saved: %s", exc)+ return self._end(MSG_PAIR_DONE, sent, pair_id, ERROR_REFUSED, "not_saved")+ self.paired = entry+ return self._done(sent, pair_id, bound)++ def _done(self, sent: list, pair_id: str, bound: dict) -> dict:+ reply = {"type": MSG_PAIR_DONE, "pair": pair_id, "ok": True, "tag": _b64(bound["done_tag"])}+ self._last = (sent, reply)+ self.cancel()+ self.outcome = "paired"+ return reply++ def _outdated(self, pair_id: str) -> dict:+ """A 1.4.2 Mac's request. It is answered in the datagram that Mac reads, and the code+ goes, because its window then says the PC cancelled it."""+ if self.active and pair_id == self.pair_id and self._bound is None:+ self.cancel()+ self.outcome = "version"+ return _failure(MSG_PAIR_REPLY, pair_id, ERROR_REFUSED)+ return _failure(MSG_PAIR_REPLY, pair_id, ERROR_REFUSED if self.active else ERROR_NOT_PAIRING)++ def _end(self, kind: str, sent: list, pair_id: str, error: str, outcome: str) -> dict:+ reply = _failure(kind, pair_id, error)+ self._last = (sent, reply)+ self.cancel()+ self.outcome = outcome+ return reply+++class PairingClient:+ """The requester's half of one attempt: builds the start, checks the answer, confirms, and+ yields the token once the host says it has stored it.++ Version 3 also takes this machine's platform and link port, `peers` (a callable giving the+ peer entries), `wall` for `paired_at`, and `qr_secret` when the code was read from a QR. It+ raises PairingError(ERROR_FULL) at once when this machine already has MAX_PEERS peers."""++ def __init__(self, pair_id: str, code: str, name: str, identity: bytes = b"", entropy=secrets.token_bytes,+ *, version: int = PAIRING_VERSION, platform: str = "", port: int = 0, qr_secret: bytes = None, peers=None, wall=time.time):+ self.version = version+ self._peers = peers or list+ self.wall = wall+ if self.v3:+ _check_own(identity, platform, port)+ if qr_secret is not None and len(qr_secret) != QR_SECRET_BYTES:+ raise ValueError("a QR secret is 16 bytes")+ if len(self._peers()) >= MAX_PEERS:+ raise PairingError(ERROR_FULL)+ self.pair_id = pair_id+ self.name = name[:MAX_NAME_CHARS]+ self.identity = identity+ self.platform = platform+ self.port = port+ self.qr_secret = qr_secret+ self._nonce = entropy(NONCE_BYTES)+ self._sid = _session_id(pair_id, self._nonce)+ self._scalar = entropy(SHARE_BYTES)+ self._share = _share(code, self._sid, self._scalar, CHANNEL_V3 if self.v3 else CHANNEL, qr_secret or b"")+ self._answered = False+ self._known = False+ self._token = None+ self._done_tag = None+ # The host's name and identity as the exchange bound them; None until its tag checks out.+ self.host_name = None+ self.host_identity = None+ self.host_platform = None+ self.host_port = None+ # Version 3: this machine's entry that the new one replaces (a lost pair_done), or None.+ self.replaces = None++ @property+ def v3(self) -> bool:+ return self.version == PAIRING_V3++ def start(self) -> dict:+ message = {+ "type": MSG_PAIR_START,+ "pair": self.pair_id,+ "v": self.version,+ "nonce": _b64(self._nonce),+ "share": _b64(self._share),+ "name": self.name,+ "id": _b64(self.identity),+ }+ if self.v3:+ message["platform"] = self.platform+ message["port"] = self.port+ if self.qr_secret is not None:+ message["qr"] = 1+ return message++ def accept(self, answer: dict) -> dict:+ """The pair_confirm to send back, or PairingError naming why not. It judges one answer+ and no more: each answer it judged would be another guess at the code for whoever is+ answering. Version 3 refuses a host this machine already has with AlreadyPaired, once+ the host's tag has proved its id."""+ if answer.get("type") != MSG_PAIR_ANSWER or answer.get("pair") != self.pair_id:+ raise PairingError("not a reply to this attempt")+ if self._answered:+ raise PairingError(ERROR_REFUSED)+ self._answered = True+ if answer.get("ok") is not True:+ raise PairingError(_error_of(answer))+ try:+ share = _unb64(answer.get("share"))+ tag = _unb64(answer.get("tag"))+ identity = _unb64(answer.get("id"))+ name = answer.get("name")+ platform = answer.get("platform")+ port = answer.get("port")+ if len(share) != SHARE_BYTES or len(identity) > MAX_IDENTITY_BYTES or not isinstance(name, str) or len(name) > MAX_NAME_CHARS:+ raise PairingError(ERROR_REFUSED)+ if self.v3:+ if not (_machine_id_ok(identity) and _name_ok(name) and _platform_ok(platform) and _port_ok(port)):+ raise PairingError(ERROR_REFUSED)+ requester = _party(ROLE_REQUESTER, self.identity, self.name, self.platform, self.port)+ host = _party(ROLE_HOST, identity, name, platform, port)+ else:+ requester = _party(ROLE_REQUESTER, self.identity, self.name)+ host = _party(ROLE_HOST, identity, name)+ shared = _x25519(self._scalar, share)+ token, requester_tag, host_tag, done_tag = _keys(self._sid, shared, self._share, requester, share, host, TOKEN_INFO_V3 if self.v3 else TOKEN_INFO)+ except (PairingError, UnicodeError) as exc:+ raise PairingError(ERROR_REFUSED) from exc+ if not hmac.compare_digest(tag, host_tag):+ raise PairingError(ERROR_REFUSED)+ if self.v3:+ self._check_host(identity, name, platform)+ self._token = token+ self._done_tag = done_tag+ self.host_name = name+ self.host_identity = identity+ self.host_platform = platform+ self.host_port = port+ return {"type": MSG_PAIR_CONFIRM, "pair": self.pair_id, "tag": _b64(requester_tag)}++ def _check_host(self, identity: bytes, name: str, platform: str) -> None:+ known, self.replaces = _find_known(self._peers(), self.identity, identity, name, platform, self.wall())+ if known is not None:+ self._known = True+ raise AlreadyPaired(None if known is True else known)++ def abort(self) -> dict:+ """What to send a host whose answer failed: a confirmation that cannot pass, so the host+ drops the code and says a wrong one was entered instead of showing it for the rest of+ its minute; or, after AlreadyPaired, that this machine has the host already."""+ message = {"type": MSG_PAIR_CONFIRM, "pair": self.pair_id, "tag": ""}+ if self._known:+ message["error"] = ERROR_KNOWN+ return message++ def finish(self, done: dict) -> str:+ """The agreed token, once the host's pair_done proves it stored the same one. Version 3+ refuses it when its key id is already one of this machine's entries'."""+ if done.get("type") != MSG_PAIR_DONE or done.get("pair") != self.pair_id or self._token is None:+ raise PairingError("not a reply to this attempt")+ if done.get("ok") is not True:+ raise PairingError(_error_of(done))+ try:+ tag = _unb64(done.get("tag"))+ except PairingError as exc:+ raise PairingError(ERROR_REFUSED) from exc+ if not hmac.compare_digest(tag, self._done_tag):+ raise PairingError(ERROR_REFUSED)+ if self.v3 and _clashes(self._peers(), self._token, self.replaces):+ raise PairingError(ERROR_REFUSED)+ return self._token++ def proves(self, done: dict) -> bool:+ """Whether an ok pair_done carries the tag only the host holding this attempt's token could+ make. Checking it tests no guess at the code."""+ try:+ return self._done_tag is not None and hmac.compare_digest(_unb64(done.get("tag")), self._done_tag)+ except PairingError:+ return False++ def entry(self, address: str) -> dict:+ """Version 3: the peer entry for the host, reached at `address`, once finish() has+ returned the token."""+ return peer_entry(self.host_identity, self.host_name, self.host_platform, self.host_port, self._token, address, self.wall())+++def _udp_socket(bind_port: int) -> socket.socket:+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)- if hasattr(socket, "SO_REUSEPORT"):- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)- sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)- sock.bind(("", bind_port))- sock.settimeout(0.5)++ try:++ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)++ if hasattr(socket, "SO_REUSEPORT"):++ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)++ sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)++ sock.bind(("", bind_port))++ sock.settimeout(0.5)++ except OSError:++ sock.close()++ raise+ return sock+++def local_address_towards(host: str) -> str:+ """This machine's address on the interface that reaches `host`; nothing is sent."""+ probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ probe.connect((host, 9))+ return probe.getsockname()[0]+ finally:+ probe.close()+++def broadcast_targets(port: int, interfaces=None) -> list:+ """Every address worth sending a beacon to, one per local IPv4 network plus the limited+ broadcast as a backstop. `interfaces` is _interfaces()'s list, read afresh when None.++ ⚠ 255.255.255.255 alone is not enough and this is not theoretical: it leaves by the default+ route only, so a PC with a second interface — a Hyper-V vEthernet switch is the common case —+ announces on whichever the routing table prefers and may never reach the LAN the Mac is on.+ Seen in practice: the PC beaconed steadily while no beacon reached the Mac at all, and the Mac+ then paired against a stale id from an older beacon that had got through, which is what+ produced `not_pairing`.++ Each network's directed broadcast follows its own netmask: a /24 guess sent a 169.254/16+ link-local interface to an address no host holds. Only where the platform will not list its+ interfaces is a /24 still assumed. The limited broadcast is always sent, so a wrong guess can+ only add delivery, never remove it."""+ if interfaces is None:+ interfaces = _interfaces()+ if interfaces:+ directed = [str(ipaddress.IPv4Network(f"{address}/{netmask}", strict=False).broadcast_address)+ for address, netmask in interfaces]+ else:+ directed = [".".join(address.split(".")[:3] + ["255"]) for address in _local_ipv4_addresses()+ if len(address.split(".")) == 4]+ targets = [("255.255.255.255", port)]+ seen = {"255.255.255.255"}+ for address in directed:+ if address not in seen:+ seen.add(address)+ targets.append((address, port))+ return targets+++def _local_ipv4_addresses() -> list:+ found = [address for address, _netmask in _interfaces()]+ try:+ for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):+ address = info[4][0]+ if not address.startswith("127.") and address not in found:+ found.append(address)+ except OSError:+ pass+ return found+++def _interfaces() -> list:+ """(address, netmask) as dotted quads for each IPv4 interface that is up and has a network to+ broadcast on: loopback, point-to-point tunnels (a VPN's) and a /31 or /32 are left out. [] when+ the platform will not say, and the callers then do as they did before they could ask."""+ try:+ listed = _windows_interfaces() if sys.platform == "win32" else _posix_interfaces()+ except Exception:+ # ctypes over the C library: whatever goes wrong there costs this list and nothing else.+ return []+ found = []+ for address, netmask in listed:+ try:+ network = ipaddress.IPv4Network(f"{address}/{netmask}", strict=False)+ except ValueError:+ continue+ if ipaddress.IPv4Address(address).is_loopback or address == "0.0.0.0" or not 0 < network.prefixlen < 31:+ continue+ if (address, netmask) not in found:+ found.append((address, netmask))+ return found+++class _Ifaddrs(ctypes.Structure):+ pass+++# The same layout on macOS and Linux; the sockaddrs it points at are not (BSD's start with a length).+_Ifaddrs._fields_ = [+ ("ifa_next", ctypes.POINTER(_Ifaddrs)),+ ("ifa_name", ctypes.c_char_p),+ ("ifa_flags", ctypes.c_uint),+ ("ifa_addr", ctypes.c_void_p),+ ("ifa_netmask", ctypes.c_void_p),+ ("ifa_dstaddr", ctypes.c_void_p),+ ("ifa_data", ctypes.c_void_p),+]+_IFF_UP, _IFF_BROADCAST, _IFF_LOOPBACK, _IFF_POINTOPOINT = 0x1, 0x2, 0x8, 0x10+++def _sockaddr_ipv4(pointer):+ """(family, the four address bytes) of a sockaddr from getifaddrs. A BSD netmask may be cut+ short by its length byte, and may say no family: the bytes it leaves out are zeros."""+ if sys.platform == "darwin":+ length = ctypes.string_at(pointer, 1)[0]+ raw = ctypes.string_at(pointer, min(max(length, 2), 8))+ family = raw[1]+ else:+ raw = ctypes.string_at(pointer, 8)+ family = int.from_bytes(raw[:2], sys.byteorder)+ return family, raw[4:8].ljust(4, b"\0")+++def _posix_interfaces() -> list:+ libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)+ libc.getifaddrs.argtypes = [ctypes.POINTER(ctypes.POINTER(_Ifaddrs))]+ libc.freeifaddrs.argtypes = [ctypes.POINTER(_Ifaddrs)]+ head = ctypes.POINTER(_Ifaddrs)()+ if libc.getifaddrs(ctypes.byref(head)) != 0:+ raise OSError(ctypes.get_errno(), "getifaddrs failed")+ found = []+ try:+ node = head+ while node:+ item = node.contents+ node = item.ifa_next+ wanted = _IFF_UP | _IFF_BROADCAST+ if item.ifa_flags & (wanted | _IFF_LOOPBACK | _IFF_POINTOPOINT) != wanted or not item.ifa_addr or not item.ifa_netmask:+ continue+ family, address = _sockaddr_ipv4(item.ifa_addr)+ if family != socket.AF_INET:+ continue+ found.append((socket.inet_ntoa(address), socket.inet_ntoa(_sockaddr_ipv4(item.ifa_netmask)[1])))+ finally:+ libc.freeifaddrs(head)+ return found+++class _IpAddrRow(ctypes.Structure):+ _fields_ = [+ ("dwAddr", ctypes.c_uint32),+ ("dwIndex", ctypes.c_uint32),+ ("dwMask", ctypes.c_uint32),+ ("dwBCastAddr", ctypes.c_uint32),+ ("dwReasmSize", ctypes.c_uint32),+ ("unused1", ctypes.c_ushort),+ ("wType", ctypes.c_ushort),+ ]+++def _windows_interfaces() -> list:+ """GetIpAddrTable: every IPv4 address with its mask, each stored in network order. Windows+ gives no point-to-point flag here; a VPN adapter's /32 is what leaves it out."""+ iphlpapi = ctypes.WinDLL("iphlpapi")+ iphlpapi.GetIpAddrTable.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong), ctypes.c_int]+ size = ctypes.c_ulong(0)+ iphlpapi.GetIpAddrTable(None, ctypes.byref(size), 0)+ for _attempt in range(3):+ table = ctypes.create_string_buffer(size.value)+ result = iphlpapi.GetIpAddrTable(table, ctypes.byref(size), 0)+ if result != 122: # ERROR_INSUFFICIENT_BUFFER: an address came up in between+ break+ if result != 0:+ raise OSError(result, "GetIpAddrTable failed")+ count = ctypes.c_uint32.from_buffer(table).value+ rows = (_IpAddrRow * count).from_buffer(table, ctypes.sizeof(ctypes.c_uint32))+ gone = 0x0008 | 0x0040 # MIB_IPADDR_DISCONNECTED, MIB_IPADDR_DELETED+ return [(socket.inet_ntoa(struct.pack("=I", row.dwAddr)), socket.inet_ntoa(struct.pack("=I", row.dwMask)))+ for row in rows if not row.wType & gone]+++def _answer_source(host: str, interfaces=None, towards=None):+ """The address to answer `host` from when the routing table would pick a different one: this+ machine's address on the network `host` is on. None when `host` is on none of them, or the+ routing table agrees. Seen on 01-10-2026: a VPN's route for the home network sent the laptop's+ answer out from the VPN's address, and the requester never knew it for an answer."""+ try:+ requester = ipaddress.IPv4Address(host)+ except ValueError:+ return None+ ours = [address for address, netmask in (_interfaces() if interfaces is None else interfaces)+ if requester in ipaddress.IPv4Network(f"{address}/{netmask}", strict=False)]+ if not ours:+ return None+ try:+ routed = (towards or local_address_towards)(host)+ except OSError:+ routed = None+ # Two addresses on one network: whichever the routing table picks is already right.+ return None if routed in ours else ours[0]+++def _oversized(exc: OSError) -> bool:+ """Windows' WSAEMSGSIZE: a datagram larger than the buffer, which Windows reports as an error+ where other platforms cut it short. Anyone can send one, so it must cost only itself; it once+ stopped a PC's pairing loop for good."""+ return getattr(exc, "winerror", None) == 10040+++def _receive_on(sock, timeout: float):+ """The next datagram on `sock` as (message, address), {} for one that is not a message, or None+ once `timeout` passes."""+ sock.settimeout(max(timeout, 0.001))+ try:+ data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)+ except socket.timeout:+ return None+ except ConnectionResetError:+ # Windows: the port-unreachable of an earlier datagram.+ return {}, ("", 0)+ except OSError as exc:+ if _oversized(exc):+ return {}, ("", 0)+ raise PairingError("no_answer") from exc+ message = decode(data)+ return (message if isinstance(message, dict) else {}), address+++def machine_name() -> str:+ return socket.gethostname().split(".", 1)[0] or "This machine"+++def _due(last: dict, host: str, now: float) -> bool:+ """Whether `host` may be sent another datagram of a rationed kind, noting it if so."""+ interval = BEACON_INTERVAL_SECONDS / 4+ if now - last.get(host, -BEACON_INTERVAL_SECONDS) < interval:+ return False+ if len(last) > 256:+ # Only what has lapsed is forgotten. Emptying the table would let a burst from+ # made-up addresses wipe the record of the one being aimed at.+ for lapsed in [known for known, sent in last.items() if now - sent >= interval]:+ del last[lapsed]+ if len(last) > 256:+ return False+ last[host] = now+ return True+++class Announcer:+ """The PC's socket loop: broadcasts the beacon and answers pairing requests on one socket.+ `port_getter` returns the current TCP port, so a changed listen port is announced without a+ restart. `on_paired(token, mac_name, mac_address)` is called on this thread."""++ def __init__(self, port_getter, on_paired, logger=None, bind_port=PAIRING_PORT, announce_to=("255.255.255.255", PAIRING_PORT), name=None):+ self.port_getter = port_getter+ self.on_paired = on_paired+ self.logger = logger or logging.getLogger("Beamer")+ self.bind_port = bind_port+ self.announce_to = announce_to+ self.name = name or machine_name()+ self.host = PairingHost(name=self.name)+ self._lock = threading.Lock()+ self._stop = threading.Event()+ self._thread = None++ self._sock = None+ self.error = None++ def start(self) -> None:+ if self._thread is not None:+ return+ self._stop.clear()+ self._thread = threading.Thread(target=self._run, name="Beamer-announcer", daemon=True)+ self._thread.start()++ def stop(self) -> None:+ self._stop.set()+ thread = self._thread+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout=2.0)+ self._thread = None+++ @property++ def listening_port(self):++ sock = self._sock++ return sock.getsockname()[1] if sock is not None else None+++ def begin_pairing(self) -> str:+ with self._lock:+ return self.host.begin()++ def cancel_pairing(self) -> None:+ with self._lock:+ self.host.cancel()++ @property+ def code(self):+ with self._lock:+ return self.host.code if self.host.active else None++ @property+ def seconds_left(self) -> int:+ with self._lock:+ return self.host.seconds_left++ @property+ def outcome(self):+ with self._lock:+ self.host.active+ return self.host.outcome++ def _beacon(self) -> bytes:+ with self._lock:+ pair_id = self.host.pair_id if self.host.active else None+ return encode(beacon_msg(self.name, self.port_getter(), pair_id))++ @staticmethod+ def _due(last: dict, host: str, now: float) -> bool:+ return _due(last, host, now)++ def _run(self) -> None:+ try:+ sock = _udp_socket(self.bind_port)+ except OSError as exc:+ self.error = str(exc)+ self.logger.error("pairing beacon could not bind UDP %s: %s", self.bind_port, exc)+ return+ self.error = None++ self.bind_port = sock.getsockname()[1]++ self._sock = sock+ next_beacon = 0.0+ answered = {}+ refused = {}+ try:+ while not self._stop.is_set():+ now = time.monotonic()+ if now >= next_beacon:+ next_beacon = now + BEACON_INTERVAL_SECONDS+ beacon = self._beacon()+ delivered = 0+ # Only a caller asking for the limited broadcast wants the per-interface+ # fan-out; a named address is honoured exactly, which keeps the tests off+ # the real network.+ if self.announce_to[0] == "255.255.255.255":+ targets = broadcast_targets(self.announce_to[1])+ else:+ targets = [self.announce_to]+ for target in targets:+ try:+ sock.sendto(beacon, target)+ delivered += 1+ except OSError:+ continue+ if not delivered:+ self.logger.warning("beacon reached no interface")+ try:+ data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)+ except socket.timeout:+ continue+ except ConnectionResetError:+ # Windows reports an ICMP port-unreachable for a datagram this+ # socket sent as a reset on the next receive. The socket is+ # fine; the peer that was not listening is the Mac's problem.+ continue+ except OSError as exc:+ if _oversized(exc):+ continue+ if self._stop.is_set():+ break+ self.error = str(exc)+ self.logger.error("pairing beacon stopped: %s", exc)+ break+ arrived = time.monotonic()+ message = decode(data)+ if message is None:+ continue+ if message.get("type") == MSG_FIND:+ # At most one answer per address per interval: a beacon is larger than the `find` that+ # draws it, so the rate is what keeps the port from being a useful amplifier.+ if self._due(answered, address[0], arrived):+ try:+ sock.sendto(self._beacon(), address)+ except OSError as exc:+ self.logger.warning("beacon to %s not sent: %s", address[0], exc)+ continue+ with self._lock:+ try:+ reply = self.host.handle(message)+ except Exception:+ # Whatever one datagram does, the next beacon still goes out.+ self.logger.exception("pairing datagram dropped")+ reply = None+ paired, self.host.paired = self.host.paired, None+ fresh, self.host.fresh_answer = self.host.fresh_answer, False+ # A refusal is larger than the smallest datagram that draws one, so it is rationed+ # the same way. A requester that misses one asks again after its own timeout.+ if reply is not None and (reply.get("ok") is True or self._due(refused, address[0], arrived)):+ if fresh:+ # Only the answer just worked out from the code is held back. A+ # retransmit's comes from memory, and holding each of those would let a+ # stream of replays stall this loop.+ self._stop.wait(max(0.0, arrived + PAIR_ANSWER_SECONDS - time.monotonic()))+ try:+ sock.sendto(encode(reply), address)+ except OSError as exc:+ self.logger.warning("pairing reply not sent: %s", exc)+ if paired is not None:+ self.logger.info("paired with %s at %s", paired[1] or "a Mac", address[0])+ try:+ self.on_paired(paired[0], paired[1], address[0])+ except Exception:+ self.logger.exception("on_paired failed")+ except Exception as exc:+ self.error = str(exc)+ self.logger.exception("pairing beacon stopped")+ finally:++ self._sock = None+ sock.close()+++class Discovery:+ """The Mac's socket loop: listens for beacons and carries pairing attempts on the same+ socket, so a reply comes back to the port the PC heard from."""++ def __init__(self, logger=None, bind_port=PAIRING_PORT, clock=time.monotonic):+ self.logger = logger or logging.getLogger("Beamer")+ self.bind_port = bind_port+ self.clock = clock+ self._lock = threading.Lock()+ self._seen = {}+ self._replies = queue.Queue(maxsize=64)+ self._awaiting = None+ self._pairing = threading.Lock()+ # Codes an answer has failed under, each with the time it may be tried again.+ self._failed = {}+ self._stop = threading.Event()+ self._thread = None+ self._sock = None+ self._finding = None+ self._find_serial = 0+ self._next_find = 0.0+ self.error = None++ def find(self, host: str, port: int = PAIRING_PORT) -> None:+ """Ask `host` for its beacon, for a PC no broadcast reaches, and keep asking while+ discovery runs so it stays listed. Returns at once; the PC appears in pcs() when it+ answers. An empty host stops asking."""+ host = (host or "").strip()+ with self._lock:+ self._find_serial += 1+ serial = self._find_serial+ self._finding = None+ self._next_find = 0.0+ if host:+ # A name can take seconds to resolve, and this loop also carries the pairing replies.+ threading.Thread(target=self._resolve, args=(host, int(port), serial),+ name="Beamer-find", daemon=True).start()++ def _resolve(self, host: str, port: int, serial: int) -> None:+ try:+ address = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_DGRAM)[0][4][0]+ except (OSError, IndexError) as exc:+ self.logger.warning("could not resolve %s: %s", host, exc)+ return+ with self._lock:+ if serial == self._find_serial:+ self._finding = (address, port)++ def start(self) -> None:+ if self._thread is not None:+ return+ self._stop.clear()+ self._thread = threading.Thread(target=self._run, name="Beamer-discovery", daemon=True)+ self._thread.start()++ def stop(self) -> None:+ self._stop.set()+ thread = self._thread+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout=2.0)+ self._thread = None+++ @property++ def listening_port(self):++ sock = self._sock++ return sock.getsockname()[1] if sock is not None else None+++ def pcs(self) -> list:+ """Every PC heard from recently: dicts of name, address, port, reply_port, pair_id and+ pairing, the version of the exchange it speaks."""+ cutoff = self.clock() - BEACON_STALE_SECONDS+ with self._lock:+ stale = [key for key, entry in self._seen.items() if entry["seen_at"] < cutoff]+ for key in stale:+ del self._seen[key]+ return sorted(+ ({k: v for k, v in entry.items() if k != "seen_at"} for entry in self._seen.values()),+ key=lambda entry: (entry["name"].lower(), entry["address"]),+ )++ def pair(self, pc: dict, code: str, name: str = None) -> tuple:+ """Runs the exchange with `pc` (an entry from pcs()) and returns (token, host_name),+ the name being the one the exchange proved. Blocks for up to PAIR_ATTEMPTS replies'+ worth, once for the answer and once for the receipt; call it off the main thread."""+ sock = self._sock+ if sock is None:+ raise PairingError("discovery is not running")+ if pc.get("pairing") != PAIRING_VERSION:+ # Said here, before anything is sent: there is no older exchange to fall back to.+ raise PairingError(ERROR_VERSION)+ if not isinstance(pc.get("pair_id"), str):+ raise PairingError(ERROR_NOT_PAIRING)+ with self._attempt(code):+ client = PairingClient(pc["pair_id"], code, name or machine_name())+ token = self._exchange_udp(sock, (pc["address"], pc["reply_port"]), client, code)+ return token, client.host_name++ @contextlib.contextmanager+ def _attempt(self, code: str):+ if not self._pairing.acquire(blocking=False):+ # One attempt at a time: a second would take the first one's replies, and could+ # slip past the record of failed codes below.+ raise PairingError("busy")+ try:+ now = self.clock()+ self._failed = {failed: until for failed, until in self._failed.items() if until > now}+ if code in self._failed:+ # An answer to this code was judged and failed, so whoever answered has had a+ # guess at it. The real host has bound the code to that attempt or dropped it;+ # sending another share would pair with nobody and only buy the answerer a+ # second guess. It is the code that is remembered, not the pairing id, which a+ # beacon can forge.+ raise PairingError(ERROR_REFUSED)+ yield+ finally:+ self._awaiting = None+ self._pairing.release()++ def _judge(self, client, answer: dict, code: str, send_abort) -> dict:+ """The pair_confirm for the first answer, which is the only one judged. Only an answer+ that claimed to be good can have tested a guess: that code is then remembered and the+ host told. A refusal tests nothing, and a stale pairing id draws one from an honest host."""+ try:+ return client.accept(answer)+ except PairingError:+ if answer.get("ok") is True:+ self._failed[code] = self.clock() + FAILED_CODE_SECONDS+ try:+ send_abort(client.abort())+ except OSError:+ pass+ raise++ def _exchange_udp(self, sock, target, client, code: str) -> str:+ while True:+ try:+ self._replies.get_nowait()+ except queue.Empty:+ break+ self._awaiting = client.pair_id+ source = _answer_source(target[0])+ if source is not None:+ # The routing table would send to `target` from another of this machine's addresses (a+ # VPN's route for the home network, the laptop on 01-10), which the host may have no+ # way back to. The attempt goes from the address on the target's network instead, on+ # a socket of its own that hears the replies itself.+ own = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ own.bind((source, 0))+ except OSError as exc:+ own.close()+ self.logger.warning("pairing not sent from %s, sent as routed: %s", source, exc)+ else:+ with own:+ return self._exchange_on(own, lambda timeout: _receive_on(own, timeout), target, client, code)+ return self._exchange_on(sock, self._take_reply, target, client, code)++ def _exchange_on(self, sock, receive, target, client, code: str) -> str:+ send = lambda datagram: sock.sendto(datagram, target)+ answer = self._ask(send, receive, target, client.pair_id, client.start(), MSG_PAIR_ANSWER)+ confirm = self._judge(client, answer, code, lambda abort: send(encode(abort)))+ return client.finish(self._ask(send, receive, target, client.pair_id, confirm, MSG_PAIR_DONE, client.proves))++ def _take_reply(self, timeout: float):+ try:+ return self._replies.get(timeout=timeout)+ except queue.Empty:+ return None++ def _ask(self, send, receive, target, pair_id: str, message: dict, reply_type: str, proves=None) -> dict:+ """Sends `message` to `target` until the reply of `reply_type` for `pair_id` comes back;+ `receive(timeout)` gives the next (reply, address), or None once `timeout` passes.++ A reply from `target` decides at once: the caller judges it and never waits for a better+ one. A reply from any other address is held (the first ok one and the first refusal), and+ decides only if a window ends with nothing from `target`, even among replies already+ waiting, an ok one before a refusal: a host whose answer a VPN's route sent out from its+ own address (01-10) is still heard, while a stranger who read the pairing id from a beacon+ loses to a host's answer from the address asked. `proves`, for a receipt, says whether an+ ok one carries the host's proof: from another address one that does decides at once and+ one that does not is ignored, since checking it tests no guess."""+ datagram = encode(message)+ # The first ok reply and the first refusal from elsewhere, and nothing more.+ held = {}++ def consider(reply, address):+ if reply.get("pair") != pair_id or reply.get("type") != reply_type:+ return None+ if address[0] == target[0]:+ return reply+ if proves is not None and reply.get("ok") is True:+ return reply if proves(reply) else None+ held.setdefault(reply.get("ok") is True, reply)+ return None++ for _attempt in range(PAIR_ATTEMPTS):+ try:+ send(datagram)+ except OSError as exc:+ raise PairingError("no_answer") from exc+ deadline = self.clock() + PAIR_REPLY_TIMEOUT_SECONDS+ while True:+ remaining = deadline - self.clock()+ if remaining <= 0:+ break+ received = receive(remaining)+ if received is None:+ break+ decided = consider(*received)+ if decided is not None:+ return decided+ if held:+ # What has already come from the address asked still beats what was held.+ for _waiting in range(MAX_HELD_SWEEP):+ received = receive(0)+ if received is None:+ break+ decided = consider(*received)+ if decided is not None:+ return decided+ return held.get(True) or held[False]+ raise PairingError("no_answer")++ def _run(self) -> None:+ try:+ sock = _udp_socket(self.bind_port)+ except OSError as exc:+ self.error = str(exc)+ self.logger.error("discovery could not bind UDP %s: %s", self.bind_port, exc)+ return+ self.error = None++ self.bind_port = sock.getsockname()[1]+ self._sock = sock+ try:+ while not self._stop.is_set():+ self._send_find(sock)+ try:+ data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)+ except socket.timeout:+ continue+ except ConnectionResetError:+ continue+ except OSError as exc:+ if _oversized(exc):+ continue+ if self._stop.is_set():+ break+ self.error = str(exc)+ self.logger.error("discovery stopped: %s", exc)+ break+ message = decode(data)+ if message is None:+ continue+ kind = message.get("type")+ if kind == MSG_BEACON:+ try:+ self._note_beacon(message, address)+ except Exception:+ self.logger.exception("beacon dropped")+ elif kind in (MSG_PAIR_ANSWER, MSG_PAIR_DONE) and self._awaits(message):+ # Only what the attempt under way is waiting for is kept, and only so much+ # of it, so nothing a stranger sends piles up in memory.+ try:+ self._replies.put_nowait((message, address))+ except queue.Full:+ pass+ except Exception as exc:+ self.error = str(exc)+ self.logger.exception("discovery stopped")+ finally:+ self._sock = None+ sock.close()++ def _awaits(self, message: dict) -> bool:+ awaiting = self._awaiting+ return awaiting is not None and message.get("pair") == awaiting++ def _send_find(self, sock) -> None:+ with self._lock:+ target = self._finding+ if target is None or self.clock() < self._next_find:+ return+ self._next_find = self.clock() + BEACON_INTERVAL_SECONDS+ try:+ sock.sendto(encode({"type": MSG_FIND}), target)+ except OSError as exc:+ self.logger.warning("could not ask %s for its beacon: %s", target[0], exc)++ def _note_beacon(self, message: dict, address) -> None:+ entry = self._beacon_entry(message, address)+ if entry is not None:+ self._remember(address, entry)++ def _beacon_entry(self, message: dict, address):+ name = message.get("name")+ port = message.get("port")+ pair_id = message.get("pair")+ version = message.get("pairing")+ if not isinstance(name, str) or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:+ return None+ try:+ name.encode("utf-8")+ except UnicodeError:+ # Half a surrogate pair is JSON a parser accepts and text no window can show.+ return None+ return {+ "name": name[:64] or address[0],+ "address": address[0],+ "port": port,+ "reply_port": address[1],+ "pair_id": pair_id if isinstance(pair_id, str) and pair_id.isascii() and 0 < len(pair_id) <= MAX_PAIR_ID_CHARS else None,+ # A beacon from 1.4.2 or earlier carries no number: that is version 1.+ "pairing": version if isinstance(version, int) and not isinstance(version, bool) else 1,+ "seen_at": self.clock(),+ }++ def _remember(self, address, entry: dict) -> None:+ with self._lock:+ if address[0] not in self._seen and len(self._seen) >= MAX_SEEN_HOSTS:+ # The list is only read while the window is open, so what has gone quiet is+ # cleared here too. Beacons from made-up addresses then cost a fixed amount of+ # memory and no more.+ cutoff = self.clock() - BEACON_STALE_SECONDS+ for stale in [key for key, known in self._seen.items() if known["seen_at"] < cutoff]:+ del self._seen[stale]+ if len(self._seen) >= MAX_SEEN_HOSTS:+ # Still full: whoever has been quiet longest gives way. A flood of forgeries+ # can crowd real PCs off the list that way, which is a denial like any+ # other here, so the one address the user typed is never the one to go.+ wanted = self._finding[0] if self._finding else None+ del self._seen[min((key for key in self._seen if key != wanted), key=lambda key: self._seen[key]["seen_at"])]+ self._seen[address[0]] = entry+++def _shut(sock) -> None:+ try:+ sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+++def _send_frame(sock, message: dict) -> None:+ body = encode(message)+ sock.sendall(struct.pack(">I", len(body)) + body)+++def _recv_exact(sock, count: int, deadline: float) -> bytes:+ data = b""+ while len(data) < count:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise PairingError("no_answer")+ sock.settimeout(remaining)+ try:+ chunk = sock.recv(count - len(data))+ except OSError as exc:+ raise PairingError("no_answer") from exc+ if not chunk:+ raise PairingError("no_answer")+ data += chunk+ return data+++def _recv_frame(sock, deadline: float) -> dict:+ """One message over TCP: a 4-byte big-endian length, then the JSON a datagram would carry. A+ length outside 1 to 1024 is refused before the body is read, and a body that is not a Beamer+ message ends the exchange like a closed connection."""+ (length,) = struct.unpack(">I", _recv_exact(sock, 4, deadline))+ if not 0 < length <= MAX_DATAGRAM_BYTES:+ raise PairingError("no_answer")+ message = decode(_recv_exact(sock, length, deadline))+ if message is None:+ raise PairingError("no_answer")+ return message+++def _linger(sock, deadline: float) -> None:+ """Shuts the sending side and reads what is left for up to a second, so the last message+ sent is not lost to a reset over unread bytes."""+ until = min(deadline, time.monotonic() + 1.0)+ try:+ sock.shutdown(socket.SHUT_WR)+ while True:+ remaining = until - time.monotonic()+ if remaining <= 0:+ return+ sock.settimeout(remaining)+ if not sock.recv(MAX_DATAGRAM_BYTES):+ return+ except OSError:+ pass+++class _Slots:+ """The pairing listener's connections, on the link's handshake terms (WIRE.md section 2): at+ most `size`, one per address, a new connection from an address replacing its earlier one,+ and one from a new address replacing the oldest when all are held. A pinned connection, the+ one whose pair_start bound the code, is never the one replaced: the exchange under way is+ left alone. With nothing left to replace, the new connection is the one closed."""++ def __init__(self, size: int):+ self.size = size+ self._held = {}+ self._pinned = set()+ self._serial = 0+ self._lock = threading.Lock()++ def take(self, address: str, close):+ """The new connection's key, or None when every slot is pinned and it was closed."""+ with self._lock:+ free = [key for key in self._held if key not in self._pinned]+ victims = [key for key in free if self._held[key][0] == address]+ if not victims and len(self._held) >= self.size:+ victims = free[:1]+ closers = [self._held.pop(key)[1] for key in victims]+ if len(self._held) >= self.size:+ closers.append(close)+ taken = None+ else:+ self._serial += 1+ self._held[self._serial] = (address, close)+ taken = self._serial+ for closer in closers:+ closer()+ return taken++ def pin(self, key: int) -> bool:+ """False when the connection was already replaced: it is gone, and cannot be pinned."""+ with self._lock:+ if key not in self._held:+ return False+ self._pinned.add(key)+ return True++ def release(self, key: int) -> None:+ with self._lock:+ self._held.pop(key, None)+ self._pinned.discard(key)++ def close_all(self) -> None:+ with self._lock:+ closers = [close for _address, close in self._held.values()]+ for closer in closers:+ closer()+++class PairingService(Discovery):+ """Pairing version 3's socket side, the same on every desktop (WIRE.md section 6, "Either+ end"). One UDP socket beacons every 2 seconds, keeps the list of machines it hears, answers+ `find`, carries this machine's requests and hosts its code; while a code is up a TCP listener+ on `tcp_port` hosts it too, with the same PairingHost, so rule 1 holds across both.++ `peers()` gives the peer entries as they stand; `store(entry, replaced)` writes a new one and+ drops `replaced` (that entry, by identity) when it is not None, raising if it cannot.+ `replaced` may be the entry migrated from 1.4.x, whose `id` is `""`: its zones go with it and+ are not moved to the new id, since pairing does not prove it is the same machine.+ `on_paired(entry)` is told of a pairing this machine hosted, after the entry is stored.++ ⚠ `peers` and `store` run on the socket threads while this service holds its own lock, which+ is what makes check-then-store one step for both roles. So they must never wait on the main+ thread (no synchronous hop to it), nor on a lock held by any thread while it calls into this+ service: the app's settings lock is taken inside `store`, and the app never calls+ `code`, `begin_pairing` and the rest while holding it. `on_paired` runs outside the lock."""++ def __init__(self, name, identity: bytes, platform: str, port_getter, peers, store, on_paired=None, logger=None,+ bind_port=PAIRING_PORT, tcp_port=PAIRING_PORT, announce_to=("255.255.255.255", PAIRING_PORT),+ clock=time.monotonic, wall=time.time):+ super().__init__(logger=logger, bind_port=bind_port, clock=clock)+ self.name = (name or machine_name())[:MAX_NAME_CHARS]+ self.identity = identity+ self.platform = platform+ self.port_getter = port_getter+ self._peer_entries = peers+ self.store = store+ self.on_paired = on_paired or (lambda entry: None)+ self.tcp_port = tcp_port+ self.announce_to = announce_to+ self.wall = wall+ self.host = PairingHost(clock, self.name, identity, version=PAIRING_V3, platform=platform, port=port_getter(),+ peers=peers, store=store, wall=wall)+ self._host_lock = threading.Lock()+ self._listener = None+ self._listener_lock = threading.Lock()+ self._slots = _Slots(TCP_MAX_CONNECTIONS)+ self._own_addresses = frozenset()+ # Why the TCP listener is not up while a code is, or None.+ self.tcp_error = None++ # The host's side.++ def begin_pairing(self) -> str:+ """Shows a new code, raising PairingError(ERROR_FULL) when this machine has 32 peers."""+ with self._host_lock:+ self.host.port = self.port_getter()+ code = self.host.begin()+ self._open_listener()+ return code++ def cancel_pairing(self) -> None:+ with self._host_lock:+ self.host.cancel()+ self._close_listener()++ @property+ def code(self):+ with self._host_lock:+ return self.host.code if self.host.active else None++ @property+ def seconds_left(self) -> int:+ with self._host_lock:+ return self.host.seconds_left++ @property+ def outcome(self):+ with self._host_lock:+ self.host.active+ return self.host.outcome++ @property+ def known(self):+ with self._host_lock:+ return self.host.known++ def qr_text(self, address: str = None):+ """The QR's text for the code on screen, at `address` or pairing_address(); None when no+ code is up or this machine has no address."""+ with self._host_lock:+ if not self.host.active:+ return None+ code, secret = self.host.code, self.host.qr_secret+ if self._listener is None:+ # The TCP listener could not bind (tcp_error says why): a QR would point at+ # nothing, so the sheet shows the code alone.+ return None+ address = address or pairing_address()+ return qr_text(address, self.tcp_port, code, secret) if address else None++ def machines(self) -> list:+ """Every machine heard from recently: pcs()'s fields, with `platform` and, while its code+ is up, `id`."""+ return self.pcs()++ def stop(self) -> None:+ super().stop()+ with self._host_lock:+ self.host.cancel()+ self._close_listener()+ self._slots.close_all()++ def _open_listener(self) -> None:+ with self._listener_lock:+ if self._listener is not None:+ return+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ try:+ if os.name != "nt":+ # To bind again while a closed connection waits out TIME_WAIT. Windows'+ # SO_REUSEADDR would let another program bind the port too, so not there.+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ listener.bind(("", self.tcp_port))+ listener.listen(TCP_MAX_CONNECTIONS * 2)+ listener.settimeout(0.25)+ except OSError as exc:+ listener.close()+ self.tcp_error = str(exc)+ self.logger.warning("pairing over TCP %s is not available: %s", self.tcp_port, exc)+ return++ self.tcp_port = listener.getsockname()[1]+ self.tcp_error = None+ stop = threading.Event()+ self._listener = (listener, stop)+ threading.Thread(target=self._accept, args=(listener, stop), name="Beamer-pairing-tcp", daemon=True).start()++ def _close_listener(self, only=None) -> None:+ with self._listener_lock:+ if only is not None and (self._listener is None or self._listener[0] is not only):+ return+ held, self._listener = self._listener, None+ if held is not None:+ held[1].set()+ held[0].close()++ def _accept(self, listener, stop) -> None:+ while not stop.is_set():+ # The listener is up only while a code is: it goes when the code expires as well as+ # when it is used or cancelled. Under the host's lock, so a new code shown at this+ # moment keeps its listener.+ with self._host_lock:+ if not self.host.active:+ self._close_listener(only=listener)+ return+ try:+ conn, address = listener.accept()+ except socket.timeout:+ continue+ except OSError as exc:+ # Closed on purpose, or failed (out of descriptors, say). Either way it is let go,+ # so the next code opens a listener of its own rather than finding this one held.+ with self._host_lock:+ if self._listener is not None and self._listener[0] is listener:+ self.tcp_error = str(exc)+ self._close_listener(only=listener)+ return+ deadline = time.monotonic() + TCP_EXCHANGE_SECONDS+ key = self._slots.take(address[0], lambda conn=conn: _shut(conn))+ if key is None:+ conn.close()+ continue+ threading.Thread(target=self._serve, args=(conn, address[0], key, deadline), name="Beamer-pairing-conn", daemon=True).start()++ def _serve(self, conn, address: str, key: int, deadline: float) -> None:+ """One TCP exchange: the beacon, then pair_start and pair_confirm in that order. Anything+ else, a second pair_start included, closes the connection with nothing sent; a refusal is+ sent before the close."""+ try:+ conn.settimeout(TCP_EXCHANGE_SECONDS)+ with self._host_lock:+ beacon = self.host.beacon(self.port_getter())+ if "pair" not in beacon:+ return+ _send_frame(conn, beacon)+ expected = MSG_PAIR_START+ while True:+ message = _recv_frame(conn, deadline)+ arrived = time.monotonic()+ if message.get("type") != expected:+ return+ reply, paired, fresh = self._host_handle(message, address, ("tcp", key), lambda: self._slots.pin(key))+ if reply is None:+ return+ if fresh:+ time.sleep(max(0.0, arrived + PAIR_ANSWER_SECONDS - time.monotonic()))+ conn.settimeout(max(0.01, deadline - time.monotonic()))+ _send_frame(conn, reply)+ self._paired(paired, address)+ if reply.get("ok") is not True or expected == MSG_PAIR_CONFIRM:+ _linger(conn, deadline)+ return+ expected = MSG_PAIR_CONFIRM+ except (OSError, PairingError):+ pass+ except Exception:+ self.logger.exception("pairing connection dropped")+ finally:+ self._slots.release(key)+ conn.close()++ def _host_handle(self, message: dict, address: str, via, pin=None) -> tuple:+ """The host's reply. `pin` holds the connection whose pair_start just bound the code, under+ the host's lock, before its answer waits out PAIR_ANSWER_SECONDS: only a fresh answer pins,+ never one repeated from the cache to a replay on another connection."""+ with self._host_lock:+ reply = self.host.handle(message, address, via)+ paired, self.host.paired = self.host.paired, None+ fresh, self.host.fresh_answer = self.host.fresh_answer, False+ if pin is not None and fresh and message.get("type") == MSG_PAIR_START and reply is not None and reply.get("ok") is True:+ if not pin():+ # Replaced in the instant before its pin: the code is bound to a connection+ # that is gone, so the attempt ends as a refusal rather than holding the code.+ self.host.cancel()+ self.host.outcome = "refused"+ reply = None+ return reply, paired, fresh++ def _paired(self, entry, address: str) -> None:+ if entry is None:+ return+ self.logger.info("paired with %s at %s", entry["name"], address)+ try:+ self.on_paired(entry)+ except Exception:+ self.logger.exception("on_paired failed")++ # The UDP socket, both ways.++ def _beacon(self) -> bytes:+ with self._host_lock:+ return encode(self.host.beacon(self.port_getter()))++ def _announce(self, sock) -> None:+ beacon = self._beacon()+ # A named address is honoured exactly, which keeps the tests off the real network.+ if self.announce_to[0] == "255.255.255.255":+ targets = broadcast_targets(self.announce_to[1])+ else:+ targets = [self.announce_to]+ delivered = 0+ for target in targets:+ try:+ sock.sendto(beacon, target)+ delivered += 1+ except OSError:+ continue+ if not delivered:+ self.logger.warning("beacon reached no interface")++ def _run(self) -> None:+ try:+ sock = _udp_socket(self.bind_port)+ except OSError as exc:+ self.error = str(exc)+ self.logger.error("pairing could not bind UDP %s: %s", self.bind_port, exc)+ return+ self.error = None++ self.bind_port = sock.getsockname()[1]+ self._sock = sock+ self._own_addresses = frozenset(_local_ipv4_addresses() + [pairing_address(), "127.0.0.1"]) - {None}+ next_beacon = 0.0+ answered = {}+ refused = {}+ try:+ while not self._stop.is_set():+ now = time.monotonic()+ if now >= next_beacon:+ next_beacon = now + BEACON_INTERVAL_SECONDS+ self._announce(sock)+ self._send_find(sock)+ try:+ data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)+ except socket.timeout:+ continue+ except ConnectionResetError:+ continue+ except OSError as exc:+ if _oversized(exc):+ continue+ if self._stop.is_set():+ break+ self.error = str(exc)+ self.logger.error("pairing stopped: %s", exc)+ break+ arrived = time.monotonic()+ message = decode(data)+ if message is None:+ continue+ try:+ self._dispatch(sock, message, address, arrived, answered, refused)+ except Exception:+ # Whatever one datagram does, the next beacon still goes out.+ self.logger.exception("pairing datagram dropped")+ except Exception as exc:+ self.error = str(exc)+ self.logger.exception("pairing stopped")+ finally:+ self._sock = None+ sock.close()++ def _dispatch(self, sock, message: dict, address, arrived: float, answered: dict, refused: dict) -> None:+ kind = message.get("type")+ if kind == MSG_BEACON:+ # This machine hears its own broadcasts, from its own port at one of its own addresses.+ if address[1] != self.bind_port or address[0] not in self._own_addresses:+ self._note_beacon(message, address)+ elif kind == MSG_FIND:+ # At most one answer per address per interval: a beacon is larger than the `find` that+ # draws it, so the rate is what keeps the port from being a useful amplifier.+ if _due(answered, address[0], arrived):+ self._answer(sock, self._beacon(), address)+ elif kind in (MSG_PAIR_START, MSG_PAIR_CONFIRM, MSG_PAIR_REQUEST):+ reply, paired, fresh = self._host_handle(message, address[0], "udp")+ # A refusal is larger than the smallest datagram that draws one, so it is rationed.+ if reply is not None and (reply.get("ok") is True or _due(refused, address[0], arrived)):+ if fresh:+ self._stop.wait(max(0.0, arrived + PAIR_ANSWER_SECONDS - time.monotonic()))+ try:+ self._answer(sock, encode(reply), address)+ except OSError as exc:+ self.logger.warning("pairing reply not sent: %s", exc)+ self._paired(paired, address[0])+ elif kind in (MSG_PAIR_ANSWER, MSG_PAIR_DONE) and self._awaits(message):+ try:+ self._replies.put_nowait((message, address))+ except queue.Full:+ pass++ def _answer(self, sock, data: bytes, address) -> None:+ """Sends a reply to a pairing request or a `find` from this machine's address on the+ requester's own network, where the routing table would pick another (_answer_source): a+ requester sorts answers by the address it asked, though never by port.++ ⚠ The socket that does it takes a port of its own. Bound to the pairing port beside the+ main socket, it would take any datagram for that address arriving while it lived (a+ pair_confirm, another machine's request), and Windows does not say which of two such+ sockets gets one. A requester takes beacons from strangers on its pairing port, so an+ answer from another port reaches it as well."""+ source = _answer_source(address[0])+ if source is not None:+ try:+ out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ out.bind((source, 0))+ out.sendto(data, address)+ return+ finally:+ out.close()+ except OSError as exc:+ self.logger.warning("pairing reply not sent from %s, sent as routed: %s", source, exc)+ sock.sendto(data, address)++ def _beacon_entry(self, message: dict, address):+ entry = super()._beacon_entry(message, address)+ if entry is not None:+ platform = message.get("platform")+ entry["platform"] = platform if _platform_ok(platform) else None+ entry["id"] = message.get("id") if _id_text_ok(message.get("id")) else None+ return entry++ # The requester's side.++ def pair(self, machine: dict, code: str) -> dict:+ """Pairs over UDP with `machine`, an entry from machines(), and returns the entry stored+ for it. Blocks for up to PAIR_ATTEMPTS replies' worth, twice; call it off the main+ thread. Raises AlreadyPaired, or PairingError naming why."""+ sock = self._sock+ if sock is None:+ raise PairingError("discovery is not running")+ if machine.get("pairing") != PAIRING_V3:+ # Said before anything is sent: versions 2 and 3 never pair.+ raise PairingError(ERROR_VERSION)+ if not isinstance(machine.get("pair_id"), str):+ raise PairingError(ERROR_NOT_PAIRING)+ with self._attempt(code):+ client = self._client(machine["pair_id"], code)+ self._exchange_udp(sock, (machine["address"], machine["reply_port"]), client, code)+ return self._keep(client, machine["address"])++ def pair_by_address(self, address: str, code: str, port: int = PAIRING_PORT) -> dict:+ """"Pair by address": the exchange over TCP with a typed address and code, for a host no+ broadcast reaches. No QR secret, so no `qr`."""+ try:+ resolved = socket.getaddrinfo((address or "").strip(), port, socket.AF_INET, socket.SOCK_STREAM)[0][4][0]+ except (OSError, IndexError, UnicodeError) as exc:+ raise PairingError("no_answer") from exc+ return self._pair_tcp(resolved, port, code, None)++ def pair_by_qr(self, text: str) -> dict:+ """The exchange over TCP from a QR's text, with its secret and `qr: 1`. A QR of a machine+ this one has already does not pair: AlreadyPaired, before anything is sent."""+ fields = read_qr(text)+ return self._pair_tcp(fields["host"], fields["port"], fields["code"], fields["secret"])++ def _client(self, pair_id: str, code: str, secret: bytes = None) -> PairingClient:+ return PairingClient(pair_id, code, self.name, self.identity, version=PAIRING_V3, platform=self.platform,+ port=self.port_getter(), qr_secret=secret, peers=self._peer_entries, wall=self.wall)++ def _pair_tcp(self, address: str, port: int, code: str, secret) -> dict:+ with self._attempt(code):+ if len(self._peer_entries()) >= MAX_PEERS:+ raise PairingError(ERROR_FULL)+ try:+ sock = socket.create_connection((address, port), timeout=TCP_CONNECT_SECONDS)+ except OSError as exc:+ raise PairingError("no_answer") from exc+ deadline = time.monotonic() + TCP_EXCHANGE_SECONDS+ try:+ with sock:+ beacon = _recv_frame(sock, deadline)+ if beacon.get("type") != MSG_BEACON:+ raise PairingError("no_answer")+ version = beacon.get("pairing")+ if not _is_int(version) or version != PAIRING_V3:+ raise PairingError(ERROR_VERSION)+ pair_id = beacon.get("pair")+ if not isinstance(pair_id, str) or not pair_id.isascii() or not 0 < len(pair_id) <= MAX_PAIR_ID_CHARS:+ raise PairingError(ERROR_NOT_PAIRING)+ if secret is not None:+ self._not_paired_already(beacon.get("id"))+ client = self._client(pair_id, code, secret)+ sock.settimeout(max(0.01, deadline - time.monotonic()))+ _send_frame(sock, client.start())+ answer = _recv_frame(sock, deadline)+ if answer.get("type") != MSG_PAIR_ANSWER:+ raise PairingError("no_answer")+ confirm = self._judge(client, answer, code, lambda abort: _send_frame(sock, abort))+ _send_frame(sock, confirm)+ client.finish(_recv_frame(sock, deadline))+ except OSError as exc:+ raise PairingError("no_answer") from exc+ return self._keep(client, address)++ def _not_paired_already(self, identity) -> None:+ """A QR of a machine this one has paired already: the caller tries its link at that+ address instead of pairing again."""+ if not _id_text_ok(identity):+ return+ if identity == _b64(self.identity):+ raise AlreadyPaired(None)+ for known in self._peer_entries():+ if known.get("id") == identity:+ raise AlreadyPaired(known)++ def _keep(self, client: PairingClient, address: str) -> dict:+ """The requester writes its entry once Td has checked out. The checks are made again,+ under the lock the host's side stores under, because this machine may have hosted or+ requested another pairing since: two at once must not pass 32 peers or share an id. A+ failed write leaves the host an entry that never links, which pairing again within ten+ minutes replaces."""+ entry = client.entry(address)+ with self._host_lock:+ peers = self._peer_entries()+ known, replaced = _find_known(peers, self.identity, client.host_identity, client.host_name, client.host_platform, self.wall())+ if known is not None:+ raise AlreadyPaired(None if known is True else known)+ replaced = replaced or _migrated_for(peers, address, client.host_name, client.host_platform)+ if _clashes(peers, entry["token"], replaced):+ raise PairingError(ERROR_REFUSED)+ if replaced is None and len(peers) >= MAX_PEERS:+ raise PairingError(ERROR_FULL)+ try:+ self.store(entry, replaced)+ except Exception as exc:+ self.logger.warning("the new peer entry could not be saved: %s", exc)+ raise PairingError("not_saved") from exc+ return entry+++def _id_text_ok(text) -> bool:+ return protocol.read_id(text) is not Nonediff --cc core/peerlist.pyindex de3286c,0000000..456fe0fmode 100644,000000..100644--- a/core/peerlist.py+++ b/core/peerlist.py@@@ -1,183 -1,0 +1,224 @@@+"""What a desktop's window does to the peers list, and the words it uses for pairing.++Pure, and shared by both desktops so a machine pairing with either reads the same sentences. The+settings layer calls `add_peer` from `PairingService`'s `store` and `remove_peer` from the Remove+button, each under its own settings lock; neither touches a file.+"""+- import copy+import time+from typing import Optional++from core import pairing++UNNAMED = "Unnamed machine"+TAIL = 4++++def desktops(peers: list) -> list:++ return [entry for entry in peers if isinstance(entry, dict) and entry.get("port") != 0]++++++def first_desktop(peers: list) -> Optional[dict]:++ return next(iter(desktops(peers)), None)++++++def normalise_phones(settings: dict) -> bool:++ """Discard receiving-only fields for zero-port senders; keep their trust and permissions."""++ changed = False++ phones = set()++ for entry in settings.get("peers", []):++ if not isinstance(entry, dict) or entry.get("port") != 0:++ continue++ if isinstance(entry.get("id"), str):++ phones.add(entry["id"])++ for key, value in (("send", False), ("host", ""), ("hw", ""), ("side", ""),++ ("side_set_at", 0), ("side_by", ""), ("jump_key", "")):++ if entry.get(key, value) != value:++ changed = True++ if key in entry or key == "send":++ entry[key] = value++ for key in ("way_back", "way_back_by"):++ if key in entry:++ del entry[key]++ changed = True++ if isinstance(settings.get("zones"), list):++ zones = [zone for zone in settings["zones"] if not isinstance(zone, dict)++ or not isinstance(zone.get("peer"), str) or zone["peer"] not in phones]++ if zones != settings["zones"]:++ settings["zones"] = zones++ changed = True++ if isinstance(settings.get("design_follow_peer"), str) and settings["design_follow_peer"] in phones:++ settings["design_follow_peer"] = ""++ changed = True++ return changed+++++def _name(entry: dict) -> str:+ return (entry.get("name") or "").strip()+++def labels(peers: list) -> dict:+ """token -> what to call each machine: its name, and where two share one (ignoring case and+ surrounding space) the last four characters of its id too, so the two can be told apart. An- entry that has no id yet (the one migrated from 1.4.x) shows the name alone."""++ entry that has no id yet (the one migrated from 1.4.x) shows the name alone. Paired phones keep++ their labels for the direction that sends input here; incomplete entries without a token do not."""++ peers = [entry for entry in peers if isinstance(entry, dict) and "token" in entry]+ counts = {}+ for entry in peers:+ key = _name(entry).casefold()+ counts[key] = counts.get(key, 0) + 1+ result = {}+ for entry in peers:+ name = _name(entry) or entry.get("host") or UNNAMED+ shared = counts[_name(entry).casefold()] > 1 and _name(entry)+ ident = entry.get("id") or ""+ result[entry["token"]] = f"{name} ({ident[-TAIL:]})" if shared and ident else name+ return result+++def sharing_a_name(machines: list) -> list:+ """For each machine heard, in order, whether another in the list has its name (as `labels()`+ compares them): one machine heard on two interfaces is two rows, told apart by address."""+ counts = {}+ for machine in machines:+ key = _name(machine).casefold()+ counts[key] = counts.get(key, 0) + 1+ return [counts[_name(machine).casefold()] > 1 for machine in machines]+++def label_for(peers: list, *, token: Optional[str] = None, peer_id: Optional[str] = None, host: Optional[str] = None) -> str:+ """`labels()` for one machine, found by its token, its id (`b64`) or its address, in that order of+ preference; "" when none matches. What a status or a notice calls a machine, so two of one name+ are told apart there as they are in the list."""++ peers = [entry for entry in peers if isinstance(entry, dict) and "token" in entry]+ shown = labels(peers)+ for key, value in (("token", token), ("id", peer_id), ("host", host)):+ if value:+ found = next((entry for entry in peers if entry.get(key) == value), None)+ if found is not None:+ return shown[found["token"]]+ return ""+++def add_peer(settings: dict, entry: dict, replaced: Optional[dict] = None) -> None:+ """Puts a newly paired `entry` in `settings` (WIRE.md section 6, item 5). `replaced`, an entry- as `peers()` gave it, is dropped by its token and the new one takes its place: the first entry- is the one the flat settings read, so the new machine must not slip behind. Zones that name++ as `peers()` gave it, is dropped by its token and the new one takes its place: the first desktop++ is the one the flat settings read, so its replacement must not slip behind. Zones that name+ an id no entry has any more go with it; a machine paired again under its own id keeps its zones.+ The entry migrated from 1.4.x (`id` empty) gives its side and zones to a pairing with the machine+ at its saved host on its platform (section 6, item 4): that is the machine the user meant to pair+ again, and a match by name alone takes nothing, a name being anyone's to claim."""+ peers = settings["peers"]+ at = next((index for index, held in enumerate(peers) if replaced is not None and held.get("token") == replaced.get("token")), None)+ if at is None:+ peers.append(entry)+ else:+ peers[at] = entry+ if (replaced is not None and replaced.get("from_1_4") is True and replaced.get("id") == "" and entry.get("id")+ and replaced.get("host") and replaced.get("host") == entry.get("host")+ and replaced.get("platform") == entry.get("platform")):+ entry.update({field: replaced.get(field, default) for field, default in+ (("side", ""), ("side_set_at", 0), ("side_by", ""))})+ for zone in settings["zones"]:+ if zone.get("peer") == "":+ zone["peer"] = entry["id"]+ _drop_orphan_zones(settings)+ # Imported here: ways names machines by this module's labels.+ from core import ways+ ways.ensure_zones(settings)+++def remove_peer(settings: dict, token: str) -> Optional[dict]:+ """Takes the entry holding `token` out of `settings` with its zones, and returns it; None when+ there is none."""+ peers = settings["peers"]+ at = next((index for index, held in enumerate(peers) if held.get("token") == token), None)+ if at is None:+ return None+ removed = peers.pop(at)+ _drop_orphan_zones(settings)+ return removed+++def _drop_orphan_zones(settings: dict) -> None:+ ids = {held.get("id") for held in settings["peers"]}+ settings["zones"] = [zone for zone in settings["zones"] if zone.get("peer") in ids]+++def day(paired_at) -> str:+ """The day an entry was paired, DD-MM-YYYY in this machine's local time; "" when unknown."""+ if not isinstance(paired_at, int) or isinstance(paired_at, bool) or paired_at <= 0:+ return ""+ return time.strftime("%d-%m-%Y", time.localtime(paired_at))+++def _since(entry: dict) -> str:+ when = day(entry.get("paired_at"))+ return f", since {when}" if when else ""+++def pairing_error_text(error: Exception, name: str) -> str:+ """A requester's failure, said to its user; `name` is how the machine is shown (its label, or+ "That machine" when it is not known yet, which starts a sentence)."""+ if isinstance(error, pairing.AlreadyPaired):+ entry = error.entry+ if entry is None:+ return "That is this machine, not another one."+ label = _name(entry) or name+ return f"{label} is already paired with this machine{_since(entry)}. Remove it from the list first to pair again."+ reason = str(error)+ if reason == pairing.ERROR_NOT_PAIRING:+ return f"{name} is not showing a code. Show one in Beamer on it, then try again."+ if reason == pairing.ERROR_REFUSED:+ return f"That code was not accepted, and {name} has cancelled it. Show a new one there to try again."+ if reason == pairing.ERROR_VERSION:+ return f"{name} runs an older Beamer. Update Beamer on it to 1.5.0, then pair again."+ if reason == "no_answer":+ return f"{name} did not answer. Check both machines are on the same network, then try again."+ if reason == pairing.ERROR_FULL:+ return (f"Either this machine or {name} already has {pairing.MAX_PEERS} machines paired, the most "+ "Beamer keeps. Remove one, then try again.")+ if reason == pairing.ERROR_KNOWN:+ return f"{name} already has this machine paired. Remove this machine from its list there, then pair again."+ if reason == "not_saved":+ return "Pairing finished, but Beamer could not save it on this machine. Try again in a moment."+ if reason == "busy":+ return "Another pairing is still finishing. Try again in a moment."+ return f"Pairing failed: {reason}."+++def refusal_text(why: str, name: str, other: Optional[str]) -> Optional[str]:+ """The alert for an `owned` or `busy` refusal, naming the machine in the way when known."""+ if why == "owned":+ return (f"Can't cross to {name}: it is being driven from {other}." if other else+ f"Can't cross to {name}: another machine is driving it.")+ if why == "busy":+ return (f"Can't cross to {name}: it is driving {other}." if other else+ f"Can't cross to {name}: it is driving another machine.")+ return None+++def host_outcome_text(outcome: Optional[str], entry: Optional[dict]) -> str:+ """How the code on screen ended, said to the person at this machine (`PairingService.outcome`,+ with `entry` the machine that paired or, for `known`, the entry it was found to be); "" while+ a code is live or after a deliberate cancel."""+ name = _name(entry or {}) or "A machine"+ if outcome == "paired":+ return f"Paired with {name}."+ if outcome == "refused":+ return "A wrong code was tried, so this code was cancelled. Show a new one to try again."+ if outcome == "version":+ return "A machine on an older Beamer tried to pair. Update Beamer on it to 1.5.0, then show a new code."+ if outcome == "expired":+ return "The code expired. Show a new one."+ if outcome == "known":+ if entry is None:+ return "That machine gave this machine's own identity, so nothing was paired. Show a new code to try again."+ return f"{name} is already paired here{_since(entry)}. Remove it from the list first to pair again."+ if outcome == "known_there":+ return "That machine may already be paired here, or the code was wrong. Show a new code to try again."+ if outcome == "full":+ return f"This machine already has {pairing.MAX_PEERS} machines paired, the most Beamer keeps. Remove one, then show a new code."+ if outcome == "not_saved":+ return "Beamer could not save the pairing on this machine, so it did not complete. Show a new code to try again."+ return ""diff --cc core/receiver.pyindex 0636ff2,0000000..32c08famode 100644,000000..100644--- a/core/receiver.py+++ b/core/receiver.py@@@ -1,1486 -1,0 +1,1471 @@@+"""The responder: the listener every machine runs for the links its peers open to it.+`LinkResponder` speaks wire version 6 (WIRE.md) for any number of peers, with one owner at a+time; an older Beamer is answered only far enough to be told to update."""++import collections+import copy+import functools+import hmac+import ipaddress+import logging+import socket+import sys+import threading+import time+from enum import Enum+from typing import Callable, Optional, Tuple++from . import return_edge as crossing+from . import peerlist+from . import protocol+++LOGGER = logging.getLogger(__name__)+# The longest an idle link goes without an ACK, so the initiator's watchdog keeps+# seeing a heartbeat when nothing is being typed.+ACK_IDLE_SECONDS = 0.4+# How long an ACK waits after input arrives, batching a burst into one reply.+# A per-event ACK at ~100Hz mouse rates would roughly double the packet count;+# 15ms caps it near 66/s while keeping the round trip the Mac reports honest,+# which a 400ms timer did not -- every reading carried up to 400ms of waiting+# that was never network latency.+ACK_COALESCE_SECONDS = 0.015+LOCK_CHECK_SECONDS = 0.5+INJECTION_ERROR_STATUS_INTERVAL_SECONDS = 5.0+# Windows hands the port back only when whatever holds it lets go — WinNAT's+# dynamic reservations move on every reboot and can land on ours — so a bind+# that fails is waited out rather than ending the listener.+BIND_RETRY_SECONDS = 5.0+# Connections still inside the handshake. Each is bounded to HANDSHAKE_SECONDS as a whole,+# so a stranger holding these slots loses them within seconds, while the real peer's handshake+# takes milliseconds and always finds one free.+MAX_PENDING_CONNECTIONS = 4+++class ServerState(Enum):+ STOPPED = "Stopped"+ WAITING = "Waiting"+ CONNECTED = "Connected"+ ERROR = "Error"+++class InputScale:+ """This machine's own speed for the pointer and scroll arriving from the peer. The peer sends+ what its own acceleration made of the hand's movement, and this machine may accelerate it+ again, so how fast it feels here is a setting here. Fractions carry over between messages, so+ a slow movement at a low speed still moves. `reverse` turns the peer's scroll round."""++ MIN, MAX = 0.25, 4.0++ def __init__(self, pointer: float = 1.0, scroll: float = 1.0, reverse: bool = False) -> None:+ self.pointer = min(self.MAX, max(self.MIN, float(pointer)))+ self.scroll = min(self.MAX, max(self.MIN, float(scroll)))+ self.reverse = bool(reverse)+ self._carry = [0.0, 0.0]++ def move(self, dx: int, dy: int) -> Tuple[int, int]:+ if self.pointer == 1.0:+ return dx, dy+ x = dx * self.pointer + self._carry[0]+ y = dy * self.pointer + self._carry[1]+ whole_x, whole_y = int(x), int(y)+ self._carry = [x - whole_x, y - whole_y]+ return whole_x, whole_y++ def wheel(self, dy, dx):+ if self.scroll == 1.0 and not self.reverse:+ return dy, dx+ sign = -1.0 if self.reverse else 1.0+ return dy * self.scroll * sign, dx * self.scroll * sign+++def _close_socket(sock: Optional[socket.socket]) -> None:+ if sock is None:+ return+ try:+ sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+ try:+ sock.close()+ except OSError:+ pass+++# The handshake's bounds, from the moment a connection is accepted (section 2).+PREAMBLE_SECONDS = 1.0+HANDSHAKE_SECONDS = 5.0+# How long an answer that ends a connection waits for the peer's bytes, so the answer is not lost to+# a reset; and how many such drains run at once. A drain holds no handshake slot, so under a flood+# of older peers the ones past the cap are closed without one rather than each costing a thread.+DRAIN_SECONDS = 1.0+MAX_DRAINS = 8+# Threads for connections not yet authenticated, drains included. A connection past it is closed at+# once, without a thread or a slot: a flood of connections must not become a flood of threads.+MAX_HANDSHAKE_THREADS = 32+# A frame goes out in pieces of this, each bounded by the link's timeout, so a large clipboard to a+# slow but working peer keeps going while bytes move (section 3, liveness).+SEND_CHUNK = 64 * 1024+# No byte at all for this long ends a link (section 3, liveness).+LINK_READ_TIMEOUT_SECONDS = 2.5+# A send-home the owner does not obey within this ends its ownership by force, and after either the+# initiator is refused `sent_home` for SENT_HOME_SECONDS (section 4).+FORCED_END_SECONDS = 1.0+SENT_HOME_SECONDS = 5.0+# Frames waiting to go to one peer. A peer that stops reading is closed at this, rather than let a+# queue grow without end; it is well past anything a working link queues between two writes.+OUTBOX_LIMIT = 512++ADMITTED = "admitted"+WRONG_ID = "wrong_id"+GONE = "gone"+IN_USE_OFF = "in_use_off"++_DROPPED_TEXT = frozenset(chr(code) for code in list(range(0x00, 0x20)) + list(range(0x7F, 0xA0))) - {"\n", "\t"}+_TEXT_KEYS = {"\n": "enter", "\t": "tab"}+++def learnable_host(address, port) -> bool:+ """Whether a link from `address`, whose `hello` gave `port`, teaches the peer's `host`: never+ for a peer that accepts no links, nor from a loopback or link-local address (section 2)."""+ if port == 0:+ return False+ try:+ ip = ipaddress.IPv4Address(address)+ except ValueError:+ return False+ return not (ip.is_loopback or ip.is_link_local)+++def ack_due(last_ack_at: float, pending_since: Optional[float]) -> float:+ """When the next `ack` goes, timed from the last (section 9): input dealt with 15 ms or more after+ it at once, input sooner 15 ms after it, and with none a heartbeat 0.4 seconds after it."""+ if pending_since is None:+ return last_ack_at + ACK_IDLE_SECONDS+ return max(pending_since, last_ack_at + ACK_COALESCE_SECONDS)+++def text_runs(text: str) -> list:+ """`text` as the injector types it (section 10): runs of characters, with each `\\n` and `\\t`+ its own run, and the other control characters dropped."""+ runs, current = [], []+ for char in text:+ if char in _TEXT_KEYS:+ if current:+ runs.append("".join(current))+ current = []+ runs.append(char)+ elif char not in _DROPPED_TEXT:+ current.append(char)+ if current:+ runs.append("".join(current))+ return runs+++def corner_offset(corner: str, edge: str) -> float:+ """Where a corner zone lands the pointer on the edge it crosses: the end nearest the corner,+ 0.0 for a top or left end and 1.0 for a bottom or right one (section 8)."""+ vertical, horizontal = corner.split("_")+ if edge in ("left", "right"):+ return 0.0 if vertical == "top" else 1.0+ return 0.0 if horizontal == "left" else 1.0+++def zone_models(zones, peers, allowed, resistance_px: int, notch_span=None) -> list:+ """[(peer id, model)] for this machine's zones (section 8) that lead to a peer in `allowed`, at+ `resistance_px`, in the order they are checked: corners, then edges, then parts, then the notch.+ `peers` are the settings' peer entries, for each peer's `side`; `notch_span` is the Mac's+ `SpanEdge` span, and without it a notch zone is left out. Zones that are off, name no learnt+ peer, or do not fit their kind are left out."""+ sides = {}+ for peer in peers or ():+ ident = protocol.read_id(peer.get("id")) if isinstance(peer, dict) else None- if ident is not None and peer.get("in_use", True) is True:++ if ident is not None and peer.get("in_use", True) is True and peer.get("port") != 0:+ sides[ident] = peer.get("side")+ found = {"corner": [], "edge": [], "part": [], "notch": []}+ for zone in zones or ():+ if not isinstance(zone, dict) or zone.get("off") is True:+ continue+ peer = protocol.read_id(zone.get("peer"))- if peer is None or peer not in allowed:++ if peer is None or peer not in allowed or peer not in sides:+ continue+ kind, side = zone.get("kind"), sides.get(peer)+ try:+ if kind == "edge" and side in crossing.EDGES:+ model = crossing.ReturnEdge(side, resistance_px)+ elif kind == "part" and side in crossing.EDGES and isinstance(zone.get("parts"), list):+ model = crossing.PartEdge(side, [part for part in zone["parts"] if isinstance(part, str)], resistance_px)+ elif kind == "corner" and isinstance(zone.get("corner"), str) and zone.get("edge") in zone["corner"].split("_"):+ model = crossing.CornerPush(zone["corner"], zone["edge"], resistance_px)+ elif kind == "notch" and notch_span is not None:+ model = crossing.SpanEdge("top", notch_span, resistance_px)+ else:+ continue+ except ValueError:+ continue+ found[kind].append((peer, model))+ return found["corner"] + found["edge"] + found["part"] + found["notch"]++- def zone_stretch(zone: dict, sides: dict) -> set:- """The stretch of screen a zone covers, for section 8's rule that two zones in use never cover- the same one: an `edge` zone its peer's side, a `part` zone the chosen thirds of it, a `corner`- zone its corner; a notch, and a zone whose peer has no side, cover none. `sides` maps a zone's- `peer` text to that peer's `side`."""- kind, side = zone.get("kind"), sides.get(zone.get("peer"), "")- if kind == "corner" and zone.get("corner") in crossing.CORNERS:- return {("corner", zone["corner"])}- if kind == "edge" and side in crossing.EDGES:- return {(side, part) for part in crossing.PARTS}- if kind == "part" and side in crossing.EDGES and isinstance(zone.get("parts"), list):- return {(side, part) for part in zone["parts"] if part in crossing.PARTS}- return set()--[email protected]_cache(maxsize=128)+def _key_id_of(token) -> bytes:+ return protocol.key_id(token)+++def _entry_key_id(entry) -> Optional[bytes]:+ # Only for an entry made by pairing: a key id is an offline test of its token (section 2).+ return _key_id_of(entry["token"]) if protocol.linkable(entry) else None+++class HandshakeSlots:+ """The connections still in their handshakes: at most `limit`, and one per address. Taking a+ slot for an address that holds one displaces that connection; taking one when all are held+ displaces the oldest. The caller closes what `take` returns. Not locked: the responder is."""++ def __init__(self, limit: int = MAX_PENDING_CONNECTIONS) -> None:+ self._limit = limit+ self._held = collections.OrderedDict()++ def take(self, host, connection):+ displaced = self._held.pop(host, None)+ if displaced is None and len(self._held) >= self._limit:+ _, displaced = self._held.popitem(last=False)+ self._held[host] = connection+ return displaced++ def free(self, host, connection) -> None:+ if self._held.get(host) is connection:+ del self._held[host]++ def __len__(self) -> int:+ return len(self._held)+++class PeerBook:+ """The peers list as the link reads and writes it: WIRE.md section 1's settings, through the+ app's own `load` (the settings as held in memory, a dict with `peers` and `zones`) and `save`+ (given a changed copy, which it writes atomically and keeps). `lock` is held around every+ read-check-write here; the app holds it too around its own changes to the peers, so an id+ learnt here and a peer removed there cannot cross. Neither the responder nor this ever takes+ the responder's lock while holding this one."""++ def __init__(self, load: Callable[[], dict], save: Callable[[dict], None], lock=None) -> None:+ self._load = load+ self._save = save+ self.lock = lock if lock is not None else threading.RLock()++ def peers(self) -> list:+ with self.lock:+ return copy.deepcopy(list((self._load() or {}).get("peers") or []))++ def zones(self) -> list:+ """The zones as the settings hold them, a copy."""+ with self.lock:+ return copy.deepcopy(list((self._load() or {}).get("zones") or []))++ def store_paired(self, peer: str, ids: list) -> None:+ """Keep, with the entry whose id is `peer` (a `b64`), the ids it said it is paired with+ (`paired`, WIRE.md section 3); saved only when the list changed."""+ with self.lock:+ settings = copy.deepcopy(self._load() or {})+ entry = next((item for item in settings.get("peers") or [] if item.get("id") == peer), None)+ if entry is None or entry.get("paired_with") == ids:+ return+ entry["paired_with"] = list(ids)+ self._save(settings)++ def find(self, key_id: bytes) -> Optional[dict]:+ """The entry, a copy, whose token (one made by pairing) has `key_id`."""+ for entry in self.peers():+ found = _entry_key_id(entry)+ if found is not None and hmac.compare_digest(found, key_id):+ return entry+ return None++ def admit(self, key_id: bytes, own_id: bytes, peer_id: bytes, changes: dict):+ """Section 2's id checks for a link under `key_id` whose first frame named `peer_id`, and on+ success the entry's update from it, in one step under the lock: `(outcome, entry)`.+ WRONG_ID when `peer_id` is this machine's own or is not the entry's; GONE when no entry has+ the key id any longer; ADMITTED otherwise. `changes` and `linked` are applied and saved when+ they change anything."""+ with self.lock:+ settings = copy.deepcopy(self._load() or {})+ peers = settings.get("peers") or []+ entry = next((p for p in peers if _entry_key_id(p) is not None and hmac.compare_digest(_entry_key_id(p), key_id)), None)+ if entry is None:+ return GONE, None+ if peer_id == own_id or entry.get("id") != protocol.id_text(peer_id):+ return WRONG_ID, None+ if entry.get("in_use", True) is not True:+ return IN_USE_OFF, None+ before = copy.deepcopy(entry)+ entry.update(changes)+ entry["linked"] = True+ if entry != before:+ self._save(settings)+ return ADMITTED, copy.deepcopy(entry)+++class _Link:+ """One authenticated link an initiator opened to this machine. Its reader thread deals with+ what arrives; its writer thread sends everything that goes out, in order (the `outbox`) and+ the `ack`s when they are due, so nothing that holds the responder's lock ever waits on a+ socket."""++ def __init__(self, sock, session, peer_id, key_id, host, name, caps, own_id, own_caps, allow_drive) -> None:+ self.sock = sock+ self.session = session+ self.peer_id = peer_id+ self.key_id = key_id+ self.host = host+ self.name = name+ self.caps = frozenset(caps)+ self.own_id = own_id+ self.own_caps = frozenset(own_caps)+ self.allow_drive = allow_drive+ self.route = 0 # the last route accepted on this link+ self.held = {} # ("key" or "button", name): `us`, what the owner holds down here+ self.closed = threading.Event()+ self.cond = threading.Condition()+ self.outbox = collections.deque()+ self.dealt = 0 # the highest seq dealt with+ self.dealt_at = 0.0+ self.pending_since = None # when the first input not yet acknowledged was dealt with+ self.acked = 0+ self.last_ack_at = time.monotonic()+ self.input_error_at = float("-inf") # when an injection error last reached the status++ def post(self, message: dict) -> bool:+ with self.cond:+ if self.closed.is_set():+ return False+ if len(self.outbox) >= OUTBOX_LIMIT:+ LOGGER.warning("%s stopped reading; closing its link", self.name)+ self._close_locked()+ return False+ self.outbox.append(message)+ self.cond.notify()+ return True++ def dealt_with(self, seq: int) -> None:+ with self.cond:+ if seq <= self.dealt:+ return+ now = time.monotonic()+ self.dealt, self.dealt_at = seq, now+ if self.pending_since is None:+ self.pending_since = now+ self.cond.notify()++ def close(self) -> None:+ with self.cond:+ self._close_locked()++ def _close_locked(self) -> None:+ self.closed.set()+ self.cond.notify_all()+ try:+ self.sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+++class LinkResponder:+ """Wire version 6's responder (WIRE.md sections 2 to 5, 9 and 10): accepts links from every+ paired peer on one port, keeps one link per peer id, and at most one owner, whose input alone+ is injected. Nothing in it knows which platform it runs on; everything platform-shaped is+ handed in.++ - `book`: a PeerBook over the app's settings.+ - `identity()`: this machine as its `welcome` says it, a dict of `id` (16 bytes), `name`,+ `platform`, `app`, `caps` and optionally `hw`; read at each handshake.+ - `injector`, `desktop`, `clipboard`, `unlock`: the platform modules.+ The injector also needs `inject_text(chars)` for the `text` capability. The clipboard needs+ `get_contents()`, `set_contents(text, image)` and `change_stamp()`, a value that changes+ whenever the clipboard does; without it, a machine let go never sends its clipboard.+ `unlock` is Windows' lock-screen module, or None.+ - `hardware(host)`: this machine's address on the interface that reaches `host`, asked for each+ link's own address so the `welcome` gives every peer the address its wake-on-LAN must go to;+ without it, the `identity()`'s `hw` is sent as it stands.+ - `away()`: whether this machine's own input is on another machine (owner.Owner.away), which+ refuses a take as `busy`. Called under the responder's lock, so a plain read that never+ blocks. The app sets `away` before it sends a take and then reads `driven`; if that is true,+ a take here won the race and the app's input goes home.+ - `zones()`: this machine's zones as settings.json keeps them; `notch_span`: the Mac's notch+ span for SpanEdge, or None.++ Callbacks, each on a link's thread, never with the responder's lock held, each by peer id:+ `owner_callback(peer or None)` when ownership begins or ends, always in the order it did; `arrival_callback(edge, x, y)`+ and `pressure_callback(edge, pressure, crossed, part)` for the crossing effects;+ `arrangement_callback(peer, {edge, set_at, by})`; `settings_callback(peer, data)`, only from a+ peer whose `caps` list `settings`; `paired_callback(peer, ids)`; `link_callback(peer, up)`; and+ `announce(peer)`, the messages to send once a link is up (section 3, announcements).+ `status_callback(state, detail)` takes ServerState.++ The app calls `peers_changed()` after every change to the peers (a removal closes that peer's+ links; `allow_drive` sends `accepts` and, turned off, ends that peer's ownership), `rearm()`+ after a change to the zones, and `send_home()` to send the owner home from here."""++ def __init__(+ self,+ book: PeerBook,+ identity: Callable[[], dict],+ *,+ status_callback: Callable[[ServerState, str], None],+ injector=None,+ desktop=None,+ clipboard=None,+ unlock=None,+ hardware: Optional[Callable[[str], Optional[str]]] = None,+ away: Optional[Callable[[], bool]] = None,+ zones: Optional[Callable[[], list]] = None,+ notch_span=None,+ owner_callback=None,+ arrival_callback=None,+ pressure_callback=None,+ arrangement_callback=None,+ settings_callback=None,+ paired_callback=None,+ link_callback=None,+ announce=None,+ ) -> None:+ self._book = book+ self._identity = identity+ self._status_callback = status_callback+ self._injector = injector+ self._desktop = desktop+ self._clipboard = clipboard+ self._unlock = unlock+ self._hardware = hardware+ self._away = away or (lambda: False)+ self._zones = zones or (lambda: [])+ self._notch_span = notch_span+ self._callbacks = {+ "owner": owner_callback, "arrival": arrival_callback, "pressure": pressure_callback,+ "arrangement": arrangement_callback, "settings": settings_callback, "paired": paired_callback,+ "link": link_callback,+ }+ self._announce = announce or (lambda peer: [])+ # This machine's speed for a peer's pointer and scroll, and whether+ # its edges are held (Pause crossing, a full-screen app), which keeps the zones from firing.+ self.input_scale: Optional[InputScale] = None+ self.edges_held: Callable[[], bool] = lambda: False+ # One lock for the links, the owner and everything the owner decides. Held while the owner's+ # input is injected, so an ownership ending on another thread cannot release keys between+ # the check and the press. Never held while calling the app, or across a socket write.+ self._lock = threading.RLock()+ self._slots = HandshakeSlots()+ self._drains = 0+ self._handshaking = 0 # threads for connections not yet authenticated+ self._links = {} # peer id: _Link+ self._owner: Optional[_Link] = None+ self._claiming: Optional[_Link] = None # a take being decided, visible before `away` is read+ self._visit = 0 # raised each time an ownership begins+ self._generation = 0 # raised on every change to the peers or the zones+ self._reach = frozenset()+ self._resistance = protocol.DEFAULT_RESISTANCE_PX+ self._armed = [] # [(peer id, model)] while the zones are live+ self._zones_live = False+ self._sent_home_at = {} # peer id: when it was sent home or ended by force+ self._forced = None # the forced end's timer after a send-home+ self._clipboard_mark = None # the clipboard's change stamp when this owner's visit began+ # Ownership changes for owner_callback, queued under the lock and delivered in order, one+ # thread at a time, so the app never hears an end after the next owner's beginning.+ self._owner_events = collections.deque()+ self._notify_lock = threading.RLock()+ self._unlocking = threading.Event()+ self._arriving_visit = None # the visit whose pointer is landing and unlock not yet asked+ self._lock_checked_at = float("-inf")+ self._locked_since = None+ self._sent_home_for_lock = False+ self._connections = set()+ self._thread: Optional[threading.Thread] = None+ self._stop_event: Optional[threading.Event] = None+ self._listener: Optional[socket.socket] = None+ self._port = None+ self._requested_running = False++ # The listener++ @property+ def listening(self) -> bool:+ with self._lock:+ return self._requested_running and self._thread is not None and self._thread.is_alive()++ @property+ def listening_port(self) -> Optional[int]:+ with self._lock:+ return self._port if self._listener is not None else None++ @property+ def owner(self) -> Optional[bytes]:+ link = self._owner+ return link.peer_id if link is not None else None++ @property+ def driven(self) -> bool:+ """True from the moment a take is being decided, before `away()` is read, until the take is+ refused or the ownership it began ends. The app sends its own input elsewhere by setting+ `away` first and reading this after: whichever of the two moves second sees the other, so+ a machine is never driven and driving at once (section 4). A plain read, never the lock: the+ hook thread asks it, and the lock is held while the owner's input is injected, which on+ Windows waits for that same thread's hook."""+ return self._claiming is not None or self._owner is not None++ def links(self) -> set:+ with self._lock:+ return set(self._links)++ def caps_of(self, peer: bytes) -> Optional[frozenset]:+ """The capabilities the peer's link announced, or None when it has no link here."""+ with self._lock:+ link = self._links.get(peer)+ return link.caps if link is not None else None++ def start(self, port: int) -> None:+ with self._lock:+ if self._thread is not None and self._thread.is_alive():+ return+ stop_event = threading.Event()+ thread = threading.Thread(target=self._server_thread, args=(port, stop_event), name="Beamer-v6-server", daemon=True)+ self._stop_event, self._thread, self._port = stop_event, thread, port+ self._requested_running = True+ self._set_status(ServerState.WAITING, f"Starting on port {port}")+ thread.start()++ def stop(self) -> None:+ with self._lock:+ self._requested_running = False+ stop_event, listener, thread = self._stop_event, self._listener, self._thread+ connections = set(self._connections)+ after = self._end_locked(self._owner) if self._owner is not None else []+ # Closed under the lock, so no take queued on one can be accepted after this.+ for link in self._links.values():+ link.close()+ self._run(after)+ if stop_event is not None:+ stop_event.set()+ for connection in connections:+ _close_socket(connection)+ _close_socket(listener)+ if thread is not None and thread is not threading.current_thread() and thread.ident is not None:+ thread.join(timeout=2.0)+ with self._lock:+ if self._thread is thread:+ self._thread = self._stop_event = self._listener = None+ self._set_status(ServerState.STOPPED, "Listening stopped")++ def _server_thread(self, port: int, stop_event: threading.Event) -> None:+ try:+ listener = self._bind(port, stop_event)+ if listener is None:+ return+ listener.listen(8)+ # Closing a listener does not wake accept() everywhere, so stop() waits on this poll.+ listener.settimeout(0.1)+ with self._lock:+ self._listener = listener+ self._port = listener.getsockname()[1]+ LOGGER.info("Listening for version 6 links on 0.0.0.0:%s", self._port)+ self._report()+ while not stop_event.is_set():+ try:+ connection, address = listener.accept()+ except socket.timeout:+ continue+ except OSError:+ if stop_event.is_set():+ break+ raise+ accepted = time.monotonic()+ with self._lock:+ crowded = self._handshaking >= MAX_HANDSHAKE_THREADS+ if not crowded:+ self._handshaking += 1+ displaced = self._slots.take(address[0], connection)+ self._connections.add(connection)+ if crowded:+ LOGGER.warning("Closed a connection from %s: %d handshakes already running", address[0], MAX_HANDSHAKE_THREADS)+ _close_socket(connection)+ continue+ if displaced is not None:+ _close_socket(displaced)+ threading.Thread(+ target=self._connection_thread, args=(connection, address[0], accepted), name="Beamer-v6-link", daemon=True+ ).start()+ except Exception as exc:+ if not stop_event.is_set():+ LOGGER.exception("The version 6 listener failed")+ self._set_status(ServerState.ERROR, f"Listener failed: {exc}")+ finally:+ with self._lock:+ listener = self._listener+ self._listener = None+ _close_socket(listener)++ def _bind(self, port: int, stop_event: threading.Event):+ reported = False+ while not stop_event.is_set():+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ # SO_REUSEADDR only off Windows, where it would let a second+ # listener share the port.+ if sys.platform != "win32":+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ try:+ listener.bind(("0.0.0.0", port))+ return listener+ except OSError as exc:+ _close_socket(listener)+ if not reported:+ reported = True+ LOGGER.error("Cannot listen on port %s: %s", port, exc)+ self._set_status(ServerState.ERROR, f"Another program is using port {port} — change the port on the Connection page")+ stop_event.wait(BIND_RETRY_SECONDS)+ return None++ def _connection_thread(self, connection: socket.socket, host: str, accepted: float) -> None:+ link = None+ try:+ link = self._handshake(connection, host, accepted)+ except Exception:+ LOGGER.exception("The handshake with %s failed", host)+ finally:+ with self._lock:+ self._slots.free(host, connection)+ self._handshaking -= 1+ try:+ if link is not None:+ self._serve(link)+ finally:+ with self._lock:+ self._connections.discard(connection)+ _close_socket(connection)++ # The handshake (section 2)++ def _handshake(self, connection: socket.socket, host: str, accepted: float) -> Optional[_Link]:+ """Steps 2 to 9 of the responder's handshake. The link, once its `welcome` has gone, or+ None once the connection has been answered or needs closing with nothing sent."""+ try:+ try:+ preamble = protocol.recv_link_preamble(connection, accepted + PREAMBLE_SECONDS)+ except protocol.VersionMismatch as exc:+ self._not_version_6(connection, host, exc.peer_version)+ return None+ _, key_id, _ = protocol.split_preamble(preamble)+ entry = self._book.find(key_id)+ if entry is None:+ LOGGER.info("%s named a pairing this machine does not have; closed", host)+ return None+ session = protocol.LinkSession(entry["token"], protocol.ROLE_RESPONDER)+ session.accept_preamble(preamble)+ deadline = accepted + HANDSHAKE_SECONDS+ # The last read left the preamble's deadline on the socket, perhaps nearly spent.+ connection.settimeout(max(0.001, deadline - time.monotonic()))+ connection.sendall(session.preamble())+ try:+ hello = protocol.read_hello(protocol.recv_first_msg(connection, session, deadline))+ except (protocol.NotAnObject, protocol.InvalidHello):+ LOGGER.warning("%s sent a first frame that is not a valid hello", host)+ self._answer(connection, host, session.seal(protocol.invalid_hello_v6()))+ return None+ identity = self._identity()+ own_id = bytes(identity["id"])+ changes = {"name": hello["name"], "platform": hello["platform"], "port": hello["port"]}+ if hello["hw"] is not None:+ changes["hw"] = hello["hw"]+ if learnable_host(host, hello["port"]):+ changes["host"] = host+ try:+ outcome, entry = self._book.admit(key_id, own_id, hello["id"], changes)+ except Exception:+ LOGGER.exception("Could not save what the link from %s taught", host)+ return None+ if outcome == GONE:+ LOGGER.info("The pairing %s linked under was removed during its handshake; closed", host)+ return None+ if outcome == WRONG_ID:+ LOGGER.warning("%s holds a pairing of this machine's under another machine's id", host)+ self._answer(connection, host, session.seal(protocol.wrong_id_v6()))+ return None+ if outcome == IN_USE_OFF:+ self._answer(connection, host, session.seal(protocol.invalid_hello_v6()))+ return None+ allow_drive = entry.get("allow_drive") is True+ welcome = protocol.welcome_v6(+ own_id, identity["name"], identity["platform"], identity["app"], identity["caps"], allow_drive, self._hardware_towards(host, identity)+ )+ protocol.send_msg(connection, session, welcome)+ except (socket.timeout, protocol.ConnectionClosed, protocol.ProtocolError, OSError) as exc:+ LOGGER.info("Handshake with %s ended: %s", host, exc)+ return None+ return _Link(connection, session, hello["id"], key_id, host, hello["name"], hello["caps"], own_id, identity["caps"], allow_drive)++ def _hardware_towards(self, host, identity):+ """The `hw` for the welcome to `host`, as the initiator's hook does for its hello: the hook is+ optional and never fatal, and one 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 _not_version_6(self, connection: socket.socket, host: str, version) -> None:+ """An older or newer Beamer: the version 5 legacy frame for one from before version 4, else+ the short reply, and the status names the peer at that address, if one is."""+ self._answer(connection, host, protocol.legacy_version_reply() if version is None else protocol.short_reply())+ who = peerlist.label_for(self._settings_now()[0], host=host) or host+ if version is not None and version > protocol.LINK_VERSION:+ detail = f"{who} runs a newer Beamer: update Beamer on this machine"+ else:+ detail = f"Update Beamer on {who}: it is older than this one"+ LOGGER.warning("%s speaks wire version %r; answered and closed", host, version)+ with self._lock:+ linked = bool(self._links)+ if not linked:+ self._set_status(ServerState.ERROR, detail)++ def _answer(self, connection: socket.socket, host: str, data: bytes) -> None:+ """Send `data`, free the handshake slot, shut the sending side, and read what the peer sends+ for up to DRAIN_SECONDS so the answer is not lost to a reset."""+ with self._lock:+ self._slots.free(host, connection)+ draining = self._drains < MAX_DRAINS+ if draining:+ self._drains += 1+ try:+ connection.settimeout(DRAIN_SECONDS)+ connection.sendall(data)+ connection.shutdown(socket.SHUT_WR)+ end = time.monotonic() + DRAIN_SECONDS+ while draining:+ left = end - time.monotonic()+ if left <= 0:+ break+ connection.settimeout(left)+ if not connection.recv(65536):+ break+ except OSError:+ pass+ finally:+ if draining:+ with self._lock:+ self._drains -= 1++ # A link++ def _serve(self, link: _Link) -> None:+ link.sock.settimeout(LINK_READ_TIMEOUT_SECONDS)+ try:+ link.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)+ except OSError:+ pass+ with self._lock:+ earlier = self._links.get(link.peer_id)+ self._links[link.peer_id] = link+ # Step 10: an earlier link from this peer is closed, its ownership ended first, and+ # closed under the lock, so no take still queued on it can be accepted after this.+ after = self._end_locked(earlier) if earlier is not None else []+ if earlier is not None:+ earlier.close()+ writer = threading.Thread(target=self._writer, args=(link,), name="Beamer-v6-writer", daemon=True)+ try:+ self._run(after)+ writer.start()+ # A peer removed, or its allow_drive changed, between the handshake's read of the book+ # and this link joining the others was missed by the app's peers_changed(): look again.+ self.peers_changed()+ self._callback("link", link.peer_id, True)+ self._report()+ try:+ for message in list(self._announce(link.peer_id)):+ link.post(message)+ except Exception:+ LOGGER.exception("Announcements for %s failed", link.name)+ while not link.closed.is_set():+ try:+ plain = link.session.open_raw(protocol.recv_frame(link.sock))+ if len(plain) > protocol.SMALL_MESSAGE_BYTES and self._owner is not link:+ # Only the owner's clipboard is this large; opening it was enough to keep+ # the counter in step, and parsing it is the peer's to make this machine pay for.+ LOGGER.info("Dropped a %d byte frame from %s, which does not own this machine", len(plain), link.name)+ continue+ message = protocol.parse_message(plain)+ except socket.timeout:+ LOGGER.warning("%s went quiet, or took too long over one message; its link is over", link.name)+ break+ except (protocol.ConnectionClosed, protocol.ProtocolError, OSError) as exc:+ if not link.closed.is_set():+ LOGGER.info("The link from %s ended: %s", link.name, exc)+ break+ self._dispatch(link, message)+ finally:+ with self._lock:+ current = self._links.get(link.peer_id) is link+ if current:+ del self._links[link.peer_id]+ after = self._end_locked(link)+ link.close()+ self._run(after)+ if writer.ident is not None:+ writer.join(timeout=1.0)+ if current:+ self._callback("link", link.peer_id, False)+ self._report()++ def _writer(self, link: _Link) -> None:+ """Everything this link sends, in order, and its `ack`s when they are due (section 9)."""+ while True:+ is_ack = False+ with link.cond:+ while True:+ if link.closed.is_set():+ return+ if link.outbox:+ message = link.outbox.popleft()+ break+ now = time.monotonic()+ due = ack_due(link.last_ack_at, link.pending_since)+ if now >= due:+ seq = link.dealt+ held_us = int((now - link.dealt_at) * 1_000_000) if seq > link.acked else 0+ link.acked, link.last_ack_at, link.pending_since = seq, now, None+ # Only the owner hears of the lock screen: to anyone else it would say who+ # has just arrived to drive this machine.+ locked = self._unlocking.is_set() and self._owner is link+ message = protocol.ack_v6(seq, held_us, locked=locked)+ is_ack = True+ break+ link.cond.wait(due - now)+ try:+ # Only this thread sends once the link is up, so sealing and sending need not be+ # one step under the session's lock to keep the counters in order.+ frame = memoryview(link.session.seal(message))+ sent = 0+ while sent < len(frame):+ sent += link.sock.send(frame[sent:sent + SEND_CHUNK])+ except (OSError, protocol.ProtocolError, ValueError) as exc:+ LOGGER.info("Sending to %s failed: %s", link.name, exc)+ link.close()+ return+ if is_ack:+ self._home_if_locked(link)++ def _dispatch(self, link: _Link, message) -> None:+ kind = message.get("type") if isinstance(message, dict) else None+ try:+ if kind in protocol.INPUT_TYPES:+ self._on_input(link, message)+ elif kind == protocol.MSG_FOCUS:+ self._on_focus(link, message)+ elif kind == protocol.MSG_CLIPBOARD:+ self._on_clipboard(link, message)+ elif kind == protocol.MSG_ARRANGEMENT:+ read = protocol.read_arrangement_v6(message, time.time())+ if read is not None:+ self._callback("arrangement", link.peer_id, read)+ elif kind == protocol.MSG_SETTINGS:+ parsed = protocol.read_message(message)+ if parsed is not None and "settings" in link.caps:+ self._callback("settings", link.peer_id, parsed[1])+ elif kind == protocol.MSG_PAIRED:+ ids = protocol.read_paired(message)+ if ids is not None:+ self._callback("paired", link.peer_id, ids)+ except Exception:+ LOGGER.exception("A %r from %s could not be dealt with", kind, link.name)++ # Input (sections 3, 4 and 10)++ def _on_input(self, link: _Link, message) -> None:+ read = protocol.read_input(message)+ if read is None:+ return+ after = []+ try:+ with self._lock:+ if self._owner is not link or not self._takes(link, read):+ pass+ elif self._unlocking.is_set():+ # Input that arrives while the lock screen clears is dropped, but a release of+ # something injected before it still goes, or that key stays down after.+ if self._releases_held(link, read):+ self._inject_locked(link, read)+ elif not (read["type"] == protocol.MSG_MOUSEMOVE and self._zones_locked(link, read, after)):+ self._inject_locked(link, read)+ except Exception:+ LOGGER.exception("Input from %s could not be injected", link.name)+ self._input_error_status(link)+ finally:+ link.dealt_with(read["seq"])+ self._run(after)++ def _input_error_status(self, link: _Link) -> None:+ """Says in the status that this peer's input is not being injected, as ReceiverServer did:+ at most once per INJECTION_ERROR_STATUS_INTERVAL_SECONDS a link, since a broken injector+ fails on every event."""+ now = time.monotonic()+ if now - link.input_error_at < INJECTION_ERROR_STATUS_INTERVAL_SECONDS:+ return+ link.input_error_at = now+ who = peerlist.label_for(self._settings_now()[0], peer_id=protocol.id_text(link.peer_id)) or link.name+ self._set_status(ServerState.CONNECTED, f"Input error from {who}; see log")++ @staticmethod+ def _releases_held(link: _Link, read: dict) -> bool:+ if read["type"] == protocol.MSG_KEYUP:+ return ("key", read["key"]) in link.held+ if read["type"] == protocol.MSG_MOUSEUP:+ return ("button", read["button"]) in link.held+ return False++ def _takes(self, link: _Link, read: dict) -> bool:+ """Whether this machine acts on this input at all: a message its capabilities do not cover+ is dropped, and still acknowledged (section 2)."""+ if read["type"] == protocol.MSG_TEXT:+ return read["text"] is not None and "text" in link.own_caps and hasattr(self._injector_module(), "inject_text")+ if read["type"] == protocol.MSG_GESTURE:+ return "gestures" in link.own_caps+ return True++ def _inject_locked(self, link: _Link, read: dict) -> None:+ injector = self._injector_module()+ kind = read["type"]+ if kind in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP):+ down = kind == protocol.MSG_KEYDOWN+ if down:+ link.held[("key", read["key"])] = read["us"]+ else:+ link.held.pop(("key", read["key"]), None)+ injector.inject_key(read["key"], down=down, us=read["us"])+ elif kind == protocol.MSG_MOUSEMOVE:+ dx, dy = read["dx"], read["dy"]+ if self.input_scale is not None and (dx or dy):+ dx, dy = self.input_scale.move(dx, dy)+ if not (dx or dy):+ return+ injector.inject_mouse_move(dx, dy)+ elif kind in (protocol.MSG_MOUSEDOWN, protocol.MSG_MOUSEUP):+ down = kind == protocol.MSG_MOUSEDOWN+ if down:+ link.held[("button", read["button"])] = None+ else:+ link.held.pop(("button", read["button"]), None)+ injector.inject_mouse_button(read["button"], down=down)+ elif kind == protocol.MSG_SCROLL:+ dy, dx = read["dy"], read["dx"]+ if self.input_scale is not None:+ dy, dx = self.input_scale.wheel(dy, dx)+ injector.inject_scroll(dy, dx, read["mode"])+ elif kind == protocol.MSG_GESTURE:+ injector.inject_gesture(read["name"])+ elif kind == protocol.MSG_TEXT:+ for run in text_runs(read["text"]):+ if run in _TEXT_KEYS:+ injector.inject_key(_TEXT_KEYS[run], down=True)+ injector.inject_key(_TEXT_KEYS[run], down=False)+ else:+ injector.inject_text(run)++ def _release_locked(self, link: _Link) -> None:+ """Let go of every key and button injected for this owner (section 4, step 1), then the+ injector's own record of what it holds, as the backstop."""+ injector = self._injector_module()+ for (kind, name), us in reversed(list(link.held.items())):+ try:+ if kind == "key":+ injector.inject_key(name, down=False, us=us)+ else:+ injector.inject_mouse_button(name, down=False)+ except Exception:+ LOGGER.exception("Could not release %r for %s", name, link.name)+ link.held.clear()+ release_all = getattr(injector, "release_all", None)+ if release_all is not None:+ try:+ release_all()+ except Exception:+ LOGGER.exception("Could not release the keys %s was holding", link.name)++ # The zones (sections 5 and 8)++ def _arm_locked(self, peers, zones) -> None:+ owner = self._owner+ if owner is None:+ self._armed, self._zones_live = [], False+ return+ try:+ self._armed = zone_models(zones, peers, {owner.peer_id} | self._reach, self._resistance, self._notch_span)+ except Exception:+ LOGGER.exception("Could not arm the zones for %s", owner.name)+ self._armed = []+ self._zones_live = True++ def _disarm_locked(self) -> None:+ self._armed, self._zones_live = [], False++ def _zones_locked(self, link: _Link, read: dict, after: list) -> bool:+ """Feeds one mouse move to the armed zones, first that holds the pointer winning. True when+ the move was used at an edge (held there, or crossed and the owner sent a `switch`)."""+ if not self._armed or self.edges_held():+ return False+ desktop = self._desktop_module()+ monitors, pointer = desktop.monitors(), desktop.cursor_position()+ for peer, model in self._armed:+ outcome = model.feed(monitors, pointer, float(read["dx"]), float(read["dy"]))+ if outcome.action == crossing.PASS:+ continue+ part = None+ if isinstance(model, crossing.PartEdge):+ part = crossing.part_of(crossing.display_fraction(monitors, model.edge, pointer))+ elif isinstance(model, crossing.CornerPush):+ part = model.corner+ if outcome.action == crossing.HOLD:+ desktop.set_cursor_position(*outcome.position)+ after.append(lambda: self._callback("pressure", model.edge, outcome.pressure, False, part))+ return True+ offset = corner_offset(model.corner, model.edge) if isinstance(model, crossing.CornerPush) else outcome.offset+ self._disarm_locked()+ LOGGER.info("The pointer pushed through the zone at this machine's %s edge; asking %s to move its input on",+ model.edge, link.name)+ link.post(protocol.switch_v6(link.route, peer, outcome.edge, offset))+ after.append(lambda: self._callback("pressure", model.edge, 1.0, True, part))+ return True+ return False++ def rearm(self) -> None:+ """Rebuilds the zones from the settings as they are now, while an owner drives and they are+ live, so a change on the Crossing page applies at once. Never revives zones spent by a+ `switch` or a send-home."""+ with self._lock:+ self._generation += 1+ self._rearm_fresh()++ def _rearm_fresh(self) -> None:+ # The settings are read without the lock, so a change landing meanwhile is caught by the+ # generation and read again, rather than armed over by what was read before it.+ for _ in range(5):+ with self._lock:+ generation = self._generation+ peers, zones = self._settings_now()+ with self._lock:+ if generation != self._generation:+ continue+ if self._owner is not None and self._zones_live:+ self._arm_locked(peers, zones)+ return++ def _settings_now(self):+ """The peers and zones as the app holds them now, or none of either when it cannot say."""+ try:+ peers = self._book.peers()+ except Exception:+ LOGGER.exception("Could not read the peers")+ peers = []+ try:+ zones = list(self._zones() or [])+ except Exception:+ LOGGER.exception("Could not read the zones")+ zones = []+ return peers, zones++ # Ownership (section 4)++ def _on_focus(self, link: _Link, message) -> None:+ focus = protocol.read_focus(message, link.own_id)+ if focus is None:+ return+ after = []+ with self._lock:+ generation = self._generation+ peers, zones = self._settings_now() if focus["here"] else ((), ())+ with self._lock:+ if link.closed.is_set() or focus["route"] <= link.route:+ return+ if not focus["here"]:+ if self._owner is link:+ link.route = focus["route"]+ after = self._end_locked(link, let_go=True)+ else:+ why = self._refusal_locked(link, focus)+ if why is not None:+ reason, other = why+ link.post(protocol.refuse_msg(focus["route"], reason, other=other))+ return+ link.route = focus["route"]+ # The answer goes before the pointer is placed or anything plays.+ link.post(protocol.accept_msg(focus["route"]))+ after = self._own_locked(link, focus, peers, zones)+ stale = focus["here"] and generation != self._generation+ self._run(after)+ if stale:+ self._rearm_fresh()++ def _refusal_locked(self, link: _Link, focus: dict):+ """Section 4's decision order, after the stale route (steps 2 to 7). The take is made+ visible (`driven`) before `away()` is read, and stays so until it is refused or becomes+ the ownership; `away()` is called under the lock, so it must be a plain read."""+ if focus["malformed"]:+ return "malformed", None+ if not link.allow_drive:+ return "not_allowed", None+ self._claiming = link+ try:+ away = self._away()+ busy = bool(away)+ except Exception:+ LOGGER.exception("Could not tell whether this machine's input is elsewhere")+ busy = False+ away = None+ why = None+ other = None+ sent_home_at = self._sent_home_at.get(link.peer_id)+ if busy:+ why = "busy"+ if isinstance(away, bytes) and len(away) == protocol.MACHINE_ID_SIZE:+ other = away+ elif sent_home_at is not None and time.monotonic() - sent_home_at < SENT_HOME_SECONDS:+ why = "sent_home"+ elif self._owner is not None and self._owner is not link:+ why = "owned"+ other = self._owner.peer_id+ elif focus["stay"] and self._owner is not link:+ why = "malformed"+ if why is not None:+ self._claiming = None+ return (why, other) if why is not None else None++ def _own_locked(self, link: _Link, focus: dict, peers, zones) -> list:+ began = self._owner is not link+ # The owner is set before the claim is dropped, so `driven` never reads false between.+ self._owner = link+ self._claiming = None+ self._reach = frozenset(peer for peer in focus["reach"] if peer not in (link.peer_id, link.own_id))+ self._resistance = focus["resistance_px"]+ self._arm_locked(peers, zones)+ after = []+ if began:+ self._visit += 1+ self._clipboard_mark = self._clipboard_stamp()+ self._sent_home_for_lock = False+ self._locked_since = None+ self._owner_events.append(link.peer_id)+ if not focus["stay"]:+ # Held until the unlock has been asked for, so the lock check cannot send this owner+ # home in the moment between its arrival and the provider's chance to clear the lock.+ visit = self._visit+ self._arriving_visit = visit+ after.append(lambda: self._land(link, focus, visit))+ return after++ def _end_locked(self, link: Optional[_Link], let_go: bool = False, why: Optional[str] = None) -> list:+ """Ends `link`'s ownership, if it holds it (section 4): its keys and buttons released before+ anything else is injected, its zones dropped; on a let-go the clipboard, when something+ other than a `clipboard` message changed it; otherwise, with `why` and the link up, a+ `refuse`. Returns what is left to do without the lock."""+ if link is None or self._owner is not link:+ return []+ self._owner = None+ self._reach = frozenset()+ self._arriving_visit = None+ self._disarm_locked()+ self._cancel_forced_locked()+ self._release_locked(link)+ self._owner_events.append(None)+ after = []+ if let_go:+ mark, visit = self._clipboard_mark, self._visit+ after.append(lambda: self._clipboard_back(link, mark, visit))+ elif why is not None and not link.closed.is_set():+ link.post(protocol.refuse_msg(link.route, why))+ return after++ def send_home(self) -> bool:+ """Sends the owner home from here (section 5): its shortcut, a menu, a direction switch+ turned off, or Windows locking. False when nobody drives this machine. If the owner has not+ let go within FORCED_END_SECONDS, its ownership ends by force."""+ return self._send_home(None)++ def _send_home(self, expected: Optional[_Link]) -> bool:+ with self._lock:+ link = self._owner+ if link is None or (expected is not None and link is not expected):+ return False+ self._disarm_locked()+ self._sent_home_at[link.peer_id] = time.monotonic()+ LOGGER.info("Sending %s's input home from here", link.name)+ link.post(protocol.switch_v6(link.route, link.peer_id))+ self._cancel_forced_locked()+ timer = threading.Timer(FORCED_END_SECONDS, lambda: self._forced_end(link, timer))+ timer.daemon = True+ self._forced = timer+ timer.start()+ return True++ def _forced_end(self, link: _Link, timer) -> None:+ with self._lock:+ if self._forced is not timer or self._owner is not link:+ return+ LOGGER.info("%s did not let go after being sent home; its ownership ends here", link.name)+ self._sent_home_at[link.peer_id] = time.monotonic()+ after = self._end_locked(link, why="sent_home")+ self._run(after)++ def _cancel_forced_locked(self) -> None:+ if self._forced is not None:+ self._forced.cancel()+ self._forced = None++ def peers_changed(self) -> None:+ """Brings the links in step with the peers list after the app changed it: a removed peer's+ links close at once, ending its ownership first; a peer whose `allow_drive` changed is sent+ `accepts`, and turned off, loses its ownership with `refuse {why: "not_allowed"}`."""+ with self._lock:+ self._generation += 1+ peers, _ = self._settings_now()+ by_key_id = {}+ for peer in peers:+ found = _entry_key_id(peer)+ if found is not None:+ by_key_id[found] = peer+ after = []+ with self._lock:+ for link in list(self._links.values()):+ peer = by_key_id.get(link.key_id)+ if peer is None or peer.get("id") != protocol.id_text(link.peer_id):+ after += self._end_locked(link)+ LOGGER.info("%s was removed; its link is closed", link.name)+ link.close()+ continue+ if peer.get("in_use", True) is not True:+ after += self._end_locked(link)+ link.close()+ LOGGER.info("%s is not in use; its link is closed", link.name)+ continue+ allow_drive = peer.get("allow_drive") is True+ if allow_drive != link.allow_drive:+ link.allow_drive = allow_drive+ if not allow_drive:+ after += self._end_locked(link, why="not_allowed")+ link.post(protocol.accepts_msg(allow_drive))+ self._run(after)+ self._rearm_fresh()++ def send(self, peer: bytes, message: dict) -> bool:+ """Sends `message` on the link `peer` opened to this machine: False when there is none."""+ with self._lock:+ link = self._links.get(peer)+ return link is not None and link.post(message)++ # The clipboard (section 5)++ def _on_clipboard(self, link: _Link, message) -> None:+ read = protocol.read_clipboard(message)+ if read is None:+ return+ text = read["text"] if read["text"] and "clipboard" in link.own_caps else None+ image = read["image"] if "clipboard_image" in link.own_caps else None+ if text is None and image is None:+ return+ # Checked and set under one hold of the lock, so an ownership ending meanwhile cannot let+ # a peer that no longer owns this machine set its clipboard.+ with self._lock:+ if self._owner is not link:+ return+ try:+ if not self._clipboard_module().set_contents(text, image):+ LOGGER.warning("Could not set the clipboard %s sent", link.name)+ except Exception:+ LOGGER.exception("Could not set the clipboard %s sent", link.name)+ self._clipboard_mark = self._clipboard_stamp()++ def _clipboard_stamp(self):+ stamp = getattr(self._clipboard_module(), "change_stamp", None)+ if stamp is None:+ return None+ try:+ return stamp()+ except Exception:+ LOGGER.exception("Could not read the clipboard's change stamp")+ return None++ def _clipboard_back(self, link: _Link, mark, visit: int) -> None:+ """A let-go owner gets this machine's clipboard only when something other than its own+ `clipboard` messages changed it during the visit, so an idle machine gives nothing away;+ and never once another ownership has begun or the clipboard changed while it was read, so+ what it gets is never the next owner's."""+ stamp = self._clipboard_stamp()+ if stamp is None or stamp == mark:+ return+ try:+ text, image = self._clipboard_module().get_contents()+ except Exception:+ LOGGER.exception("Could not read the clipboard for %s", link.name)+ return+ if "clipboard" not in link.caps or not text or len(text.encode("utf-8", "replace")) > protocol.CLIPBOARD_MAX_BYTES:+ text = None+ if "clipboard_image" not in link.caps or image is None or not protocol.png_fits(image):+ image = None+ if text is None and image is None:+ return+ with self._lock:+ if self._visit == visit and self._owner is None and self._clipboard_stamp() == stamp:+ link.post(protocol.clipboard_msg(text, image))++ # Landing and the lock screen++ def _land(self, link: _Link, focus: dict, visit: int) -> None:+ """Places the pointer where a take by a zone says, or says where it is for one by the+ shortcut, then clears Windows' lock screen out of the way; nothing, once that visit is+ over."""+ try:+ with self._lock:+ current = self._visit == visit and self._owner is link+ if not current:+ return+ desktop = self._desktop_module()+ if focus["edge"] is not None:+ x, y = crossing.arrival_position(desktop.monitors(), focus["edge"], focus["offset"])+ desktop.set_cursor_position(x, y)+ LOGGER.info("%s's pointer arrived at this machine's %s edge", link.name, focus["edge"])+ self._callback("arrival", focus["edge"], x, y)+ else:+ x, y = desktop.cursor_position()+ self._callback("arrival", None, x, y)+ except Exception:+ LOGGER.exception("Could not land %s's pointer", link.name)+ try:+ self._begin_unlock(link)+ finally:+ with self._lock:+ if self._arriving_visit == visit:+ self._arriving_visit = None++ def _begin_unlock(self, link: _Link) -> None:+ unlock = self._unlock+ if unlock is None or self._unlocking.is_set():+ return+ try:+ if unlock.is_locked() is not True:+ return+ except Exception:+ LOGGER.exception("Could not tell whether this machine is locked")+ return+ self._unlocking.set()+ LOGGER.info("%s's input arrived at a locked machine; asking the provider to unlock", link.name)+ self._set_status(ServerState.CONNECTED, "Unlocking Windows…")+ threading.Thread(target=self._unlock_worker, args=(unlock, link), name="Beamer-v6-unlock", daemon=True).start()++ def _unlock_worker(self, unlock, link: _Link) -> None:+ try:+ unlocked = unlock.ensure_unlocked()+ except Exception:+ LOGGER.exception("The unlock failed")+ unlocked = False+ finally:+ self._unlocking.clear()+ # An unlock outlives an owner whose link ended during it: that end has reported, and a+ # failure must not say CONNECTED over it.+ if unlocked or self._owner is not link:+ self._report()+ else:+ self._set_status(ServerState.CONNECTED, "Windows is locked — unlock it at the PC")++ def _home_if_locked(self, link: _Link) -> None:+ """An owner left driving a machine on its lock screen is sent home,+ once per visit, after two checks LOCK_CHECK_SECONDS apart, and never while an unlock is in+ flight or the owner is arriving."""+ if self._unlock is None or self._owner is not link:+ return+ if self._unlocking.is_set() or self._arriving_visit is not None:+ self._locked_since = None+ return+ now = time.monotonic()+ if now - self._lock_checked_at < LOCK_CHECK_SECONDS:+ return+ self._lock_checked_at = now+ try:+ locked = self._unlock.is_locked() is True+ except Exception:+ locked = False+ if not locked:+ self._locked_since = None+ return+ if self._locked_since is None:+ self._locked_since = now+ return+ if not self._sent_home_for_lock:+ LOGGER.info("This machine is locked while %s drives it; sending its input home", link.name)+ self._sent_home_for_lock = self._send_home(link)++ # Plumbing++ def _injector_module(self):+ if self._injector is not None:+ return self._injector+ import input_injector+ return input_injector++ def _desktop_module(self):+ if self._desktop is not None:+ return self._desktop+ import desktop_win+ return desktop_win++ def _clipboard_module(self):+ if self._clipboard is not None:+ return self._clipboard+ import clipboard_win+ return clipboard_win++ def _callback(self, name: str, *args) -> None:+ callback = self._callbacks[name]+ if callback is None:+ return+ try:+ callback(*args)+ except Exception:+ LOGGER.exception("The %s callback failed", name)++ def _run(self, steps) -> None:+ """What an ownership change leaves to do without the lock: the owner callbacks it queued,+ first and in order, then `steps`."""+ self._tell_owner()+ for step in steps:+ try:+ step()+ except Exception:+ LOGGER.exception("A step after an ownership change failed")+ self._tell_owner()++ def _tell_owner(self) -> None:+ # One thread at a time delivers, so the order queued under the lock is the order heard.+ with self._notify_lock:+ while True:+ with self._lock:+ if not self._owner_events:+ return+ peer = self._owner_events.popleft()+ self._callback("owner", peer)++ def _report(self) -> None:+ with self._lock:+ links = list(self._links.values())+ port = self._port+ names = []+ if links:+ peers = self._settings_now()[0]+ names = sorted(peerlist.label_for(peers, peer_id=protocol.id_text(link.peer_id)) or link.name for link in links)+ if names:+ self._set_status(ServerState.CONNECTED, "Connected to " + ", ".join(names))+ else:+ self._set_status(ServerState.WAITING, f"Waiting on port {port}")++ def _set_status(self, state: ServerState, detail: str) -> None:+ try:+ self._status_callback(state, detail)+ except Exception:+ LOGGER.exception("Status callback failed")diff --cc core/settings_sync.pyindex 1e50da9,0000000..0796449mode 100644,000000..100644--- a/core/settings_sync.py+++ b/core/settings_sync.py@@@ -1,331 -1,0 +1,410 @@@+"""Same on all machines: the Crossing and Design settings every machine keeps in step (WIRE.md section 10).++Pure, with no AppKit and no Qt.+Off by default. While it is on, a change to a shared setting at any machine is sent to every peer+that takes `settings`; on every new link each end announces its own state and the newer stamp+stands. Turning it on at one machine turns it on at the others and carries its values across;+turning it off turns it off everywhere and leaves each machine with what it has.++Newer is a higher `set_at`, or the same `set_at` and the larger `by` (the id of the machine that+made the change) compared as bytes, so there is no Mac to break a tie. A machine that takes a newer+state sends it on, unchanged, to every other peer that takes `settings`; an older or equal one+is not sent on, which is what stops it.++The wire speaks the Mac's names. The PC's settings are flat fields with a `crossing_` prefix on+some, so each end has an adapter here: `mac_values`/`apply_mac` read and write the Mac's raw+settings dict, `pc_values`/`apply_pc` the PC's Config. The shortcut is a way in the 1.4.x+settings, so the adapters read and write it there.++Never shared, whatever the switch says: zones (the ways, thirds and corner), `side`, the direction+switches, the Mac's notch way in and notch look, the haptics, whether crossings animate on each+screen, whether a full-screen app holds the edges, appearance, and anything outside the Crossing+and Design pages.+"""++import base64+import binascii+import re+import time++from . import effects- from .protocol import MACHINE_ID_SIZE++from .protocol import MACHINE_ID_SIZE, MAX_PEERS++TRIGGER_STYLES = ("double_tap", "hold")+GLOW_STYLES = ("glow", "beam") + effects.EFFECT_IDS- GLOW_COLOURS = ("signal", "colourful", "ocean", "sunset", "mono") + effects.PACK_IDS++GLOW_COLOURS = ("signal", "colourful", "ocean", "sunset", "mono", "aurora") + effects.PACK_IDS+LENGTHS = tuple(value for value, _name in effects.LENGTHS)+# Keys a trigger cannot be, beside characters and media keys, which the receiver's own table rejects.+NOT_TRIGGERS = ("browser_back", "browser_forward", "backspace", "tab", "enter", "esc", "space", "print_screen")++CROSSING_KEYS = ("resistance_px", "block_while_dragging", "shortcut", "trigger_key", "trigger_style", "double_tap_ms")+DESIGN_KEYS = ("glow_style", "glow_colour", "effect_length", "effect_size", "shortcut_arrival", "shortcut_arrival_style")++DESIGN_UNAVAILABLE = "Design not available yet: connect to this machine with Beamer 1.5.0 beta.6 or later."++NEEDS_DESIGN_SYNC = "Needs beta.6 or later"++OLD_PEER_NOTE = "A connected machine is unavailable until it has beta.6 or later."++NO_MACHINE_CONNECTED = "No paired machine is connected."++MAX_STAMP = 2 ** 53 - 2+DAY = 24 * 60 * 60++# The PC's field for each wire key that is a field of its own; `shortcut` is a way in+# `crossing_methods`.+PC_FIELDS = {+ "resistance_px": "crossing_resistance_px", "block_while_dragging": "block_while_dragging",+ "trigger_key": "trigger_key", "trigger_style": "trigger_style", "double_tap_ms": "double_tap_ms",+ "glow_style": "glow_style", "glow_colour": "glow_colour", "effect_length": "effect_length",+ "effect_size": "effect_size",+ "shortcut_arrival": "shortcut_arrival", "shortcut_arrival_style": "shortcut_arrival_style",+}+# The Mac keeps the shortcut's key at the top of its settings and the rest in `crossing`.+MAC_TOP_LEVEL = ("trigger_key", "trigger_style", "double_tap_ms")+++def _whole(value, low, high):+ return not isinstance(value, bool) and isinstance(value, int) and low <= value <= high+++def _valid(key, value, trigger_keys):+ if key == "resistance_px":+ return _whole(value, 0, 500)+ if key in ("block_while_dragging", "shortcut", "shortcut_arrival"):+ return isinstance(value, bool)+ if key == "trigger_key":+ return isinstance(value, str) and value in trigger_keys and value not in NOT_TRIGGERS+ if key == "trigger_style":+ return value in TRIGGER_STYLES+ if key == "double_tap_ms":+ return _whole(value, 50, 2000)+ if key == "glow_style":+ return value in GLOW_STYLES+ if key == "glow_colour":+ return value in GLOW_COLOURS+ if key == "effect_length":+ return value in LENGTHS+ if key == "effect_size":+ return value in tuple(size for size, _name in effects.SIZES)+ if key == "shortcut_arrival_style":+ return value in effects.SWITCH_STYLES+ return False+++def message_data(on, set_at, values=None, by="", design_state=None):+ """What a `settings` message carries: whether it is on, when that or a shared value last+ changed and by which machine (`by`, its id as base64), and while on, the values."""+ data = {"on": bool(on), "set_at": int(set_at), "by": by}+ if on and values is not None:+ data["crossing"] = {key: values[key] for key in CROSSING_KEYS if key in values}+ data["design"] = {key: values[key] for key in DESIGN_KEYS if key in values}+ if design_state is not None:+ data["design_sync"] = design_state+ return data+++def read_design_state(data, trigger_keys, now=None):+ """A directly advertised local Design state from a settings message, or None if absent or+ invalid. Each supported value stands alone, as for Same on all machines. The outer settings+ envelope is validated first, so a valid optional member cannot rescue a malformed message."""+ if not _valid_envelope(data, now):+ return None+ state = data.get("design_sync")+ if not isinstance(state, dict) or type(state.get("set_at")) is not int:+ return None+ by = state.get("by", "")+ if _id(by) is None:+ return None+ set_at = state["set_at"]+ if set_at < 0 or set_at > MAX_STAMP or set_at > (time.time() if now is None else now) + DAY:+ return None+ values = state.get("values")+ if not isinstance(values, dict):+ return None+ accepted = {key: values[key] for key in DESIGN_KEYS+ if key in values and _valid(key, values[key], trigger_keys)}+ if "effect_size" not in values:+ accepted["effect_size"] = "medium"- return {"set_at": set_at, "by": by, "values": accepted}++ result = {"set_at": set_at, "by": by, "values": accepted}++ if "path" in state:++ path = state["path"]++ if (not isinstance(path, list) or not 1 <= len(path) <= MAX_PEERS + 1++ or any(not item or _id(item) is None for item in path)++ or len({_id(item) for item in path}) != len(path)):++ return None++ result["path"] = list(path)++ return result+++def design_arrived(state, set_at_here, by_here=""):+ """Whether a validated Design state is newer than the one this machine currently holds."""+ if not isinstance(state, dict):+ return False+ by = _id(state.get("by", ""))+ if by is None:+ return False+ held_by = _id(by_here) or b""+ set_at = state.get("set_at")+ return type(set_at) is int and (set_at > int(set_at_here or 0) or+ (set_at == int(set_at_here or 0) and by > held_by))++- def followed_design(current, state, source, follower, same_on, set_at_here, by_here):- """A newer direct state to apply locally, or None. Its stamp remains the leader's so every- follower in a chain carries the same newest state; identical values need no announcement."""- if (state is None or source != follower or same_on- or not design_arrived(state, set_at_here, by_here)):++def followed_design(current, state, source, follower, same_on, set_at_here, by_here,++ own_id="", force=False):++ """Adopt a selected leader, then compare versions against that leader's last adopted state.++ The returned stamp is the adoption cursor, never this machine's advertisement version."""++ if state is None or source != follower or same_on:++ return None++ path = list(state.get("path", []))++ if not path:++ path = list({_id(item): item for item in (state.get("by"), source) if item}.values())++ if own_id and any(_id(item) == _id(own_id) for item in path):++ return {"cycle": True}++ if not force and not design_arrived(state, set_at_here, by_here):+ return None+ values = dict(current)+ for key in DESIGN_KEYS:+ if key in state["values"]:+ values[key] = state["values"][key]+ changed = any(current.get(key) != values.get(key) for key in DESIGN_KEYS)- if not changed:- return {"changed": False, "values": values, "set_at": state["set_at"], "by": state["by"]}- return {"changed": True, "values": values, "set_at": state["set_at"], "by": state["by"]}++ result = {"changed": changed, "values": values, "set_at": state["set_at"], "by": state["by"]}++ if own_id:++ result["path"] = path + [own_id]++ return result++++++def follow_rows(desktops, caps, states, following=""):++ """Match design with's machines, as [(entry, why_not)]: the paired desktops linked now, and the++ one followed even while it is away so the selection still shows. `caps` is {id: capabilities}++ for the live links only, `states` the Design states received. `why_not` is None for a machine++ that can be chosen, NEEDS_DESIGN_SYNC for one whose link lacks `design_sync`, else++ DESIGN_UNAVAILABLE until its state arrives. No version string is read: capability decides."""++ rows = []++ for entry in desktops:++ peer = entry.get("id", "")++ if not peer or (peer not in caps and peer != following):++ continue++ known = caps.get(peer)++ if known is not None and "design_sync" not in known:++ rows.append((entry, NEEDS_DESIGN_SYNC))++ else:++ rows.append((entry, None if peer in states else DESIGN_UNAVAILABLE))++ return rows++++++def follow_note(rows):++ """The one line under Match design with when nothing is followed and no machine can be chosen,++ or None when one can. Offline machines are not listed, so they never set it."""++ reasons = [why_not for _entry, why_not in rows]++ if not reasons:++ return NO_MACHINE_CONNECTED++ if None in reasons:++ return None++ return OLD_PEER_NOTE if NEEDS_DESIGN_SYNC in reasons else DESIGN_UNAVAILABLE++++++STOP_FOLLOWING = "Stop following"++++++def follow_lock(following, same_on, desktops):++ """The paired desktop whose Design this machine follows, while the followed Design controls++ (DESIGN_KEYS: style, landing animation, colour, length, size) are locked; None while they are++ this machine's to change. Same on all machines pauses following, so it unlocks them. The lock++ holds while the followed machine is away: its last design stays until Stop following."""++ if not following or same_on:++ return None++ return next((entry for entry in desktops if entry.get("id") == following), None)++++++def following_banner(name):++ return f"Following {name}'s design"+++def design_change_stamp(current, incoming, set_at_here, source_state, own_id, now=None):+ """A Same-on Design change announced as this machine's direct state, or None if unchanged."""+ if not isinstance(current, dict) or not isinstance(incoming, dict):+ return None+ if not any(current.get(key) != incoming.get(key) for key in DESIGN_KEYS):+ return None+ held = int(set_at_here or 0)+ if isinstance(source_state, dict) and type(source_state.get("set_at")) is int:+ held = max(held, source_state["set_at"])+ stamp = next_stamp(held, time.time() if now is None else now)+ return {"set_at": stamp, "by": own_id}+++def read(data, trigger_keys, now=None):+ """(on, set_at, values) from a `settings` message's data, or None when it is not one. A value+ this end cannot hold -- a key it does not have, an effect it does not know, a zone -- is left+ out rather than failing the rest. Never raises: a malformed message must not take a link down."""+ if not _valid_envelope(data, now):+ return None+ set_at = data["set_at"]+ values = {}+ for group, keys in (("crossing", CROSSING_KEYS), ("design", DESIGN_KEYS)):+ section = data.get(group)+ if not isinstance(section, dict):+ continue+ for key in keys:+ if key in section and _valid(key, section[key], trigger_keys):+ values[key] = section[key]+ return data["on"], set_at, values+++# Machine ids travel as PAIRING.md's b64 (URL-safe, unpadded); the standard alphabet and padding are read too.+_ID_SHAPE = re.compile(r"[A-Za-z0-9_+/-]*={0,2}")+++def _id(text):+ """The bytes of a `by`, or None when it is not the base64 of a 16 byte machine id. A message with none is from nobody, b''."""+ if text == "":+ return b""+ if not isinstance(text, str):+ return None+ if not _ID_SHAPE.fullmatch(text):+ return None+ try:+ ident = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))+ except (binascii.Error, ValueError):+ return None+ return ident if len(ident) == MACHINE_ID_SIZE else None+++def _valid_envelope(data, now=None):+ if not isinstance(data, dict) or not isinstance(data.get("on"), bool):+ return False+ set_at = data.get("set_at")+ if type(set_at) is not int or _id(data.get("by", "")) is None:+ return False+ return (0 <= set_at <= MAX_STAMP+ and set_at <= (time.time() if now is None else now) + DAY)+++def next_stamp(held, now):+ """The stamp for a change made here: now, or one past the stamp held if that is not older.+ Two changes in one second would otherwise tie and the second be ignored at the other end, and+ a peer whose clock runs ahead would win every time."""+ return max(int(now), int(held or 0) + 1)+++def arrived(data, set_at_here, trigger_keys, by_here="", now=None):+ """What to do with a `settings` message that arrived: (on, set_at, values) to take in place of+ this end's state, or None to keep it -- malformed, a stamp more than a day ahead of `now` or+ above 2^53 - 2, or no newer than what is held here.++ Newer is a higher stamp, or the same stamp and the larger `by` as bytes; `by_here` is the id+ that made the change this end holds. Equal in both is the copy that arrives over a second+ link, and changes nothing, so a state sent on never comes back round."""+ read_back = read(data, trigger_keys, now)+ by = _id(data.get("by", "")) if read_back is not None else None+ if read_back is None or by is None:+ return None+ set_at = read_back[1]+ if set_at > MAX_STAMP or set_at > (time.time() if now is None else now) + DAY:+ return None+ mine = int(set_at_here or 0)+ if set_at > mine or (set_at == mine and by > (_id(by_here) or b"")):+ return read_back+ return None+++def recipients(peers, source=None):+ """Whom a state goes to: every peer that lists `settings` among its capabilities, except the+ one it came from. `peers` maps a peer's id to its capabilities."""+ return [peer for peer, capabilities in peers.items() if peer != source and "settings" in capabilities]+++def _in_order(values):+ """The shortcut is a bool, whatever the adapter read."""+ values["shortcut"] = bool(values.get("shortcut"))+ return values+++def _with_shortcut(methods, on):+ """`methods` with the shortcut on or off and every other way as it was."""+ ways = [way for way in methods if way != "shortcut"]+ return ways + ["shortcut"] if on else ways+++def mac_values(raw):+ """The shared values in the Mac's raw settings dict (settings_store.config_to_raw)."""+ crossing = raw.get("crossing", {})+ values = {key: raw[key] if key in MAC_TOP_LEVEL else crossing.get(key)+ for key in CROSSING_KEYS + DESIGN_KEYS if key != "shortcut"}+ values["effect_size"] = crossing.get("effect_size", "medium")+ values["shortcut"] = "shortcut" in crossing.get("methods", [])+ return _in_order(values)+++def apply_mac(raw, values):+ """A copy of the Mac's raw settings with `values` in place. The other ways, the notch among+ them, stay as they were: they are this Mac's own zones."""+ raw = dict(raw)+ crossing = dict(raw.get("crossing", {}))+ for key, value in values.items():+ if key in MAC_TOP_LEVEL:+ raw[key] = value+ elif key == "shortcut":+ crossing["methods"] = _with_shortcut(crossing.get("methods", []), value)+ else:+ crossing[key] = value+ raw["crossing"] = crossing+ return raw+++def pc_values(config):+ """The shared values in the PC's Config."""+ values = {key: getattr(config, field) for key, field in PC_FIELDS.items()}+ values["effect_size"] = getattr(config, "effect_size", "medium")+ values["shortcut"] = "shortcut" in config.crossing_methods+ return _in_order(values)+++def apply_pc(config, values):+ """Sets `values` on the PC's Config in place."""+ for key, value in values.items():+ if key == "shortcut":+ config.crossing_methods = _with_shortcut(config.crossing_methods, value)+ else:+ setattr(config, PC_FIELDS[key], value)+++def changed(before, after):+ """Whether any shared value differs between two value dicts."""+ return any(before.get(key) != after.get(key) for key in CROSSING_KEYS + DESIGN_KEYS)+++SHARED_PAGES = ("crossing", "design")+++def who(labels):+ """How the notes name the machines the pages are kept in step with: the one paired machine by its+ label, else every paired machine."""+ return labels[0] if len(labels) == 1 else "every paired machine"++- def scope(page, who, on, own):++def scope(page, who, on, own, platform=""):+ """The line under a page's purpose: `own` (the page's usual "for this machine only") unless+ the page is kept in step and the switch is on. `who` is from `who()`."""+ if on and page in SHARED_PAGES:- return f"Kept the same as {who}. Change it on any machine."++ if page == "crossing":++ return "Resistance, drag protection and Shortcut stay in step. Ways and jump keys below are local; each side is shared with its paired machine."++ text = "Style, colour, length, size and landing animation stay in step. Animation enable and window appearance stay local."++ if platform == "mac":++ text += " Notch and trackpad controls stay local."++ return text+ return own+++def switch_note(who, on, peer_too_old):+ """The note under Overview's Same on all machines switch; `who` names the machines it keeps in step with."""+ if peer_too_old:+ return f"{who}'s Beamer is too old to keep settings in step. Update it to turn this on."- if on:- return f"The Crossing and Design pages match {who}'s. A change on any machine reaches the rest."- return (f"Off: the Crossing and Design pages are this machine's own. On, they match {who}'s, "- "and a change on any machine reaches the rest.")++ if not on:++ return "Off: each machine keeps its current values; previous separate values are not restored."++ with_machines = "compatible paired machines" if who == "every paired machine" else f"compatible versions of {who}"++ return "Shares resistance, drag protection, Shortcut and six animation settings with " + with_machines + "."++++++def switch_detail(platform=""):++ text = "Connected machines with compatible Beamer versions update now; others catch up when they reconnect. Zones, sides, jump keys, full-screen hold, animation enable and appearance stay on each machine."++ if platform == "mac":++ text += " Notch and trackpad controls stay on this Mac."++ return textdiff --cc core/tests/app_methods.pyindex 0000000,0000000..21b5c27new file mode 100644--- /dev/null+++ b/core/tests/app_methods.py@@@ -1,0 -1,0 +1,16 @@@++"""Run app decisions without constructing windows, installing hooks or loading user settings."""++++import ast++from pathlib import Path++++++def load_methods(relative_path, class_name, names, namespace):++ path = Path(__file__).resolve().parents[2] / relative_path++ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))++ cls = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == class_name)++ methods = [node for node in cls.body if isinstance(node, ast.FunctionDef) and node.name in names]++ for method in methods:++ method.decorator_list = []++ module = ast.Module(body=methods, type_ignores=[])++ exec(compile(module, str(path), "exec"), namespace)++ return type(class_name, (), {name: namespace[name] for name in names})diff --cc core/tests/colour_packs_rc3.jsonindex 0000000,0000000..64f15banew file mode 100644--- /dev/null+++ b/core/tests/colour_packs_rc3.json@@@ -1,0 -1,0 +1,119 @@@++{++ "signal": [++ "#5fd4f4"++ ],++ "colourful": [++ "#ff3264",++ "#ff7828",++ "#f032b4",++ "#b428f0",++ "#6446ff",++ "#288cff",++ "#1eb9aa",++ "#32c850"++ ],++ "ocean": [++ "#288cff",++ "#6446ff",++ "#1eb9aa",++ "#3c6eff"++ ],++ "sunset": [++ "#ff7828",++ "#ff3264",++ "#ffb43c",++ "#f03278"++ ],++ "mono": [++ "#ebebeb",++ "#969696",++ "#ebebeb"++ ],++ "oil_slick": [++ "#8a4dff",++ "#2f7dff",++ "#16c6b0",++ "#9fdc4a",++ "#f0c23c",++ "#e8477f"++ ],++ "soap_bubble": [++ "#ffd98e",++ "#ff9cc2",++ "#c3a6ff",++ "#8fcfff",++ "#9ef2cf"++ ],++ "pearl": [++ "#fbf4e8",++ "#f2c9d6",++ "#c6dcf2",++ "#d9f0dc",++ "#ffffff"++ ],++ "ember": [++ "#ffe4ad",++ "#ffb04a",++ "#ff6a24",++ "#d8321a",++ "#8e1a10"++ ],++ "forge": [++ "#fff4dc",++ "#ffc15e",++ "#ff7f2a",++ "#b8c4d2",++ "#5d7896"++ ],++ "sparkler_gold": [++ "#ffffff",++ "#fff1bf",++ "#ffd35c",++ "#f0a531"++ ],++ "phosphor": [++ "#3dff7f",++ "#1f9e52",++ "#caffdc"++ ],++ "sodium": [++ "#ffa51f",++ "#c46a12",++ "#ffe0a3"++ ],++ "contrast": [++ "#f0e442",++ "#56b4e9",++ "#ffffff"++ ],++ "vellum": [++ "#c69a60",++ "#f0ddac",++ "#88674c"++ ],++ "carbon_copy": [++ "#6688ae",++ "#bbcad9",++ "#344d72"++ ],++ "marbled": [++ "#bd6858",++ "#6c9691",++ "#e1bb78"++ ],++ "flax": [++ "#cfb885",++ "#8a9c84",++ "#efdfb8"++ ],++ "madder": [++ "#c45b68",++ "#873d57",++ "#e5b09b"++ ],++ "tide": [++ "#58a9a3",++ "#547498",++ "#b1d1c1"++ ]++}diff --cc core/tests/profile_effect_sets.pyindex 0000000,0000000..ffb0291new file mode 100644--- /dev/null+++ b/core/tests/profile_effect_sets.py@@@ -1,0 -1,0 +1,130 @@@++"""Offscreen Qt cost breakdown and before/after render comparison; no app or settings access."""++++import argparse++from collections import Counter, defaultdict++import json++from pathlib import Path++import statistics++import sys++import time++++from render_effect_sets import Bitmap, effects, preview++++++def p95(values):++ return round(sorted(values)[int(len(values) * 0.95)], 3)++++++class TimedPainter:++ def __init__(self, painter):++ self.painter = painter++ self.cost = defaultdict(float)++ self.calls = Counter()++++ def __getattr__(self, name):++ method = getattr(self.painter, name)++ def measured(*args):++ start = time.perf_counter()++ result = method(*args)++ self.cost[name] += (time.perf_counter() - start) * 1000++ self.calls[name] += 1++ return result++ return measured++++++def profile():++ import effect_overlay++ rows = []++ for effect_id in ("concertina", "jacquard"):++ fx = effects.effect(effect_id)++ palette = effects.pack("marbled" if effect_id == "concertina" else "tide")[1]++ bitmap = Bitmap(3280, 900, 2)++ timed = TimedPainter(bitmap.painter)++ measurements = defaultdict(list)++ counts = Counter()++ original = effect_overlay.qpath++ def path(*args):++ start = time.perf_counter()++ result = original(*args)++ timed.cost["qpath"] += (time.perf_counter() - start) * 1000++ return result++ effect_overlay.qpath = path++ try:++ for i in range(180):++ timed.cost.clear()++ timed.calls.clear()++ start = time.perf_counter()++ scene = effects.preview_scene(fx, 1.1 + (i % 90) * 0.025, "edge", palette, dark=bool(i % 2))++ recorded = time.perf_counter()++ bitmap.clear(bool(i % 2))++ cleared = time.perf_counter()++ effect_overlay.replay(timed, scene["pens"])++ ended = time.perf_counter()++ if i >= 20:++ measurements["generation"].append((recorded - start) * 1000)++ measurements["clear"].append((cleared - recorded) * 1000)++ measurements["replay"].append((ended - cleared) * 1000)++ measurements["total"].append((ended - start) * 1000)++ for name in ("qpath", "fillPath", "strokePath", "setOpacity", "setCompositionMode"):++ measurements[name].append(timed.cost[name])++ counts.update(timed.calls)++ counts.update({"segments": sum(len(op[1]) for pen in scene["pens"] for op in pen.ops),++ "gradients": sum(isinstance(op[2], effects.Gradient) for pen in scene["pens"] for op in pen.ops)})++ finally:++ effect_overlay.qpath = original++ bitmap.close()++ rows.append(dict(effect=effect_id,++ p95_ms={k: p95(v) for k, v in measurements.items()},++ mean_ms={k: round(statistics.mean(v), 3) for k, v in measurements.items()},++ calls_per_frame={k: round(v / 160, 2) for k, v in counts.items()}))++ print(json.dumps(rows, indent=2))++++++def renders(folder, compare, scale):++ from PIL import Image, ImageChops++ folder.mkdir(parents=True, exist_ok=True)++ frames, changed, maximum, total_difference = 0, 0, 0, 0++ for effect_id in ("concertina", "jacquard"):++ fx = effects.effect(effect_id)++ for pack in (("vellum", "carbon_copy", "marbled") if effect_id == "concertina" else ("flax", "madder", "tide")):++ palette = effects.pack(pack)[1]++ for dark in (True, False):++ for method in ("edge", "corner", "notch", "switch"):++ for index, t in enumerate((0.92, 1.35, 1.78, 2.18, 2.27, 2.44, 2.7)):++ picture = preview(fx, t, palette, dark, method, scale=scale)++ name = f"{effect_id}-{pack}-{dark}-{method}-{index}.png"++ target = folder / name++ frames += 1++ if compare:++ with Image.open(target) as before:++ if before.size != picture.size:++ raise ValueError(f"Render dimensions differ: {name}")++ difference = ImageChops.difference(before, picture)++ histogram = difference.histogram()++ peak = max(max(pair) for pair in difference.getextrema())++ maximum = max(maximum, peak)++ total_difference += sum((i % 256) * n for i, n in enumerate(histogram))++ if difference.getbbox():++ changed += 1++ picture.save(folder / name.replace(".png", "-after.png"))++ else:++ picture.save(target)++ print(json.dumps(dict(frames=frames, scale=scale, changed_frames=changed, maximum_channel_difference=maximum,++ total_channel_difference=total_difference), indent=2))++ if compare and changed:++ raise SystemExit("Renders differ")++++++if __name__ == "__main__":++ parser = argparse.ArgumentParser(description=__doc__)++ parser.add_argument("--profile", action="store_true")++ parser.add_argument("--renders", type=Path)++ parser.add_argument("--compare", action="store_true")++ parser.add_argument("--scale", type=float, default=0.6)++ args = parser.parse_args()++ if args.profile:++ if sys.platform == "darwin":++ parser.error("--profile measures the Qt replay")++ profile()++ if args.renders:++ renders(args.renders, args.compare, args.scale)diff --cc core/tests/render_effect_parity.pyindex 0000000,0000000..a7f3f41new file mode 100644--- /dev/null+++ b/core/tests/render_effect_parity.py@@@ -1,0 -1,0 +1,279 @@@++"""Render matching offscreen effect frames on Qt or Core Graphics.++++The Windows output is the reference for the Mac replay. This imports no app entrypoint and++creates no window. Run from either platform's Beamer worktree with that platform's Python.++"""++++import argparse++import json++import math++import struct++import sys++import zipfile++import zlib++from pathlib import Path++++ROOT = Path(__file__).resolve().parents[2]++sys.path.insert(0, str(ROOT))++sys.path.insert(0, str(ROOT / ("mac_app" if sys.platform == "darwin" else "win_app")))++++from core import effects++from tokens import PALETTES++++TIMES = (0.92, 1.35, 1.78, 2.18, 2.27, 2.44, 2.7)++STAGES = ("push10", "push45", "push85", "threshold", "give", "arrival", "settle")++SCALE = 0.6++FORCE_NORMAL = False++++++def catalogue():++ yield "Light", "glow", "signal"++ yield "Light", "beam", "signal"++ yield "Light", "aperture", "signal"++ for _module, name, effect_ids, pack_ids in effects.ALL_DIRECTIONS:++ for effect_id in effect_ids:++ yield name, effect_id, pack_ids[0]++++++def png_bytes(width, height, rgba):++ def chunk(kind, data):++ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff)++++ rows = b"".join(b"\0" + rgba[y * width * 4:(y + 1) * width * 4] for y in range(height))++ return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">2I5B", width, height, 8, 6, 0, 0, 0))++ + chunk(b"IDAT", zlib.compress(rows, 6)) + chunk(b"IEND", b""))++++++class Bitmap:++ def __init__(self, width, height, *, scale=SCALE, transparent=False, dark=True):++ self.width, self.height, self.scale = width, height, scale++ if sys.platform == "darwin":++ import Quartz as cg++ from effects_overlay import replay++ if FORCE_NORMAL:++ native_cg = cg++ class NormalBlend:++ def __getattr__(self, name):++ return native_cg.kCGBlendModeNormal if name == "kCGBlendModePlusLighter" else getattr(native_cg, name)++ cg = NormalBlend()++ self.cg, self.replay = cg, replay++ self.data = bytearray(width * height * 4)++ self.ctx = cg.CGBitmapContextCreate(++ self.data, width, height, 8, width * 4,++ cg.CGColorSpaceCreateWithName(cg.kCGColorSpaceSRGB),++ cg.kCGImageAlphaPremultipliedLast | cg.kCGBitmapByteOrder32Big,++ )++ cg.CGContextTranslateCTM(self.ctx, 0, height)++ cg.CGContextScaleCTM(self.ctx, scale, -scale)++ if not transparent:++ rgb = (0.065, 0.075, 0.09) if dark else (0.93, 0.92, 0.89)++ cg.CGContextSetRGBFillColor(self.ctx, *rgb, 1)++ cg.CGContextFillRect(self.ctx, ((-4000, -4000), (8000, 8000)))++ else:++ from PySide6.QtGui import QImage, QPainter, QColor++ from effect_overlay import replay++ self.replay = replay++ self.image = QImage(width, height, QImage.Format.Format_RGBA8888_Premultiplied)++ self.image.fill(0)++ self.painter = QPainter(self.image)++ self.painter.setRenderHint(QPainter.RenderHint.Antialiasing)++ self.painter.scale(scale, scale)++ if not transparent:++ rgb = (0.065, 0.075, 0.09) if dark else (0.93, 0.92, 0.89)++ self.painter.fillRect(-4000, -4000, 8000, 8000, QColor.fromRgbF(*rgb, 1))++++ def draw(self, pens):++ if sys.platform == "darwin":++ self.replay(self.cg, self.ctx, pens)++ else:++ self.replay(self.painter, pens)++++ def raw(self):++ if sys.platform == "darwin":++ return bytes(self.data)++ return bytes(self.image.bits())++++ def close(self):++ if sys.platform != "darwin":++ self.painter.end()++++++def frame(effect_id, pack_id, t, *, dark=True, transparent=False):++ fx = effects.preview_effect(effect_id) or effects.effect(effect_id)++ found = effects.pack(pack_id)++ palette = found[1] if found is not None else PALETTES[pack_id]++ scene = effects.preview_scene(fx, t, "edge", palette, dark=dark)++ scene_width, scene_height = effects.preview_size("edge")++ width, height = round(scene_width * SCALE), round(scene_height * SCALE)++ bitmap = Bitmap(width, height, scale=SCALE, transparent=transparent, dark=dark)++ if not transparent:++ boundary = effects.Pen()++ boundary.fillStyle = "#030406" if dark else "#d0cec8"++ boundary.fillRect(800, 0, 40, 450)++ bitmap.draw([boundary])++ for pen in scene["pens"]:++ x, y, w, h, _os = max(scene["screens"], key=lambda screen: max(++ 0, min(pen.bounds[2], screen[0] + screen[2]) - max(pen.bounds[0], screen[0])++ ) * max(0, min(pen.bounds[3], screen[1] + screen[3]) - max(pen.bounds[1], screen[1])))++ pen.clip = (x, y, x + w, y + h)++ bitmap.draw(scene["pens"])++ if not transparent and scene["pointer"]:++ x, y, _os = scene["pointer"]++ pointer = effects.Pen()++ pointer.fillStyle = "#f7f5ef" if dark else "#24262c"++ pointer.beginPath()++ pointer.moveTo(x, y)++ pointer.lineTo(x + 5, y + 16)++ pointer.lineTo(x + 8, y + 10)++ pointer.lineTo(x + 15, y + 8)++ pointer.closePath()++ pointer.fill()++ bitmap.draw([pointer])++ raw = bitmap.raw()++ bitmap.close()++ return width, height, raw++++++def render(output):++ output.mkdir(parents=True, exist_ok=True)++ manifest = []++ for direction, effect_id, pack_id in catalogue():++ for dark in (True, False):++ mode = "dark" if dark else "light"++ for t, stage in zip(TIMES, STAGES):++ width, height, rgba = frame(effect_id, pack_id, t, dark=dark)++ stem = f"{effect_id}-{mode}-{stage}"++ (output / f"{stem}.rgba.z").write_bytes(zlib.compress(rgba, 6))++ (output / f"{stem}.png").write_bytes(png_bytes(width, height, rgba))++ if effect_id == "beam":++ _width, _height, alpha = frame(effect_id, pack_id, t, dark=dark, transparent=True)++ (output / f"beam-{mode}-{stage}-alpha.rgba.z").write_bytes(zlib.compress(alpha, 6))++ manifest.append({"set": direction, "effect": effect_id, "pack": pack_id, "mode": mode,++ "stage": stage, "time": t, "width": width, "height": height})++ (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")++ print(f"Rendered {len(manifest)} RGBA frames with {sys.platform} to {output}")++++++def compare(windows, mac, output):++ output.mkdir(parents=True, exist_ok=True)++ results = []++ profiles = []++ try:++ import numpy as np++ except ImportError:++ np = None++ for direction, effect_id, pack_id in catalogue():++ frames = []++ strip = bytearray()++ for mode in ("dark", "light"):++ for stage in STAGES:++ stem = f"{effect_id}-{mode}-{stage}"++ win = zlib.decompress((windows / f"{stem}.rgba.z").read_bytes())++ mac_raw = zlib.decompress((mac / f"{stem}.rgba.z").read_bytes())++ if len(win) != len(mac_raw):++ raise ValueError(f"dimensions differ: {stem}")++ scene_width, scene_height = effects.preview_size("edge")++ width, height = round(scene_width * SCALE), round(scene_height * SCALE)++ edge = round(800 * SCALE)++ left, right = max(0, edge - round(150 * SCALE)), min(width, edge + round(150 * SCALE))++ if np is not None:++ win_pixels = np.frombuffer(win, dtype=np.uint8).reshape(height, width, 4)++ mac_pixels = np.frombuffer(mac_raw, dtype=np.uint8).reshape(height, width, 4)++ pixel_diffs = np.abs(win_pixels[:, left:right].astype(np.int16)++ - mac_pixels[:, left:right].astype(np.int16)).max(axis=2)++ maximum = int(pixel_diffs.max())++ total = int(pixel_diffs.sum())++ y, x_local = np.unravel_index(int(pixel_diffs.argmax()), pixel_diffs.shape)++ x = int(x_local) + left++ offset = (int(y) * width + x) * 4++ max_location = (x, int(y), tuple(win[offset:offset + 4]), tuple(mac_raw[offset:offset + 4]))++ if stage == "push85":++ for row in range(height):++ start, end = row * width * 4, (row + 1) * width * 4++ strip.extend(win[start:end])++ strip.extend(mac_raw[start:end])++ else:++ maximum = 0++ total = 0++ max_location = None++ for y in range(height):++ row = y * width * 4++ for x in range(left, right):++ offset = row + x * 4++ delta = max(abs(win[offset + c] - mac_raw[offset + c]) for c in range(4))++ total += delta++ if delta > maximum:++ maximum = delta++ max_location = (x, y, tuple(win[offset:offset + 4]), tuple(mac_raw[offset:offset + 4]))++ if stage == "push85":++ start, end = row, row + width * 4++ strip.extend(win[start:end])++ strip.extend(mac_raw[start:end])++ pixels = (right - left) * height++ frames.append({"mode": mode, "stage": stage, "roi": [left, 0, right, height],++ "mean_pixel_difference": round(total / pixels, 4), "max_pixel_difference": maximum,++ "max_pixel_location_and_rgba": max_location})++ if effect_id == "beam":++ win_alpha = zlib.decompress((windows / f"beam-{mode}-{stage}-alpha.rgba.z").read_bytes())++ mac_alpha = zlib.decompress((mac / f"beam-{mode}-{stage}-alpha.rgba.z").read_bytes())++ alpha_radius = round(40 * SCALE)++ alpha_left, alpha_right = edge - alpha_radius, edge + 1++ win_profile = [round(sum(win_alpha[(y * width + x) * 4 + 3]++ for y in range(height)) / height, 3)++ for x in range(alpha_left, alpha_right)]++ mac_profile = [round(sum(mac_alpha[(y * width + x) * 4 + 3]++ for y in range(height)) / height, 3)++ for x in range(alpha_left, alpha_right)]++ profiles.append({"mode": mode, "stage": stage, "x": list(range(alpha_left, alpha_right)),++ "windows": win_profile, "mac": mac_profile,++ "mean_difference": round(sum(abs(a - b) for a, b in zip(win_profile, mac_profile))++ / len(win_profile), 4),++ "max_difference": round(max(abs(a - b) for a, b in zip(win_profile, mac_profile)), 3)})++ results.append({"set": direction, "effect": effect_id, "pack": pack_id, "frames": frames})++ sheet_width, sheet_height = width * 2, height * 2++ (output / f"{effect_id}-side-by-side.png").write_bytes(png_bytes(sheet_width, sheet_height, strip))++ (output / "metrics.json").write_text(json.dumps(results, indent=2) + "\n", encoding="utf-8")++ (output / "beam-alpha-profiles.json").write_text(json.dumps(profiles, indent=2) + "\n", encoding="utf-8")++ for row in results:++ values = row["frames"]++ mean = sum(frame["mean_pixel_difference"] for frame in values) / len(values)++ maximum = max(frame["max_pixel_difference"] for frame in values)++ print(f"{row['effect']:16} {row['pack']:16} mean={mean:7.3f} max={maximum:3}")++++++def pack_reference(windows, output):++ manifest = []++ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as archive:++ for direction, effect_id, pack_id in catalogue():++ if effect_id == "beam":++ for mode in ("dark", "light"):++ for stage in STAGES:++ name = f"beam-{mode}-{stage}-alpha.rgba.z"++ archive.write(windows / name, name)++ continue++ for mode in ("dark", "light"):++ name = f"{effect_id}-{mode}-push85.rgba.z"++ archive.write(windows / name, name)++ manifest.append({"set": direction, "effect": effect_id, "pack": pack_id,++ "mode": mode, "stage": "push85", "frame": name})++ archive.writestr("manifest.json", json.dumps(manifest, indent=2) + "\n")++ print(f"Packed Windows reference frames to {output}")++++++if __name__ == "__main__":++ parser = argparse.ArgumentParser(description=__doc__)++ parser.add_argument("--output", type=Path)++ parser.add_argument("--compare", nargs=2, type=Path, metavar=("WINDOWS", "MAC"))++ parser.add_argument("--comparison-output", type=Path)++ parser.add_argument("--force-normal", action="store_true")++ parser.add_argument("--scale", type=float, default=SCALE)++ parser.add_argument("--pack-reference", nargs=2, type=Path, metavar=("WINDOWS", "OUTPUT"))++ args = parser.parse_args()++ SCALE = args.scale++ FORCE_NORMAL = args.force_normal++ if args.output:++ render(args.output)++ if args.compare:++ compare(*args.compare, args.comparison_output or args.compare[1] / "side-by-side")++ if args.pack_reference:++ pack_reference(*args.pack_reference)diff --cc core/tests/render_effect_sets.pyindex 19763ad,0000000..dd0aefbmode 100644,000000..100644--- a/core/tests/render_effect_sets.py+++ b/core/tests/render_effect_sets.py@@@ -1,254 -1,0 +1,254 @@@+"""Offscreen judging sequences and native frame timings; never constructs an app window.++Run with the Mac venv and --output PATH for renders, or either platform's venv and --benchmark.+"""++import argparse+import json+import statistics+import sys+import time+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / ("mac_app" if sys.platform == "darwin" else "win_app")))++from core import effects++NEW_IDS = ("aperture", "crease", "pleat", "concertina", "thread", "weave", "jacquard")+++class Bitmap:+ def __init__(self, width, height, scale=1):+ self.width, self.height = width, height+ if sys.platform == "darwin":+ import Quartz as cg+ from effects_overlay import replay+ self.cg, self.replay = cg, replay+ self.data = bytearray(width * height * 4)+ self.ctx = cg.CGBitmapContextCreate(self.data, width, height, 8, width * 4,+ cg.CGColorSpaceCreateWithName(cg.kCGColorSpaceSRGB),+ cg.kCGImageAlphaPremultipliedLast | cg.kCGBitmapByteOrder32Big)+ cg.CGContextTranslateCTM(self.ctx, 0, height)+ cg.CGContextScaleCTM(self.ctx, scale, -scale)+ else:+ from PySide6.QtGui import QImage, QPainter+ from effect_overlay import replay+ self.replay = replay+ self.image = QImage(width, height, QImage.Format.Format_RGBA8888_Premultiplied)+ self.painter = QPainter(self.image)+ self.painter.setRenderHint(QPainter.RenderHint.Antialiasing)+ self.painter.scale(scale, scale)++ def clear(self, dark):+ rgb = (0.065, 0.075, 0.09) if dark else (0.93, 0.92, 0.89)+ if sys.platform == "darwin":+ self.cg.CGContextSetRGBFillColor(self.ctx, *rgb, 1)+ self.cg.CGContextFillRect(self.ctx, ((-4000, -4000), (8000, 8000)))+ else:+ from PySide6.QtGui import QColor+ self.painter.fillRect(-4000, -4000, 8000, 8000, QColor.fromRgbF(*rgb))++ def draw(self, pens):+ if sys.platform == "darwin":+ self.replay(self.cg, self.ctx, pens)+ else:+ self.replay(self.painter, pens)++ def pil(self):+ from PIL import Image+ if sys.platform == "darwin":+ return Image.frombytes("RGBA", (self.width, self.height), bytes(self.data)).convert("RGB")+ return Image.frombytes("RGBA", (self.width, self.height), bytes(self.image.bits())).convert("RGB")++ def close(self):+ if sys.platform != "darwin":+ self.painter.end()+++def catalogue():+ from tokens import PALETTES+ yield "light", tuple(effects.CLASSIC), ("signal", "Signal", PALETTES["signal"])+ for _module, name, ids, packs in effects.DIRECTIONS:+ pack_name, palette = effects.pack(packs[0])+ yield name.lower(), ids, (packs[0], pack_name, palette)++- def preview(fx, t, palette, dark, method="edge"):++def preview(fx, t, palette, dark, method="edge", scale=0.6):+ scene = (effects.preview_switch_scene(fx, max(0, t - 1.85), palette, dark=dark) if method == "switch"+ else effects.preview_scene(fx, t, method, palette, dark=dark))+ width, height = effects.preview_size(method)- bitmap = Bitmap(round(width * 0.6), round(height * 0.6), 0.6)++ bitmap = Bitmap(round(width * scale), round(height * scale), scale)+ bitmap.clear(dark)+ if method != "switch":+ # Display boundaries belong to the judging scene, never to the effect itself.+ pen = effects.Pen()+ pen.fillStyle = "#030406" if dark else "#d0cec8"+ if method == "notch":+ pen.fillRect(0, 450, 800, 40)+ else:+ pen.fillRect(800, 0, 40, 450)+ bitmap.draw([pen])+ for pen in scene["pens"]:+ def overlap(screen):+ x, y, w, h, _os = screen+ a, b, c, d = pen.bounds+ return max(0, min(c, x + w) - max(a, x)) * max(0, min(d, y + h) - max(b, y))+ x, y, w, h, _os = max(scene["screens"], key=overlap)+ pen.clip = (x, y, x + w, y + h)+ bitmap.draw(scene["pens"])+ if scene["notch"]:+ pen = effects.Pen()+ pen.fillStyle = "#000000"+ effects.round_rect(pen, *scene["notch"])+ pen.fill()+ bitmap.draw([pen])+ pointer = scene["pointer"]+ if pointer:+ x, y, _os = pointer+ pen = effects.Pen()+ pen.fillStyle = "#f7f5ef" if dark else "#24262c"+ pen.beginPath()+ pen.moveTo(x, y)+ pen.lineTo(x + 5, y + 16)+ pen.lineTo(x + 8, y + 10)+ pen.lineTo(x + 15, y + 8)+ pen.closePath()+ pen.fill()+ bitmap.draw([pen])+ result = bitmap.pil()+ bitmap.close()+ return result+++def render(output):+ from PIL import Image, ImageDraw, ImageFont+ output.mkdir(parents=True, exist_ok=True)+ font = ImageFont.truetype(str(ROOT / "win_app/assets/HankenGrotesk-Variable.ttf"), 17)+ times = (0.92, 1.35, 1.78, 2.18, 2.27, 2.44, 2.7)+ stages = ("Push · 10%", "Push · 45%", "Push · 85%", "Threshold", "Give", "Arrival", "Settle")+ total = 0+ for direction, ids, (_pack_id, pack_name, palette) in catalogue():+ for effect_id in ids:+ fx = effects.preview_effect(effect_id)+ for dark, method in ((dark, method) for dark in (True, False)+ for method in (("edge", "corner", "notch", "switch")+ if effect_id in NEW_IDS else ("edge",))):+ mode = "dark" if dark else "light"+ suffix = "" if method == "edge" else f"-{method}"+ stem = f"{direction}-{effect_id}-{mode}{suffix}"+ background, foreground = ("#101318", "#e5e8ef") if dark else ("#eeebe3", "#26272c")+ frames = []+ for i in range(56):+ t = 0.7 + i * 0.05+ picture = preview(fx, t, palette, dark, method)+ frame = Image.new("RGB", (picture.width, picture.height + 42), background)+ frame.paste(picture, (0, 42))+ label = f"{direction.title()} / {fx.name} · {method.title()} · {pack_name}"+ ImageDraw.Draw(frame).text((16, 10), label, font=font, fill=foreground)+ frames.append(frame)+ frames[0].save(output / f"{stem}.gif", save_all=True, append_images=frames[1:],+ duration=50, loop=0, disposal=2)+ strip = Image.new("RGB", (336 * len(times), 256), background)+ draw = ImageDraw.Draw(strip)+ for i, (t, stage) in enumerate(zip(times, stages)):+ # A crop around the crossing keeps quiet effects readable at their true scale.+ box = {"edge": (324, 24, 660, 240), "corner": (324, 0, 660, 216),+ "notch": (72, 180, 408, 396), "switch": (72, 0, 408, 216)}[method]+ crop = preview(fx, t, palette, dark, method).crop(box)+ strip.paste(crop, (336 * i, 40))+ label = stage if method != "switch" else ("Waiting" if t < 2.2 else stage)+ draw.text((336 * i + 12, 10), label, font=font, fill=foreground)+ strip.save(output / f"{stem}-strip.png")+ total += 2+ print(f"Rendered {total} files to {output}")+ judging_index(output)+++def judging_index(output):+ from html import escape+ parts = ['''<!doctype html><html lang="en-GB"><meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>Beamer crossing effects</title><style>+body{margin:0 auto;padding:36px 24px;max-width:1500px;background:#17191c;color:#ede9df;+font:16px/1.5 system-ui,sans-serif}h1{font-size:32px}h2{margin:48px 0 8px}h3{margin:28px 0 4px}+p{max-width:75ch;color:#c0bbae}a{color:#d0c299}figure{margin:0}img{width:100%;display:block}+.pair{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}figcaption{padding:8px 0}+details{margin:12px 0}summary{cursor:pointer}.packs{display:flex;gap:24px;flex-wrap:wrap}+.swatch{display:inline-block;width:22px;height:22px;vertical-align:middle;margin-right:3px}+@media(max-width:700px){.pair{grid-template-columns:1fr}}+</style><h1>Beamer crossing effects</h1>+<p>Offscreen native renders. Light, Folio and Selvedge come first; the existing directions follow+for comparison. Each loop shows pressure building, breakthrough and arrival.</p>''']+ entries = list(catalogue())+ entries.sort(key=lambda row: (row[0] not in ("light", "folio", "selvedge"),+ {"light": 0, "folio": 1, "selvedge": 2}.get(row[0], 3)))+ for direction, ids, (_pack, _name, _palette) in entries:+ parts.append(f"<h2>{escape(direction.title())}</h2>")+ packs = next((row[3] for row in effects.DIRECTIONS if row[1].lower() == direction), ())+ parts.append('<div class="packs">')+ for pack_id in packs:+ name, colours = effects.pack(pack_id)+ swatches = ''.join(f'<span class="swatch" style="background:{c}"></span>' for c in colours)+ parts.append(f'<span>{swatches} {escape(name)}</span>')+ parts.append('</div>')+ for effect_id in ids:+ fx = effects.preview_effect(effect_id)+ parts.append(f'<h3>{escape(fx.name)} · {escape(fx.intensity.title())}</h3><p>{escape(fx.blurb)}</p>')+ methods = ("edge", "corner", "notch", "switch") if effect_id in NEW_IDS else ("edge",)+ for method in methods:+ if method != "edge":+ parts.append(f'<details><summary>{method.title()}</summary>')+ parts.append('<div class="pair">')+ for mode in ("dark", "light"):+ suffix = '' if method == 'edge' else f'-{method}'+ stem = f'{direction}-{effect_id}-{mode}{suffix}'+ parts.append(f'<figure><img loading="lazy" src="{stem}.gif" alt="{escape(fx.name)} on {mode} wallpaper">'+ f'<figcaption>{mode.title()} · <a href="{stem}-strip.png">Frame strip</a></figcaption></figure>')+ parts.append('</div>')+ if method != "edge":+ parts.append('</details>')+ parts.append('</html>')+ (output / 'index.html').write_text('\n'.join(parts), encoding='utf-8')+++def benchmark():+ results = []+ for effect_id in NEW_IDS:+ fx = effects.preview_effect(effect_id)+ palette = effects.pack("marbled" if effect_id in ("crease", "pleat", "concertina") else "tide")[1]+ generation, native = [], []+ bitmap = Bitmap(3280, 900, 2)+ for i in range(180):+ dark = bool(i % 2)+ t = 1.1 + (i % 90) * 0.025+ start = time.perf_counter()+ scene = effects.preview_scene(fx, t, "edge", palette, dark=dark)+ recorded = time.perf_counter()+ bitmap.clear(dark)+ bitmap.draw(scene["pens"])+ ended = time.perf_counter()+ if i >= 20:+ generation.append((recorded - start) * 1000)+ native.append((ended - start) * 1000)+ bitmap.close()+ def p95(values):+ return round(sorted(values)[int(len(values) * 0.95)], 3)+ results.append(dict(effect=effect_id, record_p95_ms=p95(generation),+ total_p95_ms=p95(native), total_median_ms=round(statistics.median(native), 3)))+ print(json.dumps(dict(platform=sys.platform, scale=2, budget_record_ms=2, budget_total_ms=8,+ frames_per_effect=160, results=results), indent=2))+ if any(row["record_p95_ms"] >= 2 or row["total_p95_ms"] >= 8 for row in results):+ raise SystemExit("Frame budget exceeded")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--output", type=Path)+ parser.add_argument("--benchmark", action="store_true")+ args = parser.parse_args()+ if args.output:+ render(args.output)+ if args.benchmark:+ benchmark()diff --cc core/tests/settings_behaviour.pyindex 0000000,0000000..f8fc3c0new file mode 100644--- /dev/null+++ b/core/tests/settings_behaviour.py@@@ -1,0 -1,0 +1,415 @@@++"""Synthetic settings fixtures exercising the actual app decisions without constructing UI."""++++import ast++import copy++import importlib++import logging++from pathlib import Path++import sys++import time++from dataclasses import replace++from types import SimpleNamespace++from typing import Optional++from unittest import TestCase++++from core import protocol, settings_sync, ways, peerlist++from core.tests.app_methods import load_methods++++ROOT = Path(__file__).resolve().parents[2]++IDS = [protocol.id_text(bytes([value]) * 16) for value in (1, 2, 3)]++VALUES = dict(glow_style="beam", glow_colour="ocean", effect_length="long",++ effect_size="large", shortcut_arrival=False, shortcut_arrival_style="locator")++++++def mac_adapter():++ sys.path.insert(0, str(ROOT / "mac_app"))++ config = importlib.import_module("config")++ tree = ast.parse((ROOT / "mac_app/settings_store.py").read_text())++ node = next(item for item in tree.body if isinstance(item, ast.FunctionDef) and item.name == "config_to_raw")++ namespace = {"config_module": config}++ exec(compile(ast.Module(body=[node], type_ignores=[]), "settings_store.py", "exec"), namespace)++ return config, namespace["config_to_raw"]++++++def fixture(platform, ident):++ namespace = dict(settings_sync=settings_sync, protocol=protocol, peerlist=peerlist, time=time,++ Optional=Optional, replace=replace, LOGGER=logging.getLogger("settings-behaviour"),++ core_ways=ways, ways=ways)++ if platform == "mac":++ config, to_raw = mac_adapter()++ namespace.update(config_to_raw=to_raw, KEY_NAME_TO_CODE={"cmd_r", "f13"}, SettingsError=ValueError)++ names = ("same_state", "_apply_followed_design", "_receive_design", "apply_same", "_set_design_follow", "_set_same",++ "_show_trigger_conflict", "_trigger_chosen")++ cls = load_methods("mac_app/kvm_bridge_app.py", "ControlWindow", names, namespace)++ app = cls()++ cfg = config.parse_config(dict(host="", port=24800, auth_token="", design_set_at=1000, design_by=ident))++ app.controller = SimpleNamespace(cfg=cfg)++ app.controller.apply_settings = lambda value: setattr(app.controller, "cfg", value)++ app.settings_store = SimpleNamespace(save=lambda raw: config.parse_config(copy.deepcopy(raw)))++ app.own_id = lambda: ident++ app.previews = None++ app._load_shared = lambda raw: None++ app.refresh = lambda: None++ app.values = lambda: settings_sync.mac_values(to_raw(app.controller.cfg))++ app.cfg = lambda: app.controller.cfg++ app.select = app._set_design_follow++ app.receive = lambda source, data: app.apply_same(data, peer=source)++ app.state = app.same_state++ app.style_hint = Label()++ app.conflict_note = app.style_hint++ app._changed = lambda: None++ app.key_recorder = SimpleNamespace(value=cfg.trigger_key)++ app.key_recorder.set_value = lambda value: setattr(app.key_recorder, "value", value)++ def record(key):++ app.key_recorder.value = key++ app._trigger_chosen(key)++ app.record = record++ else:++ sys.path.insert(0, str(ROOT / "win_app"))++ config = importlib.import_module("app_config")++ namespace.update(app_config=config, ConfigError=config.ConfigError, TRIGGER_KEYS={"cmd_r", "f13"})++ names = ("_same_state", "_apply_followed_design", "_on_settings", "_design_follow_chosen", "_set_same",++ "_show_trigger_conflict", "_record_trigger")++ namespace.update(TRIGGER_KEYS=config.TRIGGER_KEYS, TRIGGER_VKS=config.TRIGGER_VKS,++ UNRECORDABLE_TRIGGER_VKS=config.UNRECORDABLE_TRIGGER_VKS)++ cls = load_methods("win_app/kvm_bridge_win.py", "WindowsApplication", names, namespace)++ app = cls()++ app._config = config.Config(host="", port=24800, auth_token="", machine_id=ident,++ design_set_at=1000, design_by=ident)++ app._persist = lambda: True++ app._reflect_config = lambda cfg: None++ app.sender = SimpleNamespace(update_config=lambda cfg: None)++ app._configure_trigger = lambda cfg: None++ app._same_fields = lambda: ()++ app._design_fields = lambda: ()++ app.design_follow_choice = SimpleNamespace(currentData=lambda role: app.chosen)++ namespace["Qt"] = SimpleNamespace(ItemDataRole=SimpleNamespace(UserRole=0))++ app.values = lambda: settings_sync.pc_values(app._config)++ app.cfg = lambda: app._config++ def select(peer):++ app.chosen = peer++ app._design_follow_chosen(0)++ app.select = select++ app.receive = app._on_settings++ app.state = app._same_state++ app.trigger_note = Label()++ app.conflict_note = app.trigger_note++ app.trigger_recorder = SimpleNamespace(set_title=lambda title: None)++ app.record = lambda key: app._record_trigger("key", config.TRIGGER_VKS[key])++ app.logger = logging.getLogger("settings-behaviour")++ app.peers = [{"id": peer, "port": 24820} for peer in IDS if peer != ident]++ if platform == "mac":++ app.settings_store.current = lambda: {"peers": app.peers}++ app.controller.book = SimpleNamespace(peers=lambda: app.peers)++ else:++ app.book = SimpleNamespace(peers=lambda: app.peers)++ app._design_states = {}++ app._followed_version = None++ app._design_path = [ident]++ app._refresh_design_follow = lambda: None++ app._show_same = lambda: None++ app.sent = []++ app._send_same = lambda data=None, source=None: app.sent.append(copy.deepcopy(data if data is not None else app.state()))++ return app++++++class Label:++ def __init__(self):++ self.text = ""++ self.visible = True++ self.view = SimpleNamespace(setHidden_=lambda hidden: self.setVisible(not hidden))++++ def set(self, text, **kwargs):++ self.text = text++++ def setText(self, text):++ self.text = text++++ def setVisible(self, visible):++ self.visible = visible++++++def reflect_shortcut_visibility(app, platform):++ """Stop at the next unrelated UI dependency, after the actual module visibility decision."""++ class UnrelatedUI(Exception):++ pass++ def stop(*args):++ raise UnrelatedUI++ def visibility(view, visible):++ view.visible = visible++ motion = SimpleNamespace(set_hidden=lambda view, hidden: visibility(view, not hidden), set_shown=visibility)++ if platform == "mac":++ pages = importlib.import_module("pages")++ namespace = dict(pages=SimpleNamespace(crossing_rows=pages.crossing_rows, part_names=stop), motion=motion)++ cls = load_methods("mac_app/kvm_bridge_app.py", "ControlWindow", ["_reflect"], namespace)++ app.method_boxes = {name: SimpleNamespace(value=name in app.cfg().crossing["methods"])++ for name in ("shortcut", "edge", "corner", "part", "notch")}++ app.edge_row = app.parts_row = app.corner_row = SimpleNamespace()++ app.dragging_box = app.resistance_module = SimpleNamespace(view=SimpleNamespace())++ app.shortcut_module = SimpleNamespace(view=SimpleNamespace(visible=False))++ app.key_recorder.cancel = lambda: None++ app.edge_select = SimpleNamespace(value="right")++ method = lambda: cls._reflect(app)++ view = app.shortcut_module.view++ else:++ pages = importlib.import_module("pages_win")++ namespace = dict(pages_win=pages, ways=ways, motion=motion, TRIGGER_KEYS=SimpleNamespace(get=stop))++ cls = load_methods("win_app/kvm_bridge_win.py", "WindowsApplication", ["_reflect_ways"], namespace)++ app._crossing_settings = lambda: {"peers": [], "zones": []}++ app._crossing_machines = lambda: []++ app._chosen_machine = lambda: None++ app._rebuild_machine_choice = lambda values: None++ app._ways_in = lambda: set()++ ui = SimpleNamespace(++ set_value=lambda *args: None,++ set_names=lambda *args: None,++ setText=lambda *args: None,++ view=SimpleNamespace(setToolTip=lambda text: None),++ )++ for name in ("machine_choice", "edge_choice", "edge_heading", "edge_note", "edge_unlearned", "corner_choice", "parts_note"):++ setattr(app, name, ui)++ app.machine_row = app.resistance_module = SimpleNamespace()++ app.ways_module = SimpleNamespace(eyebrow=SimpleNamespace(setText=lambda text: None))++ app.shortcut_module = SimpleNamespace(visible=False)++ app.way_boxes = app.part_buttons = app.crossing_rows = {}++ method = lambda: cls._reflect_ways(app)++ view = app.shortcut_module++ try:++ method()++ except UnrelatedUI:++ pass++ return view.visible++++++def status_fixture(platform, caps, cached=False, following=False, offline=()):++ app = fixture(platform, IDS[1])++ app.peers = [{"id": IDS[0], "name": "Leader", "token": "synthetic"}]++ app.peers += [{"id": ident, "name": f"Offline {n}", "token": f"offline-{n}"} for n, ident in enumerate(offline)]++ if cached:++ app._design_states[IDS[0]] = {"set_at": 10, "by": IDS[0], "values": VALUES}++ app.cfg().design_follow_peer = IDS[0] if following else ""++ app._design_peer_caps = lambda: caps++ app._lock_followed_design = lambda entry, name: setattr(app, "locked_to", entry)++ namespace = dict(settings_sync=settings_sync, peerlist=peerlist, protocol=protocol)++ if platform == "mac":++ class MenuChoice:++ def __init__(self, choices, **kwargs):++ self.choices = choices++ self.items = []++ for value, title in choices:++ cell = SimpleNamespace(enabled=True, tooltip="", setAlphaValue_=lambda alpha: None)++ cell.setToolTip_ = lambda text, cell=cell: setattr(cell, "tooltip", text)++ cell.setEnabled_ = lambda enabled, cell=cell: setattr(cell, "enabled", enabled)++ self.items.append((value, cell))++ self.view = None++ namespace["widgets"] = SimpleNamespace(MenuChoice=MenuChoice, add=lambda *args, **kwargs: None)++ app.follow_host = SimpleNamespace(arrangedSubviews=lambda: [])++ app.follow_note = Label()++ app._set_design_follow = lambda peer: None++ method = load_methods("mac_app/kvm_bridge_app.py", "ControlWindow", ["_refresh_design_follow"], namespace)++ method._refresh_design_follow(app)++ app.status_titles = [title for value, title in app.follow_select.choices]++ app.status_tooltip = app.follow_select.items[1][1].tooltip if len(app.follow_select.items) > 1 else ""++ app.status_note = app.follow_note.text++ else:++ class Item:++ def __init__(self, title):++ self.title = title++ def setData(self, value, role):++ self.value = value++ def setEnabled(self, enabled):++ self.enabled = enabled++ def setToolTip(self, text):++ self.tooltip = text++ class Model:++ def __init__(self, choice):++ self.rows = []++ def appendRow(self, item):++ self.rows.append(item)++ namespace.update(QStandardItemModel=Model, QStandardItem=Item,++ Qt=SimpleNamespace(ItemDataRole=SimpleNamespace(UserRole=0)))++ app._peer_entries = app.peers++ app._shown = lambda text: text++ choice = SimpleNamespace(blockSignals=lambda on: None, findData=lambda *args: 0,++ setCurrentIndex=lambda index: None)++ choice.setModel = lambda model: setattr(choice, "model", model)++ app.design_follow_choice = choice++ app.design_follow_note = Label()++ method = load_methods("win_app/kvm_bridge_win.py", "WindowsApplication", ["_refresh_design_follow"], namespace)++ method._refresh_design_follow(app)++ app.status_titles = [item.title for item in choice.model.rows]++ app.status_tooltip = getattr(choice.model.rows[1], "tooltip", "") if len(choice.model.rows) > 1 else ""++ app.status_note = app.design_follow_note.text++ return app++++++def leader_message(ident, stamp=100, values=None, path=None):++ state = dict(set_at=stamp, by=ident, values=dict(VALUES if values is None else values))++ if path is not None:++ state["path"] = path++ return settings_sync.message_data(False, 0, by=ident, design_state=state)++++++class SettingsBehaviourTests(TestCase):++ platform = None++++ def setUp(self):++ self.app = fixture(self.platform, IDS[1])++++ def cache_and_select(self, stamp=100):++ self.app.receive(IDS[0], leader_message(IDS[0], stamp))++ self.app.select(IDS[0])++++ def assert_design(self, app, values=VALUES):++ self.assertEqual({key: app.values()[key] for key in settings_sync.DESIGN_KEYS}, values)++++ def test_selecting_older_leader_adopts_all_six_values_and_announces_local_version(self):++ self.cache_and_select()++ self.assert_design(self.app)++ state = self.app.state()["design_sync"]++ self.assertGreater(state["set_at"], 1000)++ self.assertEqual(state["by"], IDS[1])++ self.assertEqual(state["path"], [IDS[0], IDS[1]])++++ def test_compatible_design_not_yet_received_is_not_labelled_old(self):++ waiting = "Design not available yet: connect to this machine with Beamer 1.5.0 beta.6 or later."++ app = status_fixture(self.platform, {IDS[0]: {"settings", "design_sync"}})++ self.assertNotIn("Needs beta.6 or later", app.status_titles[1])++ self.assertEqual(app.status_titles[1], "Leader")++ self.assertEqual(app.status_tooltip, waiting)++ self.assertEqual(app.status_note, waiting)++++ def test_connected_machine_with_design_is_offered_whatever_offline_peers_say(self):++ # 05-10-2026, 1.5.0-rc.4: the PC was linked and its Design had arrived, but the Mac's other++ # paired machines were offline and their missing Design set the note to "not available".++ app = status_fixture(self.platform, {IDS[0]: {"settings", "design_sync"}}, cached=True, offline=(IDS[2],))++ self.assertEqual(app.status_titles, ["None", "Leader"])++ self.assertEqual(app.status_tooltip, "")++ self.assertTrue(app.status_note.startswith("None: this "), app.status_note)++++ def test_no_connected_machine_lists_none_with_one_quiet_line(self):++ app = status_fixture(self.platform, {}, offline=(IDS[2],))++ self.assertEqual(app.status_titles, ["None"])++ self.assertEqual(app.status_note, settings_sync.NO_MACHINE_CONNECTED)++++ def test_observed_missing_design_capability_is_labelled_old(self):++ app = status_fixture(self.platform, {IDS[0]: {"settings"}})++ self.assertIn("Needs beta.6 or later", app.status_titles[1])++++ def test_following_offline_machine_keeps_last_design_and_says_so(self):++ app = status_fixture(self.platform, {}, cached=True, following=True)++ self.assertEqual(app.status_note, "Keeping the last design received from Leader until it reconnects.")++++ def test_shared_trigger_clash_preserves_local_jump_and_trigger_and_reports_conflict(self):++ self.app.peers.append({"id": IDS[0], "jump_key": "ctrl+f13"})++ before = self.app.cfg().trigger_key++ data = settings_sync.message_data(True, 20, {"trigger_key": "f13", "resistance_px": 75}, by=IDS[0])++ self.app.peers[0]["jump_key"] = "cmd+f13"++ self.app.receive(IDS[0], data)++ self.assertEqual(self.app.cfg().trigger_key, before)++ self.assertEqual(self.app.peers[0]["jump_key"], "cmd+f13")++ self.assertEqual(self.app.values()["resistance_px"], 75)++ self.assertIn("clashes", self.app.conflict_note.text)++ self.assertTrue(self.app.conflict_note.visible)++++ def test_recording_a_trigger_clash_preserves_the_local_trigger_and_shows_a_note(self):++ self.app.peers.append({"id": IDS[0], "jump_key": "ctrl+f13"})++ before = self.app.cfg().trigger_key++ self.app.record("f13")++ self.assertEqual(self.app.cfg().trigger_key, before)++ self.assertIn("clashes", self.app.conflict_note.text)++ self.assertTrue(self.app.conflict_note.visible)++ if self.platform == "mac":++ self.assertEqual(self.app.key_recorder.value, before)++++ def test_shared_clash_note_stays_visible_when_shortcut_is_switched_off(self):++ self.app.peers.append({"id": IDS[0], "jump_key": "ctrl+f13"})++ before = self.app.cfg().trigger_key++ self.app.receive(IDS[0], settings_sync.message_data(++ True, 20, {"trigger_key": "f13", "shortcut": False}, by=IDS[0]))++ self.assertEqual(self.app.cfg().trigger_key, before)++ self.assertIn("clashes", self.app.conflict_note.text)++ self.assertTrue(reflect_shortcut_visibility(self.app, self.platform))++++ def test_next_leader_update_uses_leader_cursor_and_duplicates_do_not_resend(self):++ self.cache_and_select()++ changed = dict(VALUES, effect_length="short")++ message = leader_message(IDS[0], 101, changed)++ self.app.receive(IDS[0], message)++ self.assert_design(self.app, changed)++ count = len(self.app.sent)++ self.app.receive(IDS[0], message)++ self.app.receive(IDS[0], leader_message(IDS[0], 99))++ self.assertEqual(len(self.app.sent), count)++ self.assert_design(self.app, changed)++++ def test_same_off_here_resumes_the_already_adopted_cached_version(self):++ self.cache_and_select()++ self.app.cfg().same_on_both = True++ self._set_values(dict(VALUES, effect_length="short"))++ self.app._set_same(False)++ self.assert_design(self.app)++++ def test_same_off_received_resumes_the_already_adopted_cached_version(self):++ self.cache_and_select()++ self.app.cfg().same_on_both = True++ self._set_values(dict(VALUES, effect_length="short"))++ data = settings_sync.message_data(False, self.app.cfg().same_set_at + 1, by=IDS[2])++ self.app.receive(IDS[2], data)++ self.assert_design(self.app)++++ def _set_values(self, values):++ self.set_values(self.app, values)++++ def set_values(self, app, values):++ if self.platform == "mac":++ config, to_raw = mac_adapter()++ raw = settings_sync.apply_mac(to_raw(app.cfg()), values)++ app.controller.apply_settings(config.parse_config(raw))++ else:++ settings_sync.apply_pc(app.cfg(), values)++++ def test_downstream_follower_adopts_when_its_leader_selects_older_design(self):++ downstream = fixture(self.platform, IDS[2])++ downstream.receive(IDS[1], self.app.state())++ downstream.select(IDS[1])++ self.cache_and_select()++ downstream.receive(IDS[1], self.app.state())++ self.assert_design(downstream)++ self.assertEqual(downstream.state()["design_sync"]["path"], IDS)++++ def test_two_machine_cycle_has_bounded_announcements(self):++ self._cycle(2, False)++++ def test_three_machine_cycle_has_bounded_announcements(self):++ self._cycle(3, False)++++ def test_identical_values_cycle_has_bounded_announcements(self):++ self._cycle(3, True)++++ def test_two_machine_identical_values_cycle_has_bounded_announcements(self):++ self._cycle(2, True)++++ def _cycle(self, count, identical):++ apps = [fixture(self.platform, ident) for ident in IDS[:count]]++ if not identical:++ self.set_values(apps[0], VALUES)++ initial = [app.state() for app in apps]++ for index, app in enumerate(apps):++ leader = (index + 1) % count++ app.receive(IDS[leader], initial[leader])++ app.select(IDS[leader])++ queue = [(index, data) for index, app in enumerate(apps) for data in app.sent]++ for app in apps:++ app.sent.clear()++ processed = 0++ while queue:++ source, data = queue.pop(0)++ processed += 1++ self.assertLess(processed, 40, "follow cycle kept announcing")++ for index, app in enumerate(apps):++ if source != index:++ app.receive(IDS[source], data)++ queue.extend((index, message) for message in app.sent)++ app.sent.clear()++ self.assertTrue(any(not app.cfg().design_follow_peer for app in apps))diff --cc core/tests/spec_phone.pyindex 0000000,0000000..df0d1e1new file mode 100644--- /dev/null+++ b/core/tests/spec_phone.py@@@ -1,0 -1,0 +1,303 @@@++"""Independent phone peer from PAIRING.md and WIRE.md sections 2, 4, 5 and 6.++++No production encoding, handshake, pairing or routing code is imported here: a desktop++and this phone sharing a mistake cannot make the interoperability test pass.++"""++++import base64++import hashlib++import hmac++import json++import queue++import secrets++import socket++import struct++import threading++import time++++from nacl.bindings import (++ crypto_aead_chacha20poly1305_ietf_decrypt,++ crypto_aead_chacha20poly1305_ietf_encrypt,++ crypto_scalarmult,++ crypto_scalarmult_base,++)++from nacl.exceptions import CryptoError++++++def b64(raw):++ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")++++++def unb64(text):++ raw = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))++ if b64(raw) != text:++ raise ValueError("non-canonical base64")++ return raw++++++def lv(*parts):++ result = bytearray()++ for part in parts:++ length = len(part)++ while length >= 128:++ result.append((length & 127) | 128)++ length >>= 7++ result.append(length)++ result.extend(part)++ return bytes(result)++++++def hkdf(ikm, salt, info, length):++ prk = hmac.new(salt, ikm, hashlib.sha256).digest()++ result, block = b"", b""++ for counter in range(1, (length + 31) // 32 + 1):++ block = hmac.new(prk, block + info + bytes([counter]), hashlib.sha256).digest()++ result += block++ return result[:length]++++++def exchange(private, public):++ try:++ return crypto_scalarmult(private, public)++ except CryptoError as error:++ raise ValueError("invalid X25519 share") from error++++++def read_exact(sock, count):++ result = bytearray()++ while len(result) < count:++ chunk = sock.recv(count - len(result))++ if not chunk:++ raise EOFError("the desktop closed the connection")++ result.extend(chunk)++ return bytes(result)++++++def pair_send(sock, message):++ body = json.dumps(dict(message, beamy=1), separators=(",", ":")).encode("utf-8")++ if not 1 <= len(body) <= 1024:++ raise ValueError("pairing frame outside its limits")++ sock.sendall(struct.pack(">I", len(body)) + body)++++++def pair_read(sock):++ length = struct.unpack(">I", read_exact(sock, 4))[0]++ if not 1 <= length <= 1024:++ raise ValueError("pairing frame outside its limits")++ message = json.loads(read_exact(sock, length))++ if message.get("beamy") != 1:++ raise ValueError("not a pairing message")++ return message++++++class Phone:++ def __init__(self, identity, name, platform):++ self.identity, self.name, self.platform = identity, name, platform++ self.peers, self.links = {}, {}++ self.route = 0++ self.on = None++++ def pair(self, tcp_port, code, qr_secret=None):++ with socket.create_connection(("127.0.0.1", tcp_port), timeout=3) as sock:++ beacon = pair_read(sock)++ if beacon["type"] != "beacon" or beacon["pairing"] != 3:++ raise ValueError("not a version 3 host")++ pair_id = beacon["pair"]++ nonce = secrets.token_bytes(16)++ sid = lv(pair_id.encode("ascii"), nonce)++ password = code.encode("ascii") + (qr_secret or b"")++ padding = bytes(128 - 1 - len(lv(password)) - len(lv(b"CPace255")))++ generator_string = lv(b"CPace255", password, padding, b"beamer-pair-v3", sid)++ r = int.from_bytes(hashlib.sha512(generator_string).digest()[:32], "little") & ((1 << 255) - 1)++ p, a = (1 << 255) - 19, 486662++ v = (-a * pow(1 + 2 * r * r, -1, p)) % p++ e = pow((v**3 + a * v * v + v) % p, (p - 1) // 2, p)++ generator = (v if e == 1 else (-v - a) % p).to_bytes(32, "little")++ private = secrets.token_bytes(32)++ ya = exchange(private, generator)++ start = {++ "type": "pair_start", "pair": pair_id, "v": 3, "nonce": b64(nonce),++ "share": b64(ya), "name": self.name, "id": b64(self.identity),++ "platform": self.platform, "port": 0,++ }++ if qr_secret is not None:++ start["qr"] = 1++ pair_send(sock, start)++ answer = pair_read(sock)++ if answer["type"] != "pair_answer" or answer.get("ok") is not True or answer["pair"] != pair_id:++ raise ValueError("pairing refused")++ host_id = unb64(answer["id"])++ if len(host_id) != 16 or host_id == bytes(16) or host_id == self.identity or answer["id"] in self.peers:++ raise ValueError("invalid or known host id")++ yb = unb64(answer["share"])++ shared = exchange(private, yb)++ ada = lv(b"requester", self.identity, self.name.encode("utf-8"), self.platform.encode("ascii"), bytes(2))++ adb = lv(b"host", host_id, answer["name"].encode("utf-8"), answer["platform"].encode("ascii"),++ answer["port"].to_bytes(2, "big"))++ isk = hashlib.sha512(lv(b"CPace255_ISK", sid, shared) + lv(ya, ada) + lv(yb, adb)).digest()++ mac_key = hashlib.sha512(b"CPaceMac" + sid + isk).digest()++ tag = lambda value: hmac.new(mac_key, value, hashlib.sha512).digest()++ if not hmac.compare_digest(unb64(answer["tag"]), tag(lv(yb, adb))):++ pair_send(sock, {"type": "pair_confirm", "pair": pair_id, "tag": ""})++ raise ValueError("host confirmation failed")++ pair_send(sock, {"type": "pair_confirm", "pair": pair_id, "tag": b64(tag(lv(ya, ada)))})++ done = pair_read(sock)++ if done["type"] != "pair_done" or done.get("ok") is not True or done["pair"] != pair_id:++ raise ValueError("pairing was not saved")++ if not hmac.compare_digest(unb64(done["tag"]), tag(lv(b"beamer-pair-done"))):++ raise ValueError("receipt failed")++ peer = {"id": answer["id"], "name": answer["name"], "platform": answer["platform"],++ "host": "127.0.0.1", "port": answer["port"],++ "token": b64(hkdf(isk, sid, b"beamer-pair-token-v3", 32))}++ self.peers[peer["id"]] = peer++ return peer++++ def connect(self, peer):++ link = PhoneLink(self, self.peers[peer])++ self.links[peer] = link++ return link++++ def take(self, peer):++ self.route += 1++ self.links[peer].send("focus", route=self.route, target=peer,++ reach=[other for other in self.links if other != peer])++ self.on = peer++++ def follow_switch(self, source, message):++ if source != self.on or message["route"] != self.route:++ raise ValueError("stale switch")++ target = message["next"]++ if target == b64(self.identity):++ self.route += 1++ self.links[source].release()++ self.links[source].send("focus", route=self.route, target=target)++ self.on = None++ return++ if target not in self.links:++ raise ValueError("switch target has no direct link")++ self.route += 1++ fields = {k: message[k] for k in ("edge", "offset") if k in message}++ self.links[target].send("focus", route=self.route, target=target,++ reach=[p for p in self.links if p != target], **fields)++ answer = self.links[target].expect("accept")++ if answer != {"route": self.route}:++ raise ValueError("switch target did not accept")++ self.links[source].release()++ self.links[source].send("focus", route=self.route, target=target)++ self.on = target++++++class PhoneLink:++ def __init__(self, phone, peer):++ self.sock = socket.create_connection((peer["host"], peer["port"]), timeout=3)++ self.counter, self.received_counter, self.seq = 0, 0, 0++ self.keys, self.buttons = set(), set()++ self.lock = threading.Lock()++ self.closed = threading.Event()++ self.inbox = queue.Queue()++ self.pending = []++ self.prefix = secrets.token_bytes(8)++ private = secrets.token_bytes(32)++ share = crypto_scalarmult_base(private)++ token = peer["token"].encode("ascii")++ key_id = hkdf(token, b"beamer-link-v6", b"beamer-key-id", 16)++ try:++ self.sock.sendall(b"BEAMY\x06" + self.prefix + key_id + share)++ preamble = read_exact(self.sock, 62)++ if preamble[:6] != b"BEAMY\x06" or preamble[14:30] != key_id or preamble[6:14] == self.prefix:++ raise ValueError("wrong preamble")++ self.peer_prefix = preamble[6:14]++ shared = exchange(private, preamble[30:62])++ info = b"beamer-frames\x06" + key_id + self.prefix + self.peer_prefix + share + preamble[30:62]++ self.send_key = hkdf(token + shared, b"beamer-link-v6", info + b"\x01", 32)++ self.receive_key = hkdf(token + shared, b"beamer-link-v6", info + b"\x02", 32)++ self.send("hello", version=6, id=b64(phone.identity), name=phone.name,++ platform=phone.platform, app="1.5.0", caps=[], port=0)++ welcome = self.read()++ if welcome["type"] != "welcome" or welcome["data"].get("error"):++ raise ValueError(welcome["data"].get("error", "not a welcome"))++ self.welcome = welcome["data"]++ if self.welcome["id"] != peer["id"] or self.welcome["version"] != 6:++ raise ValueError("wrong desktop id or version")++ self.sock.settimeout(None)++ threading.Thread(target=self._reader, daemon=True).start()++ threading.Thread(target=self._heartbeat, daemon=True).start()++ except BaseException:++ self.close()++ raise++++ def send(self, kind, **data):++ body = json.dumps({"type": kind, "data": data}, separators=(",", ":")).encode("utf-8")++ with self.lock:++ self.counter += 1++ counter = struct.pack(">I", self.counter)++ sealed = crypto_aead_chacha20poly1305_ietf_encrypt(body, None, self.prefix + counter, self.send_key)++ self.sock.sendall(struct.pack(">I", 4 + len(sealed)) + counter + sealed)++++ def read(self):++ length = struct.unpack(">I", read_exact(self.sock, 4))[0]++ if not 21 <= length <= 16 * 1024 * 1024:++ raise ValueError("bad frame length")++ frame = read_exact(self.sock, length)++ counter = struct.unpack(">I", frame[:4])[0]++ if counter != self.received_counter + 1:++ raise ValueError("bad frame counter")++ self.received_counter = counter++ plain = crypto_aead_chacha20poly1305_ietf_decrypt(frame[4:], None, self.peer_prefix + frame[:4], self.receive_key)++ return json.loads(plain)++++ def _reader(self):++ try:++ while not self.closed.is_set():++ self.inbox.put(self.read())++ except (OSError, EOFError, ValueError, CryptoError):++ self.closed.set()++++ def _heartbeat(self):++ while not self.closed.wait(0.8):++ try:++ self.send("ping")++ except OSError:++ self.closed.set()++++ def input(self, kind, **data):++ self.seq += 1++ self.send(kind, seq=self.seq, **data)++ if kind == "keydown":++ self.keys.add(data["key"])++ elif kind == "keyup":++ self.keys.discard(data["key"])++ elif kind == "mousedown":++ self.buttons.add(data["button"])++ elif kind == "mouseup":++ self.buttons.discard(data["button"])++++ def release(self):++ for key in list(self.keys):++ self.input("keyup", key=key)++ for button in list(self.buttons):++ self.input("mouseup", button=button)++++ def expect(self, kind, timeout=2):++ for message in self.pending:++ if message["type"] == kind:++ self.pending.remove(message)++ return message["data"]++ deadline = time.monotonic() + timeout++ while time.monotonic() < deadline:++ try:++ message = self.inbox.get(timeout=max(0, deadline - time.monotonic()))++ except queue.Empty:++ break++ if message["type"] == kind:++ return message["data"]++ self.pending.append(message)++ return None++++ def close(self):++ self.closed.set()++ try:++ self.sock.shutdown(socket.SHUT_RDWR)++ except OSError:++ pass++ self.sock.close()diff --cc core/tests/test_colour_packs.pyindex 0000000,0000000..04e0fd0new file mode 100644--- /dev/null+++ b/core/tests/test_colour_packs.py@@@ -1,0 -1,0 +1,75 @@@++"""Colour choices stay stable across platforms and mixed-version links."""++import unittest++++from core import effects, settings_sync++import tokens++++NEW_IDS = ('aurora', 'opal', 'sea_glass', 'arc', 'magnesium', 'ruby', 'cobalt',++ 'moss', 'plum', 'woad', 'saffron', 'citron', 'laser', 'electric', 'fuchsia', 'ultraviolet')++MONO = {++ 'mono': ('White', ['#ebebeb', '#969696', '#ebebeb']),++ 'mono_silver': ('Silver', ['#c9ced2', '#a8afb6', '#e1e5e8']),++ 'mono_graphite': ('Graphite', ['#65696f', '#4a4f55', '#868c94']),++ 'mono_ink': ('Ink', ['#25282c', '#101215', '#41464d']),++ 'mono_warm': ('Warm grey', ['#b7ada0', '#8a8074', '#d8cfc2']),++}++++++def luminance(hex_value):++ channels = [int(hex_value[i:i + 2], 16) / 255 for i in (1, 3, 5)]++ linear = [c / 12.92 if c <= .04045 else ((c + .055) / 1.055) ** 2.4 for c in channels]++ return sum(c * weight for c, weight in zip(linear, (.2126, .7152, .0722)))++++++class ColourPacksTests(unittest.TestCase):++ def test_each_chromatic_group_offers_five_and_mono_has_a_neutral_home(self):++ groups = effects.colour_groups(tuple((key, key.capitalize()) for key in tokens.PALETTES))++ self.assertEqual([title for title, _ in groups],++ ['Light', 'Mono', 'Membrane', 'Sparks', 'Instrument', 'Folio', 'Selvedge', 'Bright'])++ self.assertEqual(dict(groups)['Mono'], [(key, name) for key, (name, _) in MONO.items()])++ for title, choices in groups:++ self.assertEqual(len(choices), 5, title)++ if title != 'Mono':++ self.assertNotIn('mono', [value for value, _ in choices])++++ def test_mono_stops_and_shared_resolver_preserve_the_spec(self):++ for value, expected in MONO.items():++ self.assertEqual(effects.pack(value), expected)++ self.assertEqual(effects.legible(MONO['mono_graphite'][1], True),++ ['#6d7278', '#6b727b', '#868c94'])++ self.assertEqual(effects.legible(MONO['mono_ink'][1], True),++ ['#69717d', '#637082', '#69717c'])++ self.assertEqual(effects.legible(MONO['mono'][1], False, effects.effect('aperture')),++ ['#999999', '#969696', '#999999'])++++ def test_new_colours_survive_both_sync_envelopes(self):++ for value in NEW_IDS + tuple(MONO):++ with self.subTest(value=value):++ state = {'set_at': 2, 'by': '', 'values': {'glow_colour': value}}++ data = settings_sync.message_data(True, 2, {'glow_colour': value}, design_state=state)++ self.assertEqual(settings_sync.read(data, {})[2]['glow_colour'], value)++ self.assertEqual(settings_sync.read_design_state(data, {})['values']['glow_colour'], value)++++ def test_unknown_peer_colour_retains_the_current_choice_and_other_fields_apply(self):++ raw = {'crossing': {'glow_colour': 'mono', 'effect_length': 'normal'}}++ data = settings_sync.message_data(True, 2, {'glow_colour': 'future_colour', 'effect_length': 'long'})++ values = settings_sync.read(data, {})[2]++ raw = settings_sync.apply_mac(raw, values)++ self.assertEqual(raw['crossing']['glow_colour'], 'mono')++ self.assertEqual(raw['crossing']['effect_length'], 'long')++++ def test_new_packs_keep_three_to_one_contrast_on_light_and_dark(self):++ for value in NEW_IDS:++ stops = tokens.PALETTES[value] if value in tokens.PALETTES else effects.pack(value)[1]++ for dark, background in ((True, tokens.PALETTE['well']), (False, '#ffffff'),++ (False, tokens.PALETTE_LIGHT['well'])):++ for stop in effects.legible(stops, dark):++ a, b = sorted((luminance(stop), luminance(background)))++ self.assertGreaterEqual((b + .05) / (a + .05), 3, (value, dark, stop))++++ def test_saved_original_palettes_and_packs_resolve_to_the_same_stops(self):++ self.assertEqual(tokens.PALETTES['mono'], ('#ebebeb', '#969696', '#ebebeb'))++ for value, stops in (('vellum', ['#c69a60', '#f0ddac', '#88674c']),++ ('phosphor', ['#3dff7f', '#1f9e52', '#caffdc']),++ ('tide', ['#58a9a3', '#547498', '#b1d1c1'])):++ self.assertEqual(effects.pack(value)[1], stops)diff --cc core/tests/test_locale.pyindex 0000000,0000000..c2d6f46new file mode 100644--- /dev/null+++ b/core/tests/test_locale.py@@@ -1,0 -1,0 +1,70 @@@++import json++import sys++import unittest++from unittest import mock++++from core import locale, settings_sync++++++class LocaleTests(unittest.TestCase):++ @unittest.skipUnless(sys.platform == "darwin", "NSLocale is available on macOS")++ def test_mac_region_matches_nslocale_country_code(self):++ from Foundation import NSLocale, NSLocaleCountryCode++++ country = str(NSLocale.currentLocale().objectForKey_(NSLocaleCountryCode) or "").upper()++ self.assertEqual(locale.is_us_region(), country == "US")++++ def test_linux_region_uses_the_first_defined_locale(self):++ with mock.patch.object(locale.sys, "platform", "linux"), \++ mock.patch.object(locale, "_linux_locale", return_value="en_GB.UTF-8"):++ self.assertFalse(locale.is_us_region())++++ with mock.patch.object(locale.sys, "platform", "linux"), \++ mock.patch.object(locale, "_linux_locale", return_value="en_US.UTF-8"):++ self.assertTrue(locale.is_us_region())++++ def test_linux_locale_variables_follow_posix_precedence(self):++ values = {"LC_ALL": "en_GB.UTF-8", "LC_MESSAGES": "en_US.UTF-8", "LANG": "en_US.UTF-8"}++ with mock.patch.dict(locale.os.environ, values, clear=True):++ self.assertEqual(locale._linux_locale(), "en_GB.UTF-8")++ values["LC_ALL"] = ""++ with mock.patch.dict(locale.os.environ, values, clear=True):++ self.assertEqual(locale._linux_locale(), "en_US.UTF-8")++++ def test_mac_and_windows_use_the_operating_system_region(self):++ with mock.patch.object(locale.sys, "platform", "darwin"), \++ mock.patch.object(locale, "_mac_country", return_value="US"):++ self.assertTrue(locale.is_us_region())++ with mock.patch.object(locale.sys, "platform", "win32"), \++ mock.patch.object(locale, "_windows_locale", return_value="en-GB"):++ self.assertFalse(locale.is_us_region())++ with mock.patch.object(locale.sys, "platform", "win32"), \++ mock.patch.object(locale, "_windows_locale", return_value="en-US"):++ self.assertTrue(locale.is_us_region())++++ def test_unknown_and_non_us_regions_keep_british_text(self):++ for platform in ("unknown", "linux"):++ with self.subTest(platform=platform), \++ mock.patch.object(locale.sys, "platform", platform), \++ mock.patch.object(locale, "_linux_locale", return_value="C"):++ self.assertFalse(locale.is_us_region())++ self.assertEqual(locale.americanise("Colourful behaviour at the centre"),++ "Colourful behaviour at the centre")++++ def test_us_display_text_maps_words_and_preserves_case(self):++ british = "Colourful colours; behaviour at the centre, favourite, organise, licence"++ american = "Colorful colors; behavior at the center, favorite, organize, license"++ with mock.patch.object(locale, "is_us_region", return_value=True):++ self.assertEqual(locale.americanise(british), american)++ self.assertEqual(locale.americanise("MINIMISE, Initialising, cancelled"),++ "MINIMIZE, Initializing, canceled")++++ def test_region_does_not_change_settings_wire_bytes(self):++ settings = {"glow_colour": "colourful", "glow_style": "glow"}++ with mock.patch.object(locale, "is_us_region", return_value=False):++ british = settings_sync.message_data(True, 7, settings)++ with mock.patch.object(locale, "is_us_region", return_value=True):++ american = settings_sync.message_data(True, 7, settings)++ self.assertEqual(json.dumps(british, sort_keys=True, separators=(",", ":")),++ json.dumps(american, sort_keys=True, separators=(",", ":")))++ self.assertEqual(settings["glow_colour"], "colourful")diff --cc core/tests/test_pairing_paths.pyindex bd880d6,0000000..e2cb0aamode 100644,000000..100644--- a/core/tests/test_pairing_paths.py+++ b/core/tests/test_pairing_paths.py@@@ -1,326 -1,0 +1,333 @@@+"""Pairing over a machine with more than one way to the other (beta.4).++On 01-10-2026 the spare laptop took a VPN's subnet route for its own home network, so its UDP answer+left from the VPN's address rather than the Wi-Fi address the request had come in on, and the+requester, which took an answer only from the address it asked, ignored it: both directions said+"did not answer". Now the host answers from the address on the requester's own network where it has+one, and the requester takes an answer by its pairing id and its crypto, from any address.++The beacons' directed broadcasts used to assume a /24; they now follow each interface's netmask.+"""++import ipaddress+import socket+import threading+import unittest+from unittest import mock++from core import pairing+from core.pairing import PairingError+- from .test_pairing_service import MAC_ID, PC_ID, Machine, free_port, wait_until++from .test_pairing_service import MAC_ID, PC_ID, Machine, wait_until+++def _can_bind(address):+ probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ probe.bind((address, 0))+ return True+ except OSError:+ return False+ finally:+ probe.close()+++class BroadcastTargetTests(unittest.TestCase):+ def test_each_interface_is_sent_the_broadcast_of_its_own_netmask(self):+ interfaces = [("192.168.1.20", "255.255.255.0"), ("169.254.3.7", "255.255.0.0"),+ ("10.1.2.5", "255.255.255.252"), ("172.20.9.9", "255.240.0.0")]+ self.assertEqual(pairing.broadcast_targets(47000, interfaces), [+ ("255.255.255.255", 47000), ("192.168.1.255", 47000), ("169.254.255.255", 47000),+ ("10.1.2.7", 47000), ("172.31.255.255", 47000),+ ])++ def test_two_addresses_on_one_network_send_it_one_broadcast(self):+ interfaces = [("192.168.1.20", "255.255.255.0"), ("192.168.1.21", "255.255.255.0")]+ self.assertEqual(pairing.broadcast_targets(1, interfaces), [("255.255.255.255", 1), ("192.168.1.255", 1)])++ def test_with_no_interfaces_known_it_falls_back_to_a_24(self):+ with mock.patch.object(pairing, "_local_ipv4_addresses", return_value=["10.9.8.7"]):+ self.assertEqual(pairing.broadcast_targets(1, []), [("255.255.255.255", 1), ("10.9.8.255", 1)])+++class InterfaceTests(unittest.TestCase):+ def test_this_machine_s_interfaces_are_read_with_real_netmasks(self):+ found = pairing._interfaces()+ if not found:+ self.skipTest("no IPv4 network here")+ for address, netmask in found:+ network = ipaddress.IPv4Network(f"{address}/{netmask}", strict=False)+ self.assertFalse(ipaddress.IPv4Address(address).is_loopback, address)+ self.assertLess(network.prefixlen, 31, (address, netmask))+ # Checked against the routing table, which knows nothing of how the list was read.+ routed = pairing.pairing_address()+ if routed is not None:+ self.assertIn(routed, [address for address, _netmask in found])++ def test_a_platform_that_will_not_say_gives_none(self):+ failing = mock.patch.object(pairing, "_posix_interfaces" if pairing.sys.platform != "win32" else "_windows_interfaces",+ side_effect=OSError("no"))+ with failing:+ self.assertEqual(pairing._interfaces(), [])+++class AnswerSourceTests(unittest.TestCase):+ INTERFACES = [("192.168.50.22", "255.255.255.0"), ("192.168.56.1", "255.255.255.0")]++ def test_a_requester_on_one_of_this_machine_s_networks_is_answered_from_that_network(self):+ source = pairing._answer_source("192.168.50.5", self.INTERFACES, towards=lambda host: "100.64.0.7")+ self.assertEqual(source, "192.168.50.22")++ def test_where_the_routing_table_agrees_nothing_changes(self):+ self.assertIsNone(pairing._answer_source("192.168.50.5", self.INTERFACES, towards=lambda host: "192.168.50.22"))++ def test_two_addresses_on_the_requester_s_network_leave_the_routing_table_s_choice_alone(self):+ interfaces = [("192.168.50.10", "255.255.255.0"), ("192.168.50.20", "255.255.255.0")]+ self.assertIsNone(pairing._answer_source("192.168.50.5", interfaces, towards=lambda host: "192.168.50.20"))+ self.assertEqual(pairing._answer_source("192.168.50.5", interfaces, towards=lambda host: "100.64.0.7"), "192.168.50.10")++ def test_a_requester_on_no_network_of_this_machine_s_is_routed_as_ever(self):+ self.assertIsNone(pairing._answer_source("203.0.113.9", self.INTERFACES, towards=lambda host: "100.64.0.7"))+ self.assertIsNone(pairing._answer_source("not an address", self.INTERFACES, towards=lambda host: "x"))+++class RequesterTakesAnAnswerFromAnyAddressTests(unittest.TestCase):+ def setUp(self):- mac_udp, pc_udp = free_port(socket.SOCK_DGRAM), free_port(socket.SOCK_DGRAM)- self.mac = Machine(self, "Loop Mac", MAC_ID, "macos", peer_udp=pc_udp, udp_port=mac_udp)- self.pc = Machine(self, "Loop PC", PC_ID, "windows", peer_udp=mac_udp, udp_port=pc_udp)++ self.mac = Machine(self, "Loop Mac", MAC_ID, "macos")++ self.pc = Machine(self, "Loop PC", PC_ID, "windows", peer_udp=self.mac.udp_port)++ self.mac.pair_with(self.pc)++ def _answer_from(self, address):+ """The PC's answers leave from `address`, as a VPN's route sent the laptop's."""+ out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ out.bind((address, 0))+ self.addCleanup(out.close)+ sent = []++ def answer(sock, data, to):+ sent.append(to)+ out.sendto(data, to)++ self.pc.service._answer = answer+ return sent++ def _pair(self):+ code = self.pc.service.begin_pairing()- self.assertTrue(wait_until(lambda: any(m["pair_id"] for m in self.mac.service.machines())))++ self.assertTrue(++ wait_until(lambda: any(m["pair_id"] for m in self.mac.service.machines())),++ f"pairing id not announced; mac error={self.mac.service.error!r}, "++ f"pc error={self.pc.service.error!r}, "++ f"ports={self.mac.service.bind_port!r}/{self.pc.service.bind_port!r}",++ )+ seen = [m for m in self.mac.service.machines() if m["pair_id"]][0]+ return seen, code++ def test_an_answer_from_another_address_still_pairs(self):+ # macOS's loopback holds 127.0.0.1 alone; a LAN address reaches it as well.+ stand_in = "127.0.0.2" if _can_bind("127.0.0.2") else pairing.pairing_address()+ if stand_in is None:+ self.skipTest("no second address to answer from")+ sent = self._answer_from(stand_in)+ seen, code = self._pair()+ saved = self.mac.service.pair(seen, code)+ self.assertTrue(sent, "the PC answered through the stand-in")+ self.assertEqual(saved["host"], "127.0.0.1", "the entry keeps the address the beacon came from")+ self.assertTrue(wait_until(lambda: self.pc.paired))+ self.assertEqual(self.pc.paired[0]["token"], saved["token"])++ def test_an_answer_for_another_pairing_id_is_not_taken(self):+ service = self.mac.service+ service._awaiting = "ours"+ for message in ({"type": "pair_answer", "pair": "theirs"}, {"type": "pair_answer"}):+ service._dispatch(None, message, ("192.0.2.9", 1), 0.0, {}, {})+ self.assertTrue(service._replies.empty())+ service._dispatch(None, {"type": "pair_answer", "pair": "ours"}, ("192.0.2.9", 1), 0.0, {}, {})+ self.assertEqual(service._replies.get_nowait()[1], ("192.0.2.9", 1))++ def test_nothing_is_taken_while_no_attempt_is_under_way(self):+ service = self.mac.service+ service._dispatch(None, {"type": "pair_answer"}, ("192.0.2.9", 1), 0.0, {}, {})+ service._dispatch(None, {"type": "pair_answer", "pair": None}, ("192.0.2.9", 1), 0.0, {}, {})+ self.assertTrue(service._replies.empty())++ def _forge(self, forged):+ """Each reply in `forged`, by type, reaches the requester from a stranger's address just+ before the host's own."""+ service = self.mac.service+ real_ask = service._ask++ def ask(send, receive, target, pair_id, message, reply_type, proves=None):+ for reply in forged.get(reply_type, ()):+ service._replies.put((dict(reply, pair=pair_id), ("192.0.2.9", 4)))+ return real_ask(send, receive, target, pair_id, message, reply_type, proves)++ service._ask = ask++ def test_forged_answers_from_another_address_lose_to_the_host_s_own(self):+ seen, code = self._pair()+ good = {"type": "pair_answer", "ok": True, "share": pairing._b64(bytes(32)), "tag": pairing._b64(bytes(32)),+ "id": pairing._b64(PC_ID), "name": "Loop PC", "platform": "windows", "port": 24820}+ self._forge({"pair_answer": [good, {"type": "pair_answer", "ok": False, "error": "refused"}]})+ saved = self.mac.service.pair(seen, code)+ self.assertNotIn(code, self.mac.service._failed, "no forgery was judged")+ self.assertTrue(wait_until(lambda: self.pc.paired))+ self.assertEqual(self.pc.paired[0]["token"], saved["token"])++ def test_a_forged_receipt_from_any_address_leaves_no_half_pairing(self):+ seen, code = self._pair()+ self._forge({"pair_done": [{"type": "pair_done", "ok": True, "tag": pairing._b64(bytes(32))},+ {"type": "pair_done", "ok": True, "tag": "not base64!"}]})+ saved = self.mac.service.pair(seen, code)+ self.assertEqual(len(self.mac.book.entries), 1)+ self.assertTrue(wait_until(lambda: self.pc.paired))+ self.assertEqual(self.pc.paired[0]["token"], saved["token"])++ def test_with_nothing_from_the_host_a_refusal_from_elsewhere_still_ends_the_attempt(self):+ service = self.mac.service+ service.clock = iter(range(0, 10**6, 1)).__next__+ replies = iter([({"type": "pair_answer", "pair": "p", "ok": False, "error": "busy"}, ("192.0.2.9", 4)), None])+ reply = service._ask(lambda data: None, lambda timeout: next(replies, None), ("127.0.0.1", 1), "p",+ {"type": "pair_start"}, "pair_answer")+ self.assertEqual(reply["error"], "busy")+++class AskTests(unittest.TestCase):+ """_ask on its own, with replies handed in as they would arrive."""++ TARGET = ("192.168.50.3", 47000)+ ELSEWHERE = ("192.0.2.9", 4)++ def ask(self, arrivals, reply_type="pair_answer", proves=None, windows=None):+ """`arrivals`: per window, the (reply, address) pairs that come in it; the window then ends."""+ service = pairing.Discovery(logger=None)+ now = [0.0]+ service.clock = lambda: now[0]+ windows = [list(window) for window in arrivals]+ queued = []++ def send(data):+ if windows:+ queued.extend(windows.pop(0))++ def receive(timeout):+ if queued:+ return queued.pop(0)+ now[0] += timeout+ return None++ return service._ask(send, receive, self.TARGET, "p", {"type": "pair_start"}, reply_type, proves)++ def reply(self, ok=True, **fields):+ return dict({"type": "pair_answer", "pair": "p", "ok": ok}, **fields)++ def test_the_asked_address_wins_even_when_its_reply_is_queued_behind_the_window_s_end(self):+ service = pairing.Discovery(logger=None)+ now = [0.0]+ service.clock = lambda: now[0]+ queued = [(self.reply(name="forged"), self.ELSEWHERE), (self.reply(name="real"), self.TARGET)]++ def receive(timeout):+ # The forgery is read just as the window closes; the real answer is already waiting.+ now[0] += pairing.PAIR_REPLY_TIMEOUT_SECONDS+ return queued.pop(0) if queued else None++ reply = service._ask(lambda data: None, receive, self.TARGET, "p", {"type": "pair_start"}, "pair_answer")+ self.assertEqual(reply["name"], "real")++ def test_with_nothing_from_the_asked_address_an_ok_reply_from_elsewhere_beats_a_refusal(self):+ reply = self.ask([[(self.reply(ok=False, error="busy"), self.ELSEWHERE), (self.reply(name="ok"), self.ELSEWHERE)]])+ self.assertEqual(reply["name"], "ok")++ def test_only_the_first_of_each_kind_from_elsewhere_is_kept(self):+ flood = [(self.reply(name=str(n)), self.ELSEWHERE) for n in range(500)]+ reply = self.ask([flood])+ self.assertEqual(reply["name"], "0")++ def test_a_bad_receipt_from_elsewhere_is_ignored_and_one_from_the_asked_address_decides(self):+ done = lambda ok=True, tag="bad": {"type": "pair_done", "pair": "p", "ok": ok, "tag": tag}+ proves = lambda reply: reply["tag"] == "good"+ reply = self.ask([[(done(), self.ELSEWHERE), (done(tag="good"), self.ELSEWHERE)]], "pair_done", proves)+ self.assertEqual(reply["tag"], "good")+ reply = self.ask([[(done(), self.TARGET), (done(tag="good"), self.ELSEWHERE)]], "pair_done", proves)+ self.assertEqual(reply["tag"], "bad", "the asked address decides, and finish() refuses it")+ with self.assertRaises(PairingError):+ self.ask([[(done(), self.ELSEWHERE)], [], []], "pair_done", proves)+++class ReceiveTests(unittest.TestCase):+ class Socket:+ def __init__(self, error):+ self.error = error++ def settimeout(self, timeout):+ pass++ def recvfrom(self, size):+ raise self.error++ def test_an_oversized_datagram_on_windows_is_passed_over(self):+ error = OSError(10040, "message too long")+ error.winerror = 10040+ self.assertEqual(pairing._receive_on(self.Socket(error), 1.0), ({}, ("", 0)))++ def test_any_other_failure_ends_the_attempt_as_no_answer(self):+ with self.assertRaises(PairingError) as caught:+ pairing._receive_on(self.Socket(OSError(9, "bad file descriptor")), 1.0)+ self.assertEqual(str(caught.exception), "no_answer")+++class OversizedDatagramTests(unittest.TestCase):+ def test_a_datagram_too_large_for_the_buffer_does_not_stop_the_service(self):- mac_udp, pc_udp = free_port(socket.SOCK_DGRAM), free_port(socket.SOCK_DGRAM)- mac = Machine(self, "Loop Mac", MAC_ID, "macos", peer_udp=pc_udp, udp_port=mac_udp)- Machine(self, "Loop PC", PC_ID, "windows", peer_udp=mac_udp, udp_port=pc_udp)++ mac = Machine(self, "Loop Mac", MAC_ID, "macos")++ pc = Machine(self, "Loop PC", PC_ID, "windows", peer_udp=mac.udp_port)++ mac.pair_with(pc)+ self.assertTrue(wait_until(lambda: mac.service.machines()))+ stranger = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ self.addCleanup(stranger.close)+ for _ in range(3):- stranger.sendto(b"x" * 4000, ("127.0.0.1", mac_udp))++ stranger.sendto(b"x" * 4000, ("127.0.0.1", mac.udp_port))+ mac.service._seen.clear()+ self.assertTrue(wait_until(lambda: mac.service.machines()), "the PC's beacons are still heard")+ self.assertIsNone(mac.service.error)+++class HostAnswersFromTheRequesterSNetworkTests(unittest.TestCase):+ def test_both_ends_send_from_the_address_on_the_other_s_network(self):- mac_udp, pc_udp = free_port(socket.SOCK_DGRAM), free_port(socket.SOCK_DGRAM)- mac = Machine(self, "Loop Mac", MAC_ID, "macos", peer_udp=pc_udp, udp_port=mac_udp)- pc = Machine(self, "Loop PC", PC_ID, "windows", peer_udp=mac_udp, udp_port=pc_udp)- sent = {}++ mac = Machine(self, "Loop Mac", MAC_ID, "macos")++ pc = Machine(self, "Loop PC", PC_ID, "windows", peer_udp=mac.udp_port)++ mac.pair_with(pc)++ attempts = []+ real_sendto = socket.socket.sendto++ def sendto(sock, data, address):- result = real_sendto(sock, data, address)+ kind = (pairing.decode(data) or {}).get("type")++ source = sock.getsockname()+ if kind in ("pair_start", "pair_confirm", "pair_answer", "pair_done"):- sent.setdefault(kind, []).append((sock.getsockname(), address))- return result++ # The receiver can finish pairing before this thread resumes after sendto.++ attempts.append((kind, source, address))++ return real_sendto(sock, data, address)++ code = pc.service.begin_pairing()+ self.assertTrue(wait_until(lambda: any(m["pair_id"] for m in mac.service.machines())))+ seen = [m for m in mac.service.machines() if m["pair_id"]][0]+ # Each machine's routing table would send to 127.0.0.1 from elsewhere; its loopback holds it.+ with mock.patch.object(pairing, "_interfaces", return_value=[("127.0.0.1", "255.0.0.0")]), \+ mock.patch.object(pairing, "local_address_towards", return_value="192.0.2.1"), \+ mock.patch.object(socket.socket, "sendto", sendto):+ saved = mac.service.pair(seen, code)- (start_from, start_to), = sent["pair_start"][:1]- self.assertEqual(start_to, ("127.0.0.1", pc_udp))++ (start_from, start_to), = [(source, target) for kind, source, target in attempts if kind == "pair_start"][:1]++ self.assertEqual(start_to, ("127.0.0.1", pc.udp_port))+ self.assertEqual(start_from[0], "127.0.0.1")- self.assertNotEqual(start_from[1], mac_udp, "the request went on a socket of its own")- self.assertEqual({source for source, _to in sent["pair_confirm"]}, {start_from})- for kind in ("pair_answer", "pair_done"):- for (address, port), to in sent[kind]:++ self.assertNotEqual(start_from[1], mac.udp_port, "the request went on a socket of its own")++ self.assertEqual({source for kind, source, _to in attempts if kind == "pair_confirm"}, {start_from})++ self.assertIn("pair_done", [kind for kind, _source, _target in attempts])++ for kind, (address, port), to in attempts:++ if kind in ("pair_answer", "pair_done"):+ self.assertEqual((address, to), ("127.0.0.1", start_from), kind)- self.assertNotEqual(port, pc_udp, "never bound beside the main socket, whose datagrams it could take")++ self.assertNotEqual(port, pc.udp_port, "never bound beside the main socket, whose datagrams it could take")+ self.assertTrue(wait_until(lambda: pc.paired))+ self.assertEqual(pc.paired[0]["token"], saved["token"])+++if __name__ == "__main__":+ unittest.main()diff --cc core/tests/test_pairing_service.pyindex 6ff5f8d,0000000..1e64422mode 100644,000000..100644--- a/core/tests/test_pairing_service.py+++ b/core/tests/test_pairing_service.py@@@ -1,572 -1,0 +1,599 @@@+"""Pairing version 3 on the sockets (WIRE.md section 6): every desktop announces and discovers on+one UDP socket, hosts over UDP and TCP with one PairingHost, and requests over either.++Loopback only: the beacons go to a named port on 127.0.0.1, never the broadcast address.+"""++import json+import logging+import socket+import struct+import threading+import time+import unittest+from unittest import mock++from core import pairing+from core.pairing import AlreadyPaired, PairingClient, PairingError, PairingService++from .test_pairing_v3 import Book, entry++MAC_ID = bytes(range(1, 17))+PC_ID = bytes(range(101, 117))+++def quiet_logger():+ logger = logging.getLogger("pairing-service-tests")+ logger.handlers = [logging.NullHandler()]+ logger.propagate = False+ return logger++- def free_port(kind):- sock = socket.socket(socket.AF_INET, kind)- sock.bind(("127.0.0.1", 0))- port = sock.getsockname()[1]- sock.close()- return port--+def wait_until(predicate, timeout=5.0):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return True+ time.sleep(0.02)+ return False+++def send_frame(sock, message):+ body = pairing.encode(message)+ sock.sendall(struct.pack(">I", len(body)) + body)+++def read_frame(sock):+ """The next framed message, or None when the connection closed first."""+ header = b""+ while len(header) < 4:+ chunk = sock.recv(4 - len(header))+ if not chunk:+ return None+ header += chunk+ (length,) = struct.unpack(">I", header)+ body = b""+ while len(body) < length:+ chunk = sock.recv(length - len(body))+ if not chunk:+ return None+ body += chunk+ return json.loads(body)+++def closed_without_a_byte(sock, timeout=2.0):+ sock.settimeout(timeout)+ try:+ return sock.recv(1) == b""+ except ConnectionResetError:+ return True+++class Machine:+ def __init__(self, test, name, identity, platform, peer_udp=None, entries=(), udp_port=None):+ self.book = Book(entries)- self.udp_port = udp_port or free_port(socket.SOCK_DGRAM)- self.tcp_port = free_port(socket.SOCK_STREAM)++ self.udp_port = 0 if udp_port is None else udp_port+ self.paired = []+ self.service = PairingService(+ name=name, identity=identity, platform=platform, port_getter=lambda: 24820,+ peers=self.book.peers, store=self.book.store, on_paired=self.paired.append,- logger=quiet_logger(), bind_port=self.udp_port, tcp_port=self.tcp_port,- announce_to=("127.0.0.1", peer_udp or free_port(socket.SOCK_DGRAM)),++ logger=quiet_logger(), bind_port=self.udp_port, tcp_port=0,++ announce_to=("127.0.0.1", peer_udp if peer_udp is not None else 0),+ )+ self.service.start()+ test.addCleanup(self.service.stop)++ assert wait_until(lambda: self.service.listening_port is not None), "the pairing service did not bind"++ self.udp_port = self.service.listening_port++++ @property++ def tcp_port(self):++ return self.service.tcp_port++++ def pair_with(self, peer):++ self.service.announce_to = ("127.0.0.1", peer.udp_port)++ def connect(self):+ sock = socket.create_connection(("127.0.0.1", self.tcp_port), timeout=3.0)+ sock.settimeout(3.0)+ return sock++++class EphemeralPortTests(unittest.TestCase):++ def test_pairing_service_reports_the_ports_bound_by_the_os(self):++ book = Book()++ service = PairingService(++ "Loop PC", PC_ID, "windows", lambda: 24820, book.peers, book.store,++ logger=quiet_logger(), bind_port=0, tcp_port=0, announce_to=("127.0.0.1", 0),++ )++ self.addCleanup(service.stop)++ service.start()++ self.assertTrue(wait_until(lambda: service._sock is not None))++ udp_port = service._sock.getsockname()[1]++ self.assertEqual(getattr(service, "listening_port", None), udp_port)++ service.begin_pairing()++ self.assertGreater(service.tcp_port, 0)++++ def test_two_pairing_services_announce_on_their_actual_ports(self):++ mac = Machine(self, "Loop Mac", MAC_ID, "macos")++ pc = Machine(self, "Loop PC", PC_ID, "windows", peer_udp=mac.udp_port)++ mac.pair_with(pc)++ code = pc.service.begin_pairing()++ self.assertTrue(wait_until(lambda: any(machine["pair_id"] for machine in mac.service.machines())))++ seen = next(machine for machine in mac.service.machines() if machine["pair_id"])++ saved = mac.service.pair(seen, code)++ self.assertTrue(wait_until(lambda: pc.paired))++ self.assertEqual(pc.paired[0]["token"], saved["token"])+++++class BothEndsTests(unittest.TestCase):+ def setUp(self):- mac_udp, pc_udp = free_port(socket.SOCK_DGRAM), free_port(socket.SOCK_DGRAM)- self.mac = Machine(self, "Loop Mac", MAC_ID, "macos", peer_udp=pc_udp, udp_port=mac_udp)- self.pc = Machine(self, "Loop PC", PC_ID, "windows", peer_udp=mac_udp, udp_port=pc_udp)++ self.mac = Machine(self, "Loop Mac", MAC_ID, "macos")++ self.pc = Machine(self, "Loop PC", PC_ID, "windows", peer_udp=self.mac.udp_port)++ self.mac.pair_with(self.pc)++ def _pair_over_udp(self, host, requester):+ code = host.service.begin_pairing()+ self.assertTrue(wait_until(lambda: any(m["pair_id"] for m in requester.service.machines())))+ seen = [m for m in requester.service.machines() if m["pair_id"]][0]+ saved = requester.service.pair(seen, code)+ self.assertTrue(wait_until(lambda: host.paired))+ return seen, saved++ def test_each_hears_the_other_and_either_can_host(self):+ self.assertTrue(wait_until(lambda: self.mac.service.machines() and self.pc.service.machines()))+ heard = self.mac.service.machines()[0]+ self.assertEqual((heard["name"], heard["platform"], heard["pairing"], heard["port"], heard["id"]), ("Loop PC", "windows", 3, 24820, None))+ self.assertEqual(self.pc.service.machines()[0]["name"], "Loop Mac", "a machine does not list itself")+ self.assertEqual(len(self.pc.service.machines()), 1)++ seen, saved = self._pair_over_udp(self.pc, self.mac)+ self.assertEqual(seen["id"], pairing._b64(PC_ID))+ self.assertEqual((saved["id"], saved["name"], saved["platform"], saved["host"]), (pairing._b64(PC_ID), "Loop PC", "windows", "127.0.0.1"))+ self.assertEqual(self.pc.paired[0]["token"], saved["token"])+ self.assertEqual(self.pc.book.entries[0]["id"], pairing._b64(MAC_ID))++ # The other way round, once each has forgotten the other.+ self.mac.book.entries, self.pc.book.entries = [], []+ _seen, saved = self._pair_over_udp(self.mac, self.pc)+ self.assertEqual((saved["name"], saved["platform"]), ("Loop Mac", "macos"))+ self.assertEqual(self.mac.book.entries[0]["token"], saved["token"])++ def test_an_already_paired_host_is_refused_by_the_requester_over_udp(self):+ self.mac.book.entries.append(entry(PC_ID, name="Loop PC", paired_at=1_700_000_000))+ code = self.pc.service.begin_pairing()+ self.assertTrue(wait_until(lambda: any(m["pair_id"] for m in self.mac.service.machines())))+ seen = [m for m in self.mac.service.machines() if m["pair_id"]][0]+ with self.assertRaises(AlreadyPaired) as caught:+ self.mac.service.pair(seen, code)+ self.assertEqual(caught.exception.entry["paired_at"], 1_700_000_000)+ self.assertTrue(wait_until(lambda: self.pc.service.outcome == "known_there"))+ self.assertEqual(self.pc.book.entries, [])+++class OwnBeaconTests(unittest.TestCase):+ def test_a_machine_that_hears_its_own_beacons_does_not_list_itself(self):- port = free_port(socket.SOCK_DGRAM)- alone = Machine(self, "Alone", MAC_ID, "macos", peer_udp=port, udp_port=port)++ alone = Machine(self, "Alone", MAC_ID, "macos")++ alone.pair_with(alone)+ arrived = []+ original = alone.service._dispatch+ alone.service._dispatch = lambda sock, message, *rest: (arrived.append(message.get("type")), original(sock, message, *rest))+ # Its beacons reach its own socket: the filter, not the addressing, keeps it off the list.+ self.assertTrue(wait_until(lambda: "beacon" in arrived))+ time.sleep(0.2)+ self.assertEqual(alone.service.machines(), [])+++class BeaconTests(unittest.TestCase):+ def setUp(self):+ self.listener = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ self.listener.bind(("127.0.0.1", 0))+ self.listener.settimeout(3.0)+ self.addCleanup(self.listener.close)+ self.pc = Machine(self, "Beacon PC", PC_ID, "windows", peer_udp=self.listener.getsockname()[1])++ def _next_beacon(self):+ while True:+ data, _address = self.listener.recvfrom(2048)+ message = pairing.decode(data)+ if message and message.get("type") == "beacon":+ return message++ def test_id_and_pair_only_while_a_code_is_up(self):+ idle = self._next_beacon()+ self.assertEqual(idle, {"beamy": 1, "type": "beacon", "name": "Beacon PC", "port": 24820, "pairing": 3, "platform": "windows"})+ self.pc.service.begin_pairing()+ live = self._next_beacon()+ while "id" not in live:+ live = self._next_beacon()+ self.assertEqual(live["id"], pairing._b64(PC_ID))+ self.pc.service.cancel_pairing()+ after = self._next_beacon()+ while "id" in after:+ after = self._next_beacon()+ self.assertNotIn("pair", after)++ def test_a_pairing_2_beacon_is_reported_older_and_sent_nothing(self):+ mac = Machine(self, "Mac", MAC_ID, "macos")+ old = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ old.bind(("127.0.0.1", 0))+ old.settimeout(0.5)+ self.addCleanup(old.close)+ beacon = pairing.encode({"type": "beacon", "name": "Old PC", "port": 24820, "pairing": 2, "pair": "ab" * 16})+ # Sent until heard, since the service binds its socket on its own thread.+ self.assertTrue(wait_until(lambda: old.sendto(beacon, ("127.0.0.1", mac.udp_port)) and mac.service.machines()))+ seen = mac.service.machines()[0]+ self.assertEqual(seen["pairing"], 2)+ with self.assertRaises(PairingError) as caught:+ mac.service.pair(seen, "123456")+ self.assertEqual(str(caught.exception), pairing.ERROR_VERSION)+ while True:+ try:+ old.recvfrom(2048)+ except socket.timeout:+ break+ except ConnectionResetError:+ # Windows: the port-unreachable of a beacon sent before the service had bound.+ continue+ self.fail("the older machine was sent something")+++class TcpTests(unittest.TestCase):+ def setUp(self):+ self.pc = Machine(self, "TCP PC", PC_ID, "windows")+ self.mac = Machine(self, "TCP Mac", MAC_ID, "macos")++ def test_a_whole_exchange_over_tcp_agrees_one_token(self):+ code = self.pc.service.begin_pairing()+ saved = self.mac.service.pair_by_address("127.0.0.1", code, port=self.pc.tcp_port)+ self.assertTrue(wait_until(lambda: self.pc.paired))+ self.assertEqual(self.pc.paired[0]["token"], saved["token"])+ self.assertEqual((saved["host"], saved["port"], saved["id"]), ("127.0.0.1", 24820, pairing._b64(PC_ID)))+ self.assertEqual(self.pc.book.entries[0]["host"], "127.0.0.1")+ self.assertEqual(self.pc.service.outcome, "paired")++ def test_the_requester_replaces_the_1_4_entry_held_at_that_address(self):+ old = {"id": "", "name": "Old PC", "platform": "windows", "token": "typed-in-1.4", "host": "127.0.0.1",+ "port": 24820, "linked": False, "paired_at": 0, "from_1_4": True}+ self.mac.book.entries.append(old)+ code = self.pc.service.begin_pairing()+ saved = self.mac.service.pair_by_address("127.0.0.1", code, port=self.pc.tcp_port)+ self.assertEqual(self.mac.book.entries, [saved])+ self.assertEqual(self.mac.book.stored[-1][1]["from_1_4"], True)++ def test_a_qr_exchange_sends_qr_and_pairs(self):+ self.pc.service.begin_pairing()+ text = self.pc.service.qr_text("127.0.0.1")+ self.assertEqual(pairing.read_qr(text)["port"], self.pc.tcp_port)+ saved = self.mac.service.pair_by_qr(text)+ self.assertTrue(wait_until(lambda: self.pc.paired))+ self.assertEqual(self.pc.paired[0]["token"], saved["token"])++ def test_scanning_the_qr_of_a_machine_already_paired_does_not_pair(self):+ self.mac.book.entries.append(entry(PC_ID, name="TCP PC", paired_at=1_700_000_000))+ self.pc.service.begin_pairing()+ with self.assertRaises(AlreadyPaired) as caught:+ self.mac.service.pair_by_qr(self.pc.service.qr_text("127.0.0.1"))+ self.assertEqual(caught.exception.entry["id"], pairing._b64(PC_ID))+ # Nothing was sent: the host's code is still up and unspent.+ self.assertIsNotNone(self.pc.service.code)+ self.assertIsNone(self.pc.service.outcome)++ def test_rule_1_holds_across_the_two_transports(self):+ # UDP first: its pair_start binds the code, and the TCP one is refused.+ code = self.pc.service.begin_pairing()+ client = PairingClient(self.pc.service.host.pair_id, code, "Stranger", bytes([5]) * 16, version=3, platform="linux", port=24820, peers=list)+ udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ udp.bind(("127.0.0.1", 0))+ udp.settimeout(3.0)+ self.addCleanup(udp.close)+ udp.sendto(pairing.encode(client.start()), ("127.0.0.1", self.pc.udp_port))+ self.assertTrue(pairing.decode(udp.recvfrom(2048)[0])["ok"])+ with self.assertRaises(PairingError) as caught:+ self.mac.service.pair_by_address("127.0.0.1", code, port=self.pc.tcp_port)+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)++ # TCP first: the UDP one is refused.+ code = self.pc.service.begin_pairing()+ sock = self.pc.connect()+ self.addCleanup(sock.close)+ beacon = read_frame(sock)+ client = PairingClient(beacon["pair"], code, "Stranger", bytes([5]) * 16, version=3, platform="linux", port=24820, peers=list)+ send_frame(sock, client.start())+ self.assertTrue(read_frame(sock)["ok"])+ other = PairingClient(beacon["pair"], code, "Other", bytes([6]) * 16, version=3, platform="linux", port=24820, peers=list)+ udp.sendto(pairing.encode(other.start()), ("127.0.0.1", self.pc.udp_port))+ self.assertEqual(pairing.decode(udp.recvfrom(2048)[0])["error"], pairing.ERROR_REFUSED)++ def test_the_host_s_beacon_comes_first_with_pair_and_id(self):+ self.pc.service.begin_pairing()+ sock = self.pc.connect()+ self.addCleanup(sock.close)+ beacon = read_frame(sock)+ self.assertEqual((beacon["type"], beacon["pairing"], beacon["pair"], beacon["id"], beacon["platform"]),+ ("beacon", 3, self.pc.service.host.pair_id, pairing._b64(PC_ID), "windows"))++ def test_a_length_of_0_or_over_1024_closes_before_the_body(self):+ for length in (0, 1025):+ with self.subTest(length=length):+ self.pc.service.begin_pairing()+ sock = self.pc.connect()+ self.addCleanup(sock.close)+ read_frame(sock)+ sock.sendall(struct.pack(">I", length))+ self.assertTrue(closed_without_a_byte(sock))+ self.assertIsNotNone(self.pc.service.code, "a bad frame costs the connection, not the code")++ def test_out_of_order_messages_close_with_nothing_sent(self):+ code = self.pc.service.begin_pairing()+ sock = self.pc.connect()+ self.addCleanup(sock.close)+ beacon = read_frame(sock)+ send_frame(sock, {"type": "pair_confirm", "pair": beacon["pair"], "tag": ""})+ self.assertTrue(closed_without_a_byte(sock))++ sock = self.pc.connect()+ self.addCleanup(sock.close)+ read_frame(sock)+ client = PairingClient(beacon["pair"], code, "Stranger", bytes([5]) * 16, version=3, platform="linux", port=24820, peers=list)+ start = client.start()+ send_frame(sock, start)+ self.assertTrue(read_frame(sock)["ok"])+ send_frame(sock, start)+ self.assertTrue(closed_without_a_byte(sock))++ def test_a_refusal_is_sent_before_the_close(self):+ code = self.pc.service.begin_pairing()+ sock = self.pc.connect()+ self.addCleanup(sock.close)+ beacon = read_frame(sock)+ client = PairingClient(beacon["pair"], code, "Stranger", bytes([5]) * 16, version=3, platform="linux", port=24820, peers=list)+ send_frame(sock, dict(client.start(), v=2))+ self.assertEqual(read_frame(sock), {"beamy": 1, "type": "pair_answer", "pair": beacon["pair"], "ok": False, "error": "version"})+ self.assertIsNone(read_frame(sock))++ def test_a_tcp_beacon_of_pairing_2_stops_the_requester_before_it_sends(self):+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ server.bind(("127.0.0.1", 0))+ server.listen(1)+ self.addCleanup(server.close)+ received = []++ def old_host():+ conn, _address = server.accept()+ with conn:+ send_frame(conn, {"type": "beacon", "name": "Old", "port": 24820, "pairing": 2, "pair": "ab" * 16})+ conn.settimeout(3.0)+ received.append(conn.recv(1))++ thread = threading.Thread(target=old_host)+ thread.start()+ with self.assertRaises(PairingError) as caught:+ self.mac.service.pair_by_address("127.0.0.1", "123456", port=server.getsockname()[1])+ thread.join(5)+ self.assertEqual(str(caught.exception), pairing.ERROR_VERSION)+ self.assertEqual(received, [b""])++ def test_the_listener_is_up_only_while_a_code_is(self):+ with self.assertRaises(OSError):+ self.pc.connect().close()+ self.pc.service.begin_pairing()+ self.pc.connect().close()+ self.pc.service.cancel_pairing()+ self.assertTrue(wait_until(lambda: not self._can_connect()))++ def test_the_listener_closes_when_the_code_expires(self):+ clock = [1000.0]+ self.pc.service.host.clock = lambda: clock[0]+ self.pc.service.begin_pairing()+ self.pc.connect().close()+ clock[0] += pairing.CODE_LIFETIME_SECONDS+ self.assertTrue(wait_until(lambda: not self._can_connect()))++ def _can_connect(self):+ try:+ self.pc.connect().close()+ return True+ except OSError:+ return False++ def test_a_connection_has_ten_seconds(self):+ with mock.patch.object(pairing, "TCP_EXCHANGE_SECONDS", 0.5):+ self.pc.service.begin_pairing()+ sock = self.pc.connect()+ self.addCleanup(sock.close)+ read_frame(sock)+ started = time.monotonic()+ self.assertTrue(closed_without_a_byte(sock, timeout=3.0))+ self.assertLess(time.monotonic() - started, 2.0)++ def test_a_second_connection_from_one_address_replaces_the_first(self):+ self.pc.service.begin_pairing()+ first = self.pc.connect()+ self.addCleanup(first.close)+ read_frame(first)+ second = self.pc.connect()+ self.addCleanup(second.close)+ self.assertEqual(read_frame(second)["type"], "beacon")+ self.assertTrue(closed_without_a_byte(first))++ def test_the_answer_leaves_a_fixed_time_after_its_start(self):+ code = self.pc.service.begin_pairing()+ sock = self.pc.connect()+ self.addCleanup(sock.close)+ beacon = read_frame(sock)+ client = PairingClient(beacon["pair"], code, "Timing", bytes([5]) * 16, version=3, platform="linux", port=24820, peers=list)+ sent = time.monotonic()+ send_frame(sock, client.start())+ self.assertTrue(read_frame(sock)["ok"])+ self.assertGreaterEqual(time.monotonic() - sent, pairing.PAIR_ANSWER_SECONDS - 0.005)+++class SlotTests(unittest.TestCase):+ """The four handshake slots, held to the link's terms: one per address, the oldest gives way."""++ def test_one_per_address_and_the_oldest_gives_way(self):+ slots = pairing._Slots(4)+ closed = []+ keys = [slots.take(f"192.168.77.{n}", lambda n=n: closed.append(n)) for n in range(1, 5)]+ self.assertEqual(closed, [])+ slots.take("192.168.77.2", lambda: closed.append("2b"))+ self.assertEqual(closed, [2])+ slots.take("192.168.77.9", lambda: closed.append(9))+ self.assertEqual(closed, [2, 1])+ slots.release(keys[2])+ slots.take("192.168.77.10", lambda: closed.append(10))+ self.assertEqual(closed, [2, 1], "a freed slot is used before anyone is replaced")++ def test_the_connection_that_bound_the_code_is_never_replaced(self):+ slots = pairing._Slots(4)+ closed = []+ bound = slots.take("192.168.77.1", lambda: closed.append("bound"))+ slots.pin(bound)+ for n in range(2, 12):+ slots.take(f"192.168.77.{n}", lambda n=n: closed.append(n))+ slots.take("192.168.77.1", lambda: closed.append("again"))+ self.assertNotIn("bound", closed)+ slots.close_all()+ self.assertIn("bound", closed)++ def test_with_every_slot_bound_a_new_connection_is_turned_away(self):+ slots = pairing._Slots(1)+ closed = []+ slots.pin(slots.take("192.168.77.1", lambda: closed.append("bound")))+ self.assertIsNone(slots.take("192.168.77.2", lambda: closed.append("new")))+ self.assertEqual(closed, ["new"])+ self.assertEqual(len(slots._held), 1)+++ def test_pinning_a_connection_already_replaced_says_so(self):+ slots = pairing._Slots(1)+ first = slots.take("10.9.9.1", lambda: None)+ second = slots.take("10.9.9.2", lambda: None)+ self.assertIs(slots.pin(first), False)+ self.assertIs(slots.pin(second), True)+++class BoundToAGoneConnectionTests(unittest.TestCase):+ def test_a_code_bound_by_a_connection_already_replaced_ends_rather_than_waiting_on_it(self):+ # The review of the fixes: a newcomer could replace the connection in the instant between+ # its pair_start binding the code and its pin, leaving the code bound to nobody.+ pc = Machine(self, "Gone PC", PC_ID, "windows")+ code = pc.service.begin_pairing()+ start = PairingClient(pc.service.host.pair_id, code, "Gone", bytes([7]) * 16, version=3, platform="linux", port=24820, peers=list).start()+ reply, paired, fresh = pc.service._host_handle(start, "10.9.9.1", ("tcp", 99), lambda: False)+ self.assertIsNone(reply)+ self.assertFalse(pc.service.host.active)+ self.assertEqual(pc.service.host.outcome, "refused")+++class ReplayedStartTests(unittest.TestCase):+ """The review's probe: one pair_start replayed on new connections drew the cached answer and+ was pinned each time, so the four slots grew without limit."""++ def test_replays_of_the_bound_start_keep_to_the_four_slots(self):+ pc = Machine(self, "Replay PC", PC_ID, "windows")+ code = pc.service.begin_pairing()+ held = []++ def start(frame=None):+ sock = pc.connect()+ held.append(sock)+ beacon = read_frame(sock)+ if frame is None:+ frame = PairingClient(beacon["pair"], code, "Replayer", bytes([9]) * 16, version=3, platform="linux", port=24820, peers=list).start()+ send_frame(sock, frame)+ self.assertTrue(read_frame(sock)["ok"])+ return frame++ frame = start()+ for _ in range(12):+ start(frame)+ self.addCleanup(lambda: [sock.close() for sock in held])+ self.assertTrue(wait_until(lambda: len(pc.service._slots._held) <= pairing.TCP_MAX_CONNECTIONS))+ self.assertLessEqual(len(pc.service._slots._pinned), 1)+++class RequesterLimitTests(unittest.TestCase):+ def test_a_requester_with_32_peers_does_not_start(self):+ mac = Machine(self, "Full Mac", MAC_ID, "macos", entries=[entry(bytes([n]) * 16) for n in range(1, 33)])+ with self.assertRaises(PairingError) as caught:- mac.service.pair_by_address("127.0.0.1", "123456", port=free_port(socket.SOCK_STREAM))++ mac.service.pair_by_address("127.0.0.1", "123456", port=0)+ self.assertEqual(str(caught.exception), pairing.ERROR_FULL)++ def test_a_host_with_32_peers_shows_no_code(self):+ pc = Machine(self, "Full PC", PC_ID, "windows", entries=[entry(bytes([n]) * 16) for n in range(1, 33)])+ with self.assertRaises(PairingError):+ pc.service.begin_pairing()+ self.assertIsNone(pc.service.code)++ def test_the_failed_code_memory_covers_both_transports(self):- mac_udp, pc_udp = free_port(socket.SOCK_DGRAM), free_port(socket.SOCK_DGRAM)- pc = Machine(self, "PC", PC_ID, "windows", peer_udp=mac_udp, udp_port=pc_udp)- mac = Machine(self, "Mac", MAC_ID, "macos", peer_udp=pc_udp, udp_port=mac_udp)++ mac = Machine(self, "Mac", MAC_ID, "macos")++ pc = Machine(self, "PC", PC_ID, "windows", peer_udp=mac.udp_port)++ mac.pair_with(pc)++ def over_udp(code):+ self.assertTrue(wait_until(lambda: any(m["pair_id"] for m in mac.service.machines())))+ return mac.service.pair([m for m in mac.service.machines() if m["pair_id"]][0], code)++ def over_tcp(code):+ return mac.service.pair_by_address("127.0.0.1", code, port=pc.tcp_port)++ for first, second in ((over_udp, over_tcp), (over_tcp, over_udp)):+ with self.subTest(first=first.__name__):+ code = pc.service.begin_pairing()+ wrong = str((int(code) + 1) % 10**6).zfill(6)+ with self.assertRaises(PairingError):+ first(wrong)+ self.assertTrue(wait_until(lambda: pc.service.outcome == "refused"))+ pc.service.begin_pairing()+ pc.service.host.code = wrong+ with self.assertRaises(PairingError) as caught:+ second(wrong)+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ self.assertIsNone(pc.service.outcome, "the second try sent nothing")+ self.assertEqual(pc.book.entries, [])+ mac.service._failed.clear()++ def test_the_requester_checks_again_just_before_it_stores(self):+ pc = Machine(self, "PC", PC_ID, "windows")+ mac = Machine(self, "Mac", MAC_ID, "macos")+ code = pc.service.begin_pairing()+ real = PairingClient.finish++ def finish(client, done):+ token = real(client, done)+ # Another pairing with the same machine landed while this one was finishing.+ mac.book.entries.append(entry(PC_ID, name="PC"))+ return token++ with mock.patch.object(PairingClient, "finish", finish):+ with self.assertRaises(AlreadyPaired):+ mac.service.pair_by_address("127.0.0.1", code, port=pc.tcp_port)+ self.assertEqual(mac.book.stored, [])++ def test_stop_ends_the_code_and_its_listener(self):+ pc = Machine(self, "PC", PC_ID, "windows")+ pc.service.begin_pairing()+ held = pc.connect()+ self.addCleanup(held.close)+ read_frame(held)+ pc.service.stop()+ self.assertIsNone(pc.service.code)+ self.assertTrue(closed_without_a_byte(held))+ with self.assertRaises(OSError):+ pc.connect().close()++ def test_a_listener_that_cannot_bind_gives_no_qr(self):+ blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ blocker.bind(("", 0))+ blocker.listen(1)+ self.addCleanup(blocker.close)+ pc = Machine(self, "PC", PC_ID, "windows")+ pc.service.tcp_port = blocker.getsockname()[1]+ self.assertIsNotNone(pc.service.begin_pairing())+ self.assertIsNotNone(pc.service.tcp_error)+ self.assertIsNone(pc.service.qr_text("127.0.0.1"))+++if __name__ == "__main__":+ unittest.main()diff --cc core/tests/test_peerlist.pyindex f50d0d8,0000000..93df5demode 100644,000000..100644--- a/core/tests/test_peerlist.py+++ b/core/tests/test_peerlist.py@@@ -1,239 -1,0 +1,252 @@@+"""What the windows do to the peers list, and the words they use for pairing, the same on every desktop."""++import copy+import time+import unittest++from core import pairing, peerlist++A = "AAAAAAAAAAAAAAAAAAAAAA"+B = "BBBBBBBBBBBBBBBBBBBBBw"+C = "CCCCCCCCCCCCCCCCCCCCCg"+++def peer(ident, name="STUDIO-PC", token=None, **extra):+ return {"id": ident, "name": name, "platform": "windows", "token": token or ident * 3, "host": "10.1.1.2",+ "port": 24820, "send": True, "allow_drive": True, "side": "", "linked": True, "from_1_4": False,+ "paired_at": 1_700_000_000, **extra}+++def settings(*peers, zones=()):+ return {"peers": [dict(entry) for entry in peers], "zones": [dict(zone) for zone in zones]}+++class LabelTests(unittest.TestCase):+ def test_a_name_is_its_own_label_while_nothing_shares_it(self):+ labels = peerlist.labels([peer(A, "Desk"), peer(B, "Laptop")])+ self.assertEqual(labels, {A * 3: "Desk", B * 3: "Laptop"})++ def test_two_machines_with_one_name_each_show_the_last_four_characters_of_their_id(self):+ labels = peerlist.labels([peer(A, "Desk"), peer(B, "Desk"), peer(C, "Laptop")])+ self.assertEqual(labels[A * 3], "Desk (AAAA)")+ self.assertEqual(labels[B * 3], "Desk (BBBw)")+ self.assertEqual(labels[C * 3], "Laptop")++ def test_the_comparison_ignores_case_and_surrounding_space(self):+ labels = peerlist.labels([peer(A, "Desk"), peer(B, " desk ")])+ self.assertTrue(all("(" in label for label in labels.values()))++ def test_an_entry_with_no_id_yet_has_the_name_alone(self):+ labels = peerlist.labels([peer("", "Desk", token="legacy", from_1_4=True), peer(B, "Desk")])+ self.assertEqual(labels["legacy"], "Desk")+ self.assertEqual(labels[B * 3], "Desk (BBBw)")++ def test_an_entry_with_no_name_is_called_by_its_address_then_by_what_it_is(self):+ labels = peerlist.labels([peer(A, ""), peer(B, "", host="")])+ self.assertEqual(labels[A * 3], "10.1.1.2")+ self.assertEqual(labels[B * 3], "Unnamed machine")+++ def test_a_phone_without_a_token_is_not_labelled_as_a_machine(self):++ phone = {"id": "phone", "name": "Toby's phone", "port": 0}++ labels = peerlist.labels([peer(A, "Desk"), phone])++ self.assertEqual(labels, {A * 3: "Desk"})++++ def test_a_paired_phone_keeps_its_label_for_input_sent_to_this_machine(self):++ phone = {"id": "phone", "name": "Toby's phone", "port": 0, "token": "phone-token"}++ self.assertEqual(peerlist.labels([phone]), {"phone-token": "Toby's phone"})++++class AddPeerTests(unittest.TestCase):+ def test_a_new_entry_goes_on_the_end(self):+ held = settings(peer(A))+ peerlist.add_peer(held, peer(B))+ self.assertEqual([entry["id"] for entry in held["peers"]], [A, B])++ def test_a_replaced_entry_gives_its_place_to_the_new_one(self):+ # The first entry is the one the flat settings read, so the new one must not slip behind.+ held = settings(peer("", "Old", token="legacy", from_1_4=True), peer(B))+ peerlist.add_peer(held, peer(A, "New"), replaced=copy.deepcopy(held["peers"][0]))+ self.assertEqual([entry["id"] for entry in held["peers"]], [A, B])++ def test_a_machine_paired_crosses_by_its_whole_edge_until_its_ways_are_chosen(self):+ # Pairing made no zones before beta.5, so a second machine's side, once set, led nowhere+ # (the rig and the laptop, 01-10-2026).+ held = settings(peer(A, side="left"), zones=[{"peer": A, "kind": "edge"}])+ peerlist.add_peer(held, peer(B, token="second"))+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])++ def test_the_replaced_entrys_zones_go_with_it_when_it_was_matched_by_name_alone(self):+ held = settings(peer("", token="legacy", host="10.1.1.9", from_1_4=True), zones=[{"peer": "", "kind": "edge"}])+ peerlist.add_peer(held, peer(A), replaced=copy.deepcopy(held["peers"][0]))+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"}])++ def test_the_machine_at_the_1_4_entrys_host_takes_over_its_side_and_zones(self):+ # Every 1.4.x upgrader pairs again (no token migrates), and the user is at the screen+ # pairing that machine on purpose: its arrangement is not theirs to set a second time.+ old = peer("", token="legacy", from_1_4=True, linked=False, side="left", side_set_at=1_790_000_000,+ side_by=C, paired_at=0)+ held = settings(old, zones=[{"peer": "", "kind": "edge"}, {"peer": "", "kind": "corner", "corner": "top_left",+ "edge": "left", "off": True}])+ peerlist.add_peer(held, peer(A, token="fresh"), replaced=copy.deepcopy(old))+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"},+ {"peer": A, "kind": "corner", "corner": "top_left", "edge": "left", "off": True}])+ entry = held["peers"][0]+ self.assertEqual((entry["side"], entry["side_set_at"], entry["side_by"]), ("left", 1_790_000_000, C))+ self.assertEqual(entry["token"], "fresh")++ def test_a_machine_at_that_host_of_another_platform_takes_nothing(self):+ old = peer("", token="legacy", platform="macos", from_1_4=True, side="left")+ held = settings(old, zones=[{"peer": "", "kind": "edge"}])+ peerlist.add_peer(held, peer(A, token="fresh"), replaced=copy.deepcopy(old))+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"}])+ self.assertEqual(held["peers"][0]["side"], "")++ def test_an_entry_that_is_not_the_1_4_one_gives_nothing_by_host(self):+ old = peer(B, token="legacy", linked=False, side="left")+ held = settings(old, zones=[{"peer": B, "kind": "edge"}])+ peerlist.add_peer(held, peer(A, token="fresh"), replaced=copy.deepcopy(old))+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"}])++ def test_zones_of_a_machine_paired_again_under_its_own_id_stay(self):+ held = settings(peer(A, linked=False), zones=[{"peer": A, "kind": "edge"}])+ peerlist.add_peer(held, peer(A, token="fresh"), replaced=copy.deepcopy(held["peers"][0]))+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"}])+ self.assertEqual(held["peers"][0]["token"], "fresh")++ def test_other_machines_zones_are_left_alone(self):+ held = settings(peer(A), peer("", token="legacy", from_1_4=True), zones=[{"peer": A, "kind": "edge"}])+ peerlist.add_peer(held, peer(B), replaced=copy.deepcopy(held["peers"][1]))+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])++ def test_an_entry_replaced_by_token_is_found_though_the_caller_holds_a_copy(self):+ held = settings(peer(A, token="one"))+ peerlist.add_peer(held, peer(B), replaced={**held["peers"][0]})+ self.assertEqual([entry["id"] for entry in held["peers"]], [B])+++class RemovePeerTests(unittest.TestCase):+ def test_the_entry_and_its_zones_go(self):+ held = settings(peer(A), peer(B), zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])+ removed = peerlist.remove_peer(held, A * 3)+ self.assertEqual(removed["id"], A)+ self.assertEqual([entry["id"] for entry in held["peers"]], [B])+ self.assertEqual(held["zones"], [{"peer": B, "kind": "edge"}])++ def test_an_unknown_token_removes_nothing(self):+ held = settings(peer(A))+ self.assertIsNone(peerlist.remove_peer(held, "nope"))+ self.assertEqual(len(held["peers"]), 1)++ def test_the_entry_migrated_from_1_4_goes_with_the_zones_that_name_no_one(self):+ held = settings(peer("", token="legacy", from_1_4=True), zones=[{"peer": "", "kind": "edge"}])+ peerlist.remove_peer(held, "legacy")+ self.assertEqual((held["peers"], held["zones"]), ([], []))+++class WordsTests(unittest.TestCase):+ def test_every_requester_error_has_a_sentence_naming_the_machine(self):+ for reason in (pairing.ERROR_NOT_PAIRING, pairing.ERROR_REFUSED, pairing.ERROR_VERSION, "no_answer"):+ text = peerlist.pairing_error_text(pairing.PairingError(reason), "Desk")+ self.assertIn("Desk", text, reason)+ self.assertTrue(text.endswith("."), reason)++ def test_an_old_beamer_is_told_to_update_to_1_5_0(self):+ text = peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_VERSION), "Desk")+ self.assertEqual(text, "Desk runs an older Beamer. Update Beamer on it to 1.5.0, then pair again.")++ def test_known_names_the_entry_and_the_day_it_was_paired(self):+ entry = peer(A, "Desk", paired_at=int(time.mktime((2026, 9, 24, 12, 0, 0, 0, 0, -1))))+ text = peerlist.pairing_error_text(pairing.AlreadyPaired(entry), "that machine")+ self.assertIn("Desk", text)+ self.assertIn("24-09-2026", text)+ self.assertIn("Remove", text)++ def test_known_without_a_day_for_an_entry_that_has_none(self):+ text = peerlist.pairing_error_text(pairing.AlreadyPaired(peer(A, "Desk", paired_at=0)), "that machine")+ self.assertNotIn("1970", text)+ self.assertIn("Desk", text)++ def test_known_where_the_other_machine_claimed_this_ones_own_id(self):+ text = peerlist.pairing_error_text(pairing.AlreadyPaired(None), "that machine")+ self.assertIn("this machine", text.lower())++ def test_full_may_be_either_machine_and_known_from_the_host_says_to_remove_this_one_there(self):+ full = peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_FULL), "Desk")+ self.assertIn("Either this machine or Desk", full)+ self.assertIn("Remove one", full)+ known = peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_KNOWN), "Desk")+ self.assertEqual(known, "Desk already has this machine paired. Remove this machine from its list there, then pair again.")++ def test_not_saved_and_busy_say_what_to_do(self):+ self.assertIn("could not save", peerlist.pairing_error_text(pairing.PairingError("not_saved"), "Desk"))+ self.assertIn("moment", peerlist.pairing_error_text(pairing.PairingError("busy"), "Desk"))++ def test_a_reason_nobody_has_seen_is_still_said(self):+ self.assertEqual(peerlist.pairing_error_text(pairing.PairingError("strange"), "Desk"), "Pairing failed: strange.")++ def test_every_outcome_a_code_can_end_in_has_a_sentence(self):+ for outcome in ("paired", "refused", "version", "expired", "known", "known_there", "full", "not_saved"):+ text = peerlist.host_outcome_text(outcome, peer(A, "Desk"))+ self.assertTrue(text and text.endswith("."), outcome)++ def test_known_there_says_what_wire_md_says(self):+ self.assertIn("That machine may already be paired here, or the code was wrong.",+ peerlist.host_outcome_text("known_there", None))++ def test_a_code_that_ended_without_an_outcome_says_nothing(self):+ self.assertEqual(peerlist.host_outcome_text(None, None), "")+++class LabelForTests(unittest.TestCase):+ def test_finds_the_label_by_token_by_id_or_by_host(self):+ first, second = peer(A, "Studio"), peer(B, "studio")+ first.update(host="192.0.2.10")+ second.update(host="192.0.2.11")+ labels = peerlist.labels([first, second])+ self.assertEqual(peerlist.label_for([first, second], token=second["token"]), labels[second["token"]])+ self.assertEqual(peerlist.label_for([first, second], peer_id=first["id"]), labels[first["token"]])+ self.assertEqual(peerlist.label_for([first, second], host="192.0.2.11"), labels[second["token"]])+ self.assertIn("(", peerlist.label_for([first, second], token=first["token"]))+++ def test_a_phone_without_a_token_has_no_machine_label(self):++ phone = {"id": "phone", "name": "Toby's phone", "port": 0}++ self.assertEqual(peerlist.label_for([peer(A, "Desk"), phone], peer_id="phone"), "")+++ def test_a_machine_nobody_knows_has_no_label(self):+ self.assertEqual(peerlist.label_for([peer(A, "Desk")], token="nope"), "")+ self.assertEqual(peerlist.label_for([], peer_id="nope"), "")+++class SharingANameTests(unittest.TestCase):+ def test_names_are_compared_as_labels_compares_them(self):+ machines = [{"name": " Studio "}, {"name": "studio"}, {"name": "Other"}]+ self.assertEqual(peerlist.sharing_a_name(machines), [True, True, False])++ def test_a_lone_machine_shares_with_nobody(self):+ self.assertEqual(peerlist.sharing_a_name([{"name": "Studio"}]), [False])+ self.assertEqual(peerlist.sharing_a_name([]), [])+++class RefusalTextTests(unittest.TestCase):+ """What a refused crossing says on either desktop, naming the machine in the way when the+ refusal's `other` named one this machine knows (WIRE.md section 5)."""++ def test_owned_and_busy_name_the_machine_in_the_way(self):+ self.assertEqual(peerlist.refusal_text("owned", "Laptop-PC", "Desk-PC"),+ "Can't cross to Laptop-PC: it is being driven from Desk-PC.")+ self.assertEqual(peerlist.refusal_text("busy", "Desk-PC", "Laptop-PC"),+ "Can't cross to Desk-PC: it is driving Laptop-PC.")++ def test_with_no_machine_named_it_is_another_machine(self):+ self.assertEqual(peerlist.refusal_text("owned", "Laptop-PC", ""),+ "Can't cross to Laptop-PC: another machine is driving it.")+ self.assertEqual(peerlist.refusal_text("busy", "Desk-PC", None),+ "Can't cross to Desk-PC: it is driving another machine.")++ def test_other_reasons_are_left_to_the_apps_own_words(self):+ for why in ("not_allowed", "sent_home", "malformed", "refused", "no_answer", "link_lost"):+ self.assertIsNone(peerlist.refusal_text(why, "Bee", "Sea"))+++if __name__ == "__main__":+ unittest.main()diff --cc core/tests/test_phone_contract.pyindex 0000000,0000000..03f8354new file mode 100644--- /dev/null+++ b/core/tests/test_phone_contract.py@@@ -1,0 -1,0 +1,155 @@@++"""A phone written from WIRE.md and PAIRING.md, against the real desktop sockets."""++++import logging++import unittest++++from core.pairing import PairingService++from core.tests.responder_harness import Machine, entry, ident, wait_for++from core.tests.spec_phone import Phone, PhoneLink, b64++++++PHONE, MAC, PC = ident(130), ident(160), ident(190)++LOGGER = logging.getLogger("phone-contract-tests")++LOGGER.handlers = [logging.NullHandler()]++LOGGER.propagate = False++++++class PhoneContractTests(unittest.TestCase):++ def desktop(self, own, name, platform, peers=(), zones=()):++ machine = Machine(peers, zones, own=own, name=name).start()++ self.addCleanup(machine.stop)++++ def store(peer, replaces):++ held = machine.settings.load()++ if replaces is not None:++ held["peers"] = [p for p in held["peers"] if p["id"] != replaces["id"]]++ held["peers"].append(dict(peer))++ machine.settings.save(held)++++ service = PairingService(++ name, own, platform, lambda: machine.port,++ lambda: machine.settings.load()["peers"], store,++ logger=LOGGER,++ bind_port=0, tcp_port=0, announce_to=("127.0.0.1", 0),++ )++ service.start()++ self.addCleanup(service.stop)++ self.assertTrue(wait_for(lambda: service.listening_port is not None))++ machine.pairing = service++ return machine++++ def pair(self, phone, machine, qr=False):++ code = machine.pairing.begin_pairing()++ secret = machine.pairing.host.qr_secret if qr else None++ peer = phone.pair(machine.pairing.tcp_port, code, qr_secret=secret)++ saved = next(p for p in machine.settings.load()["peers"] if p["id"] == b64(PHONE))++ self.assertEqual(peer["token"], saved["token"])++ self.assertEqual((saved["port"], saved["host"], saved["send"], saved["allow_drive"]),++ (0, "", False, True))++ self.assertEqual((saved["name"], saved["platform"]), (phone.name, phone.platform))++ return peer++++ def link(self, phone, machine):++ link = phone.connect(b64(machine.own))++ self.addCleanup(link.close)++ self.assertTrue(link.welcome["accepts"])++ return link++++ def test_phone_pairs_drives_switches_and_is_revoked_over_real_tcp(self):++ for platform in ("ios", "android"):++ with self.subTest(platform=platform):++ phone = Phone(PHONE, "Alex's phone", platform)++ mac = self.desktop(MAC, "Loop Mac", "macos", [++ entry(PC, "Loop PC", side="right", token=b64(bytes(range(32)))),++ ], [{"peer": b64(PC), "kind": "edge"}])++ pc = self.desktop(PC, "Loop PC", "windows")++ self.pair(phone, mac)++ self.pair(phone, pc)++ mac_link, pc_link = self.link(phone, mac), self.link(phone, pc)++++ # Input before ownership is dropped and acknowledged.++ mac_link.input("text", text="not owned")++ self.assertIsNotNone(mac_link.expect("ack"))++ self.assertNotIn(("text", "not owned"), mac.injected())++ phone.take(b64(MAC))++ self.assertEqual(mac_link.expect("accept"), {"route": 1})++ self.assertTrue(wait_for(lambda: mac.responder.owner == PHONE))++ mac_link.input("text", text="Phone input")++ mac_link.input("keydown", key="a")++ mac_link.input("mousemove", dx=3, dy=4)++ self.assertTrue(wait_for(lambda: ("text", "Phone input") in mac.injected()))++ self.assertTrue(wait_for(lambda: ("key", "a", True) in mac.injected()))++ self.assertTrue(wait_for(lambda: ("move", 3, 4) in mac.injected()))++++ # A desktop's own zone asks the phone to move to its direct link to the PC.++ mac.desktop.cursor = (1919, 540)++ for _ in range(5):++ mac_link.input("mousemove", dx=200, dy=0)++ switch = mac_link.expect("switch")++ self.assertIsNotNone(switch)++ self.assertEqual((switch["route"], switch["next"]), (1, b64(PC)))++ phone.follow_switch(b64(MAC), switch)++ self.assertTrue(wait_for(lambda: mac.responder.owner is None))++ self.assertTrue(wait_for(lambda: pc.responder.owner == PHONE))++ self.assertTrue(wait_for(lambda: ("key", "a", False) in mac.injected()))++ pc_link.input("text", text="After switch")++ pc_link.input("keydown", key="b")++ self.assertTrue(wait_for(lambda: ("text", "After switch") in pc.injected()))++ self.assertTrue(wait_for(lambda: ("key", "b", True) in pc.injected()))++++ # Removing the entry ends ownership and makes the old key id unknown.++ pc.settings.data["peers"] = [p for p in pc.settings.data["peers"] if p["id"] != b64(PHONE)]++ pc.responder.peers_changed()++ self.assertTrue(wait_for(lambda: pc.responder.owner is None))++ self.assertTrue(wait_for(lambda: ("key", "b", False) in pc.injected()))++ self.assertTrue(pc_link.closed.wait(2))++ with self.assertRaises((EOFError, ConnectionError)):++ PhoneLink(phone, phone.peers[b64(PC)])++ mac_link.close()++ pc_link.close()++ mac.pairing.stop()++ pc.pairing.stop()++ mac.stop()++ pc.stop()++++ def test_phone_pairs_using_the_qr_password_without_production_pairing_helpers(self):++ phone = Phone(PHONE, "QR phone", "ios")++ mac = self.desktop(MAC, "Loop Mac", "macos")++ self.pair(phone, mac, qr=True)++ link = self.link(phone, mac)++ phone.take(b64(MAC))++ self.assertEqual(link.expect("accept"), {"route": 1})++ link.input("mousedown", button="left")++ self.assertTrue(wait_for(lambda: ("button", "left", True) in mac.injected()))++ self.assertTrue(mac.responder.send_home())++ switch = link.expect("switch")++ self.assertEqual(switch, {"route": 1, "next": b64(PHONE)})++ phone.follow_switch(b64(MAC), switch)++ self.assertIsNone(phone.on)++ self.assertTrue(wait_for(lambda: mac.responder.owner is None))++ self.assertTrue(wait_for(lambda: ("button", "left", False) in mac.injected()))++++ def test_phone_in_use_and_drive_permissions_are_enforced(self):++ phone = Phone(PHONE, "Phone", "ios")++ mac = self.desktop(MAC, "Loop Mac", "macos")++ self.pair(phone, mac)++ link = self.link(phone, mac)++ phone.take(b64(MAC))++ self.assertEqual(link.expect("accept"), {"route": 1})++ saved = mac.settings.data["peers"][0]++ saved["allow_drive"] = False++ mac.responder.peers_changed()++ self.assertEqual(link.expect("accepts"), {"accepts": False})++ self.assertEqual(link.expect("refuse"), {"route": 1, "why": "not_allowed"})++ self.assertTrue(wait_for(lambda: mac.responder.owner is None))++ phone.take(b64(MAC))++ self.assertEqual(link.expect("refuse"), {"route": 2, "why": "not_allowed"})++ saved["in_use"] = False++ mac.responder.peers_changed()++ self.assertTrue(link.closed.wait(2))++ with self.assertRaisesRegex(ValueError, "invalid_hello"):++ PhoneLink(phone, phone.peers[b64(MAC)])++++++if __name__ == "__main__":++ unittest.main()diff --cc core/tests/test_phone_targets.pyindex 0000000,0000000..d8a781cnew file mode 100644--- /dev/null+++ b/core/tests/test_phone_targets.py@@@ -1,0 -1,0 +1,51 @@@++"""A sender-only peer cannot acquire desktop crossing controls."""++import unittest++from core import protocol, receiver, ways++++++class PhoneTargetsTests(unittest.TestCase):++ def setUp(self):++ self.ident = protocol.id_text(bytes([1]) * 16)++ self.phone = {"id": self.ident, "token": "synthetic", "port": 0, "send": True, "side": "right", "jump_key": "ctrl+shift+2"}++ self.settings = {"machine_id": protocol.id_text(bytes([2]) * 16), "peers": [self.phone], "zones": []}++++ def test_phone_has_no_jump_key_even_if_stale_settings_hold_one(self):++ self.assertIsNone(ways.jump_key(self.phone))++++ def test_phone_is_never_a_recorded_jump_target(self):++ self.assertIsNone(ways.jump_peer([self.phone], "ctrl+shift+2"))++++ def test_phone_cannot_be_given_a_shared_edge(self):++ with self.assertRaises(ValueError):++ ways.share(self.settings, "right", {part: self.ident for part in ways.PARTS}, kinds=["part"])++ self.assertEqual(self.settings["zones"], [])++++ def test_phone_does_not_change_a_lone_desktops_default_side(self):++ desktop = {"id": self.settings["machine_id"], "token": "desktop", "port": 24820, "side": ""}++ for peers in ([self.phone, desktop], [desktop, self.phone]):++ desktop["side"] = ""++ self.settings["peers"] = peers++ self.assertTrue(ways.default_side(self.settings))++ self.assertEqual(desktop["side"], "right")++++ def test_phone_cannot_be_given_jump_key(self):++ with self.assertRaises(ValueError):++ ways.check_jump_key(self.settings, self.ident, "ctrl+shift+2", "alt_r")++++ def test_phone_cannot_be_given_side_or_zones(self):++ with self.assertRaises(ValueError):++ ways.edit(self.settings, self.ident, side="right", methods=["edge"], parts=["start"],++ corner="top_right", kinds=["edge"], corner_edge=lambda c, s: s, now=100)++ self.assertEqual(self.settings["zones"], [])++++ def test_phone_arrangement_is_ignored(self):++ self.assertEqual(ways.arrangement(self.settings, self.ident, "left", 100,++ self.ident, "this machine"), (False, []))++++ def test_no_kind_of_zone_can_lead_to_phone(self):++ zones = [{"peer": self.ident, "kind": "edge"},++ {"peer": self.ident, "kind": "corner", "corner": "top_right", "edge": "right"},++ {"peer": self.ident, "kind": "part", "parts": ["start"]},++ {"peer": self.ident, "kind": "notch"}]++ self.assertEqual(receiver.zone_models(zones, [self.phone], {protocol.read_id(self.ident)},++ 120, notch_span=(0.4, 0.6)), [])diff --cc core/tests/test_settings_sync.pyindex a9e4bc9,0000000..c80f3a4mode 100644,000000..100644--- a/core/tests/test_settings_sync.py+++ b/core/tests/test_settings_sync.py@@@ -1,466 -1,0 +1,551 @@@+"""Same on all machines, without AppKit or Qt: the message, the merge and the window's words."""++import base64+import unittest+from types import SimpleNamespace++from core import settings_sync++KEYS = {"alt_r", "cmd_r", "f13"}+NOW = 1790000000+++def b64(raw):+ return base64.b64encode(raw).decode()+++def mac_raw(**crossing):+ base = {+ "methods": ["shortcut", "edge", "notch"], "edge": "right", "edge_parts": ["middle"],+ "corner": "top_right", "resistance_px": 120, "block_while_dragging": True, "glow": True,+ "glow_style": "glow", "glow_colour": "signal", "effect_length": "normal", "effect_size": "medium",+ "shortcut_arrival": True,+ "shortcut_arrival_style": "match", "notch_style": "beam", "notch_after_ms": 1200, "haptics": True,+ "hold_full_screen": False,+ }+ base.update(crossing)+ return {"trigger_key": "alt_r", "trigger_style": "double_tap", "double_tap_ms": 300,+ "appearance": "dark", "crossing": base}+++def pc_config(**fields):+ base = dict(+ crossing_methods=["edge", "shortcut"], crossing_edge_parts=["middle"], crossing_corner="top_left",+ crossing_resistance_px=120, block_while_dragging=True, trigger_key="cmd_r", trigger_style="double_tap",+ double_tap_ms=300, glow_style="glow", glow_colour="signal", effect_length="normal", effect_size="medium",+ shortcut_arrival=True, shortcut_arrival_style="match", mac_return_edge="left", edge_glow=True,+ appearance="light",+ )+ base.update(fields)+ return SimpleNamespace(**base)+++class MessageTests(unittest.TestCase):+ def test_pc_modifier_style_is_local_and_not_part_of_same_on_all_machines(self):+ self.assertNotIn("modifier_style", settings_sync.CROSSING_KEYS + settings_sync.DESIGN_KEYS)++ def test_new_design_choices_survive_the_settings_message_round_trip(self):+ from core import effects++ styles = ("aperture", "crease", "pleat", "concertina", "thread", "weave", "jacquard")+ colours = ("vellum", "carbon_copy", "marbled", "flax", "madder", "tide")+ for style in styles:+ for colour in colours:+ with self.subTest(style=style, colour=colour):+ values = settings_sync.mac_values(mac_raw(+ glow_style=style, glow_colour=colour, shortcut_arrival_style=style,+ ))+ data = settings_sync.message_data(True, 7, values)+ _on, _stamp, received = settings_sync.read(data, KEYS)+ self.assertEqual(received["glow_style"], style)+ self.assertEqual(received["glow_colour"], colour)+ self.assertEqual(received["shortcut_arrival_style"], style)+ self.assertTrue(set(styles) <= set(effects.EFFECT_IDS))+ self.assertTrue(set(colours) <= set(effects.PACK_IDS))+ def test_an_optional_design_state_keeps_its_own_stamp_and_effect_size(self):+ values = {**settings_sync.mac_values(mac_raw()), "effect_size": "large"}+ design_state = {"set_at": 63, "by": b64(b"\x03" * 16), "values": values}+ data = settings_sync.message_data(False, 50, design_state=design_state)++ self.assertFalse(data["on"])+ self.assertEqual(data["design_sync"], design_state)++ def test_a_settings_message_without_a_design_state_remains_readable(self):+ data = settings_sync.message_data(False, 50)++ self.assertIsNone(settings_sync.read_design_state(data, KEYS))++ def test_a_design_state_is_validated_independently_of_same_on_all_machines(self):+ values = {"glow_style": "beam", "unknown": "ignored"}+ state = {"set_at": NOW, "by": b64(b"\x03" * 16), "values": values}++ self.assertEqual(settings_sync.read_design_state(+ {"on": False, "set_at": NOW, "by": b64(bytes(16)), "design_sync": state}, KEYS),+ {"set_at": NOW, "by": state["by"],+ "values": {"effect_size": "medium", "glow_style": "beam"}})++ def test_an_invalid_effect_size_is_ignored_but_a_missing_one_defaults_to_medium(self):+ state = {"set_at": NOW, "by": b64(bytes(16)),+ "values": {"effect_size": "giant", "glow_style": "beam"}}++ self.assertEqual(settings_sync.read_design_state(+ {"on": False, "set_at": NOW, "by": b64(bytes(16)), "design_sync": state}, KEYS),+ {"set_at": NOW, "by": state["by"], "values": {"glow_style": "beam"}})++ def test_a_design_state_in_a_malformed_settings_envelope_is_ignored(self):+ for outer in ({"on": "no"}, {"set_at": True}, {"by": "not an id"}):+ data = {"on": False, "set_at": NOW, "by": b64(bytes(16)), **outer,+ "design_sync": {"set_at": NOW + 1, "by": b64(bytes([1]) * 16),+ "values": {"glow_style": "beam"}}}+ self.assertIsNone(settings_sync.read_design_state(data, KEYS), outer)++ def test_same_on_design_change_gets_a_new_local_design_stamp(self):+ changed = settings_sync.design_change_stamp(+ {"effect_length": "normal"}, {"effect_length": "long"}, 50,+ {"set_at": 90}, b64(b"\x02" * 16), now=100,+ )++ self.assertEqual(changed, {"set_at": 100, "by": b64(b"\x02" * 16)})+ self.assertIsNone(settings_sync.design_change_stamp(+ {"effect_length": "long"}, {"effect_length": "long"}, 50,+ {"set_at": 90}, b64(b"\x02" * 16), now=100,+ ))++ def test_design_states_use_the_same_stamp_order_as_same_on_all_machines(self):+ larger = {"set_at": 100, "by": b64(b"\x02" * 16), "values": {"glow_style": "beam"}}+ self.assertTrue(settings_sync.design_arrived(larger, 100, b64(b"\x01" * 16)))+ self.assertFalse(settings_sync.design_arrived(larger, 100, larger["by"]))+ self.assertFalse(settings_sync.design_arrived(larger, 101, ""))++ def test_design_follow_chain_keeps_the_leaders_stamp(self):+ a_id, b_id = (b64(bytes([byte]) * 16) for byte in (1, 2))+ a_state = {"set_at": 100, "by": a_id, "values": {"glow_style": "beam"}}++ b = settings_sync.followed_design({"glow_style": "glow"}, a_state, a_id, a_id, False,+ 50, b64(bytes(16)))+ c = settings_sync.followed_design({"glow_style": "glow"},+ {"set_at": b["set_at"], "by": b["by"], "values": b["values"]},+ b_id, b_id, False, 20, b64(bytes(16)))++ self.assertTrue(b["changed"] and c["changed"])+ self.assertEqual(c["values"]["glow_style"], "beam")+ self.assertEqual((b["set_at"], b["by"], c["set_at"], c["by"]),+ (100, a_id, 100, a_id))+++ def test_explicit_follow_adopts_all_six_values_despite_a_newer_local_stamp(self):++ peer = b64(bytes([2]) * 16)++ current = settings_sync.mac_values(mac_raw())++ desired = dict(glow_style="beam", glow_colour="ocean", effect_length="long",++ effect_size="large", shortcut_arrival=False, shortcut_arrival_style="locator")++ state = {"set_at": 10, "by": peer, "values": desired}++ taken = settings_sync.followed_design(current, state, peer, peer, False, 500, "", force=True)++ self.assertEqual({key: taken["values"][key] for key in settings_sync.DESIGN_KEYS}, desired)++ self.assertEqual(taken["values"]["resistance_px"], 120)++++ def test_follow_path_detects_a_cycle_even_when_values_are_identical(self):++ own, peer = b64(bytes([1]) * 16), b64(bytes([2]) * 16)++ state = {"set_at": 10, "by": peer, "values": {"glow_style": "beam"}, "path": [own, peer]}++ taken = settings_sync.followed_design({"glow_style": "beam"}, state, peer, peer, False,++ 0, "", own_id=own)++ self.assertTrue(taken["cycle"])++++ def test_follow_path_survives_validation_and_invalid_paths_are_rejected(self):++ own, peer = b64(bytes([1]) * 16), b64(bytes([2]) * 16)++ for path in ([own, peer], [], ["garbage"], [own, own], [None]):++ data = settings_sync.message_data(False, 10, design_state={++ "set_at": 10, "by": peer, "values": {"glow_style": "beam"}, "path": path})++ state = settings_sync.read_design_state(data, KEYS)++ if path == [own, peer]:++ self.assertEqual(state["path"], path)++ else:++ self.assertIsNone(state)++++ def test_legacy_padded_author_and_source_produce_a_valid_downstream_path(self):++ from core import protocol++ source, own = (protocol.id_text(bytes([value]) * 16) for value in (1, 2))++ state = {"set_at": 10, "by": source + "==", "values": {"glow_style": "beam"}}++ taken = settings_sync.followed_design({"glow_style": "glow"}, state, source, source, False,++ 0, "", own_id=own)++ advertised = {"set_at": 20, "by": own, "values": taken["values"], "path": taken["path"]}++ received = settings_sync.read_design_state(settings_sync.message_data(False, 20, design_state=advertised), KEYS)++ self.assertIsNotNone(received)++ self.assertEqual(len(received["path"]), 2)+++ def test_follower_accepts_the_leaders_next_stamp_after_reannouncing_it(self):+ a_id, b_id = b64(b"\x01" * 16), b64(b"\x02" * 16)+ current = {"glow_style": "glow"}+ first = {"set_at": 100, "by": a_id, "values": {"glow_style": "beam"}}+ applied = settings_sync.followed_design(current, first, a_id, a_id, False,+ 50, "")+ next_from_a = {"set_at": 101, "by": a_id, "values": {"glow_style": "flint"}}++ updated = settings_sync.followed_design(+ applied["values"], next_from_a, a_id, a_id, False,+ applied["set_at"], applied["by"],+ )++ self.assertTrue(updated["changed"])+ self.assertEqual(updated["values"]["glow_style"], "flint")+ self.assertEqual((updated["set_at"], updated["by"]), (101, a_id))++ def test_mutual_design_follow_converges_without_a_second_announcement(self):+ a_id, b_id = b64(b"\x01" * 16), b64(b"\x02" * 16)+ b_after_a = settings_sync.followed_design(+ {"glow_style": "glow"}, {"set_at": 100, "by": a_id, "values": {"glow_style": "beam"}},+ a_id, a_id, False, 90, b64(bytes(16)),+ )+ a_after_b = settings_sync.followed_design(+ {"glow_style": "beam"},+ {"set_at": b_after_a["set_at"], "by": b_after_a["by"], "values": b_after_a["values"]},+ b_id, b_id, False, 100, a_id,+ )++ self.assertTrue(b_after_a["changed"])+ self.assertIsNone(a_after_b)++ def test_mutual_design_announcements_crossing_in_flight_converge_on_the_newer_stamp(self):+ a_id, b_id = b64(bytes([1]) * 16), b64(bytes([2]) * 16)+ ids = {"A": a_id, "B": b_id}+ held = {+ "A": {"values": {"glow_style": "beam"}, "set_at": 200, "by": a_id},+ "B": {"values": {"glow_style": "glow"}, "set_at": 100, "by": b_id},+ }+ # Both link-up announcements are already in flight before either side reacts.+ queue = [("A", "B", dict(held["A"])), ("B", "A", dict(held["B"]))]+ sent = 0+ while queue:+ source, follower, incoming = queue.pop(0)+ sent += 1+ self.assertLess(sent, 10, "mutual follows kept re-announcing")+ current = held[follower]+ applied = settings_sync.followed_design(+ current["values"], incoming,+ source, source, False, current["set_at"], current["by"],+ )+ if applied is not None and applied["changed"]:+ held[follower] = {"values": applied["values"], "set_at": applied["set_at"], "by": applied["by"]}+ queue.append((follower, source, dict(held[follower])))++ self.assertEqual(held["A"]["values"]["glow_style"], "beam")+ self.assertEqual(held["B"]["values"]["glow_style"], "beam")+ self.assertEqual((held["A"]["set_at"], held["A"]["by"]), (200, a_id))+ self.assertEqual((held["B"]["set_at"], held["B"]["by"]), (200, a_id))++ def test_design_follow_ignores_other_peers_and_waits_while_same_is_on(self):+ state = {"set_at": 100, "by": b64(b"\x02" * 16), "values": {"glow_style": "beam"}}+ peer = state["by"]+ current = {"glow_style": "glow"}++ self.assertIsNone(settings_sync.followed_design(current, state, peer, "", False, 0, ""))+ self.assertIsNone(settings_sync.followed_design(current, state, peer, peer, True, 0, ""))++ def test_a_newer_identical_design_keeps_its_stamp_without_an_announcement(self):+ peer = b64(bytes([2]) * 16)+ applied = settings_sync.followed_design(+ {"glow_style": "beam"}, {"set_at": 100, "by": peer, "values": {"glow_style": "beam"}},+ peer, peer, False, 50, "",+ )++ self.assertEqual(applied, {"changed": False, "values": {"glow_style": "beam"},+ "set_at": 100, "by": peer})++ def test_off_carries_no_values(self):+ data = settings_sync.message_data(False, 50, settings_sync.mac_values(mac_raw()))+ self.assertEqual(data, {"on": False, "set_at": 50, "by": ""})++ def test_on_carries_crossing_and_design_and_never_the_notch_or_this_machines_own(self):+ data = settings_sync.message_data(True, 50, settings_sync.mac_values(mac_raw()))+ self.assertEqual(set(data["crossing"]), set(settings_sync.CROSSING_KEYS))+ self.assertEqual(set(data["design"]), set(settings_sync.DESIGN_KEYS))+ self.assertEqual(data["design"]["effect_size"], "medium")+ self.assertIs(data["crossing"]["shortcut"], True)+ flat = {**data["crossing"], **data["design"]}+ for own in ("notch_style", "notch_after_ms", "haptics", "glow", "appearance", "edge", "hold_full_screen",+ "methods", "edge_parts", "corner"):+ self.assertNotIn(own, flat)++ def test_jump_keys_are_not_sent_by_same_on_all_machines(self):+ values = settings_sync.mac_values(mac_raw())+ values["jump_key"] = "ctrl+alt+2"+ self.assertNotIn("jump_key", settings_sync.message_data(True, 50, values)["crossing"])++ def test_a_round_trip_reads_back_what_was_sent(self):+ values = settings_sync.mac_values(mac_raw())+ on, set_at, read = settings_sync.read(settings_sync.message_data(True, 7, values), KEYS)+ self.assertEqual((on, set_at), (True, 7))+ self.assertEqual(read, values)++ def test_a_value_this_end_cannot_hold_is_left_out_and_the_rest_kept(self):+ data = settings_sync.message_data(True, 7, settings_sync.mac_values(mac_raw()))+ data["crossing"]["trigger_key"] = "hyper"+ data["crossing"]["resistance_px"] = 9000+ data["design"]["glow_style"] = "from-the-future"+ data["crossing"]["shortcut"] = "yes"+ data["crossing"]["methods"] = ["edge"]+ _on, _set_at, values = settings_sync.read(data, KEYS)+ for dropped in ("trigger_key", "resistance_px", "glow_style", "shortcut", "methods"):+ self.assertNotIn(dropped, values)+ self.assertEqual(values["trigger_style"], "double_tap")++ def test_a_key_that_cannot_be_the_trigger_is_left_out(self):+ for name in ("browser_back", "browser_forward", "backspace", "tab", "enter", "esc", "space", "print_screen"):+ data = settings_sync.message_data(True, 7, settings_sync.mac_values(mac_raw()))+ data["crossing"]["trigger_key"] = name+ _on, _set_at, values = settings_sync.read(data, KEYS | {name})+ self.assertNotIn("trigger_key", values, name)++ def test_the_message_names_who_made_the_change(self):+ self.assertEqual(settings_sync.message_data(False, 5, by="QUJD"), {"on": False, "set_at": 5, "by": "QUJD"})+ self.assertEqual(settings_sync.message_data(False, 5), {"on": False, "set_at": 5, "by": ""})++ def test_malformed_data_is_not_a_message(self):+ for data in (None, [], {}, {"on": "yes", "set_at": 1}, {"on": True}, {"on": True, "set_at": True}):+ self.assertIsNone(settings_sync.read(data, KEYS))++ def test_a_change_here_always_stamps_newer_than_what_is_held(self):+ self.assertEqual(settings_sync.next_stamp(0, 1000.7), 1000)+ self.assertEqual(settings_sync.next_stamp(1000, 1000.2), 1001)+ # A peer's clock ahead of this one's: the change made here still wins.+ self.assertEqual(settings_sync.next_stamp(5000, 1000), 5001)++ def test_a_tie_goes_to_the_larger_id_as_bytes_and_a_lower_one_changes_nothing(self):+ values = settings_sync.mac_values(mac_raw(glow_style="beam"))+ big, small = b64(b"\x02" * 16), b64(b"\x01" * 16)+ theirs = settings_sync.message_data(True, 100, values, by=big)+ self.assertIsNotNone(settings_sync.arrived(theirs, 100, KEYS, by_here=small, now=NOW))+ self.assertIsNone(settings_sync.arrived(theirs, 100, KEYS, by_here=big, now=NOW))+ lower = settings_sync.message_data(True, 100, values, by=small)+ self.assertIsNone(settings_sync.arrived(lower, 100, KEYS, by_here=big, now=NOW))++ def test_compared_as_bytes_not_as_text(self):+ # As text "AAAA..." sorts above "////...", but as bytes 0x00.. is below 0xff..+ low, high = b64(b"\x00" * 16), b64(b"\xff" * 16)+ self.assertGreater(low, high)+ theirs = settings_sync.message_data(False, 9, by=high)+ self.assertIsNotNone(settings_sync.arrived(theirs, 9, KEYS, by_here=low, now=NOW))+ self.assertIsNone(settings_sync.arrived(settings_sync.message_data(False, 9, by=low), 9, KEYS, by_here=high, now=NOW))++ def test_a_newer_stamp_wins_whatever_the_ids(self):+ theirs = settings_sync.message_data(False, 101, by=b64(b"\x00" * 16))+ self.assertEqual(settings_sync.arrived(theirs, 100, KEYS, by_here=b64(b"\xff" * 16), now=NOW)[:2], (False, 101))++ def test_a_bad_by_is_not_a_message_and_a_missing_one_is_empty(self):+ for by in (5, "not base64!", None, True):+ data = {"on": False, "set_at": 9, "by": by}+ self.assertIsNone(settings_sync.arrived(data, 0, KEYS, now=NOW), by)+ self.assertIsNotNone(settings_sync.arrived({"on": False, "set_at": 9}, 0, KEYS, now=NOW))++ def test_a_stamp_that_is_not_an_integer_is_not_a_message(self):+ for set_at in (9.5, 9.0, "9", None, [9]):+ data = {"on": False, "set_at": set_at, "by": b64(b"\x01" * 16)}+ self.assertIsNone(settings_sync.read(data, KEYS), set_at)+ self.assertIsNone(settings_sync.arrived(data, 0, KEYS, now=NOW), set_at)++ def test_a_by_that_is_not_a_machine_id_in_length_is_not_a_message(self):+ for raw in (b"", b"\x01", b"\x01" * 15, b"\x01" * 17, b"\x01" * 64):+ data = {"on": False, "set_at": 9, "by": b64(raw)}+ if raw:+ self.assertIsNone(settings_sync.arrived(data, 0, KEYS, now=NOW), raw)++ def test_a_stamp_more_than_a_day_ahead_or_past_2_to_the_53_is_ignored(self):+ self.assertIsNotNone(settings_sync.arrived(settings_sync.message_data(False, NOW + 86400), 0, KEYS, now=NOW))+ self.assertIsNone(settings_sync.arrived(settings_sync.message_data(False, NOW + 86401), 0, KEYS, now=NOW))+ self.assertIsNone(settings_sync.arrived(settings_sync.message_data(False, 2 ** 53 - 1), 0, KEYS, now=2 ** 54))+ self.assertIsNotNone(settings_sync.arrived(settings_sync.message_data(False, 2 ** 53 - 2), 0, KEYS, now=2 ** 54))++ def test_a_local_change_after_a_far_ahead_stamp_still_stamps_held_plus_one(self):+ self.assertEqual(settings_sync.next_stamp(NOW + 5000, NOW), NOW + 5001)+++class AdapterTests(unittest.TestCase):+ def test_size_is_read_applied_and_transmitted_on_both_machines(self):+ mac = mac_raw(effect_size="large")+ values = settings_sync.mac_values(mac)+ self.assertEqual(values["effect_size"], "large")+ self.assertEqual(settings_sync.apply_mac(mac_raw(), values)["crossing"]["effect_size"], "large")+ message = settings_sync.message_data(True, 1, values)+ self.assertEqual(message["design"]["effect_size"], "large")+ self.assertEqual(settings_sync.read(message, KEYS)[2]["effect_size"], "large")++ pc = pc_config(effect_size="small")+ values = settings_sync.pc_values(pc)+ self.assertEqual(values["effect_size"], "small")+ target = pc_config()+ settings_sync.apply_pc(target, values)+ self.assertEqual(target.effect_size, "small")++ def test_the_mac_keeps_its_notch_its_zones_and_its_own_rows(self):+ raw = mac_raw()+ values = settings_sync.mac_values(mac_raw(glow_style="beam", resistance_px=40))+ values["trigger_key"] = "f13"+ values["shortcut"] = False+ applied = settings_sync.apply_mac(raw, values)+ self.assertEqual(applied["crossing"]["methods"], ["edge", "notch"])+ self.assertEqual((applied["crossing"]["glow_style"], applied["crossing"]["resistance_px"]), ("beam", 40))+ self.assertEqual(applied["trigger_key"], "f13")+ for own in ("notch_style", "notch_after_ms", "haptics", "glow", "edge", "edge_parts", "corner"):+ self.assertEqual(applied["crossing"][own], raw["crossing"][own])+ self.assertEqual(applied["appearance"], "dark")+ self.assertEqual(raw["crossing"]["methods"], ["shortcut", "edge", "notch"])++ def test_the_shortcut_is_added_to_the_ways_when_the_peer_has_it_on(self):+ applied = settings_sync.apply_mac(mac_raw(methods=["corner"]), {"shortcut": True})+ self.assertEqual(applied["crossing"]["methods"], ["corner", "shortcut"])+ self.assertEqual(settings_sync.apply_mac(mac_raw(methods=["shortcut"]), {"shortcut": True})["crossing"]["methods"], ["shortcut"])++ def test_the_shortcut_is_read_from_the_ways(self):+ self.assertIs(settings_sync.mac_values(mac_raw(methods=["edge"]))["shortcut"], False)+ self.assertIs(settings_sync.pc_values(pc_config(crossing_methods=["edge", "shortcut"]))["shortcut"], True)++ def test_a_values_dict_has_no_zones(self):+ for values in (settings_sync.mac_values(mac_raw()), settings_sync.pc_values(pc_config())):+ for zone in ("methods", "edge_parts", "corner"):+ self.assertNotIn(zone, values)++ def test_values_from_the_mac_land_on_the_pcs_fields_and_leave_its_own_and_its_zones(self):+ config = pc_config()+ values = settings_sync.mac_values(mac_raw(glow_colour="ocean", methods=["edge"]))+ settings_sync.apply_pc(config, values)+ self.assertEqual(config.crossing_methods, ["edge"])+ self.assertEqual((config.crossing_edge_parts, config.crossing_corner), (["middle"], "top_left"))+ self.assertEqual((config.glow_colour, config.trigger_key), ("ocean", "alt_r"))+ self.assertEqual((config.edge_glow, config.appearance, config.mac_return_edge), (True, "light", "left"))++ def test_the_pc_turns_its_shortcut_on_and_keeps_the_other_ways(self):+ config = pc_config(crossing_methods=["edge"])+ settings_sync.apply_pc(config, {"shortcut": True})+ self.assertEqual(config.crossing_methods, ["edge", "shortcut"])+ settings_sync.apply_pc(config, {"shortcut": False})+ self.assertEqual(config.crossing_methods, ["edge"])++ def test_a_change_is_seen_only_in_a_shared_value(self):+ before = settings_sync.mac_values(mac_raw())+ self.assertFalse(settings_sync.changed(before, settings_sync.mac_values(mac_raw(notch_style="island", glow=False, corner="bottom_left", edge_parts=["end"]))))+ self.assertTrue(settings_sync.changed(before, settings_sync.mac_values(mac_raw(effect_length="long"))))+ self.assertTrue(settings_sync.changed(before, settings_sync.mac_values(mac_raw(methods=["edge"]))))++ def test_hold_full_screen_is_never_shared(self):+ for values in (settings_sync.mac_values(mac_raw(hold_full_screen=True)), settings_sync.pc_values(pc_config())):+ self.assertNotIn("hold_full_screen", values)+ data = settings_sync.message_data(True, 1, settings_sync.mac_values(mac_raw(hold_full_screen=True)))+ self.assertNotIn("hold_full_screen", {**data["crossing"], **data["design"]})+++class RelayTests(unittest.TestCase):+ PEERS = {"a": {"settings", "text"}, "b": {"settings"}, "c": set(), "d": {"settings"}}++ def test_a_newer_state_goes_to_every_other_peer_that_takes_settings(self):+ self.assertEqual(settings_sync.recipients(self.PEERS, source="a"), ["b", "d"])++ def test_a_state_made_here_goes_to_every_peer_that_takes_settings(self):+ self.assertEqual(settings_sync.recipients(self.PEERS), ["a", "b", "d"])++ def test_a_peer_without_settings_is_never_a_recipient(self):+ self.assertNotIn("c", settings_sync.recipients(self.PEERS))++ def test_three_machines_in_a_line_all_reach_the_first_ones_change_and_nothing_loops(self):+ # A - B - C; A and C are not linked. Each holds (set_at, by); B sends on what it takes.+ links = {"A": {"B": {"settings"}}, "B": {"A": {"settings"}, "C": {"settings"}}, "C": {"B": {"settings"}}}+ ids = {"A": b64(b"\x01" * 16), "B": b64(b"\x02" * 16), "C": b64(b"\x03" * 16)}+ held = {name: (100, ids[name]) for name in links}+ held["A"] = (200, ids["A"])+ sent = []+ queue = [("A", "B", settings_sync.message_data(True, 200, settings_sync.mac_values(mac_raw(glow_style="beam")), by=ids["A"]))]+ while queue:+ src, dst, data = queue.pop(0)+ sent.append((src, dst))+ assert len(sent) < 10, "looping"+ taken = settings_sync.arrived(data, held[dst][0], KEYS, by_here=held[dst][1], now=NOW)+ if taken is None:+ continue+ held[dst] = (taken[1], data["by"])+ for other in settings_sync.recipients(links[dst], source=src):+ queue.append((dst, other, data))+ self.assertEqual([held[name][0] for name in "ABC"], [200, 200, 200])+ self.assertEqual(sent, [("A", "B"), ("B", "C")])+++class WordsTests(unittest.TestCase):+ def test_a_shared_page_says_so_only_while_on(self):+ own = "For this Mac only; the other machine keeps its own."+ everyone = settings_sync.who(["Studio", "Laptop"])+ self.assertEqual(settings_sync.scope("crossing", everyone, False, own), own)+ self.assertEqual(settings_sync.scope("design", everyone, True, own),- "Kept the same as every paired machine. Change it on any machine.")++ "Style, colour, length, size and landing animation stay in step. Animation enable and window appearance stay local.")+ self.assertEqual(settings_sync.scope("keyboard", everyone, True, own), own)++ def test_one_machine_is_named_and_none_or_several_are_every_paired_machine(self):+ self.assertEqual(settings_sync.who(["Studio"]), "Studio")+ self.assertEqual(settings_sync.who([]), "every paired machine")+ self.assertEqual(settings_sync.who(["Studio", "Laptop"]), "every paired machine")- self.assertEqual(settings_sync.scope("design", "Studio", True, "x"), "Kept the same as Studio. Change it on any machine.")-- def test_the_switch_note_names_both_pages_and_an_old_peer(self):- self.assertIn("Crossing and Design", settings_sync.switch_note("Studio", True, False))- self.assertIn("match Studio's", settings_sync.switch_note("Studio", False, False))- self.assertNotIn("Mac", settings_sync.switch_note("every paired machine", True, False))++ self.assertEqual(settings_sync.scope("design", "Studio", True, "x"),++ "Style, colour, length, size and landing animation stay in step. Animation enable and window appearance stay local.")++++ def test_the_switch_note_names_shared_values_and_an_old_peer(self):++ self.assertIn("resistance, drag protection, Shortcut", settings_sync.switch_note("Studio", True, False))++ self.assertIn("previous separate values are not restored", settings_sync.switch_note("Studio", False, False))++ self.assertIn("compatible paired machines", settings_sync.switch_note("every paired machine", True, False))++ self.assertIn("catch up when they reconnect", settings_sync.switch_detail())+ self.assertIn("Studio's Beamer is too old", settings_sync.switch_note("Studio", True, True))+++class RealIdTests(unittest.TestCase):+ def test_a_by_in_the_unpadded_urlsafe_spelling_of_a_machine_id_is_read(self):+ from core import protocol+ ident = bytes(range(1, 17))+ text = protocol.id_text(ident)+ self.assertEqual(settings_sync._id(text), ident)+ data = settings_sync.message_data(True, 100, {}, by=text)+ self.assertIsNotNone(settings_sync.arrived(data, 0, {}))++ def test_garbage_is_still_not_an_id(self):+ self.assertIsNone(settings_sync._id("not base64!"))+ self.assertIsNone(settings_sync._id(5))++++class FollowRowsTests(unittest.TestCase):++ PC, LIVE, AWAY, OLD = (b64(bytes([n]) * 16) for n in (1, 2, 3, 4))++++ def entries(self, *ids):++ return [{"id": ident} for ident in ids]++++ def test_only_connected_machines_are_listed_and_away_ones_never_set_the_note(self):++ caps = {self.PC: frozenset({"settings", "design_sync"})}++ rows = settings_sync.follow_rows(self.entries(self.PC, self.AWAY), caps, {self.PC: {}})++ self.assertEqual(rows, [({"id": self.PC}, None)])++ self.assertIsNone(settings_sync.follow_note(rows))++++ def test_the_followed_machine_stays_listed_while_away(self):++ rows = settings_sync.follow_rows(self.entries(self.PC, self.AWAY), {}, {self.AWAY: {}}, following=self.AWAY)++ self.assertEqual(rows, [({"id": self.AWAY}, None)])++++ def test_why_each_connected_machine_cannot_be_chosen(self):++ caps = {self.LIVE: frozenset({"settings", "design_sync"}), self.OLD: frozenset({"settings"})}++ rows = settings_sync.follow_rows(self.entries(self.LIVE, self.OLD), caps, {})++ self.assertEqual([why for _entry, why in rows], [settings_sync.DESIGN_UNAVAILABLE, settings_sync.NEEDS_DESIGN_SYNC])++ self.assertEqual(settings_sync.follow_note(rows), settings_sync.OLD_PEER_NOTE)++ self.assertEqual(settings_sync.follow_note(rows[:1]), settings_sync.DESIGN_UNAVAILABLE)++++ def test_nothing_connected_is_one_quiet_line(self):++ rows = settings_sync.follow_rows(self.entries(self.AWAY), {}, {self.AWAY: {}})++ self.assertEqual(rows, [])++ self.assertEqual(settings_sync.follow_note(rows), settings_sync.NO_MACHINE_CONNECTED)++++++class FollowLockTests(unittest.TestCase):++ PC, OTHER = (b64(bytes([n]) * 16) for n in (1, 2))++++ def test_following_a_paired_desktop_locks_its_design_controls(self):++ desktops = [{"id": self.OTHER}, {"id": self.PC, "name": "DESK-PC"}]++ self.assertEqual(settings_sync.follow_lock(self.PC, False, desktops), desktops[1])++ self.assertEqual(settings_sync.following_banner("DESK-PC"), "Following DESK-PC's design")++++ def test_unlocked_with_no_selection_with_same_on_or_once_the_machine_is_unpaired(self):++ desktops = [{"id": self.PC}]++ self.assertIsNone(settings_sync.follow_lock("", False, desktops))++ self.assertIsNone(settings_sync.follow_lock(self.PC, True, desktops))++ self.assertIsNone(settings_sync.follow_lock(self.OTHER, False, desktops))+++++if __name__ == "__main__":+ unittest.main()diff --cc core/tests/test_way_helpers.pyindex 0000000,0000000..60eb227new file mode 100644--- /dev/null+++ b/core/tests/test_way_helpers.py@@@ -1,0 -1,0 +1,22 @@@++import unittest++++from core import ways++++++class WayHelperTests(unittest.TestCase):++ def test_part_names_follow_the_edge_direction(self):++ self.assertEqual(ways.part_names("right"), {"start": "Top", "middle": "Middle", "end": "Bottom"})++ self.assertEqual(ways.part_names("bottom"), {"start": "Left", "middle": "Middle", "end": "Right"})++++ def test_parts_phrase_orders_known_parts_and_defaults_to_middle(self):++ self.assertEqual(ways.parts_phrase("left", ["end", "start"]), "the top and bottom of the left edge")++ self.assertEqual(ways.parts_phrase("top", ["unknown"]), "the middle of the top edge")++++ def test_toggle_part_keeps_one_part_and_uses_edge_order(self):++ self.assertEqual(ways.toggle_part(["start", "end"], "start", False), ["end"])++ self.assertEqual(ways.toggle_part(["middle"], "middle", False), ["middle"])++ self.assertEqual(ways.toggle_part(["middle"], "start", True), ["start", "middle"])++++++if __name__ == "__main__":++ unittest.main()diff --cc core/tests/test_ways.pyindex 3e09d1a,0000000..40a2490mode 100644,000000..100644--- a/core/tests/test_ways.py+++ b/core/tests/test_ways.py@@@ -1,580 -1,0 +1,587 @@@+"""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)+++if __name__ == "__main__":+ unittest.main()diff --cc core/ways.pyindex 0ab0978,0000000..5063799mode 100644,000000..100644--- a/core/ways.py+++ b/core/ways.py@@@ -1,530 -1,0 +1,585 @@@+"""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 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")++ 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")- parts = value.split("+")- if parts[-1] == trigger_key or (isinstance(trigger_key, str) and trigger_key.removesuffix("_r") in parts):++ 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 entry.get("jump_key") == value:++ 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 entry.get("jump_key") == chord), None)++ 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])+ 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."""+ 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)+ 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 settings["peers"]}++ 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+ if part is None:+ part = {"peer": peer, "kind": "part"}+ settings["zones"].append(part)+ 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):+ """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"."""+ entry = _entry(settings, peer)+ by_bytes = _id_bytes(by)- if entry is None or edge not in EDGES or by_bytes is None:++ 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)+++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 entry in all, as the page counts them: 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."""- if len(settings["peers"]) != 1:++ desktops = peerlist.desktops(settings["peers"])++ if len(desktops) != 1:+ return False- entry = settings["peers"][0]++ 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:+ """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."""+ 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)+ 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."""+ 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):+ holders.append(owner)+ return holders+++def settle(settings: dict, peer: str, here: str) -> 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."""+ entry = _entry(settings, peer)+ return _turn_off_clashes(settings, entry, here) if entry is not None else []+++def _turn_off_clashes(settings: dict, entry: dict, here: str) -> list:+ 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."""+ 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)+++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 0000000,0000000..4053069new file mode 100644--- /dev/null+++ b/docs/flatpak-build.md@@@ -1,0 -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.++++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 flatpak/beamerindex 0000000,0000000..e703dd7new file mode 100755--- /dev/null+++ b/flatpak/beamer@@@ -1,0 -1,0 +1,2 @@@++#!/bin/sh++exec python3 /app/share/beamer/win_app/kvm_bridge_win.py "$@"diff --cc flatpak/uk.co.kalkman.beamer.desktopindex 0000000,0000000..5788541new file mode 100644--- /dev/null+++ b/flatpak/uk.co.kalkman.beamer.desktop@@@ -1,0 -1,0 +1,10 @@@++[Desktop Entry]++Type=Application++Name=Beamer++Comment=Share one keyboard and mouse between your computers++Exec=beamer++Icon=uk.co.kalkman.beamer++Terminal=false++Categories=Utility;Network;++Keywords=keyboard;mouse;clipboard;sharing;++StartupNotify=truediff --cc flatpak/uk.co.kalkman.beamer.metainfo.xmlindex 0000000,0000000..89c427enew file mode 100644--- /dev/null+++ b/flatpak/uk.co.kalkman.beamer.metainfo.xml@@@ -1,0 -1,0 +1,18 @@@++<?xml version="1.0" encoding="UTF-8"?>++<component type="desktop-application">++ <id>uk.co.kalkman.beamer</id>++ <name>Beamer</name>++ <summary>Share one keyboard and mouse between your computers</summary>++ <metadata_license>CC0-1.0</metadata_license>++ <project_license>GPL-3.0-only</project_license>++ <developer id="uk.co.kalkmancode"><name>Kalkman Code</name></developer>++ <description>++ <p>Beamer shares your keyboard, mouse and clipboard between paired computers on your network. Move through a screen edge to control another computer.</p>++ <p>On Linux, Beamer uses the desktop's input capture, remote desktop and clipboard portals on Wayland, or X11. Wayland support depends on the portals your desktop provides. Crossing effects are unavailable on Wayland.</p>++ </description>++ <launchable type="desktop-id">uk.co.kalkman.beamer.desktop</launchable>++ <url type="homepage">https://kalkmancode.co.uk/beamer</url>++ <url type="bugtracker">https://github.com/kalkman-code/beamer/issues</url>++ <content_rating type="oars-1.1"/>++ <releases><release version="@VERSION@" timestamp="@TIMESTAMP@"/></releases>++</component>diff --cc mac_app/bridge.pyindex c5565fb,307b03c..57a9d3c--- a/mac_app/bridge.py+++ b/mac_app/bridge.py@@@ -50,8 -40,10 +50,7 @@@ except ImportError: # pragma: no coveAppKit = None-ACK_TIMEOUT_SECONDS = 2.0-CONNECT_TIMEOUT_SECONDS = 1.0-AUTH_TIMEOUT_SECONDS = 2.0-SOCKET_IO_TIMEOUT_SECONDS = 0.5+CONNECT_TIMEOUT_SECONDS = link_module.CONNECT_SECONDS- SOCKET_IO_TIMEOUT_SECONDS = 0.5OUTBOUND_QUEUE_SIZE = 2048SSH_FALLBACK_HOST = "127.0.0.1"# Below 49152 for the same reason the listening ports are: macOS hands out@@@ -565,12 -537,9 +564,13 @@@ class KVMControllerself.tap_run_loop = Noneself.tap_callback_ref = self._event_tap_callbackself.translator = QuartzEventTranslator(quartz)++ self._sent_names = {}self.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]+ self._jump_swallowed = set()+ self.jump_recording = Falseself.last_trigger_down = 0.0self.trigger_suppressed = False+ self.redirect_started_at = 0.0self.ignore_gate = ignored.Gate(cfg.ignored_inputs)# Crossing: the engine is pure and runs on the event-tap thread; the# desktop bounds come from CoreGraphics (already in the top-left@@@ -592,6 -561,6 +592,7 @@@self.on_crossing = Noneself._crossing_failed = Falseself._crossing_failed_at = 0.0++ self._cursor_read_error_logged = Falseself._bounds_cache = Noneself._bounds_at = 0.0self._displays_cache = None@@@ -946,38 -692,75 +947,41 @@@touching the link: the trigger, key map, crossing and how it looks and feels. The settingswindow calls this as each control changes; update_config is for a new address or token,which has to reconnect."""- was = self.cfg.crossing.get("edge") if self.cfg is not None else None- self.cfg = cfg- edge = cfg.crossing.get("edge")- if edge != was and edge in crossing.EDGES:- # The arrangement is one value both machines hold. Changing it- # here is a change for Windows too, so it travels the moment it- # changes rather than waiting for the next reconnect.- self.send_arrangement(edge, cfg.crossing.get("arrangement_set_at", 0))+ with self._cfg_lock:+ self.cfg = cfg+ # No machine's side goes from here: the flat settings only mirror the first machine's, and a+ # new first machine's would be the default. Sides go from the window, one machine at a time+ # (`send_arrangement`), and with every link that comes up.self.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]++ if "shortcut" not in cfg.crossing.get("methods", ()):++ self.last_trigger_down = 0.0++ self.trigger_suppressed = Falseself.ignore_gate.configure(cfg.ignored_inputs)- self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)+ if self._memory is not None:+ self._memory.follow(cfg)+ self.crossing = self._crossing_engine()self._crossing_failed = False- def set_redirecting(self, value, edge=None, offset=None, came_home=True):- """`edge` and `offset` are the Windows edge and fraction along it a- crossing arrives at; absent for the shortcut, when Windows leaves its- pointer where it is. The way home is sent on every switch.+ def set_redirecting(self, value, edge=None, offset=None, came_home=True, peer=None):+ """`edge` and `offset` are the edge of the other machine and fraction along it a+ crossing arrives at; absent for the shortcut, when it leaves its pointer where it is.+ `peer` is the machine to send input to: a zone's, or one a menu names; without it, the+ machine the shortcut picks (core/ways.py).- Input coming home this way is a switch, the shortcut, the menu or the- PC sending it back, and says so through on_crossing as "home" with- where the pointer is, for the arrival that shows it. `came_home` is- False for the two ways back that show their own: a crossing that lands- here, and the PC taking this Mac over."""+ Input coming home this way is a switch, the shortcut or the menu, and says so through+ on_crossing as "home" with where the pointer is, for the arrival that shows it.+ `came_home` is False for the ways back that show their own: a crossing that lands here+ (it arrives through the owner as a `switch`), and another machine taking this Mac over."""value = bool(value)- if value == self.redirecting:+ if not value:+ self._go_generation += 1+ onward = value and self.redirecting and peer is not None and peer != self.owner.on+ if value == self.redirecting and not onward:return Falseif value:- if not self.connected:- self.logger.warning("cannot redirect: the Windows receiver is not connected")- self._alert("Beamer", f"Cannot switch — {self.connection_status}")- return False- if self.receiving:- # The PC is driving this Mac over the other link, so switching- # to Windows means sending the PC's input home: the one way- # back that does not depend on the PC or on the return edge.- send_home = self.send_peer_home- if send_home is not None and send_home():- return True- self.logger.warning("cannot redirect: Windows is driving this Mac and cannot be reached")- return False- if not self.cfg.send_to_windows:- self.logger.info("cannot redirect: sending this Mac's input to Windows is switched off")- return False- self.redirect_started_at = self.clock()- self.redirecting = True- self.cursor_pin_point = self._capture_cursor_pin_point()- self._set_cursor_follows_mouse(False)- if not self.redirecting:- # A link failure on another thread went local in the gap- # above; its reassociation must not be the one overwritten.- self._set_cursor_follows_mouse(True)- self.cursor_pin_point = None- return False- # The sentinel is expanded into a real clipboard message (or- # dropped) by the outbound worker at send time, not here -- this- # runs on the event-tap thread and must never block on reading- # the pasteboard.- self._enqueue_control({"type": _LOCAL_CLIPBOARD_SENTINEL_TYPE, "data": {}})- self._enqueue_control(- protocol.focus_msg(- "windows",- edge=edge,- offset=offset,- return_edge=edge or self.crossing.home_edge(),- resistance_px=int(self.crossing.resistance_px),- )- )- self.logger.info("redirecting input to Windows")- return True+ # A menu naming another machine while input is away moves it straight there (WIRE.md+ # section 5, "Moving input"): the owner lets go of the one it leaves in the same route.+ return self._redirect(edge, offset, peer)self._return_local()self.logger.info("input returned to this Mac")if came_home:@@@ -1282,6 -985,6 +1286,7 @@@# fires cannot strand the PC's mouse here.if (event_type in (self.quartz.kCGEventKeyDown, self.quartz.kCGEventKeyUp, self.quartz.kCGEventFlagsChanged)++ and "shortcut" in self.cfg.crossing.get("methods", ())and not self._was_injected(event)and self.quartz.CGEventGetIntegerValueField(event, self.quartz.kCGKeyboardEventKeycode) == self.trigger_code):@@@ -1332,18 -1019,13 +1337,18 @@@result = self.translator.key_result(event_type,event,-- self.trigger_code,- self.cfg.key_map,++ self.trigger_code if "shortcut" in self.cfg.crossing.get("methods", ()) else None,+ {},)if result.is_trigger:return self._handle_trigger(result, event)+ if self.redirecting and not self.owner.away:+ self._repair_redirecting_disagreement()+ return event+ had = len(result.messages)+ result.messages = self._after_home_presses(result.messages)++ keycode = self.quartz.CGEventGetIntegerValueField(event, self.quartz.kCGKeyboardEventKeycode)if self.redirecting:-- keycode = self.quartz.CGEventGetIntegerValueField(event, self.quartz.kCGKeyboardEventKeycode)entry = ignored.key(keycode)kept = self.ignore_gate.keeps(entry, result.is_down)if keycode == CAPS_LOCK_KEY_CODE:@@@ -1353,29 -1035,11 +1358,32 @@@self.ignore_gate.keeps(entry, False)if kept:return event++ elif not result.is_down and self.ignore_gate.keeps(ignored.key(keycode), False):++ return eventmessages = result.messages+ if had and not messages:+ # The release of a key pressed here, while the input was home, stays here.+ return eventelse:+ if self.redirecting and not self.owner.away:+ self._repair_redirecting_disagreement()+ return event+ button = self.translator.button_of(event_type, event)if not self.redirecting:+ if button is not None:+ if button[1]:+ self._home_presses.add(("button", button[0]))+ elif ("button", button[0]) in self._home_presses:+ self._home_presses.discard(("button", button[0]))+ else:++ self.ignore_gate.keeps(ignored.button(button[0]), False)+ self._enqueue_control({"type": protocol.MSG_MOUSEUP, "data": {"button": button[0]}})return self._handle_local_mouse(event_type, event)- button = self.translator.button_of(event_type, event)+ if button is not None and not button[1] and ("button", button[0]) in self._home_presses:+ self._home_presses.discard(("button", button[0]))+ return event+ if button is not None and button[1]:+ self._home_presses.discard(("button", button[0]))if button is not None and self.ignore_gate.keeps(ignored.button(button[0]), button[1]):return eventmessages = self.translator.mouse_messages(event_type, event)@@@ -1475,6 -1103,6 +1483,13 @@@try:quartz = self.quartzlocation = quartz.CGEventGetLocation(event)++ except Exception:++ if not self._cursor_read_error_logged:++ self.logger.warning("could not read the cursor position; skipping this edge event", exc_info=True)++ self._cursor_read_error_logged = True++ return event++ self._cursor_read_error_logged = False++ try:x, y = location[0], location[1]dx = quartz.CGEventGetDoubleValueField(event, quartz.kCGMouseEventDeltaX)dy = quartz.CGEventGetDoubleValueField(event, quartz.kCGMouseEventDeltaY)@@@ -1774,81 -1386,155 +1789,81 @@@self.trigger_suppressed = Falsereturn None if suppress else event+ # The links, and what the owner decides++ def _sync_links(self):+ """One link per peer with `send` on, made and ended to match the peers as the book has them+ now. Cheap, and called every couple of seconds as well as when the settings change."""- peers = self.book.peers()++ peers = peerlist.desktops(self.book.peers())+ wanted = {peer["token"] for peer in peers if peer.get("token") and peer.get("in_use", True) is True+ and peer.get("send") is True}+ first = next((peer["token"] for peer in peers+ if peer.get("token") and peer.get("in_use", True) is True and peer.get("send") is True), None)+ with self._links_lock:+ gone = [self.links.pop(token) for token in [token for token in self.links if token not in wanted]]+ if not self.stop_event.is_set():+ hardware = {"hardware": self._hardware} if self._hardware is not None else {}+ for token in wanted - set(self.links):+ link = self.link_factory(+ token, self.book, self.identity,+ state=self._link_state, up=self._link_up, message=self._link_message,+ socket_factory=self.socket_factory,+ tunnel=self._connect_via_ssh_fallback if token == first else None,+ clock=self.clock, reconnect_seconds=self.cfg.reconnect_interval_s, **hardware,+ large=lambda link, began: self.owner.expects_clipboard(link.peer_id, began),+ )+ self.links[token] = link+ if self.started:+ link.start()+ self._primary_token = first+ self._primary_link = self.links.get(first)+ for link in gone:+ # Without waiting: a link thread can be in a 3 second connect, and this runs on the+ # main thread when a window removes or switches off machines.+ link.stop(wait=False)+ self._forget_link(link)++ def peers_changed(self):+ """The peers changed under the links (a pairing made or removed): bring the links in step,+ and tell every peer we can send to who else this machine has (`paired`)."""+ self._sync_links()+ self.zones_changed()+ for link in list(self.links.values()):+ link.refresh()+ if link.live():+ self._announce_paired(link)+ self._paired_ids = self._pairing_ids()++ def _forget_link(self, link):+ self._drop_up(link)++ def _drop_up(self, link):+ """The link is no longer one this Mac can send on: forget it and tell the owner."""+ peer = link.peer_id+ if peer and self._peers_up.get(peer) is link:+ self._peers_up.pop(peer, None)+ self._forget_held(peer)+ self._step(lambda owner: owner.link_down(peer))+def _connection_worker(self):while not self.stop_event.is_set():- if not self.connected and self._config_ready():- if not self._connect_once():- self._follow_the_pc()+ try:+ self._sync_links()+ self._announce_changes()+ self._follow_the_peers()+ except Exception:+ self.logger.exception("keeping the links in step failed")self.stop_event.wait(self.cfg.reconnect_interval_s)- def _follow_the_pc(self):- """Try the address the paired PC is beaconing from now, if it is not the saved one."""- discovery, cfg = self.discovery, self.cfg- if discovery is None or not cfg.pc_name:+ def _follow_the_peers(self):+ """A peer that changed address after a router restart still beacons under its name: the link+ itself decides whether to try that address (down for ten seconds, once in thirty)."""+ discovery = self.discovery+ if discovery is None or not self.links:return- moved = next((pc["address"] for pc in discovery.pcs()- if pc["name"] == cfg.pc_name and pc["port"] == cfg.port and pc["address"] != cfg.host), None)- if moved is None or not self._connect_once(host=moved):- return- self.logger.info("%s moved from %s to %s", cfg.pc_name, cfg.host, moved)- self.cfg = dataclasses.replace(self.cfg, host=moved)- if self.on_host_learned is not None:- try:- self.on_host_learned(moved)- except Exception:- self.logger.exception("saving the PC's new address failed")-- def _config_ready(self):- return bool(self.cfg.host and self.cfg.auth_token and 1 <= self.cfg.port <= 65535)-- def _connect_once(self, host=None):- sock = None- fallback = False- # Read once: update_config can replace self.cfg from the AppKit thread mid-handshake.- endpoint = (host or self.cfg.host, self.cfg.port, self.cfg.auth_token)- # The tunnel leads to the saved address, so a new one is tried directly or not at all.- tunnel_allowed = host is None- host, port = endpoint[0], endpoint[1]- self.connection_status = f"Connecting to {host}:{port}"- try:- try:- sock = self.socket_factory(- (host, port),- timeout=CONNECT_TIMEOUT_SECONDS,- )- except OSError as exc:- if exc.errno != errno.EHOSTUNREACH or not tunnel_allowed:- raise- sock = self._connect_via_ssh_fallback()- fallback = True- sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)- sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)- session = protocol.SecureSession(endpoint[2])- sock.sendall(session.preamble())- sock.settimeout(AUTH_TIMEOUT_SECONDS)- try:- protocol.recv_preamble(sock, session)- except socket.timeout:- if self.answered == endpoint:- raise _HandshakeError("Windows stopped responding") from None- raise _HandshakeError(OLD_RECEIVER_STATUS) from None- except protocol.VersionMismatch as exc:- raise _HandshakeError(- f"Windows receiver speaks Beamer protocol v{exc.peer_version}, this Mac v{protocol.PROTOCOL_VERSION} — update both apps"- ) from None- # The way home travels in the hello as well as on every switch,- # so Windows knows which of its edges leads back here before this- # Mac has ever crossed -- which is what lets the PC push its own- # pointer out across that same border first.- protocol.send_msg(- sock,- session,- protocol.hello_msg(- return_edge=self.crossing.home_edge(),- resistance_px=int(self.crossing.resistance_px),- ),- )- try:- reply = protocol.recv_msg(sock, session)- except protocol.ConnectionClosed:- # The receiver closes without a word when the first frame fails to authenticate.- raise _HandshakeError(AUTH_FAILED_STATUS) from None- except protocol.AuthenticationError:- raise _HandshakeError(AUTH_FAILED_STATUS) from None- reply_type = reply.get("type")- if reply_type != protocol.MSG_WELCOME:- raise protocol.ProtocolError("receiver did not confirm authentication")- welcome_data = reply.get("data")- if not isinstance(welcome_data, dict):- raise protocol.ProtocolError("welcome message missing data")- error = welcome_data.get("error")- if error == "version_mismatch":- raise _HandshakeError(OLD_RECEIVER_STATUS)- if error:- raise _HandshakeError(f"Windows rejected the connection: {error}")- if welcome_data.get("version") != protocol.PROTOCOL_VERSION:- raise _HandshakeError(OLD_RECEIVER_STATUS)- sock.settimeout(SOCKET_IO_TIMEOUT_SECONDS)- except _HandshakeError as exc:- self.redirecting = False- self.connection_status = exc.status- if sock is not None:- try:- sock.close()- except OSError:- pass- self.logger.warning("connection to Windows failed: %s", exc.status)- return False- except protocol.ConnectionClosed:- self.redirecting = False- self.connection_status = "Windows closed the connection during the handshake."- if sock is not None:- try:- sock.close()- except OSError:- pass- self.logger.warning(self.connection_status)- return False- except (OSError, protocol.ProtocolError) as exc:- self.redirecting = False- self.connection_status = connection_error_message(exc)- if sock is not None:- try:- sock.close()- except OSError:- pass- self.logger.warning("connection to Windows failed: %s", exc)- return False- with self.socket_lock:- if self.stop_event.is_set() or self.sock is not None:- try:- sock.close()- except OSError:- pass- return False- self.sock = sock- self.session = session- self.clipboard.forget_sync()- now = self.clock()- with self.sequence_lock:- self.last_ack_seq = -1- self.last_ack_at = now- self.connected_at = now- self.last_send_at = now- self.answered = endpoint- if fallback:- self.connection_status = "Connected to Windows via secure macOS 27 fallback"- self.logger.info("connected to Windows through the SSH fallback")- else:- self.connection_status = f"Connected to {host}:{port}"- self.logger.info("connected to Windows at %s:%s", host, port)- return True+ machines = list(discovery.pcs())+ for link in list(self.links.values()):+ link.follow(machines)def _connect_via_ssh_fallback(self):try:@@@ -1862,468 -1548,50 +1877,482 @@@"Open /Applications/Beamer Tunnel.command",) from exc- def _outbound_worker(self):- while not self.stop_event.is_set():+ def _name_of(self, peer):+ return self._label(lambda entry: entry.get("id") == peer) or self._up_names.get(peer) or "the other machine"++ # Link callbacks: each on a link's own thread++ def _link_state(self, link, up, text):+ if link.token == self._primary_token:+ self.connection_status = text+ if up:+ return+ self.logger.warning("link to %s: %s", link.peer_name or link.token[:6], text)+ self._drop_up(link)++ def _link_up(self, link, fields):+ if self.links.get(link.token) is not link:+ # Its machine went while the handshake finished: it must not take a place in the owner.+ return+ peer = protocol.id_text(fields["id"])+ self._up_names[peer] = fields["name"]+ self._accepts[peer] = bool(fields["accepts"])+ self._peers_up[peer] = link+ forget = getattr(self.clipboard, "forget_sync", None)+ if forget is not None:+ forget()+ self._step(lambda owner: owner.link_up(peer, fields["accepts"]))+ if self.links.get(link.token) is not link:+ # Its machine went after the check above, and `_sync_links` ran its `_drop_up` before+ # this registered the link: undo what that could not see.+ if self._peers_up.get(peer) is link:+ del self._peers_up[peer]+ self._forget_held(peer)+ self._step(lambda owner: owner.link_down(peer))+ return+ self.logger.info("connected to %s", fields["name"])+ # The handshake may have just given a migrated machine its id, and its zones with it.+ self.zones_changed()+ self._announce_to(link, fields)+ self._peer_up(link, fields)+ if link.token == self._primary_token:+ self._primary_up(link, fields)++ def _peer_up(self, link, fields):+ """Any machine's link is up: a hook for WakingController, which learns its hardware address."""++ def _primary_up(self, link, fields):+ """The primary peer's link is up: its saved address is the one now in use. A hook for+ WakingController, which learns the hardware address."""+ entry = link.entry() or {}+ host = entry.get("host")+ with self._cfg_lock:+ changed = bool(host) and host != self.cfg.host+ if changed:+ self.cfg = dataclasses.replace(self.cfg, host=host)+ if changed:+ callback = self.on_host_learned+ if callback is not None:+ try:+ callback(host)+ except Exception:+ self.logger.exception("saving the peer's new address failed")++ def _announce_to(self, link, fields):+ """What this Mac tells a peer the moment the link is up (WIRE.md section 3)."""+ entry = link.entry() or {}+ own = bytes(self.identity()["id"])+ if entry.get("side") in crossing.EDGES:+ by = protocol.read_id(entry.get("side_by")) or own+ link.post(protocol.arrangement_v6(+ entry["side"], entry.get("side_set_at", 0), by, way_back=self.way_back(link.peer_id),+ way_back_by=protocol.read_id(self.way_back_by(link.peer_id)),+ ))+ if "settings" in link.caps:try:- message = self.outbound.get(timeout=0.2)- except queue.Empty:+ announcements = list(self.announce())+ except Exception:+ self.logger.exception("announce failed")+ announcements = []+ for message in announcements:+ if message.get("type") == protocol.MSG_SETTINGS:+ link.post(message)+ self._announce_paired(link)++ def _pairing_ids(self):+ return tuple(peer.get("id") for peer in self.book.peers()+ if peer.get("in_use", True) is True and protocol.read_id(peer.get("id")) is not None)++ def _announce_paired(self, link):+ ids = [protocol.read_id(peer.get("id")) for peer in self.book.peers()+ if peer.get("in_use", True) is True and peer.get("id") != link.peer_id]+ ids = [ident for ident in ids if ident is not None][:protocol.MAX_PEERS]+ link.post(protocol.paired_msg(ids))++ def _announce_changes(self):+ """Who this Mac has changed (a pairing made or removed): every live peer is told again."""+ ids = self._pairing_ids()+ if ids == self._paired_ids:+ return+ self._paired_ids = ids+ for link in list(self.links.values()):+ if link.live():+ self._announce_paired(link)++ def _link_message(self, link, message):+ kind = message.get("type")+ peer = link.peer_id+ try:+ if kind == protocol.MSG_SWITCH:+ read = protocol.read_switch(message)+ if read is not None:+ data = {"route": read["route"], "next": protocol.id_text(read["next"]),+ "edge": read["edge"], "offset": read["offset"]}+ self._step(lambda owner: owner.switch(peer, data))+ elif kind == protocol.MSG_ACCEPT:+ read = protocol.read_accept(message)+ if read is not None:+ self._step(lambda owner: owner.accept(peer, read))+ elif kind == protocol.MSG_REFUSE:+ read = protocol.read_refuse(message)+ if read is not None:+ self._step(lambda owner: owner.refuse(peer, read))+ elif kind == protocol.MSG_ACCEPTS:+ read = protocol.read_accepts(message)+ if read is not None:+ self._accepts[peer] = read["accepts"]+ self._step(lambda owner: owner.accepts(peer, read["accepts"]))+ elif kind == protocol.MSG_CLIPBOARD:+ began = getattr(message, "began_at", self.clock())+ read = protocol.read_clipboard(message)+ if read is not None:+ # Rebuilt from what was read: the owner sends it on to the machine input is on.+ clean = protocol.clipboard_msg(read["text"], read["image"])+ self._step(lambda owner: owner.clipboard_arrived(peer, began, clean))+ elif kind == protocol.MSG_ARRANGEMENT:+ self._handle_arrangement(message, peer)+ elif kind == protocol.MSG_SETTINGS:+ data = message.get("data")+ if isinstance(data, dict) and "settings" in link.caps and self.on_settings is not None:+ self.on_settings(data, peer)+ elif kind == protocol.MSG_PAIRED:+ ids = protocol.read_paired(message)+ if ids is not None:+ texts = [protocol.id_text(ident) for ident in ids]+ self.book.store_paired(peer, texts)+ if self.on_paired is not None:+ self.on_paired(peer, texts)+ else:+ self.logger.debug("ignoring inbound message of type %r", kind)+ except Exception:+ self.logger.exception("handling a %r from the other machine failed", kind)++ def _handle_arrangement(self, message, peer):+ """A machine changed which edge of its screen faces this one. Handed to the app, which owns+ the settings file, as (that machine's id, its edge, the stamp, who made it); nothing is+ applied here."""+ read = protocol.read_arrangement_v6(message, time.time())+ if read is None or self.on_arrangement is None or not peer:+ return+ args = (peer, read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back"))+ if read.get("way_back_by"):+ args += (protocol.id_text(read["way_back_by"]),)+ self.on_arrangement(*args)++ def way_back(self, peer):+ """Whether one of this Mac's zones in use leads to `peer` and can fire: what every `arrangement`+ to it says as `way_back` (WIRE.md section 8)."""+ with self.book.lock:+ return ways.has_way({"peers": self.book.peers(), "zones": self.book.zones()}, peer)++ def way_back_by(self, peer):+ with self.book.lock:+ return ways.way_back_by({"machine_id": protocol.id_text(self.identity()["id"]),+ "peers": self.book.peers(), "zones": self.book.zones()}, peer)++ def send_arrangement(self, peer, mac_edge, set_at, by=None):+ """Tell `peer` which edge of this Mac faces it, stamped `set_at` by `by` (a b64 id, this Mac when+ None), with whether a way leads there, over this Mac's own link to it. Sent straight out: it is+ not input, and it goes whether or not input is redirected. False when that link is not up; the+ app then tries the link the peer opened."""+ link = self._peers_up.get(peer) if peer else None+ if link is None or not link.live():+ return False+ author = protocol.read_id(by) or bytes(self.identity()["id"])+ return link.post(protocol.arrangement_v6(+ mac_edge, int(set_at), author, way_back=self.way_back(peer),+ way_back_by=protocol.read_id(self.way_back_by(peer)),+ ))++ def send_settings(self, data, source=None):+ """Tell every peer that keeps Same on all machines this Mac's state, but `source` (the peer+ it came from, when this is a newer state passed on)."""+ sent = False+ for peer, link in list(self._peers_up.items()):+ if peer != source and "settings" in link.caps and link.live():+ sent = link.post(protocol.settings_msg(data)) or sent+ return sent++ # The owner++ def _step(self, call):+ """One call into the owner, its messages sent, and then what it asks for here (the+ pointer, an alert) done in the order it was decided in, whichever thread decided it."""+ with self._owner_lock:+ self.owner.resistance_px = int(self.crossing.resistance_px)+ effects = self._execute(call(self.owner))+ self._effects_lock.acquire()+ try:+ self._apply_effects(effects)+ finally:+ self._effects_lock.release()++ def _execute(self, actions):+ """Under `_owner_lock`: send what the owner says to send, and return the rest."""+ effects = []+ for action in actions:+ if not isinstance(action, (owner_module.Send, owner_module.SendClipboard, owner_module.SetClipboard, owner_module.Drop)):+ effects.append(action)continuetry:- self._process_outbound(message)+ if isinstance(action, owner_module.Drop):+ self._drop(action.peer)+ elif isinstance(action, (owner_module.Send, owner_module.SendClipboard)):+ self._deliver(action)+ else:+ self._on_pasteboard(lambda message=action.message: self._set_clipboard(message))except Exception:- # One bad message must not end the only thread that drains- # this queue: nothing restarts it, and the tap would keep- # swallowing input into a queue nobody reads.- self._force_local(f"outbound message {message.get('type')!r} failed")- self.logger.exception("outbound worker recovered")- finally:- self.outbound.task_done()+ # One message that cannot go must not stop the move it belongs to: its Moved is next.+ self.logger.exception("carrying out %s failed", type(action).__name__)+ return effects++ def _apply_effects(self, effects):+ for effect in effects:+ if isinstance(effect, owner_module.Moved):+ self._on_moved(effect)+ elif isinstance(effect, owner_module.Unreachable):+ self._on_unreachable(effect)++ def _deliver(self, action):+ """Sends in the order the owner gave them, except that reading the pasteboard (which can take+ seconds, while the event tap waits for the owner's lock) is done on a thread of its own:+ what follows a clipboard read for the same peer waits for it, and everything else goes on."""+ with self._clip_lock:+ waiting = self._clip_wait.get(action.peer)+ if waiting is not None:+ waiting.append(action)+ return+ if isinstance(action, owner_module.SendClipboard):+ waiting = self._clip_wait[action.peer] = collections.deque()+ try:+ self._on_pasteboard_locked(lambda peer=action.peer: self._clipboard_then_rest(peer, waiting))+ except RuntimeError:+ # No thread at shutdown: nothing must wait behind a read that never starts.+ del self._clip_wait[action.peer]+ raise+ return+ self._send(action)- def _process_outbound(self, message):- """Handle one dequeued outbound item. Control messages (focus,- clipboard, and the local-clipboard sentinel) are exempt from the- `not redirecting` gate -- otherwise the switch-back focus message- would be dropped, since set_redirecting(False) closes the gate- before this worker gets to dequeue it -- and bypass sequence- assignment entirely, the same way ping does via _send_raw."""- message_type = message.get("type")- if message_type not in _GATE_EXEMPT_TYPES and not self.redirecting:+ def _on_pasteboard(self, job):+ with self._clip_lock:+ self._on_pasteboard_locked(job)++ def _on_pasteboard_locked(self, job):+ """Under `_clip_lock`: `job` done after every pasteboard job before it, on the one thread+ that does them, started when there is none."""+ self._pasteboard_jobs.append(job)+ if self._pasteboard_busy:return- if message_type == _LOCAL_CLIPBOARD_SENTINEL_TYPE:- self._send_local_clipboard()+ try:+ threading.Thread(target=self._pasteboard_worker, name="Beamer-clipboard", daemon=True).start()+ except RuntimeError:+ self._pasteboard_jobs.pop()+ raise+ self._pasteboard_busy = True++ def _pasteboard_worker(self):+ while True:+ with self._clip_lock:+ if not self._pasteboard_jobs:+ self._pasteboard_busy = False+ return+ job = self._pasteboard_jobs.popleft()+ try:+ job()+ except Exception:+ self.logger.exception("pasteboard work failed")++ def _clipboard_then_rest(self, peer, waiting):+ """The clipboard for `peer`, then what `waiting` held behind it, in order. `waiting` belongs to+ the link it was made on: once that link is lost (`_forget_held`) none of it is sent, as the+ machine that reconnects will be taken afresh. A clipboard asked for again takes its turn+ among the pasteboard's other work, behind any write decided before it."""+ try:+ self._send_clipboard(peer, waiting)+ except Exception:+ self.logger.exception("the clipboard could not be sent")+ while True:+ with self._clip_lock:+ if self._clip_wait.get(peer) is not waiting:+ return+ if not waiting:+ del self._clip_wait[peer]+ return+ action = waiting.popleft()+ if isinstance(action, owner_module.SendClipboard):+ self._on_pasteboard_locked(lambda: self._clipboard_then_rest(peer, waiting))+ return+ try:+ self._send(action)+ except Exception:+ self.logger.exception("a message held behind the clipboard could not be sent")++ def _drop(self, peer):+ """A hand-over given up before its answer: that machine's link is closed, which ends any+ ownership a late accept began there, and it reconnects (WIRE.md section 5)."""+ self._forget_held(peer)+ link = self._peers_up.get(peer)+ if link is not None:+ link.drop(owner_module.DROPPED)++ def _forget_held(self, peer):+ """`peer`'s link is lost: what waited for its clipboard is for a link that is gone."""+ with self._clip_lock:+ self._clip_wait.pop(peer, None)++ for held in tuple(self._sent_names):++ if held[0] == peer:++ self._sent_names.pop(held, None)++ def _send(self, send):+ link = self._peers_up.get(send.peer)+ if link is None:+ return+ message = send.message+ if message.get("type") == gestures.CHORD:+ receiver = "mac" if keytable.is_mac(link.peer_platform) else "windows"+ for part in gestures.chord_for(message["data"]["action"], receiver):+ if not link.send_input(part):+ if link.live():+ link.drop("The outbound queue filled")+ return+ return+ if message.get("type") in protocol.INPUT_TYPES:+ message = self._for_peer(message, link)+ if message is None:+ return+ sent = link.send_input(message)+ else:+ sent = link.post(message)+ if not sent and link.live():+ link.drop("The outbound queue filled")++ def _key_style(self):+ return config_module.key_map_style(self.cfg.key_map) or self.cfg.key_map++ def _for_peer(self, message, link):+ """A captured input message as the peer it is going to names it: modifiers by the key+ table (WIRE.md section 7), and media keys only to a peer that acts on them."""+ if message.get("type") not in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP):+ return message+ data = dict(message["data"])+ key = data.get("key")+ if key in MEDIA_KEY_NAMES:+ return message if "media_keys" in link.caps else None- data["key"] = keytable.wire_name(key, OWN_PLATFORM, link.peer_platform, self._key_style())++ held = (link.peer_id, key)++ if message["type"] == protocol.MSG_KEYUP and held in self._sent_names:++ name = self._sent_names.pop(held)++ if any(peer == held[0] and sent == name for (peer, _physical), sent in self._sent_names.items()):++ return None++ elif message["type"] == protocol.MSG_KEYDOWN and held in self._sent_names:++ name = self._sent_names[held]++ else:++ name = keytable.wire_name(key, OWN_PLATFORM, link.peer_platform, self._key_style())++ if message["type"] == protocol.MSG_KEYDOWN:++ self._sent_names[held] = name++ data["key"] = name+ return {"type": message["type"], "data": data}++ def _on_moved(self, moved):+ self.logger.info(+ "move applied: to %s from %s why %s%s (thread %s)",+ self._name_of(moved.to) if moved.to is not None else "home",+ self._name_of(moved.left) if moved.left is not None else "home",+ moved.why,+ f" at the {moved.edge} edge" if isinstance(moved.edge, str) else "",+ threading.current_thread().name,+ )+ if moved.to is not None:+ with self._repair_lock:+ self._repair_disagreement_seen = False+ if not self.redirecting:+ self.redirect_started_at = self.clock()+ self.redirecting = True+ self.cursor_pin_point = self._capture_cursor_pin_point()+ self._set_cursor_follows_mouse(False)+ self.pointer.hide()+ self._last_peer = moved.to+ self.logger.info("redirecting input to %s", self._name_of(moved.to))+ return+ self._local_cleanup()+ other = ""+ if isinstance(moved.other, bytes) and moved.other != bytes(self.identity()["id"]):+ other = peerlist.label_for(self.book.peers(), peer_id=protocol.id_text(moved.other))+ name = self._name_of(moved.left)+ text = peerlist.refusal_text(moved.why, name, other)+ if text is None and moved.why in WHY_TEXT:+ text = WHY_TEXT[moved.why].format(name=name)+ if text is not None:+ self.logger.warning("%s; input returned to this Mac", text)+ self._alert("Beamer", text)+ if moved.why == "switch":+ self._arrive(moved.edge, moved.offset)++ def _arrive(self, edge, offset):+ """The other machine sent input back: land the pointer where it left, `edge` being the edge+ of this Mac to arrive at and `offset` the fraction along it. Without an edge the pointer+ stays where it was and the arrival says so."""+ crossed = edge in crossing.EDGES and isinstance(offset, (int, float)) and not isinstance(offset, bool)+ point = None+ if crossed:+ try:+ point = crossing.CrossingEngine.arrival_point(+ edge, offset, self._current_desktop_bounds(), displays=self._current_displays())+ except Exception:+ self.logger.exception("failed to place the pointer on arrival")+ else:+ self._warp_cursor_to(point)+ # `pin` is where the pointer landed, for the arrival effect; None when it was not placed.+ self._notify_crossing("arrive", crossing.Step(mac_edge=edge if edge in crossing.EDGES else None, pin=point))++ def _on_unreachable(self, unreachable):+ name = self._name_of(unreachable.peer)+ why = unreachable.why+ if why == "unreachable" and self._accepts.get(unreachable.peer) is False:+ why = "not_allowed"+ other = ""+ if isinstance(unreachable.other, bytes) and unreachable.other != bytes(self.identity()["id"]):+ other = peerlist.label_for(self.book.peers(), peer_id=protocol.id_text(unreachable.other))+ text = peerlist.refusal_text(why, name, other)+ if text is None:+ text = WHY_TEXT.get(why, "{name} could not be reached").format(name=name)+ self.logger.warning("%s", text)+ self._alert("Beamer", text)++ # The clipboard (WIRE.md section 5)++ def _clipboard_stamp_now(self):+ stamp = getattr(self.clipboard, "change_stamp", None)+ if stamp is None:+ return None+ try:+ return stamp()+ except Exception:+ self.logger.exception("could not read the clipboard's change stamp")+ return None++ def _note_clipboard(self):+ """Before this Mac takes a peer: if the clipboard changed by its owner's hand since this+ Mac last wrote it from a peer, no peer holds what it holds now."""+ stamp = self._clipboard_stamp_now()+ if stamp != self._clipboard_stamp:+ self._clipboard_stamp = stamp+ with self._owner_lock:+ self.owner.clipboard_changed()++ def _send_clipboard(self, peer, waiting):+ """Read this Mac's clipboard and send it as a clipboard message. Text over CLIPBOARD_MAX_BYTES+ and an image protocol.png_fits refuses are each dropped on their own, so an oversized+ screenshot still lets its text through; with nothing left nothing is sent. Nothing is sent+ either when `waiting` was dropped with its link while the pasteboard was read."""+ if self._peers_up.get(peer) is None:return- if message_type in CONTROL_MESSAGE_TYPES:- self._send_raw(message)+ text, image = self.clipboard.get_contents()+ with self._clip_lock:+ if self._clip_wait.get(peer) is not waiting:+ return+ link = self._peers_up.get(peer)+ if link is None:return- prepared = self._prepare_outbound(message)- self._send_prepared(prepared)-- def _send_local_clipboard(self):- """Expand the local-clipboard sentinel: read this Mac's clipboard and- send it as a clipboard message, unless it is unchanged since it was- last sent or written from the PC. Text over CLIPBOARD_MAX_BYTES and an- image over CLIPBOARD_IMAGE_MAX_BYTES are each dropped on their own,- so an oversized screenshot still lets its text through; with nothing- left the message is skipped and the focus message still goes out."""- text, image = self.clipboard.changed_contents()if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:self.logger.warning("local clipboard text is too large; skipping the text")text = Nonediff --cc mac_app/crossing.pyindex c27fd2c,3dd6b86..e866257--- a/mac_app/crossing.py+++ b/mac_app/crossing.py@@@ -38,10 -38,8 +38,10 @@@ DEFAULT_CROSSING ="haptic_feel": "medium","haptic_steps": "quarters","glow_style": "glow",-- "glow_colour": "signal",++ "glow_colour": "colourful","block_while_dragging": True,+ # A full-screen app in front holds this Mac's edges. This Mac's own choice, never shared.+ "hold_full_screen": False,# "Part of the edge": the thirds of `edge` that cross, as return_edge.PARTS names them."edge_parts": ["middle"],# A switch by the shortcut or a menu, not a crossing, plays an arrival around the pointer.diff --cc mac_app/diagram.pyindex 9a8812f,c147766..1ee6049--- a/mac_app/diagram.py+++ b/mac_app/diagram.py@@@ -4,6 -4,6 +4,7 @@@ far the pointer is pushed past the edgfrom __future__ import annotations++import mathimport AppKitimport Quartzimport objc@@@ -35,6 -35,6 +36,21 @@@ def _text_layer(size, ink, align=Quartzreturn layer++def _text_height(text, font, width):++ return AppKit.NSAttributedString.alloc().initWithString_attributes_(++ text, {AppKit.NSFontAttributeName: font}++ ).boundingRectWithSize_options_((max(1, width), 10000), AppKit.NSStringDrawingUsesLineFragmentOrigin).size.height++++++def _fit_text(layer, text, frame):++ x, y, width, height = frame++ layer.setString_(text)++ layer.setWrapped_(True)++ layer.setTruncationMode_(Quartz.kCATruncationNone)++ text_height = _text_height(text, layer.font(), width)++ layer.setFrame_(((x, y + max(0, (height - text_height) / 2)), (width, text_height)))++++def _box(fill=None, stroke=None, radius=0.0):layer = Quartz.CALayer.layer()theme.tint(layer, background=fill, border=stroke)@@@ -148,67 -116,40 +164,69 @@@ class ArrangementDiagram(AppKit.NSView)bounds = self.bounds().sizeif bounds.width <= 0:return- this, frames = pages.diagram_layout(bounds.width, bounds.height - self.LEGEND, [pages.placement(m) for m in machines])- this, other = pages.arrangement(bounds.width, bounds.height, side)++ font = theme.font(theme.TYPE["small"], 500)++ width = min(bounds.width - 24, 24 + _text_width(key_text, theme.font(theme.TYPE["small"], 600)))++ how = _text_width(key_how, font) + 4++ stacked = bool(shortcut and width + 8 + how > bounds.width - 24)++ legend = self.LEGEND + (20 if stacked else 0)++ this, frames = pages.diagram_layout(bounds.width, bounds.height - legend, [pages.placement(m) for m in machines])+ # With one machine nothing is chosen between, and it looks as the one-machine drawing did.+ several = len(machines) > 1motion.transaction(animate)self.this.setFrame_(_rect(this))- self.other.setFrame_(_rect(other))-- self.this_label.setString_("This Mac")- self.other_label.setString_(other_name)line = theme.TYPE["small"] + 4- for layer, (x, y, w, h) in ((self.this_label, this), (self.other_label, other)):- layer.setFrame_(((x + 6, y + (h - line) / 2 + (4 if layer is self.this_label and has_notch else 0)), (w - 12, line)))+ x, y, w, h = this- self.this_label.setFrame_(((x + 6, y + (h - line) / 2 + (4 if has_notch else 0)), (w - 12, line)))++ _fit_text(self.this_label, "This Mac", (x + 6, y + (4 if has_notch else 0), w - 12, h))+ keys = {machine["key"] for machine in machines}+ for key in [key for key in self.screens if key not in keys]:+ for layer in self.screens.pop(key):+ layer.removeFromSuperlayer()+ for machine, frame in zip(machines, frames):+ screen, label = self._screen(machine["key"])+ strong = several and machine["chosen"]+ screen.setHidden_(frame is None)+ label.setHidden_(frame is None)+ if frame is None:+ continue+ theme.tint(screen, border="ink_3" if strong else "rule")+ theme.tint(label, foreground="ink" if strong else "ink_3")+ label.setFont_(theme.font(theme.TYPE["small"], 600 if strong else 500))+ screen.setFrame_(_rect(frame))- label.setString_(machine["label"])+ fx, fy, fw, fh = frame- label.setFrame_(((fx + 4, fy + (fh - line) / 2), (fw - 8, line)))++ _fit_text(label, machine["label"], (fx + 4, fy, fw - 8, fh))+ marks, notch = pages.diagram_marks(this, machines)+ for key in [key for key in self.marks if key not in marks]:+ self.marks.pop(key).removeFromSuperlayer()+ self.lit.pop(key, None)+ sides = {machine["key"]: machine["side"] for machine in machines}+ for key, (frame, tone) in marks.items():+ layer = self._mark_layer(key)+ if tone is not None:+ theme.tint(layer, background=self.TONES[tone])+ # The chosen machine's ways on top where two machines' marks meet.+ layer.setZPosition_(1.0 if tone in ("chosen", "track") else 0.0)+ self._mark(key, layer, frame, tone, sides[key[0]] if key[1] != "corner" else None, animate)self.notch.setFrame_(_rect(pages.notch_mark(this)))self.notch.setHidden_(not has_notch)- lit_notch = has_notch and "notch" in methods+ lit_notch = has_notch and notch is not Noneself.notch.setBorderWidth_(1.5 if lit_notch else 0)- theme.tint(self.notch, border="signal", background=("signal", 0.25) if lit_notch else "ground")- part = "part" in methods- self._mark("side", self.side, pages.side_mark(this, side), "edge" in methods, side, animate)- for name, frame in pages.third_marks(this, side).items():- layer = self.thirds[name]- chosen = part and name in parts- # Unchosen thirds stay as a dim track while Part of the edge is on, so the gaps read- # as walls rather than as nothing.- theme.tint(layer, background="signal" if chosen else "edge")- self._mark(name, layer, frame, part, side, animate, lit=chosen)- self._mark("corner", self.corner, pages.corner_mark(this, corner), "corner" in methods, None, animate)- shortcut = "shortcut" in methods and bool(key_text)+ theme.tint(self.notch, border=self.TONES[notch] if lit_notch else "signal",+ background=("signal", 0.25 if notch == "chosen" else 0.12) if lit_notch else "ground")+ shortcut = shortcut and bool(key_text)self.key_label.setString_(key_text)self.key_how.setString_(key_how)- font = theme.font(theme.TYPE["small"], 500)-- width = min(bounds.width - 20, 24 + _text_width(key_text, theme.font(theme.TYPE["small"], 600)))-- top = bounds.height - 36++ top = bounds.height - legendself.key.setFrame_(((12, top), (width, 24)))self.key_label.setFrame_(((0, (24 - line) / 2), (width, line)))- how = _text_width(key_how, font) + 4- self.key_how.setFrame_(((12 + width + 8, top + (24 - line) / 2), (how, line)))- self.key_how.setFrame_(((12 + width + 8, top + (24 - line) / 2), (max(0, bounds.width - width - 32), line)))++ how_left = 12 if stacked else 12 + width + 8++ how_top = top + 26 if stacked else top + (24 - line) / 2++ self.key_how.setFrame_(((how_left, how_top), (min(how, bounds.width - 12 - how_left), line)))for layer in (self.key, self.key_how):layer.setOpacity_(1.0 if shortcut else 0.0)+ # The machines with no side, on the key cap's line, from wherever the legend ends.- start = 12 + width + 8 + how + 16 if shortcut else 12++ start = how_left + how + 16 if shortcut else 12+ self.not_placed.setString_(pages.not_placed(machines))- self.not_placed.setFrame_(((start, top + (24 - line) / 2), (max(0, bounds.width - 12 - start), line)))++ self.not_placed.setFrame_(((min(start, bounds.width - 12), how_top), (max(0, bounds.width - 12 - start), line)))Quartz.CATransaction.commit()@objc.python_method@@@ -264,7 -201,7 +282,8 @@@ class PushStrip(AppKit.NSView)@objc.python_methoddef setup(self):self.setTranslatesAutoresizingMaskIntoConstraints_(False)-- self.heightAnchor().constraintEqualToConstant_(self.HEIGHT).setActive_(True)++ self.minimum_height = self.heightAnchor().constraintEqualToConstant_(self.HEIGHT)++ self.minimum_height.setActive_(True)self.setWantsLayer_(True)root = self.layer()root.setCornerRadius_(3)@@@ -324,18 -261,18 +343,19 @@@width, height = self.bounds().size.width, self.bounds().size.heightif width <= 0:return-- edge = round(width * self.EDGE_AT)- # The full 500 px stops short of the PC's name, so the name is never under the push.- room = width - edge - 120++ edge = max(round(width * self.EDGE_AT), 20 + _text_width("THIS MAC", self.this_label.font()))++ needed_height = max(self.HEIGHT, math.ceil(_text_height(++ self.other_name.upper(), self.other_label.font(), width - edge - 20)) + 8)++ if self.minimum_height.constant() != needed_height:++ self.minimum_height.setConstant_(needed_height)+ # The full 500 px stops short of the other machine's name, so the name is never under the push.- room = width - edge - 120++ room = max(0, width - edge - min(120, _text_width(self.other_name.upper(), self.other_label.font()) + 20))depth = room * self.fractionmotion.transaction(animate)self.this.setFrame_(((0, 0), (edge, height)))self.edge.setFrame_(((edge - 1, 0), (2, height)))self.fill.setFrame_(((edge, 0), (depth, height)))self.pointer.setPosition_((edge + depth - 1, (height - 16) / 2))-- line = theme.TYPE["eyebrow"] + 4-- self.this_label.setString_("THIS MAC")-- self.other_label.setString_(self.other_name.upper())-- self.this_label.setFrame_(((10, (height - line) / 2), (edge - 20, line)))-- self.other_label.setFrame_(((edge + 10, (height - line) / 2), (width - edge - 20, line)))++ _fit_text(self.this_label, "THIS MAC", (10, 0, edge - 20, height))++ _fit_text(self.other_label, self.other_name.upper(), (edge + 10, 0, width - edge - 20, height))Quartz.CATransaction.commit()diff --cc mac_app/kvm_bridge_app.pyindex 8a5c1c4,6dd0e4d..be6d856--- a/mac_app/kvm_bridge_app.py+++ b/mac_app/kvm_bridge_app.py@@@ -4,11 -4,10 +4,8 @@@ import fcntimport loggingimport logging.handlersimport os--import re- import socketimport subprocessimport sys--import threadingimport timefrom dataclasses import replacefrom pathlib import Path@@@ -22,15 -21,13 +19,16 @@@ 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 effects++from core.locale import americaniseimport effects_overlayimport gestures+import hardware_macimport ignored_titlesimport keyboard_layoutimport notch_beam@@@ -59,10 -51,9 +57,10 @@@ from settings_store importeditable_default_config,)import theme--from wake import WakingController, lookup_mac++from wake import WakingControllerimport widgetsfrom windows_input import WindowsInput+from core.receiver import ServerStateLOG_DIRECTORY = Path.home() / "Library" / "Logs" / "Beamer"@@@ -669,6 -653,6 +667,7 @@@ class EdgeGlowself.fill.setColors_(notch_beam.palette_colours(feel["glow_colour"], dark=self.dark_appearance()))fade = self._taper()ends = (lambda at: 1.0) if fade is None else (lambda at: min(1.0, at / fade, (1.0 - at) / fade))++ notch_beam.mask_edge_falloff(self.comet, self.mac_edge, beam)if beam:stops = [index / 24 for index in range(25)]self.comet.setLocations_(stops)@@@ -765,7 -748,7 +764,7 @@@Quartz.CATransaction.begin()Quartz.CATransaction.setDisableActions_(True)try:-- for layer, mask, frame, (start, end), path in walls:++ for wall, (layer, mask, frame, (start, end), path) in zip((vertical, horizontal), walls):layer.setHidden_(False)layer.setFrame_(frame)layer.setStartPoint_(start)@@@ -781,6 -764,6 +780,7 @@@).CGColor()for u in stops])++ notch_beam.mask_edge_falloff(mask, wall, beam)layer.setMask_(mask)layer.setOpacity_(min(1.0, strength) if beam else min(1.0, 0.3 + 0.7 * level + 0.6 * flash))finally:@@@ -868,7 -851,7 +868,7 @@@ def install_main_menu(control_window)key equivalent of the Quit item in the application menu — so with no main menu the app couldnot be quit from the keyboard, and Cmd+C/V/A in the token field did nothing either."""def item(menu, title, action, key, modifiers=None, target=None):-- entry = menu.addItemWithTitle_action_keyEquivalent_(title, action, key)++ entry = menu.addItemWithTitle_action_keyEquivalent_(americanise(title), action, key)if modifiers is not None:entry.setKeyEquivalentModifierMask_(modifiers)if target is not None:@@@ -929,51 -912,14 +929,160 @@@AppKit.NSApp.setMainMenu_(main_menu)--class FlippedView(AppKit.NSView):-- """A plain view that lays out top-down, so the scrolling page starts at the top of the window-- rather than the bottom of the document."""++class FlippedView(AppKit.NSTableRowView):++ """A native flipped container avoids Python callbacks for every descendant's frame change.+- def isFlipped(self):- return True++ The row supplies native top-left coordinates; the settings column owns its layout.++ """+++def window_fill_frame(window):+ screen = window.screen() or AppKit.NSScreen.mainScreen()+ return screen.visibleFrame()++++def page_column_width(free):++ return max(0, min(880, free - 48))++++++def settings_normal_frame(saved, work):++ import math++ try:++ x, y, width, height = map(float, saved)++ if not all(math.isfinite(value) for value in (x, y, width, height)):++ raise ValueError++ except (TypeError, ValueError):++ width, height = 900, 640++ x = work.origin.x + (work.size.width - min(width, work.size.width)) / 2++ y = work.origin.y + (work.size.height - min(height, work.size.height)) / 2++ width = min(work.size.width, max(320, width))++ height = min(work.size.height, max(300, height))++ x = min(max(x, work.origin.x), work.origin.x + work.size.width - width)++ y = min(max(y, work.origin.y), work.origin.y + work.size.height - height)++ return x, y, width, height++++++def ordinary_window_frame(window):++ if (not window.isVisible() or window.isZoomed()++ or window.styleMask() & AppKit.NSWindowStyleMaskFullScreen++ or '"tilingState"' in window.stringWithSavedFrame()):++ return None++ frame = window.frame()++ return [frame.origin.x, frame.origin.y, frame.size.width, frame.size.height]+++++def titlebar_action(setting):+ value = (setting or "").strip().casefold()- if value in {"fill", "zoom"}:++ if value in {"fill", "zoom", "maximize"}:+ return "fill"+ if value in {"minimise", "minimize"}:+ return "minimise"- return None++ if value in {"none", "do nothing"}:++ return None++ return "fill"+++def perform_titlebar_double_click(window, setting=None):+ if setting is None:+ domain = AppKit.NSUserDefaults.standardUserDefaults().persistentDomainForName_("NSGlobalDomain") or {}+ setting = domain.get("AppleActionOnDoubleClick")+ action = titlebar_action(setting)+ if action == "fill":+ window.zoom_(None)+ elif action == "minimise":+ window.miniaturize_(None)+++def perform_titlebar_drag(window, event):+ window.performWindowDragWithEvent_(event)+++class TitlebarStrip(AppKit.NSView):+ def mouseDown_(self, event):- if event.clickCount() >= 2:- perform_titlebar_double_click(self.window())- else:++ if event.clickCount() == 1:+ perform_titlebar_drag(self.window(), event)+- def isFlipped(self):++class SettingsWindow(AppKit.NSWindow):++ @objc.python_method++ def refresh_input_focus(self):++ responder = self.firstResponder()++ if isinstance(responder, widgets.Pressable):++ responder._ring(True)++ elif isinstance(responder, widgets._RulerView):++ responder.refresh_keyboard_focus()++ delegate = self.delegate()++ if delegate is not None and hasattr(delegate, 'sidebar'):++ delegate.sidebar.refresh_focus()++++ @objc.python_method++ def navigate_key_view(self, backwards, sender):++ self.keyboard_navigation = True++ sidebar = self.delegate().sidebar++ sidebar_rows = [values[1] for values in sidebar.rows.values()]++ previous = self.firstResponder()++ advance = (objc.super(SettingsWindow, self).selectPreviousKeyView_ if backwards++ else objc.super(SettingsWindow, self).selectNextKeyView_)++ advance(sender)++ current = self.firstResponder()++ if previous == self or (current in sidebar_rows and previous not in sidebar_rows):++ self.makeFirstResponder_(sidebar.rows[sidebar.selected][1])++ elif previous in sidebar_rows:++ for _ in sidebar_rows:++ if self.firstResponder() not in sidebar_rows:++ break++ advance(sender)++ self.refresh_input_focus()++++ def selectNextKeyView_(self, sender):++ self.navigate_key_view(False, sender)++++ def selectPreviousKeyView_(self, sender):++ self.navigate_key_view(True, sender)++++ @objc.python_method++ def titlebar_background(self, point):++ content = self.contentView()++ height = content.bounds().size.height++ in_top = (0 <= point.x <= content.bounds().size.width++ and height - 18 <= point.y <= self.frame().size.height)++ delegate = self.delegate()++ header = getattr(getattr(delegate, "sidebar", None), "header", None)++ in_header = header is not None and AppKit.NSPointInRect(++ header.convertPoint_fromView_(point, None), header.bounds()++ )++ if not (in_top or in_header):++ return False++ # Title text is a non-editable NSTextField. Traffic lights and other controls keep++ # their own clicks even when they lie inside one of the draggable backgrounds.++ hit = content.superview().hitTest_(point)++ while hit is not None:++ if isinstance(hit, (AppKit.NSButton, widgets.Pressable)):++ return False++ if isinstance(hit, AppKit.NSTextField) and hit.isEditable():++ return False++ hit = hit.superview()+ return True+++ def sendEvent_(self, event):++ if event.type() == AppKit.NSEventTypeKeyDown and widgets.is_navigation_key(event):++ self.keyboard_navigation = True++ elif event.type() in (AppKit.NSEventTypeLeftMouseDown, AppKit.NSEventTypeRightMouseDown):++ self.keyboard_navigation = False++ self.refresh_input_focus()++ # Native titlebar and sidebar events never visit TitlebarStrip. All three++ # backgrounds must use the same preference fallback, once, on mouse-up.++ if (event.type() in (AppKit.NSEventTypeLeftMouseDown, AppKit.NSEventTypeLeftMouseUp)++ and event.clickCount() == 2++ and self.titlebar_background(event.locationInWindow())):++ # Consume the second down too: native tracking may otherwise handle the up itself++ # before it reaches sendEvent:, or apply its own action as well as this one.++ if event.type() == AppKit.NSEventTypeLeftMouseUp:++ perform_titlebar_double_click(self)++ return++ objc.super(SettingsWindow, self).sendEvent_(event)+++class ControlWindow(AppKit.NSObject):def initWithController_settingsStore_logger_(self, controller, settings_store, logger):self = objc.super(ControlWindow, self).init()@@@ -1007,16 -956,9 +1116,19 @@@self.haptics = Noneself.previews = Noneself._apply_serial = 0+ self._save_pending = False+ self._design_states = {}++ self._followed_version = None++ self._design_path = []+ # The machine the Crossing page shows and writes the ways of: an id ("" is the entry+ # migrated from 1.4.x), None while nothing is paired.+ self.chosen_peer = None+ self._picker_choices = None+ self.machine_select = Noneself.page = Noneself.opened = False-- self.window = AppKit.NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(++ self.side_by_side = []++ self.window = SettingsWindow.alloc().initWithContentRect_styleMask_backing_defer_(((0, 0), (900, 640)),AppKit.NSWindowStyleMaskTitled| AppKit.NSWindowStyleMaskClosable@@@ -1027,15 -969,15 +1139,20 @@@)self.window.setTitle_("Beamer")self.window.setReleasedWhenClosed_(False)-- self.window.setDelegate_(self)-- self.window.setContentMinSize_(AppKit.NSMakeSize(*theme.MIN_WINDOW))++ self.window.setMinSize_((320, 300))++ self.window.keyboard_navigation = False# The window always carries the palette's own appearance, never nil: the title bar's# buttons and text then match the palette whatever the Mac is set to, and the transparent# title bar takes the window's ground.self.window.setAppearance_(theme.appearance_named(theme.is_dark()))self.window.setBackgroundColor_(theme.colour("ground"))self.window.setTitlebarAppearsTransparent_(True)-- self.window.center()++ screen = self.window.screen() or AppKit.NSScreen.mainScreen()++ x, y, width, height = settings_normal_frame(++ self.settings_store.current().get("settings_window_frame"), screen.visibleFrame())++ self.window.setFrame_display_(((x, y), (width, height)), False)++ self._normal_frame = [x, y, width, height]++ self._frame_transition = Falsecontent = self.window.contentView()content.setWantsLayer_(True)theme.tint(content.layer(), background="ground")@@@ -1056,6 -993,6 +1173,7 @@@footer_label="Open Beamer's website, kalkmancode.co.uk/beamer",on_footer=self._open_beamer_site,)++ self.sidebar.footer_icon.setImage_(menu_bar_glyph("local"))divider = widgets.box("rule")pane = widgets.stack(spacing=0)for view in (top, self.sidebar.view, divider, pane):@@@ -1085,7 -1017,7 +1203,9 @@@])# The page host is the only part of the pane that gives way when the window is resized;# the commit bar keeps its height on every page.-- host = widgets.box()++ host = widgets.stack(spacing=0)++ host.setAlignment_(AppKit.NSLayoutAttributeWidth)++ host.setDetachesHiddenViews_(True)host.setContentHuggingPriority_forOrientation_(AppKit.NSLayoutPriorityDefaultLow, AppKit.NSLayoutConstraintOrientationVertical)@@@ -1093,14 -1025,11 +1213,16 @@@AppKit.NSLayoutPriorityDefaultLow, AppKit.NSLayoutConstraintOrientationVertical)widgets.add(pane, host)++ self.page_host = hostwidgets.add(pane, widgets.hairline())widgets.add(pane, self._commit())-- self.page_titles = []- self.page_paddings = []++ self.page_titles = {}+ # Same on all machines: each shared page's scope line, and the notes on this Mac's own rows.+ self.scope_labels = {}+ self.own_notes = []- self.page_paddings = []++ self.page_paddings = {}++ self.page_width_constraints = {}self.pages = {}builders = {"overview": self._overview_page,@@@ -1111,70 -1040,65 +1233,141 @@@"permissions": self._permissions_page,}for key, name, _symbol, purpose in pages.PAGES:- scroll, body = self._page(name, purpose, pages.SCOPE.get(key))- host.addSubview_(scroll)- widgets.pin(scroll, host)+ scroll, body = self._page(name, purpose, pages.SCOPE.get(key), key)- host.addSubview_(scroll)- widgets.pin(scroll, host)++ host.addArrangedSubview_(scroll)scroll.setHidden_(True)self.pages[key] = scrollbuilders[key](body)self._load(config_to_raw(controller.cfg))self._select_page(pages.opening_page(None, accessibility_granted(), input_monitoring_granted()))++ self.window.setDelegate_(self)self.windowDidResize_(None)self.refresh()return selfdef windowDidResize_(self, _notification):++ self._remember_normal_frame()width = self.window.contentView().frame().size.width-- low, high = theme.SIDEBAR_WIDTH-- sidebar = min(high, max(low, width * 0.25))++ if width == getattr(self, "_last_resize_width", None):++ return++ self._last_resize_width = width++ sidebar = 56 if width < 640 else 144 if width < 800 else 176self.sidebar_width.setConstant_(sidebar)-- self._apply_width(width - sidebar - 1)++ self.sidebar.set_collapsed(width < 640)++ page_width = width - sidebar - 1 - 16++ self._apply_width(page_width)++ body_width = page_column_width(page_width)++ if self.page == "design":++ inner_width = body_width - 32++ for choices in (self.glow_style_select, self.switch_style_select, self.glow_colour_select):++ for row in choices.rows:++ if not row.view.isHiddenOrHasHiddenAncestor():++ row.grid.arrange(inner_width)++ for row in (self.length_row, self.size_row, self.style_for_row, self.effect_method_view,++ self.tick_steps_pair):++ if not row.isHiddenOrHasHiddenAncestor():++ row.field_owner.arrange(inner_width)++ self.page_width_constraints[self.page].setConstant_(body_width)++ self.page_width_constraints[self.page].setPriority_(499)++ for pair in self.side_by_side:++ if not pair.view.enclosingScrollView().isHidden():++ pair.update_orientation(body_width - 2 * theme.MODULE_PADDING[1])++++ @objc.python_method++ def _remember_normal_frame(self):++ if self._frame_transition:++ return++ frame = ordinary_window_frame(self.window)++ if frame is not None:++ self._normal_frame = frame++++ def windowDidMove_(self, _notification):++ self._remember_normal_frame()++++ def windowWillEnterFullScreen_(self, _notification):++ self._remember_normal_frame()++ self._frame_transition = True++++ def windowWillExitFullScreen_(self, _notification):++ self._frame_transition = True++++ def windowDidExitFullScreen_(self, _notification):++ screen = self.window.screen() or AppKit.NSScreen.mainScreen()++ x, y, width, height = settings_normal_frame(self._normal_frame, screen.visibleFrame())++ self.window.setFrame_display_(((x, y), (width, height)), False)++ self._frame_transition = False++++ def windowDidFailToEnterFullScreen_(self, _window):++ self._frame_transition = False++++ def windowDidFailToExitFullScreen_(self, _window):++ self._frame_transition = False++++ def windowDidBecomeKey_(self, _notification):++ self.sidebar.refresh_focus()++ def windowWillUseStandardFrame_defaultFrame_(self, window, _default_frame):+ return window_fill_frame(window)@objc.python_methoddef _apply_width(self, width):- """Two layouts, not a continuous reflow. Wide, Pairing puts the PC list beside the code;+ """Two layouts, not a continuous reflow. Wide, Pairing puts the machine list beside the code;narrow, it stacks and the large figures step down a size."""-- wide = width >= WIDE_WIDTH++ threshold = WIDE_WIDTH if self.wide is None else WIDE_WIDTH + (-16 if self.wide else 16)++ wide = width >= thresholdif wide == self.wide:returnself.wide = wide++ self._apply_page_width(self.page, wide)++++ @objc.python_method++ def _apply_page_width(self, key, wide):++ if key == "design":++ returnnarrow = not wide-- top, leading, bottom, trailing = theme.PAGE_PADDING_NARROW if narrow else theme.PAGE_PADDING-- for constraints in self.page_paddings:-- for constraint, constant in zip(constraints, (top, leading, bottom, trailing)):-- constraint.setConstant_(constant)-- for title in self.page_titles:-- title.set(size=theme.PAGE_TITLE_NARROW if narrow else theme.PAGE_TITLE)-- self.state_word.set(size=theme.TYPE["status_word_narrow" if narrow else "status_word"])-- for readout in (self.round_trip, self.peer):-- readout.set_narrow(narrow)-- numeral = theme.TYPE["numeral_narrow" if narrow else "numeral"]-- self.resistance_numeral.set(size=numeral)-- self.double_tap_numeral.set(size=numeral)-- # Stacked, each half takes the full width; side by side, FillEqually shares it. The-- # distribution runs along the orientation, so stacked it must go back to Fill.-- self._show_peer()- panel = self.panel- panel.wide = wide- AppKit.NSLayoutConstraint.deactivateConstraints_(panel.pair_stacked)- panel.pair_grid.setOrientation_(- AppKit.NSLayoutConstraint.deactivateConstraints_(self.pair_stacked)- self.pair_grid.setOrientation_(-- AppKit.NSUserInterfaceLayoutOrientationHorizontal if wide else AppKit.NSUserInterfaceLayoutOrientationVertical-- )- panel.pair_grid.setDistribution_(- self.pair_grid.setDistribution_(-- AppKit.NSStackViewDistributionFillEqually if wide else AppKit.NSStackViewDistributionFill-- )-- if narrow:- AppKit.NSLayoutConstraint.activateConstraints_(panel.pair_stacked)- AppKit.NSLayoutConstraint.activateConstraints_(self.pair_stacked)++ top, leading, bottom, trailing = (24, 24, 24, 24)++ constraints = self.page_paddings[key]++ for constraint, constant in zip(constraints, (top, leading, bottom, trailing)):++ constraint.setConstant_(constant)++ constraints[-1].setConstant_(-(leading + trailing))++ self.page_titles[key].set(size=theme.PAGE_TITLE_NARROW if narrow else theme.PAGE_TITLE)++ if key == "overview":++ self.state_word.set(size=theme.TYPE["status_word_narrow" if narrow else "status_word"])++ for readout in (self.round_trip, self.peer):++ readout.set_narrow(narrow)++ self._show_peer()++ panel = self.panel++ if panel.wide != wide:++ panel.wide = wide++ # Stacked, each half takes the full width; side by side, FillEqually shares it.++ AppKit.NSLayoutConstraint.deactivateConstraints_(panel.pair_stacked)++ panel.pair_grid.setOrientation_(++ AppKit.NSUserInterfaceLayoutOrientationHorizontal if wide else AppKit.NSUserInterfaceLayoutOrientationVertical++ )++ panel.pair_grid.setDistribution_(++ AppKit.NSStackViewDistributionFillEqually if wide else AppKit.NSStackViewDistributionFill++ )++ if narrow:++ AppKit.NSLayoutConstraint.activateConstraints_(panel.pair_stacked)++ panel.refresh()++ elif key == "crossing":++ self.resistance_numeral.set(size=theme.TYPE["numeral_narrow" if narrow else "numeral"])++ self.double_tap_numeral.set(size=theme.TYPE["numeral_narrow" if narrow else "numeral"])@objc.python_methoddef _select_page(self, key):self.page = keyfor name, scroll in self.pages.items():scroll.setHidden_(name != key)++ if name != key and scroll.superview() is not None:++ self.page_host.removeArrangedSubview_(scroll)++ scroll.removeFromSuperview()++ if self.pages[key].superview() is None:++ self.page_host.addArrangedSubview_(self.pages[key])++ self._last_resize_width = None++ self.windowDidResize_(None)++ self._apply_page_width(key, self.wide)self.sidebar.select(key)self._say(pages.footer(key))# Both recorders listen application-wide; left armed, they would take the first key typed on@@@ -1264,7 -1183,7 +1457,8 @@@for key, view in (("edge", self.edge_row), ("parts", self.parts_row), ("corner", self.corner_row),("dragging", self.dragging_box.view), ("resistance", self.resistance_module.view),("shortcut", self.shortcut_module.view)):-- motion.set_hidden(view, not rows[key])++ visible = rows[key] or key == "shortcut" and bool(getattr(self, "_trigger_conflict", ""))++ motion.set_hidden(view, not visible)if not rows["shortcut"]:# Hidden, an armed recorder would still take the next key typed anywhere on the page.self.key_recorder.cancel()@@@ -1348,8 -1267,8 +1542,7 @@@)after = (self.notch_after_select.value or 1200) / 1000self.notch_note.set(- f"Once the pointer is through to another machine the notch keeps playing for {after:g} seconds, so the "- f"Once the pointer is through to Windows the notch keeps playing for {after:g} seconds, so the "-- "animation finishes instead of cutting off."++ f"Once the pointer is through to another machine the notch keeps playing for {after:g} seconds. Outline and Island apply to Glow and Beam; other styles draw their own notch.")self._run_previews()notch_range = self.controller.notch_range@@@ -1365,186 -1280,23 +1558,188 @@@hold = self.style_select.value == "hold"motion.set_hidden(self.double_tap_head, hold)self.style_hint.set(- "Input is on another machine for as long as the key is held."- "Input is on Windows for as long as the key is held."++ getattr(self, "_trigger_conflict", "") or ("Input is on another machine for as long as the key is held. If you jump while holding the shortcut, releasing it brings input home."if hold-- else "Tap twice to switch; tap twice again to come back."++ else "Tap twice to switch; tap twice again to come back."),++ ink="amber" if getattr(self, "_trigger_conflict", "") else "ink_2",)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"{side} edge of this screen so you can feel the size of it."- 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 "How far to push past the edge before it gives. It applies as you drag."++ 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 = settings["peers"]++ 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 = settings["peers"]++ 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+ 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.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 = settings["peers"]++ 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):@@@ -1571,78 -1326,13 +1766,79 @@@@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 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()- first = peers[0]["token"] if peers else ""++ 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):@@@ -1707,21 -1389,18 +1903,28 @@@AppHelper.callLater(0.3, lambda: serial == self._apply_serial and self._apply_settings())def windowWillClose_(self, _notification):++ self._remember_normal_frame()++ try:++ with self.settings_store.lock:++ settings = dict(self.settings_store.current())++ settings["settings_window_frame"] = self._normal_frame++ self.settings_store.save_settings(settings)++ except SettingsError as exc:++ self.logger.warning("Could not save settings window frame: %s", exc)self.key_recorder.cancel()+ self.jump_recorder.cancel()self.ignored_recorder.cancel()+ # A code that stays up with nobody watching would still accept a pairing.+ self.panel.stop_showing()if self.previews is not None:self.tile_hover.stop()self.previews.stop()@objc.python_methoddef _head(self, title, figure):-- line = widgets.stack(vertical=False, spacing=12)-- line.setAlignment_(AppKit.NSLayoutAttributeTop)-- line.addArrangedSubview_(widgets.hug(widgets.eyebrow(title), AppKit.NSLayoutPriorityDefaultLow))-- line.addArrangedSubview_(figure)++ line = widgets.stack(spacing=12)++ widgets.add(line, widgets.eyebrow(title))++ widgets.add(line, figure, full_width=False)return line@objc.python_method@@@ -1741,44 -1420,30 +1944,59 @@@scroll.setHasVerticalScroller_(True)# Nothing scrolls sideways, at any width.scroll.setHasHorizontalScroller_(False)-- scroll.setAutohidesScrollers_(True)++ scroll.setAutohidesScrollers_(False)++ scroll.setScrollerStyle_(AppKit.NSScrollerStyleLegacy)page = FlippedView.alloc().init()++ page.setBackgroundColor_(AppKit.NSColor.clearColor())++ page.setSelectionHighlightStyle_(AppKit.NSTableViewSelectionHighlightStyleNone)++ page.setAccessibilityRole_(AppKit.NSAccessibilityGroupRole)++ page.setAccessibilityLabel_(title)page.setTranslatesAutoresizingMaskIntoConstraints_(False)-- body = widgets.stack(spacing=theme.MODULE_GAP)++ body = widgets.stack(spacing=20)page.addSubview_(body)-- top, leading, bottom, trailing = theme.PAGE_PADDING++ top, leading, bottom, trailing = (24, 24, 24, 24)padding = [body.topAnchor().constraintEqualToAnchor_constant_(page.topAnchor(), top),- body.leadingAnchor().constraintEqualToAnchor_constant_(page.leadingAnchor(), leading),- page.bottomAnchor().constraintEqualToAnchor_constant_(body.bottomAnchor(), bottom),- page.trailingAnchor().constraintEqualToAnchor_constant_(body.trailingAnchor(), trailing),+ body.leadingAnchor().constraintGreaterThanOrEqualToAnchor_constant_(page.leadingAnchor(), leading),+ page.bottomAnchor().constraintGreaterThanOrEqualToAnchor_constant_(body.bottomAnchor(), bottom),+ page.trailingAnchor().constraintGreaterThanOrEqualToAnchor_constant_(body.trailingAnchor(), trailing),+ body.centerXAnchor().constraintEqualToAnchor_(page.centerXAnchor()),- body.widthAnchor().constraintLessThanOrEqualToConstant_(theme.PAGE_CONTENT_WIDTH),++ body.widthAnchor().constraintLessThanOrEqualToConstant_(880),]- available_width = body.widthAnchor().constraintEqualToAnchor_constant_(page.widthAnchor(), -(leading + trailing))- # Below WindowSizeStayPut (500): above it, the column's 960 pt cap became the window's.- available_width.setPriority_(AppKit.NSLayoutPriorityDragThatCannotResizeWindow)++ available_width = body.widthAnchor().constraintLessThanOrEqualToAnchor_constant_(++ page.widthAnchor(), -(leading + trailing)++ )++ column_width = body.widthAnchor().constraintEqualToConstant_(640)++ # Keep the fill preference below WindowSizeStayPut so page contents cannot cap the window.++ # Stronger than child fills (490), below native frame preservation (500).++ column_width.setPriority_(499)++ self.page_width_constraints[key] = column_width+ padding.append(available_width)++ padding.append(column_width)+ # The page ends where its body does, unless motion props it up with the floor while a+ # module folds away, so the scroll offset eases down rather than snapping. Only the+ # page is pulled short; pulling the body would stretch a module into the held space.+ page.floor = page.heightAnchor().constraintGreaterThanOrEqualToConstant_(0.0)+ page.floor.setActive_(True)+ shrink = page.heightAnchor().constraintEqualToConstant_(0.0)+ shrink.setPriority_(1)+ shrink.setActive_(True)AppKit.NSLayoutConstraint.activateConstraints_(padding)-- self.page_paddings.append(padding)++ self.page_paddings[key] = padding[:4] + [available_width]scroll.setDocumentView_(page)clip = scroll.contentView()-- AppKit.NSLayoutConstraint.activateConstraints_([++ document_bridge = [page.topAnchor().constraintEqualToAnchor_(clip.topAnchor()),page.leadingAnchor().constraintEqualToAnchor_(clip.leadingAnchor()),page.widthAnchor().constraintEqualToAnchor_(clip.widthAnchor()),-- ])++ ]++ for constraint in document_bridge:++ # A scrolling document must not contribute its fitting size to the outer window.++ constraint.setPriority_(490)++ AppKit.NSLayoutConstraint.activateConstraints_(document_bridge)header = widgets.stack(spacing=6)heading = widgets.Label(title, theme.PAGE_TITLE, 700, tracking=-0.01)-- self.page_titles.append(heading)++ self.page_titles[key] = headingwidgets.add(header, heading.view)purpose_label = widgets.Label(purpose, theme.TYPE["body"], ink="ink_2", wrap=True)purpose_label.view.widthAnchor().constraintLessThanOrEqualToConstant_(theme.READING_WIDTH).setActive_(True)@@@ -1796,213 -1460,49 +2014,233 @@@@objc.python_methoddef _overview_page(self, body):- # The machines and the pairing sheet lead until there is one, since nothing else here works- # without it; once paired they sit under the controls (see _place_machines).- # Pairing leads until there is a PC, since nothing else here works without one; once- # paired it is a quiet block further down with the one way to change it.- widgets.add(body, self._pair_module().view)++ # Pairing stays at the top even when machines are already paired.+ self.overview_body = body- widgets.add(body, self._status_module().view)- widgets.add(body, self._keyboard_module().view)+ widgets.add(body, self.panel.machines_module.view)+ widgets.add(body, self.panel.sheet.view)+ widgets.add(body, self._status_module().view)+ widgets.add(body, self._keyboard_module().view)- widgets.add(body, self._directions_module().view)- widgets.add(body, self._paired_module().view)+ widgets.add(body, self._same_module().view)widgets.add(body, self._login_module().view)widgets.add(body, self._updates_module().view)@objc.python_method- def _directions_module(self):- """The menu bar's two ticks, here too, as the PC has them on its Overview: either- direction can be switched off while the other keeps working."""- module = widgets.Module(spacing=10)- module.add(widgets.eyebrow("Directions"))- self.send_switch = widgets.Switch(- "This Mac drives Windows", on_change=lambda on: self._set_direction(send_to_windows=on)- )- module.add(self.send_switch.view)- self.receive_switch = widgets.Switch(- "Windows drives this Mac", on_change=lambda on: self._set_direction(allow_windows_to_drive=on)- )- module.add(self.receive_switch.view)- self._show_directions()+ def _place_machines(self, first):- """The machines list and the pairing sheet at the top of Overview while nothing is paired,- under Keyboard and pointer once something is."""- if first == self._machines_first:++ """Keep the primary pairing action immediately below the Overview title."""++ if self._machines_first is True:+ return- self._machines_first = first++ self._machines_first = True+ body = self.overview_body+ views = (self.panel.machines_module.view, self.panel.sheet.view)+ for view in views:+ body.removeArrangedSubview_(view)- # Under the page's title block, which is the first view; after Keyboard and pointer otherwise.- at = 1 if first else 3++ at = 1+ for offset, view in enumerate(views):+ body.insertArrangedSubview_atIndex_(view, at + offset)++ @objc.python_method+ def _same_module(self):- module = widgets.Module(spacing=10)++ module = widgets.Module()+ module.add(widgets.eyebrow("Settings"))+ self.same_switch = widgets.Switch("Same on all machines", on_change=self._set_same)+ module.add(self.same_switch.view)+ self.same_note = widgets.note()+ module.add(self.same_note.view)return module@objc.python_method- def _set_direction(self, **change):- if self.direction_handler is not None:- self.direction_handler(**change)- self._show_directions()+ def _own_note(self, text=pages.OWN_ROW):+ """A note on a row this Mac keeps to itself, shown only while the pages are kept in step."""+ note = widgets.note(text)+ note.view.setHidden_(True)+ self.own_notes.append(note)+ return note.view++ @objc.python_method+ def _peer_too_old(self):+ """Whether a link is up to a PC whose Beamer does not keep settings in step."""+ links = [(True, getattr(self.controller, "peer_settings", None))]+ if self.windows_input is not None:+ links.append((self.windows_input.state == ServerState.CONNECTED, self.windows_input.peer_settings))+ return any(up and known is False for up, known in links)++ @objc.python_method+ def _show_same(self):+ cfg = self.controller.cfg+ old = self._peer_too_old()+ on = cfg.same_on_both and not old+ if self.same_switch.value != on:+ self.same_switch.value = on+ self.same_switch.set_enabled(not old)- who = settings_sync.who(list(peerlist.labels(self.controller.book.peers()).values()))++ who = settings_sync.who(list(peerlist.labels(peerlist.desktops(self.controller.book.peers())).values()))+ self.same_note.set(settings_sync.switch_note(who, cfg.same_on_both, old), ink="amber" if old else "ink_2")++ self.same_note.view.setToolTip_(settings_sync.switch_detail("mac"))+ for key, label in self.scope_labels.items():- text = settings_sync.scope(key, who, on, pages.SCOPE.get(key))++ text = settings_sync.scope(key, who, on, pages.SCOPE.get(key), "mac")+ if label.text != text:+ label.set(text)+ for note in self.own_notes:+ if note.view.isHidden() == on:+ motion.set_hidden(note.view, not on)+ self._refresh_design_follow()++ @objc.python_method+ def _set_same(self, on):+ """Turning it on carries this Mac's Crossing and Design across; off, each end keeps what it+ has. Either way the PC follows, now if a link is up, else when one next comes up."""+ raw = config_to_raw(self.controller.cfg)+ raw["same_on_both"] = bool(on)+ raw["same_set_at"] = settings_sync.next_stamp(raw["same_set_at"], time.time())+ raw["same_by"] = self.own_id()+ try:+ cfg = self.settings_store.save(raw)+ except SettingsError as exc:+ self.logger.warning("Same on all machines not saved: %s", exc)+ return+ self.controller.apply_settings(cfg)+ self._send_same()+ if not on:- self._apply_followed_design()++ self._apply_followed_design(force=True)+ self._show_same()++ @objc.python_method+ def same_state(self):+ """This Mac's settings message, for a change here and for announcing on a new link. Called+ from the links' threads as well, so it reads the settings once."""+ cfg = self.controller.cfg+ values = settings_sync.mac_values(config_to_raw(cfg))+ design_state = {+ "set_at": cfg.design_set_at,+ "by": cfg.design_by or self.own_id(),+ "values": {key: values[key] for key in settings_sync.DESIGN_KEYS},++ "path": (self._design_path or [self.own_id()])++ if cfg.design_follow_peer and not cfg.same_on_both else [self.own_id()],+ }+ return settings_sync.message_data(cfg.same_on_both, cfg.same_set_at,+ values, by=cfg.same_by or self.own_id(), design_state=design_state)++ @objc.python_method- def _apply_followed_design(self):++ def _apply_followed_design(self, force=False):+ cfg = self.controller.cfg+ peer = cfg.design_follow_peer+ state = self._design_states.get(peer)+ if not peer or state is None or cfg.same_on_both:+ return+ current = settings_sync.mac_values(config_to_raw(cfg))++ 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, cfg.same_on_both,- cfg.design_set_at, cfg.design_by)++ stamp, author, own_id=self.own_id(), force=force)+ if taken is None:+ return- raw = settings_sync.apply_mac(config_to_raw(cfg), taken["values"])- raw["design_set_at"] = taken["set_at"]- raw["design_by"] = taken["by"]++ cycle = taken.get("cycle", False)++ path = [self.own_id()] if cycle else taken["path"]++ announce = cycle or taken["changed"] or path != self._design_path or force++ raw = config_to_raw(cfg) if cycle else settings_sync.apply_mac(config_to_raw(cfg), taken["values"])++ if cycle:++ raw["design_follow_peer"] = ""++ if announce:++ raw["design_set_at"] = settings_sync.next_stamp(cfg.design_set_at, time.time())++ raw["design_by"] = self.own_id()+ try:+ cfg = self.settings_store.save(raw)+ except (SettingsError, TypeError, ValueError):+ self.logger.exception("could not save followed Design from %s", peer)+ return+ self.controller.apply_settings(cfg)++ self._design_path = path++ self._followed_version = None if cycle else (peer, taken["set_at"], taken["by"])+ self._load_shared(config_to_raw(cfg))- if taken["changed"]:++ if announce:+ self._send_same()++ self._refresh_design_follow()++ @objc.python_method- def _receive_design(self, data, peer):++ def _receive_design(self, data, peer, apply=True):+ if peer is None:+ return+ peer_id = protocol.id_text(peer) if isinstance(peer, bytes) else peer++ if peer_id not in {entry.get("id") for entry in peerlist.desktops(self.controller.book.peers())}:++ return+ state = settings_sync.read_design_state(data, KEY_NAME_TO_CODE)+ if state is None:+ return+ held = self._design_states.get(peer_id)+ if held is None or settings_sync.design_arrived(state, held["set_at"], held["by"]):+ self._design_states[peer_id] = state+ self._refresh_design_follow()- if peer_id == self.controller.cfg.design_follow_peer:++ if apply and peer_id == self.controller.cfg.design_follow_peer:+ self._apply_followed_design()@objc.python_method- def _show_directions(self):+ def own_id(self):+ """This machine's id as a b64 text: who made a change to what is kept in step."""+ return self.settings_store.current()["machine_id"]++ @objc.python_method+ def _send_same(self, data=None, source=None):+ """This Mac's state to every machine that keeps it, or a newer state taken from `source`+ passed on, unchanged, to all the others."""+ data = data if data is not None else self.same_state()+ self.controller.send_settings(data, source=source)+ if self.windows_input is not None:+ self.windows_input.send_settings(data, source=source)++ @objc.python_method+ def apply_same(self, data, peer=None):+ """A peer's settings message, over either link, on the main thread. Its state stands only+ when it is newer than this Mac's; then its values replace the shared ones here, and it is+ sent on, unchanged, to every other machine that keeps it."""++ peer_id = protocol.id_text(peer) if isinstance(peer, bytes) else peer++ if peer_id is not None and peer_id not in {entry.get("id") for entry in peerlist.desktops(self.controller.book.peers())}:++ returncfg = self.controller.cfg- for switch, value in ((self.send_switch, cfg.send_to_windows), (self.receive_switch, cfg.allow_windows_to_drive)):- if switch.value != bool(value):- switch.value = value+ was_on = cfg.same_on_both+ taken = settings_sync.arrived(data, cfg.same_set_at, KEY_NAME_TO_CODE, by_here=cfg.same_by)+ if taken is not None:+ on, set_at, values = taken+ raw = config_to_raw(cfg)+ design_stamp = None+ if on:++ values, conflict = core_ways.shared_trigger_values(self.settings_store.current(), values)++ if conflict is not None:++ self._show_trigger_conflict(conflict)+ design_stamp = settings_sync.design_change_stamp(+ settings_sync.mac_values(raw), values, cfg.design_set_at,+ settings_sync.read_design_state(data, KEY_NAME_TO_CODE), self.own_id(),+ )+ raw["same_on_both"] = on+ raw["same_set_at"] = set_at+ raw["same_by"] = data.get("by", "")+ if on:+ raw = settings_sync.apply_mac(raw, values)+ if design_stamp is not None:+ raw["design_set_at"] = design_stamp["set_at"]+ raw["design_by"] = design_stamp["by"]+ try:+ cfg = self.settings_store.save(raw)+ except (SettingsError, TypeError, ValueError):+ self.logger.exception("could not save the settings %s sent", peer)+ return+ self.controller.apply_settings(cfg)+ # Keep global settings' existing forwarding, but replace the optional direct state+ # with this machine's own state instead of relaying the sender's state.+ forwarded = dict(data)+ forwarded["design_sync"] = self.same_state()["design_sync"]+ self._send_same(forwarded, source=peer)+ if self.previews is not None:+ self.previews.repaint()+ self.logger.info("settings from %s applied (same on all machines %s)", peer, "on" if on else "off")+ self._load_shared(config_to_raw(cfg))+ self.refresh()- self._receive_design(data, peer)- if taken is not None and was_on and not on:- self._apply_followed_design()++ resuming = taken is not None and was_on and not on++ self._receive_design(data, peer, apply=not resuming)++ if resuming:++ self._apply_followed_design(force=True)@objc.python_methoddef _login_module(self):-- module = widgets.Module(spacing=10)++ module = widgets.Module()module.add(widgets.eyebrow("At login"))self.login_switch = widgets.Switch("Start Beamer when you log in", on_change=self._set_login)module.add(self.login_switch.view)@@@ -2013,7 -1513,7 +2251,7 @@@@objc.python_methoddef _updates_module(self):-- module = widgets.Module(spacing=10)++ module = widgets.Module()module.add(widgets.eyebrow("Updates"))self.updates_switch = widgets.Switch("Check for updates", on_change=self._set_check_updates)self.updates_switch.value = self.controller.cfg.check_updates@@@ -2103,69 -1603,6 +2341,89 @@@for module in (self._on_screen_module(), self.style_module, self.colour_module,self._trackpad_module(), self._appearance_module()):widgets.add(body, module.view)- self.follow_module = widgets.Module(spacing=10)++ self.follow_module = widgets.Module()+ self.follow_module.add(widgets.eyebrow("Match design with"))+ self.follow_host = widgets.stack(spacing=0)+ self.follow_module.add(self.follow_host)+ self.follow_note = widgets.note()+ self.follow_module.add(self.follow_note.view)+ widgets.add(body, self.follow_module.view)+ self._refresh_design_follow()+++ @objc.python_method++ def _design_peer_caps(self):++ desktops = {entry.get("id") for entry in peerlist.desktops(self.controller.book.peers())}++ caps = {peer: link.caps for peer, link in list(self.controller._peers_up.items()) if peer in desktops and link.live()}++ if self.windows_input is not None:++ server = self.windows_input.server++ for peer in server.links():++ if protocol.id_text(peer) not in desktops:++ continue++ known = server.caps_of(peer)++ if known is not None:++ caps[protocol.id_text(peer)] = known++ return caps+++ @objc.python_method+ def _refresh_design_follow(self):+ if not hasattr(self, "follow_host"):+ return+ for view in self.follow_host.arrangedSubviews():+ self.follow_host.removeArrangedSubview_(view)+ view.removeFromSuperview()- peers = self.settings_store.current()["peers"]++ peers = peerlist.desktops(self.settings_store.current()["peers"])+ labels = peerlist.labels(peers)+ choices = [("", "None")]- unsupported = set()- for entry in peers:- peer = entry.get("id", "")- if not peer:- continue++ caps = self._design_peer_caps()++ rows = settings_sync.follow_rows(peers, caps, self._design_states, self.controller.cfg.design_follow_peer)++ unsupported = {entry["id"]: why_not for entry, why_not in rows if why_not is not None}++ for entry, why_not in rows:+ title = labels.get(entry.get("token", ""), entry.get("name") or "Machine")- if peer not in self._design_states:- title += " — Needs beta.6 or later"- unsupported.add(peer)- choices.append((peer, title))- self.follow_select = widgets.Segmented(choices, columns=min(2, len(choices)),- on_change=self._set_design_follow)++ if why_not == settings_sync.NEEDS_DESIGN_SYNC:++ title += f" — {why_not}"++ choices.append((entry["id"], title))++ self.follow_select = widgets.MenuChoice(choices, on_change=self._set_design_follow)+ self.follow_select.value = self.controller.cfg.design_follow_peer- for value, cell, _words in self.follow_select.cells:++ for value, cell in self.follow_select.items:+ if value in unsupported:- cell.enabled = False- cell.setAlphaValue_(0.45)- cell.setToolTip_("Needs beta.6 or later")- widgets.add(self.follow_host, self.follow_select.view)++ cell.setEnabled_(False)++ cell.setToolTip_(unsupported[value])++ widgets.add(self.follow_host, self.follow_select.view, full_width=False)+ peer = self.controller.cfg.design_follow_peer++ entry = next((item for item in peers if item.get("id") == peer), {}) if peer else {}++ name = labels.get(entry.get("token", ""), entry.get("name") or "that machine")+ if peer:- entry = next((item for item in peers if item.get("id") == peer), {})- name = labels.get(entry.get("token", ""), entry.get("name") or "that machine")+ if self.controller.cfg.same_on_both:- self.follow_note.set(f"Following {name}, paused while Same on all machines is on.")++ note = f"Following {name}, paused while Same on all machines is on."++ elif peer not in caps:++ note = f"Keeping the last design received from {name} until it reconnects."+ else:- self.follow_note.set(f"Following {name}. Change a Design setting to stop following.")- elif unsupported:- self.follow_note.set("A paired machine is unavailable until it has beta.6 or later.")++ note = ""+ else:- self.follow_note.set("None: this machine keeps its own Design.")++ note = settings_sync.follow_note(rows) or "None: this machine keeps its own Design."++ self.follow_note.set(note)++ self.follow_note.view.setHidden_(not note)++ self._lock_followed_design(settings_sync.follow_lock(peer, self.controller.cfg.same_on_both, peers), name)++ @objc.python_method+ def _set_design_follow(self, peer):+ raw = config_to_raw(self.controller.cfg)+ raw["design_follow_peer"] = peer or ""++ if not peer:++ raw["design_set_at"] = settings_sync.next_stamp(raw["design_set_at"], time.time())++ raw["design_by"] = self.own_id()+ try:+ cfg = self.settings_store.save(raw)+ except (SettingsError, TypeError, ValueError):+ self.logger.exception("could not save Match design with")+ return+ self.controller.apply_settings(cfg)++ self._followed_version = None++ if not peer:++ self._design_path = [self.own_id()]++ self._send_same()+ self._refresh_design_follow()- self._apply_followed_design()++ self._apply_followed_design(force=True)@objc.python_methoddef _appearance_module(self):@@@ -2202,6 -1638,6 +2460,12 @@@theme.set_dark(dark)self.window.setAppearance_(theme.appearance_named(dark))theme.repaint(content)++ # _select_page takes every page but the open one out of the window, so the walk above++ # never reaches them; their layers would keep the old palette's CGColors while their text,++ # which resolves as it draws, took the new one (05-10-2026, Light over dark cards).++ for scroll in self.pages.values():++ if scroll.superview() is None:++ theme.repaint(scroll)Quartz.CATransaction.commit()if self.previews is not None:# The renderers take the palette as they draw, which a held still does not do again.@@@ -2254,7 -1690,7 +2518,7 @@@@objc.python_methoddef _status_module(self):-- module = widgets.Module(spacing=10)++ module = widgets.Module()head = widgets.stack(vertical=False, spacing=7)head.addArrangedSubview_(widgets.hug(widgets.eyebrow("Link"), AppKit.NSLayoutPriorityDefaultLow))self.link_led = widgets.LED()@@@ -2295,13 -1731,6 +2559,14 @@@widgets.add(self.pause_row, self.crossing_state.view)module.add(self.pause_row)module.body.setCustomSpacing_afterView_(14, self.toggle_button.view)+ self.hold_box = widgets.Switch("Hold this Mac's edges while an app on it is full screen", on_change=self._hold_changed)+ module.add(self.hold_box.view)+ module.add(self._own_note())- module.add(widgets.note(- "Off, your pointer can leave a full-screen game or video, and another machine's pointer can go home "- "through this Mac's edge. Useful if your keyboard has no key for the shortcut."- ).view)++ self.hold_note = widgets.note(++ "This screen decides, including when another machine drives it. On, a full-screen app here holds pointer crossings; shortcuts and jump keys still work. Off, another machine's pointer can go home or onward through the configured ways."++ )++ module.add(self.hold_note.view)++ self.hold_box.view.setToolTip_("This screen's setting applies to every pointer on it.")return module@objc.python_method@@@ -2323,18 -1752,12 +2588,17 @@@@objc.python_methoddef _ways_module(self):module = widgets.Module()-- module.add(widgets.eyebrow("Ways in"))++ self.ways_heading = widgets.eyebrow("Ways from this screen")+ # With several machines paired, which one everything per machine below shows and writes.++ module.add(self.ways_heading)+ self.machine_row = widgets.stack(spacing=0)+ self.machine_row.setHidden_(True)+ module.add(self.machine_row)+ # The picker scopes everything under it, so it stands a step apart from what it scopes.+ module.body.setCustomSpacing_afterView_(18, self.machine_row)self.ways_note = widgets.note()module.add(self.ways_note.view)self.arrangement_diagram = diagram.ArrangementDiagram.alloc().init().setup()-- module.add(self.arrangement_diagram)-- module.body.setCustomSpacing_afterView_(16, self.arrangement_diagram)# The pointer's ways first, the shortcut on its own row above its settings.ways = (("edge", "Edge", "One whole side"),@@@ -2347,33 -1770,14 +2611,44 @@@way: widgets.WayTile(title, detail, on_change=lambda on, way=way: self._way_toggled(way, on))for way, title, detail in ways}-- module.add(widgets.grid([tile.view for tile in self.method_boxes.values()], 2))- # The values are the side of this Mac the PC is on, which is also the edge that crosses.++ ways_list = widgets.stack(spacing=0)++ widgets.add(ways_list, widgets.grid([tile.view for tile in self.method_boxes.values()], 2))++ self.ways_pair = widgets.SideBySide(++ self.arrangement_diagram,++ ways_list,++ theme.tokens.CROSSING_ARRANGEMENT_MIN_WIDTH,++ theme.tokens.CROSSING_WAYS_MIN_WIDTH,++ )++ self.side_by_side.append(self.ways_pair)++ module.add(self.ways_pair.view)++ module.body.setCustomSpacing_afterView_(16, self.ways_pair.view)+ module.add(self._own_note(pages.OWN_NOTCH))+ # The values are the side of this Mac the chosen machine is on, which is also the edge that crosses.self.edge_select = widgets.Segmented([("left", "Left"), ("right", "Right"), ("top", "Above"), ("bottom", "Below")], on_change=self._changed)- self.edge_row = widgets.field_row("Where the PC is", self.edge_select.view)[0]++ self.edge_select.view.setToolTip_("Changing a side updates the other end's side; it can turn overlapping ways off, with a notice.")+ self.edge_row, self.edge_caption = widgets.field_row(pages.where_caption(None), self.edge_select.view)module.add(self.edge_row)- self.edge_note = widgets.note(pages.NOTCH_OR_CORNER_NOTE)+ # A group within Ways, never a panel of its own: a panel inside a panel also forced the+ # window's layout and squeezed the pairing sheet's code boxes to 28 pt.+ self.share_box = widgets.stack(spacing=8)+ self.share_title = widgets.Label("Share the edge", theme.TYPE["eyebrow"], 700, "ink_3",+ tracking=theme.TRACKING["eyebrow"], upper=True)+ widgets.add(self.share_box, self.share_title.view)+ self.share_sentence = widgets.note()+ widgets.add(self.share_box, self.share_sentence.view)+ self.share_thirds = {}+ self.share_tiles = {+ part: widgets.WayTile(pages.part_names("right")[part], on_change=lambda _on, part=part:+ self._share_third(part)) for part in return_edge.PARTS+ }+ widgets.add(self.share_box, widgets.grid([tile.view for tile in self.share_tiles.values()], 3))+ self.share_button = widgets.action_button("Share the right edge", self._share_side, style="primary")+ self.share_box.addArrangedSubview_(self.share_button.view)+ self.share_box.setHidden_(True)+ module.add(self.share_box)+ self.edge_note = widgets.note(pages.notch_or_corner_note(None))self.edge_note.view.setHidden_(True)module.add(self.edge_note.view)self.part_boxes = {@@@ -2392,69 -1796,12 +2667,79 @@@columns=2,on_change=self._changed,)++ self.corner_select.view.setToolTip_(pages.corner_note())self.corner_row = widgets.field_row("Corner", self.corner_select.view)[0]module.add(self.corner_row)- self.dragging_box = widgets.Switch("Don't cross while dragging", on_change=self._changed)+ # What stops a way working, under the ways it is about: a side another machine's edge holds,+ # a machine that may drive this Mac and is not paired with the chosen one, and the chosen one+ # saying none of its own ways leads back here.+ self.blocked_note = widgets.note(ink="amber")+ self.missing_note = widgets.note(ink="amber")+ self.no_way_back_note = widgets.note()+ for note in (self.blocked_note, self.missing_note, self.no_way_back_note):+ note.view.setHidden_(True)+ module.add(note.view)- self.dragging_box = widgets.Switch("Don't cross while dragging", on_change=self._changed)++ self.dragging_box = widgets.Switch("Don't cross while dragging with this Mac's pointer", on_change=self._changed)++ self.dragging_box.view.setToolTip_("Applies when this physical pointer pushes through this screen's ways; visiting pointers are not protected by this switch.")module.add(self.dragging_box.view)+ self.jump_box = widgets.stack(spacing=8)- widgets.add(self.jump_box, widgets.eyebrow("Jump straight here"))++ self.jump_heading = widgets.eyebrow("Jump to this machine")++ widgets.add(self.jump_box, self.jump_heading)+ self.jump_recorder = widgets.JumpKeyRecorder(on_change=self._record_jump_key, on_arm=self._jump_arming)+ jump_controls = widgets.stack(vertical=False, spacing=8)+ jump_controls.addArrangedSubview_(self.jump_recorder.view)+ self.jump_clear = widgets.Button("Clear", self, "clearJumpKey:", scale="small")+ jump_controls.addArrangedSubview_(self.jump_clear.view)+ widgets.add(self.jump_box, jump_controls)+ self.jump_note = widgets.note()+ widgets.add(self.jump_box, self.jump_note.view)+ module.add(self.jump_box)+ module.body.setCustomSpacing_afterView_(18, self.dragging_box.view)return module+ @objc.python_method+ def _show_jump_key(self):+ peers = self.settings_store.current()["peers"]+ entry = next((peer for peer in peers if peer.get("id") == self.chosen_peer), None)+ self.jump_box.setHidden_(entry is None)+ if entry is None:+ self.jump_recorder.cancel()+ return+ self.jump_recorder.set_value(entry.get("jump_key", ""))+ name = self._shown(peerlist.label_for(peers, peer_id=self.chosen_peer) or "this machine")- self.jump_note.set(f"sends input to {name}")++ self.jump_heading.setStringValue_(f"Jump to {name}")++ self.jump_recorder.view.setAccessibilityLabel_(f"Jump to {name} key, {self.jump_recorder._title()}")++ chord = self.jump_recorder._title()++ if entry.get("jump_key"):++ self.jump_note.set(f"Press {chord} to send input to {name}; press again to bring it home.")++ else:++ self.jump_note.set(f"Choose a key combination to jump to {name} and back.")++ self.jump_note.view.setToolTip_(f"Works while edges are held. Needs In use, This Mac drives it and permission from {name} to drive it.")+ self.jump_clear.view.setAccessibilityLabel_(f"Clear jump key for {name}")++ @objc.python_method+ def _jump_arming(self, armed):+ self.controller.jump_recording = armed++ @objc.python_method+ def _record_jump_key(self, value):+ self._save_jump_key(value)++ @objc.python_method+ def _save_jump_key(self, value):+ try:+ self.settings_store.set_jump_key(self.chosen_peer, value, self.controller.cfg.trigger_key)+ except SettingsError as exc:+ peer = next((peer for peer in self.settings_store.current()["peers"] if peer.get("id") == self.chosen_peer), None)+ if peer is not None:+ self.jump_recorder.set_value(peer.get("jump_key", ""))+ self.jump_note.set(str(exc), ink="amber")+ return+ self._show_jump_key()++ def clearJumpKey_(self, _sender):+ self._save_jump_key("")+@objc.python_methoddef _way_toggled(self, way, on):methods = pages.toggle_way([name for name, tile in self.method_boxes.items() if tile.value], way, on)@@@ -2475,19 -1822,19 +2760,15 @@@def _shortcut_module(self):module = widgets.Module()module.add(widgets.eyebrow("Shortcut"))-- self.key_recorder = widgets.KeyRecorder("alt_r", on_change=self._changed)++ self.key_recorder = widgets.KeyRecorder("alt_r", on_change=self._trigger_chosen)module.add(self.key_recorder.view)self.style_select = widgets.Segmented([("double_tap", "Double-tap"), ("hold", "Hold")], on_change=self._changed)module.add(widgets.field_row("How you press it", self.style_select.view)[0])# The figure sits on the ruler's own line, so it reads as the ruler's value rather than as# a heading for the whole module, and the two hide together under Hold.self.double_tap_head = widgets.stack(spacing=6)-- caption = widgets.stack(vertical=False, spacing=12)-- caption.setAlignment_(AppKit.NSLayoutAttributeLastBaseline)-- caption.addArrangedSubview_(widgets.hug(widgets.label("Time between taps", theme.TYPE["note"], ink="ink_2"),-- AppKit.NSLayoutPriorityDefaultLow))figure, self.double_tap_numeral = self._numeral("ms")-- caption.addArrangedSubview_(figure)++ caption, _ = widgets.field_row("Time between taps", figure)widgets.add(self.double_tap_head, caption)# The stored window runs 50 to 2000 ms, but only about 150 to 600 is useful, so the ruler# shows 50 to 1000 on a square-root scale; a stored value past 1000 pins the thumb.@@@ -2501,6 -1848,6 +2782,23 @@@module.add(self.style_hint.view)return module++ @objc.python_method++ def _show_trigger_conflict(self, note):++ self._trigger_conflict = note++ if note:++ self.style_hint.set(note, ink="amber")++++ @objc.python_method++ def _trigger_chosen(self, key):++ try:++ core_ways.check_trigger_key(self.settings_store.current(), key)++ except ValueError as exc:++ self.key_recorder.set_value(self.controller.cfg.trigger_key)++ self._show_trigger_conflict(str(exc))++ return++ self._show_trigger_conflict("")++ self._changed()++@objc.python_methoddef _ignored_module(self):module = widgets.Module()@@@ -2575,30 -1922,29 +2873,32 @@@@objc.python_methoddef _on_screen_module(self):-- module = widgets.Module(spacing=8)++ module = widgets.Module()module.add(widgets.eyebrow("On screen"))self.glow_box = widgets.Switch("Animate crossings on this Mac", on_change=self._changed)module.add(self.glow_box.view)+ module.add(self._own_note())module.add(widgets.note(- "Lights the edge, the corner or the notch as you push toward another machine. Switched off, crossing "- "still works; you feel it rather than see it. Each machine sets how its own edge looks."- "Lights the edge, the corner or the notch as you push toward Windows. Switched off, crossing "- "still works; you feel it rather than see it. Windows sets how its own edge looks."++ "Turns crossing and landing animations on or off on this screen. Saved style choices stay in place.").view)self.landing_box = widgets.Switch("Show where the pointer lands", on_change=self._changed)self.landing_row = widgets.stack(spacing=8)widgets.add(self.landing_row, self.landing_box.view)widgets.add(self.landing_row, widgets.note(-- "When the shortcut or the menu brings input to this Mac, an animation plays around the "-- "pointer. Choose it under Style, for Shortcut and menu."++ "For shortcut, menu and jump arrivals; requires Animate crossings on this screen.").view)module.add(self.landing_row)return module@objc.python_method-- def _preview_tile(self, base, value, title, detail, notch, **overrides):++ def _preview_tile(self, base, value, title, detail, notch, flexible=False, **overrides):"""One tile's preview: its own screen, a feed pinned to the style the tile shows, and thereal renderer hosted on it, registered with the page's loop."""-- screen = widgets.size(previews.PreviewScreen.alloc().init().setup(notch), height=84)++ screen = previews.PreviewScreen.alloc().init().setup(notch)++ if flexible:++ screen.widthAnchor().constraintEqualToAnchor_multiplier_(screen.heightAnchor(), 2.0).setActive_(True)++ else:++ screen = widgets.size(screen, height=84)feed = previews.PreviewFeed(self.controller, **overrides)if notch is None:renderer = previews.hosted_edge(base)(feed, self.logger, screen)@@@ -2622,6 -1968,6 +2922,9 @@@self._preview_tile(NotchIsland, "island", "Island", "The notch grows as you push, with a meter inside, and flashes as you go through.", notch),],on_change=self._changed,++ vertical=True,++ responsive=True,++ aspect=False,)self._hover(self.notch_style_select)widgets.add(row, self.notch_style_select.view)@@@ -2634,6 -1979,6 +2937,36 @@@widgets.add(row, self.notch_note.view)return row++ @objc.python_method++ def _follow_banner(self):++ """Shown at the top of Style while this Mac follows another machine's design, whose++ followed controls are locked until Stop following (settings_sync.follow_lock)."""++ self.follow_banner = widgets.stack(spacing=8)++ self.follow_banner.setWantsLayer_(True)++ widgets.paint(self.follow_banner, "well", "rule", theme.RADIUS["button"])++ self.follow_banner.setEdgeInsets_(AppKit.NSEdgeInsetsMake(10, 12, 10, 12))++ self.follow_banner_label = widgets.Label("", theme.TYPE["body"], 600, wrap=True)++ widgets.add(self.follow_banner, self.follow_banner_label.view)++ self.stop_follow_button = widgets.Button(settings_sync.STOP_FOLLOWING, self, "stopFollowing:", scale="small")++ widgets.add(self.follow_banner, self.stop_follow_button.view, full_width=False)++ self.follow_banner.setHidden_(True)++ return self.follow_banner++++ def stopFollowing_(self, _sender):++ self._set_design_follow("")++++ @objc.python_method++ def _lock_followed_design(self, entry, name):++ """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_select, self.switch_style_select, self.glow_colour_select,++ self.length_select, self.size_select, self.landing_box):++ control.set_enabled(not locked)++ self.follow_banner_label.set(settings_sync.following_banner(name) if locked else "")++ self.follow_banner.setHidden_(not locked)++@objc.python_methoddef _edge_module(self):"""Every style, grouped as effects.DIRECTIONS groups them: today's Glow and Beam first with@@@ -2641,6 -1986,6 +2974,9 @@@its style at the place chosen above them, and plays while the pointer is over it."""module = widgets.Module()module.add(widgets.eyebrow("Style"))++ module.add(self._follow_banner())++ self.style_preview_hint = widgets.note("Hover to preview", ink="ink_2")++ module.add(self.style_preview_hint.view)self.style_for_select = widgets.Segmented([("crossing", "Crossing"), ("switch", "Shortcut and menu")], on_change=self._changed)@@@ -2654,17 -1999,16 +2990,16 @@@self.effect_method_view = widgets.field_row("Show at", self.effect_method_select.view)[0]module.add(self.effect_method_view)self.place_note = widgets.note()-- module.add(self.place_note.view)module.body.setCustomSpacing_afterView_(6, self.effect_method_view)self.notch_row = self._notch_row()-- module.add(self.notch_row)-- module.body.setCustomSpacing_afterView_(22, self.notch_row)colour = lambda: self.glow_colour_select.value or "signal"place = lambda: self.placepace = lambda: effects.pace(self.length_select.value)+ effect_size = lambda: self.size_select.value or "medium"# The two sets of tiles, one per mode; only the chosen mode's shows.self.crossing_styles_box = widgets.stack(spacing=0)++ tile_sets = widgets.stack(spacing=6)++ widgets.add(tile_sets, self.crossing_styles_box)rows = []for group, choices in pages.style_groups(self.effects_ready):# Glow and Beam as stills of the same scene as the effects, so every tile reads alike.@@@ -2678,31 -2021,30 +3013,32 @@@notch = previews.notch_size()stacked = []for value, title, detail, still in tiles:-- screens = {style: self._preview_tile(base, style, "", "", notch)[3]++ screens = {style: self._preview_tile(base, style, "", "", notch, flexible=True)[3]for style, base in (("beam", NotchBeam), ("island", NotchIsland))}stack = previews.TileStack.alloc().init().setup([still, *screens.values()])self.classic_pictures.append((stack, still, screens))stacked.append((value, title, detail, stack))tiles = stackedrows.append(self._style_group(self.crossing_styles_box, group, tiles))-- module.add(self.crossing_styles_box)self.glow_style_select = widgets.Linked(rows, on_change=self._changed, host=self.crossing_styles_box)++ self._style_grid(self.crossing_styles_box)self.switch_styles_box = widgets.stack(spacing=0)++ widgets.add(tile_sets, self.switch_styles_box)rows = []for group, choices in pages.switch_style_groups(self.effects_ready):tiles = []for value, title, detail in choices:fx = lambda value=value: effects.switch_effect(value, self.glow_style_select.value or "glow")- tiles.append((value, title, detail, previews.switch_still(fx, colour, self.logger, pace=pace)))+ tiles.append((value, title, detail, previews.switch_still(+ fx, colour, self.logger, pace=pace, effect_size=effect_size)))self.effect_stills.extend(tile[3] for tile in tiles)rows.append(self._style_group(self.switch_styles_box, group, tiles))++ self._style_grid(self.switch_styles_box)widgets.add(self.switch_styles_box, widgets.note(-- "What plays around the pointer when the shortcut or the menu brings input to this Mac. "-- "Same as crossing follows the style you chose for crossing, with a ring for Glow and Beam."++ "What plays around the pointer for shortcut, menu and jump arrivals. Same as crossing uses this screen's crossing style.").view)-- module.add(self.switch_styles_box)self.switch_style_select = widgets.Linked(rows, on_change=self._changed, host=self.switch_styles_box)++ module.add(tile_sets)# The chosen style's name and what it does, under the tiles that chose it.self.chosen_box = widgets.stack(spacing=6)self.effect_name = widgets.Label("", theme.TYPE["body"], 600)@@@ -2710,19 -2052,13 +3046,19 @@@self.effect_blurb = widgets.note()widgets.add(self.chosen_box, self.effect_blurb.view)module.add(self.chosen_box)-- module.body.setCustomSpacing_afterView_(18, self.chosen_box)++ module.body.setCustomSpacing_afterView_(12, self.chosen_box)# Every style and every switch plays at this length, so it follows the tiles either way.self.length_select = widgets.Segmented(effects.LENGTHS, on_change=self._changed)- module.add(widgets.field_row("Length", self.length_select.view)[0])+ self.size_select = widgets.Segmented(effects.SIZES, on_change=self._changed)- length_size = widgets.stack(vertical=False, spacing=14)- length_size.setDistribution_(AppKit.NSStackViewDistributionFillEqually)- length_size.addArrangedSubview_(widgets.field_row("Length", self.length_select.view)[0])- length_size.addArrangedSubview_(widgets.field_row("Size", self.size_select.view)[0])- widgets.add(module.body, length_size)++ self.length_row = widgets.field_row("Length", self.length_select.view)[0]++ self.size_row = widgets.field_row("Size", self.size_select.view)[0]++ module.add(self.length_row)++ module.add(self.size_row)module.add(widgets.note(- "Length sets how long each animation takes to play through once the pointer crosses, and to land. "- "Size sets the depth of the edge band."- "How long each animation takes to play through once the pointer crosses, and to land."++ "Length changes effect playback time, not crossing resistance or key timing. Size changes depth for styles that support it; it does not change resistance.").view)++ module.add(self.place_note.view)++ module.add(self.notch_row)return module@objc.python_method@@@ -2744,15 -2080,15 +3080,20 @@@@objc.python_methoddef _style_group(self, box, group, tiles):++ group_box = widgets.stack(spacing=8)++ group_box.setAlignment_(AppKit.NSLayoutAttributeWidth)heading = widgets.label(group, theme.TYPE["note"], 600, ink="ink_2")-- widgets.add(box, heading)-- row = widgets.ChoiceTiles(tiles, columns=3)++ widgets.add(group_box, heading)++ row = widgets.ChoiceTiles(tiles, vertical=True, responsive=True)++ widgets.add(group_box, row.view)self._hover(row)-- widgets.add(box, row.view)-- box.setCustomSpacing_afterView_(8, heading)-- box.setCustomSpacing_afterView_(22, row.view)++ widgets.add(box, group_box)return row++ @objc.python_method++ def _style_grid(self, box):++ box.setSpacing_(20)++@objc.python_methoddef _colour_module(self):module = widgets.Module()@@@ -2763,7 -2099,7 +3104,7 @@@choices = [(value, title, effects_overlay.palette(value)) for value, title in choices]heading = module.add(widgets.label(group, theme.TYPE["note"], 600, ink="ink_2"))module.body.setCustomSpacing_afterView_(8, heading)-- row = widgets.Swatches(choices, columns=len(crossing.GLOW_COLOURS))++ row = widgets.Swatches(choices, responsive=True)module.add(row.view)module.body.setCustomSpacing_afterView_(18, row.view)rows.append(row)@@@ -2782,7 -2117,7 +3123,9 @@@[("quarters", "Every quarter"), ("halves", "Halfway"), ("breakthrough", "Only when through")],on_change=self._changed,)-- module.add(widgets.field_row("Ticks at", self.tick_steps_select.view)[0])++ ticks, _caption = widgets.field_row("Ticks at", self.tick_steps_select.view)++ self.tick_steps_pair = ticks++ module.add(ticks)# On the press, not the release: macOS plays nothing once the finger has left the trackpad.self.try_button = widgets.Button("Try it", self, "tryTick:", scale="small")self.try_button.view.sendActionOn_(AppKit.NSEventMaskLeftMouseDown)@@@ -2817,12 -2152,93 +3160,12 @@@module.add(self.modifier_note.view)return module- @objc.python_method- def _paired_module(self):- """What the page leads with once a PC is paired: which one, where, and the one way to change- it. The PC list and code boxes stay hidden until they are wanted, or they read as an- invitation to pair a Mac that already is."""- module = widgets.Module()- module.add(widgets.eyebrow("Paired with"))- self.paired_name = widgets.Label("", theme.TYPE["readout"], 400, mono=True)- module.add(self.paired_name.view)- self.paired_address = widgets.Label("", theme.TYPE["small"], mono=True, ink="ink_3")- module.add(self.paired_address.view)- line = widgets.stack(vertical=False, spacing=10)- line.setAlignment_(AppKit.NSLayoutAttributeCenterY)- self.paired_note = widgets.note()- line.addArrangedSubview_(self.paired_note.view)- self.repair_button = widgets.Button("Pair a different PC", self, "togglePairing:", scale="small")- line.addArrangedSubview_(self.repair_button.view)- module.add(line)- self.paired_module = module- return module-- @objc.python_method- def _pair_module(self):- module = widgets.Module()- module.add(widgets.eyebrow("Pair with your PC"))- module.add(widgets.note(- "Open Beamer on the PC and press Pair a Mac. Then choose the PC here and type the "- "six-digit code it shows. You only do this once."- ).view)- self.pair_grid = widgets.stack(spacing=20)- self.pair_grid.setAlignment_(AppKit.NSLayoutAttributeTop)- found = widgets.stack(spacing=8)- widgets.add(found, widgets.eyebrow("On this network"))- self.pc_list = widgets.stack(spacing=1)- self.pc_frame = widgets.box("rule")- self.pc_frame.addSubview_(self.pc_list)- widgets.pin(self.pc_list, self.pc_frame, (1, 1, 1, 1))- widgets.add(found, self.pc_frame)- self.pc_empty = widgets.note()- widgets.add(found, self.pc_empty.view)- # For a PC no broadcast reaches: asked by its address, it answers with its beacon and- # joins the list above, and pairing carries on with its code as usual.- # As dots while addresses are hidden, as the PC's address on Connection is.- find_box, self.find_field = widgets.field()- find_secret_box, self.find_secret = widgets.field(secure=True)- find_secret_box.setHidden_(True)- self.find_boxes = (find_box, find_secret_box)- for control in (self.find_field, self.find_secret):- control.setPlaceholderAttributedString_(widgets.attributed("PC's address", theme.TYPE["small"], ink="ink_3", mono=True))- control.setAccessibilityLabel_("Address of a PC that is not listed")- control.setTarget_(self)- control.setAction_("findPC:")- find_line = widgets.stack(vertical=False, spacing=8)- for box in self.find_boxes:- find_line.addArrangedSubview_(widgets.hug(box, AppKit.NSLayoutPriorityDefaultLow))- find_line.addArrangedSubview_(widgets.Button("Find", self, "findPC:").view)- find_caption = widgets.label("PC not listed? Type its address.", theme.TYPE["note"], ink="ink_2")- widgets.add(found, find_caption)- found.setCustomSpacing_afterView_(14, self.pc_empty.view)- found.setCustomSpacing_afterView_(14, self.pc_frame)- widgets.add(found, find_line)- self.find_status = widgets.note()- widgets.add(found, self.find_status.view)- self.find_status.view.setHidden_(True)- code = widgets.stack(spacing=8)- widgets.add(code, widgets.eyebrow("Code shown on the PC"))- self.code_boxes = widgets.CodeBoxes(pairing.CODE_DIGITS, self.confirmPair_)- widgets.add(code, self.code_boxes.view)- line = widgets.stack(vertical=False, spacing=10)- line.setAlignment_(AppKit.NSLayoutAttributeTop)- self.pair_status = widgets.note()- line.addArrangedSubview_(self.pair_status.view)- self.confirm_button = widgets.Button("Pair", self, "confirmPair:", style="primary")- line.addArrangedSubview_(self.confirm_button.view)- widgets.add(code, line)- self.pair_grid.addArrangedSubview_(found)- self.pair_grid.addArrangedSubview_(code)- module.add(self.pair_grid)- self.pair_stacked = [- view.widthAnchor().constraintEqualToAnchor_(self.pair_grid.widthAnchor()) for view in (found, code)- ]- self.pair_module = module- return module-@objc.python_methoddef _connection_module(self):-- module = widgets.Module(spacing=10)++ module = widgets.Module()+ # The page edits the first machine paired; any other is changed by pairing it again.+ self.connection_note = widgets.note()+ module.add(self.connection_note.view)self.hide_switch = widgets.Switch("Hide addresses", on_change=self._set_hide_addresses)module.add(self.hide_switch.view)module.add(widgets.note(@@@ -2836,12 -2252,26 +3179,12 @@@for box in self.host_boxes:host_line.addArrangedSubview_(box)widgets.hug(box, AppKit.NSLayoutPriorityDefaultLow)- module.add(widgets.field_row("PC's address", host_line)[0])+ module.add(widgets.field_row("Address", host_line)[0])for control in (self.host_field, self.host_secret):- control.setAccessibilityLabel_("PC's address")+ control.setAccessibilityLabel_("Address")port_box, self.port_field = widgets.field()-- module.add(widgets.field_row("Port", port_box)[0])-- self.port_field.setAccessibilityLabel_("Port")- token_box, self.token_field = widgets.field(secure=True)- plain_box, self.token_plain = widgets.field()- plain_box.setHidden_(True)- self.token_boxes = (token_box, plain_box)- self.show_button = widgets.Button("Show", self, "showToken:", scale="small")- token_line = widgets.stack(vertical=False, spacing=6)- token_line.addArrangedSubview_(token_box)- token_line.addArrangedSubview_(plain_box)- token_line.addArrangedSubview_(self.show_button.view)- for box in self.token_boxes:- widgets.hug(box, AppKit.NSLayoutPriorityDefaultLow)- module.add(widgets.field_row("Shared token", token_line)[0])- for control in (self.token_field, self.token_plain):- control.setAccessibilityLabel_("Shared token")++ module.add(widgets.field_row("First paired machine's port", port_box)[0])++ self.port_field.setAccessibilityLabel_("First paired machine's port")self.wake_state = widgets.Label("", theme.TYPE["small"], mono=True)module.add(widgets.field_row("Wake-on-LAN", self.wake_state.view)[0])self.wake_hint = widgets.note()@@@ -2855,9 -2285,9 +3198,9 @@@@objc.python_methoddef _access_module(self):-- module = widgets.Module(spacing=10)++ module = widgets.Module()self.access_status, self.access_button = self._permission_row(- module, "Accessibility", "Lets Beamer move this Mac's pointer and type on it when the PC drives.",+ module, "Accessibility", "Lets Beamer move this Mac's pointer and type on it when another machine drives.","requestAccessibility:",)module.add(widgets.hairline())@@@ -3036,24 -2470,16 +3379,23 @@@"glow_style": self.glow_style_select.value,"glow_colour": self.glow_colour_select.value,"effect_length": self.length_select.value or "normal",+ "effect_size": self.size_select.value or "medium","block_while_dragging": self.dragging_box.value,+ "hold_full_screen": self.hold_box.value,"arrangement_set_at": self.controller.cfg.crossing.get("arrangement_set_at", 0),}- moved = raw["crossing"]["edge"] != self.controller.cfg.crossing.get("edge")- if moved:- # The edge is half of a value Windows holds too, so a change- # here is stamped with the moment it was made. When the two- # ends meet holding different answers -- one changed while the- # other was asleep -- the newer stamp is the one that stands.- raw["crossing"]["arrangement_set_at"] = int(time.time())+ before = settings_sync.mac_values(config_to_raw(self.controller.cfg))+ after = settings_sync.mac_values(raw)+ shared = self.controller.cfg.same_on_both and settings_sync.changed(before, after)+ design_changed = any(before.get(key) != after.get(key) for key in settings_sync.DESIGN_KEYS)+ if design_changed:- raw["design_follow_peer"] = ""+ raw["design_set_at"] = settings_sync.next_stamp(+ max(self.controller.cfg.design_set_at, self.controller.cfg.same_set_at), time.time())+ raw["design_by"] = self.own_id()+ if shared:+ raw["same_set_at"] = settings_sync.next_stamp(+ max(self.controller.cfg.same_set_at, raw.get("design_set_at", 0)), time.time())+ raw["same_by"] = self.own_id()cfg = self.settings_store.save(raw)except (SettingsError, TypeError, ValueError) as exc:self._say(str(exc), "fault")@@@ -3315,13 -2865,6 +3657,13 @@@self.spark.setNeedsDisplay_(True)cfg = controller.cfgself._show_peer()+ # The first machine by name, which the Connection page edits; peer_label follows the+ # machine in question instead.- peers = controller.book.peers()++ peers = peerlist.desktops(controller.book.peers())+ first = peerlist.labels(peers)[peers[0]["token"]] if peers else None+ self.connection_note.set(self._shown(+ f"The address and port of {first}, the first machine paired. Another machine is changed by pairing it again."+ if first else "Nothing is paired yet. Pairing fills the address and port in."))self.pause_button.set_title("Resume crossing" if controller.crossing_paused else "Pause crossing")self.pause_button.set_style("primary" if controller.crossing_paused else "plain")@@@ -3411,6 -2952,6 +3753,14 @@@ class _LaunchWatch(AppKit.NSObject)self.tray.hidden = True++def _tray_item(title, **kwargs):++ return rumps.MenuItem(americanise(title), **kwargs)++++++def _set_tray_title(item, title):++ item.title = americanise(title)++++class TrayApp(rumps.App):def __init__(self, controller, settings_store, logger, hidden=False):self.hidden = hidden@@@ -3475,16 -3003,14 +3825,16 @@@)self.control_window.update_checker = self.update_checkerself._notch_failed = False-- self.header_item = header = rumps.MenuItem(f"Beamer {VERSION}", callback=None)++ self.header_item = header = _tray_item(f"Beamer {VERSION}", callback=None)self.update_url = None-- self.status_item = rumps.MenuItem("Starting", callback=None)- self.toggle_item = rumps.MenuItem(TOGGLE_ITEM, callback=self.toggle_redirect)- self.toggle_item = rumps.MenuItem("Send input to Windows", callback=self.toggle_redirect)- self.pause_item = rumps.MenuItem("Pause crossing", callback=self.toggle_pause)++ self.status_item = _tray_item("Starting", callback=None)++ self.toggle_item = _tray_item(TOGGLE_ITEM, callback=self.toggle_redirect)+ # With several machines to send to, one item each after the one above, keyed by machine id.+ self._send_keys = []- self.pause_item = rumps.MenuItem("Pause crossing", callback=self.toggle_pause)++ self.pause_item = _tray_item("Pause crossing", callback=self.toggle_pause)# One tick per direction, so either can be switched off while the other keeps working.- self.send_item = rumps.MenuItem("This Mac drives other machines", callback=self.toggle_send_to_windows)- self.receive_item = rumps.MenuItem("Other machines drive this Mac", callback=self.toggle_windows_drives)- self.send_item = rumps.MenuItem("This Mac drives Windows", callback=self.toggle_send_to_windows)- self.receive_item = rumps.MenuItem("Windows drives this Mac", callback=self.toggle_windows_drives)++ self.send_item = _tray_item("This Mac drives other machines", callback=self.toggle_send_to_windows)++ self.receive_item = _tray_item("Other machines drive this Mac", callback=self.toggle_windows_drives)self._symbol = Nonesuper().__init__("Beamer",@@@ -3499,12 -3025,12 +3849,12 @@@self.send_item,self.receive_item,rumps.separator,-- rumps.MenuItem("Settings…", callback=self.open_window),-- rumps.MenuItem("Reload configuration", callback=self.reload_config),-- rumps.MenuItem("Open log folder", callback=self.open_log_folder),++ _tray_item("Settings…", callback=self.open_window),++ _tray_item("Reload configuration", callback=self.reload_config),++ _tray_item("Open log folder", callback=self.open_log_folder),rumps.separator,-- rumps.MenuItem("About Beamer", callback=self.show_about),-- rumps.MenuItem("Quit Beamer", callback=self.quit_app),++ _tray_item("About Beamer", callback=self.show_about),++ _tray_item("Quit Beamer", callback=self.quit_app),],quit_button=None,)@@@ -3522,10 -3048,10 +3872,10 @@@"""On the main thread. The version line in the menu becomes the way to the download."""self.update_url = found[1] if found else Noneif found:-- self.header_item.title = f"Beamer {found[0]} is available…"++ _set_tray_title(self.header_item, f"Beamer {found[0]} is available…")self.header_item.set_callback(self.open_update)else:-- self.header_item.title = f"Beamer {VERSION}"++ _set_tray_title(self.header_item, f"Beamer {VERSION}")self.header_item.set_callback(None)self.control_window.show_update(found)@@@ -3580,66 -3098,14 +3930,72 @@@self.set_menu_bar_symbol("windows" if controller.redirecting or controller.receiving else "held" if held else "local")+ hide = controller.cfg.hide_addressesif controller.redirecting:-- self.toggle_item.title = "Return input to Mac"++ _set_tray_title(self.toggle_item, "Return input to Mac")else:- self.toggle_item.title = pages.redact(- f"Send input to {controller.peer_label}" if controller.peer_label else "Send input", hide)- self.toggle_item.title = "Send input to Windows"-- self.pause_item.title = "Resume crossing" if controller.crossing_paused else "Pause crossing"- self.send_item.state = int(controller.cfg.send_to_windows)- self.receive_item.state = int(controller.cfg.allow_windows_to_drive)- self.status_item.title = link_state.describe(controller).word++ _set_tray_title(self.toggle_item, pages.redact(++ f"Send input to {controller.peer_label}" if controller.peer_label else "Send input", hide))++ _set_tray_title(self.pause_item, "Resume crossing" if controller.crossing_paused else "Pause crossing")+ self._machine_items()+ self._direction_items()- self.status_item.title = pages.redact(link_state.describe(controller).word, hide)++ _set_tray_title(self.status_item, pages.redact(link_state.describe(controller).word, hide))++ def _machine_items(self):+ """With more than one machine to send to, Send input to each of them in place of the one+ item, and Bring input back on the one input is on; with one, the one item as it always was."""+ controller = self.controller+ wanted = pages.send_items(controller.book.peers(), controller.owner.on if controller.redirecting else None,+ controller.cfg.hide_addresses)+ keys = [ident for ident, _title in wanted]+ if keys != self._send_keys:+ for key in self._send_keys:+ del self.menu[key]+ anchor = TOGGLE_ITEM+ for ident in keys:+ # Created under its id, which is its key in the menu, then given its words.- self.menu.insert_after(anchor, rumps.MenuItem(ident, callback=lambda _sender, ident=ident: self._send_to(ident)))++ self.menu.insert_after(anchor, _tray_item(ident, callback=lambda _sender, ident=ident: self._send_to(ident)))+ anchor = ident+ self._send_keys = keys+ for ident, title in wanted:- self.menu[ident].title = title++ _set_tray_title(self.menu[ident], title)+ self.toggle_item.hidden = bool(keys)++ def _send_to(self, peer):+ """One machine's item: input goes to it, straight from the machine it is on (WIRE.md section 5,+ "Moving input"), or home when it is already there."""+ controller = self.controller+ if not controller.input_ready:+ self.notify_user("Beamer", "Grant both Mac permissions first.")+ return+ if controller.redirecting and controller.owner.on == peer:+ controller.set_redirecting(False)+ else:+ controller.set_redirecting(True, peer=peer)+ self.refresh_status(None)++ def _direction_items(self):+ """The two direction ticks, named for the machine when there is one, for every machine+ when there are several; mixed when the machines differ."""+ peers = self.controller.book.peers()+ hide = self.controller.cfg.hide_addresses+ labels = [pages.redact(label, hide) for label in peerlist.labels(peers).values()]+ if len(labels) == 1:+ send, receive = f"This Mac drives {labels[0]}", f"{labels[0]} drives this Mac"+ elif labels:+ send, receive = "This Mac drives every machine", "Every machine drives this Mac"+ else:+ send, receive = "This Mac drives other machines", "Other machines drive this Mac"- self.send_item.title, self.receive_item.title = send, receive++ _set_tray_title(self.send_item, send)++ _set_tray_title(self.receive_item, receive)++ desktops = peerlist.desktops(peers)++ send_labels = [pages.redact(label, hide) for label in peerlist.labels(desktops).values()]++ _set_tray_title(self.send_item,++ f"This Mac drives {send_labels[0]}" if len(send_labels) == 1 else++ "This Mac drives every machine" if send_labels else "This Mac drives other machines")+ for item, name in ((self.send_item, "send"), (self.receive_item, "allow_drive")):- on = [peer.get(name) is True for peer in peers]++ on = [peer.get(name) is True for peer in (desktops if name == "send" else peers)]+ item.state = 1 if on and all(on) else -1 if any(on) else 0def set_menu_bar_symbol(self, state):"""One template glyph per state instead of words. rumps only takes an icon as a file@@@ -3668,26 -3134,14 +4024,26 @@@self.control_window.show()def toggle_send_to_windows(self, _sender):- self._set_direction(send_to_windows=not self.controller.cfg.send_to_windows)+ """The menu's tick covers every machine: all on turns them all off, anything else all on."""- peers = self.controller.book.peers()++ peers = peerlist.desktops(self.controller.book.peers())+ self._switch([peer["token"] for peer in peers], send=not all(peer.get("send") is True for peer in peers))def toggle_windows_drives(self, _sender):- self._set_direction(allow_windows_to_drive=not self.controller.cfg.allow_windows_to_drive)+ peers = self.controller.book.peers()+ self._switch([peer["token"] for peer in peers], allow_drive=not all(peer.get("allow_drive") is True for peer in peers))++ def _set_direction(self, token, **change):+ """One machine's switch from its row on Overview."""+ self._switch([token], **change)- def _set_direction(self, **change):+ def _switch(self, tokens, **change):+ controller = self.controller+ entries = []try:- cfg = self.settings_store.save(config_to_raw(replace(self.controller.cfg, **change)))+ for token in tokens:+ entry = self.settings_store.set_peer(token, **change)+ if entry is not None:+ entries.append(entry)except SettingsError as exc:self.logger.warning("direction not saved: %s", exc)self.notify_user("Beamer", f"Could not save the change: {exc}")diff --cc mac_app/machines.pyindex 07e4f65,0000000..d992265mode 100644,000000..100644--- a/mac_app/machines.py+++ b/mac_app/machines.py@@@ -1,85 -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")+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,++ 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/machines_panel.pyindex 272e6c0,0000000..88e29f0mode 100644,000000..100644--- a/mac_app/machines_panel.py+++ b/mac_app/machines_panel.py@@@ -1,655 -1,0 +1,675 @@@+"""The Overview's list of paired machines and the pairing sheet (WIRE.md section 6).++The list shows every machine this Mac has paired, each with its state, the two directions as that+machine's own switches, and a way to remove it. The sheet is the other half of pairing: this Mac+shows a code (and the same code as a QR) for another machine to enter, or enters one shown by a+machine it hears on the network, or at an address typed in. The sentences are core/peerlist.py's,+the same on Windows.++All of it runs on the main thread. The pairing itself blocks, so it runs on a thread of its own+and comes back through AppHelper; `PairingService` calls `store` and `peers` from its socket+threads, so nothing here hops to the main thread from those.+"""++import re+import threading++import AppKit+from PyObjCTools import AppHelper++import machines+import motion+import qr+import theme+import widgets- from core import pairing, peerlist, protocol, ways as core_ways++from core import feature_flags, pairing, peerlist, ways as core_ways++QR_SIDE = 176+CODE_GROUP = 3+++def grouped(code):+ """The six digits as two groups of three, which is how a person reads them across a room."""+ return " ".join(code[start:start + CODE_GROUP] for start in range(0, len(code), CODE_GROUP))+++def seconds(count):+ return f"Expires in {count} s"+++class MachinesPanel:+ def __init__(self, controller, settings_store, logger, owner):+ self.controller = controller+ self.settings_store = settings_store+ self.logger = logger+ self.owner = owner+ # Set by the app once the beacon listener exists.+ self.service = None+ self.open = False+ self.removing = None+ self.chosen = None+ self.pairing = False+ self._focus_after = None+ self.wide = True+ self._targets = []+ self._rows_key = None+ self.directions_open = set()+ self._heard_key = None+ self._heard = []+ self._showing = False+ self._shown_outcome = None+ self._hosted = None+ self._pair_ink = "ink_2"+ self._qr_for = None+ self.machines_module = self._machines_module()+ self.sheet = self._sheet()++ # Building++ def _machines_module(self):- module = widgets.Module(spacing=10)- module.add(widgets.eyebrow("Machines"))++ module = widgets.Module()++ header = widgets.stack(spacing=12)++ widgets.add(header, widgets.eyebrow("Machines"))++ self.pair_button = widgets.action_button("Pair a machine", self._toggle_sheet, style="primary")++ widgets.add(header, self.pair_button.view, full_width=False)++ module.add(header)+ self.list = widgets.stack(spacing=8)+ module.add(self.list)+ self.empty = widgets.note("No machines paired yet.")+ module.add(self.empty.view)+ line = widgets.stack(vertical=False, spacing=10)+ self.list_note = widgets.note("Beamer connects to each machine on its own whenever both are running.", reading=False)+ line.addArrangedSubview_(self.list_note.view)- self.pair_button = widgets.action_button("Pair a machine", self._toggle_sheet, scale="small")- line.addArrangedSubview_(self.pair_button.view)+ module.add(line)+ return module++ def _sheet(self):+ module = widgets.Module()+ module.add(widgets.eyebrow("Pair a machine"))+ self.pair_grid = widgets.stack(spacing=20)+ self.pair_grid.setAlignment_(AppKit.NSLayoutAttributeTop)+ show = self._show_half()+ enter = self._enter_half()+ self.pair_grid.addArrangedSubview_(show)+ self.pair_grid.addArrangedSubview_(enter)+ module.add(self.pair_grid)+ self.pair_stacked = [+ view.widthAnchor().constraintEqualToAnchor_(self.pair_grid.widthAnchor()) for view in (show, enter)+ ]+ return module++ def _show_half(self):+ half = widgets.stack(spacing=8)+ widgets.add(half, widgets.label("Show a code on this Mac", theme.TYPE["body"], 600))+ widgets.add(half, widgets.note(+ "On the other machine, open Beamer, choose this Mac in its list and type the code."+ ).view)+ self.show_button = widgets.action_button("Show a code", self._show_code, style="primary")+ half.addArrangedSubview_(self.show_button.view)- self.code_label = widgets.Label("", theme.TYPE["readout"], 700, mono=True, tracking=theme.TIGHT["readout"])- widgets.add(half, self.code_label.view)++ self.shown_code_boxes = widgets.CodeBoxes(pairing.CODE_DIGITS, None, editable=False)++ for control in self.shown_code_boxes.fields:++ control.setFont_(theme.mono_font(theme.TYPE["readout"], 700))++ widgets.add(half, self.shown_code_boxes.view)+ self.code_expiry = widgets.Label("", theme.TYPE["small"], mono=True, ink="ink_3")+ widgets.add(half, self.code_expiry.view)- self.code_address = widgets.Label("", theme.TYPE["small"], mono=True, ink="ink_3")++ self.code_address = widgets.Label("", theme.TYPE["small"], ink="ink_3")+ widgets.add(half, self.code_address.view)+ self.qr_view = widgets._autolayout(AppKit.NSImageView.alloc().init())+ # Whole points to a module already: scaling would soften the edges.+ self.qr_view.setImageScaling_(AppKit.NSImageScaleNone)+ self.qr_view.setImageAlignment_(AppKit.NSImageAlignTopLeft)+ self.qr_view.setAccessibilityLabel_("The pairing code as a QR code")+ widgets.size(self.qr_view, QR_SIDE, QR_SIDE)+ half.addArrangedSubview_(self.qr_view)+ self.qr_caption = widgets.note("")+ widgets.add(half, self.qr_caption.view)+ self.hosted_status = widgets.note()+ widgets.add(half, self.hosted_status.view)+ self.cancel_button = widgets.action_button("Cancel code", self._cancel_code, scale="small")+ half.addArrangedSubview_(self.cancel_button.view)+ self._show_code_widgets(False)+ return half++ def _enter_half(self):+ half = widgets.stack(spacing=8)+ widgets.add(half, widgets.label("Enter a code from another machine", theme.TYPE["body"], 600))+ heard = widgets.stack(spacing=8)+ widgets.add(heard, widgets.label("On this network", theme.TYPE["note"], 600, ink="ink_2"))+ self.heard_list = widgets.stack(spacing=1)+ self.heard_frame = widgets.box("rule")+ self.heard_frame.addSubview_(self.heard_list)+ widgets.pin(self.heard_list, self.heard_frame, (1, 1, 1, 1))+ widgets.add(heard, self.heard_frame)+ self.heard_empty = widgets.note()+ widgets.add(heard, self.heard_empty.view)+ find_box, self.find_field = widgets.field()+ find_secret_box, self.find_secret = widgets.field(secure=True)+ find_secret_box.setHidden_(True)+ self.find_boxes = (find_box, find_secret_box)+ for control in (self.find_field, self.find_secret):+ control.setPlaceholderAttributedString_(widgets.attributed("Address", theme.TYPE["small"], ink="ink_3", mono=True))+ control.setAccessibilityLabel_("Address of a machine that is not listed")+ control.setTarget_(self._target(self._address_typed))+ control.setAction_("fire:")+ heard.setCustomSpacing_afterView_(14, self.heard_empty.view)+ heard.setCustomSpacing_afterView_(14, self.heard_frame)+ widgets.add(heard, widgets.label("Not listed? Type its address.", theme.TYPE["note"], ink="ink_2"))+ find_line = widgets.stack(vertical=False, spacing=8)+ for box in self.find_boxes:+ find_line.addArrangedSubview_(widgets.hug(box, AppKit.NSLayoutPriorityDefaultLow))+ widgets.add(heard, find_line)+ widgets.add(half, heard)+ widgets.add(half, widgets.label("Code shown on the other machine", theme.TYPE["note"], 600, ink="ink_2"))+ self.code_boxes = widgets.CodeBoxes(pairing.CODE_DIGITS, lambda _control: self._pair())+ widgets.add(half, self.code_boxes.view)+ line = widgets.stack(vertical=False, spacing=10)+ line.setAlignment_(AppKit.NSLayoutAttributeTop)+ self.pair_status = widgets.note()+ line.addArrangedSubview_(self.pair_status.view)+ self.confirm_button = widgets.action_button("Pair", self._pair, style="primary")+ line.addArrangedSubview_(self.confirm_button.view)+ widgets.add(half, line)+ self._say("Choose a machine, or type its address, then type the code it shows.")+ return half++ def _target(self, callback):+ target = widgets.callback_target(callback)+ self._targets.append(target)+ return target++ # Reading the window's state++ def _shown(self, text):+ return self.owner._shown(text)++ def rows(self):+ """The list's rows, from the controller and the settings as they stand now."""+ controller = self.controller+ peers = controller.book.peers()+ names = peerlist.labels(peers)+ inbound = self.owner.inbound_ids()+ rows = []+ for entry in peers:+ link = controller.links.get(entry["token"])+ ident = entry.get("id") or None+ rows.append(machines.row(+ entry, names[entry["token"]],+ live=bool(link is not None and link.live()),+ kind=link.kind if link is not None else "none",+ status=link.status if link is not None else "",+ here=ident is not None and controller.owner.on == ident,+ driving=ident is not None and controller.driver == ident,+ inbound=ident is not None and ident in inbound,+ has_link=link is not None,+ ))+ return rows++ # The list++ def refresh(self):+ rows = self.rows()+ hide = self.controller.cfg.hide_addresses+ # Not the sentence under each state: a link that is still trying changes it every attempt,+ # and a rebuild takes keyboard and VoiceOver focus off whatever it was on.+ key = (hide, self.removing, self.wide, tuple(+ (r.token, r.label, r.platform, r.address, r.state.key, r.state.word, r.state.tone, r.state.led,+ r.in_use, r.drives, r.driven)+ for r in rows))+ key += (tuple(sorted(self.directions_open)),)+ if key != self._rows_key:+ self._rows_key = key+ self._build_rows(rows)+ self.empty.view.setHidden_(bool(rows))+ self.list_note.view.setHidden_(not rows)+ wanted = self.open or not rows+ motion.set_hidden(self.sheet.view, not wanted)+ self.pair_button.set_title("Cancel" if self.open and rows else "Pair a machine")- self.pair_button.view.setHidden_(not rows)++ self.pair_button.view.setHidden_(False)+ if wanted:+ self._refresh_sheet(hide)+ elif self._showing:+ self._cancel_code()++ def _build_rows(self, rows):+ focus = self._focus_after or self._focused_control()+ self._focus_after = None+ for view in list(self.list.arrangedSubviews()):+ self.list.removeArrangedSubview_(view)+ view.removeFromSuperview()+ for row in rows:+ widgets.add(self.list, self._row_view(row))+ if focus is not None:+ self._focus(focus)++ def _focused_control(self):+ """The id of the list control that has keyboard focus, or None."""+ view = self.owner.window.firstResponder()+ if view is None or not hasattr(view, "isDescendantOf_") or not view.isDescendantOf_(self.list):+ return None+ while view is not None and getattr(view, "focus_id", None) is None:+ view = view.superview()+ return getattr(view, "focus_id", None)++ def _focus(self, ident):+ """Gives focus to the control rebuilt under `ident`, as a rebuild takes it off the old one."""+ stack = [self.list]+ while stack:+ view = stack.pop()+ if getattr(view, "focus_id", None) == ident:+ self.owner.window.makeFirstResponder_(view)+ return+ stack.extend(view.subviews())++ def _row_view(self, row):+ state = row.state+ frame = widgets.box("ground", "rule", theme.RADIUS["field"])+ label = self._shown(row.label)+ frame.setAccessibilityLabel_(f"{label}, {self._shown(state.word)}")+ body = widgets.stack(spacing=6)+ head = widgets.stack(vertical=False, spacing=9)+ led = widgets.LED()+ led.set(state.led, state.blink)+ head.addArrangedSubview_(led.view)- name = widgets.Label(label, theme.TYPE["body"], 600)++ name = widgets.Label(label, theme.TYPE["body"], 600, wrap=True)+ head.addArrangedSubview_(widgets.hug(widgets.squeeze(name.view), AppKit.NSLayoutPriorityDefaultLow))+ tag = widgets.Label(self._shown(state.word), theme.TYPE["eyebrow"], 700, state.tone, tracking=theme.TRACKING["eyebrow"], upper=True)- head.addArrangedSubview_(tag.view)++ if self.wide:++ head.addArrangedSubview_(tag.view)+ widgets.add(body, head)++ if not self.wide:++ widgets.add(body, tag.view)+ remove = self._removal(row)- where = " ".join((row.platform, self._shown(row.address)))- place = widgets.stack(vertical=False, spacing=10)- place.addArrangedSubview_(widgets.hug(widgets.squeeze(widgets.Label(where, theme.TYPE["small"], mono=True, ink="ink_3").view),- AppKit.NSLayoutPriorityDefaultLow))- if not self.wide and self.removing != row.token:- place.addArrangedSubview_(remove)- widgets.add(body, place)++ where = row.platform if row.phone else " ".join((row.platform, self._shown(row.address)))++ widgets.add(body, widgets.Label(where, theme.TYPE["small"], ink="ink_3", wrap=True).view)+ widgets.add(body, widgets.note(self._shown(state.detail)).view)+ in_use = widgets.Switch("In use", on_change=lambda on, t=row.token: self._direction(t, in_use=on))+ in_use.value = row.in_use++ in_use.view.setToolTip_(f"Off: no input or settings link to {label}. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect.")++ if row.phone:++ in_use.view.setToolTip_(f"Off: {label} cannot connect or drive this Mac. Turn it back on here to reconnect.")+ in_use.view.focus_id = (row.token, "in_use")+ drives = widgets.Switch("This Mac drives it", on_change=lambda on, t=row.token: self._direction(t, send=on))+ drives.value = row.drives++ drives.view.setToolTip_(f"Input moves only when this Mac enables this switch and {label} enables It drives this Mac.")+ drives.view.focus_id = (row.token, "drives")+ driven = widgets.Switch("It drives this Mac", on_change=lambda on, t=row.token: self._direction(t, allow_drive=on))+ driven.value = row.driven++ driven.view.setToolTip_(f"Input moves only when {label} enables This machine drives it and this Mac enables this switch.")+ driven.view.focus_id = (row.token, "driven")+ opened = row.token in self.directions_open+ disclosure = self._chip("Hide directions" if opened else "Directions", lambda t=row.token: self._toggle_directions(t),+ f"{'Hide' if opened else 'Show'} directions for {label}",+ (row.token, "directions"))+ widgets.add(body, self._controls(row, in_use, disclosure, drives, driven, remove))+ frame.addSubview_(body)+ widgets.pin(body, frame, (10, 12, 10, 12))+ return frame++ def _chip(self, text, callback, label, focus_id=None):+ chip = widgets.pressable(callback, "well", "edge", theme.RADIUS["field"])+ chip.focus_id = focus_id+ chip.setAccessibilityLabel_(label)+ word = widgets.Label(text, theme.TYPE["small"], 600, ink="ink")+ chip.addSubview_(word.view)+ widgets.pin(word.view, chip, (6, 12, 6, 12))+ return chip++ def _controls(self, row, in_use, disclosure, drives, driven, remove):+ """The machine switch leads; its two direction switches stay under their disclosure."""+ if self.removing == row.token:+ column = widgets.stack(spacing=6)+ for view in (remove,):+ widgets.add(column, view)+ return column- line = widgets.stack(vertical=False, spacing=16)- line.addArrangedSubview_(widgets.hug(in_use.view, AppKit.NSLayoutPriorityRequired))- line.addArrangedSubview_(widgets.hug(widgets.box(), AppKit.NSLayoutPriorityDefaultLow))- line.addArrangedSubview_(disclosure)++ line = widgets.stack(vertical=not self.wide, spacing=12)++ if not self.wide:++ line.setAlignment_(AppKit.NSLayoutAttributeTrailing)+ if self.wide:- line.addArrangedSubview_(remove)++ line.addArrangedSubview_(widgets.hug(widgets.box(), AppKit.NSLayoutPriorityDefaultLow))++ widgets.add(line, in_use.view, full_width=not self.wide)++ if not row.phone:++ line.addArrangedSubview_(disclosure)++ line.addArrangedSubview_(remove)+ column = widgets.stack(spacing=4)- column.addArrangedSubview_(line)- if row.token in self.directions_open:- directions = widgets.stack(vertical=False, spacing=24)++ widgets.add(column, line)++ if not row.phone and row.token in self.directions_open:++ directions = widgets.stack(vertical=not self.wide, spacing=12)+ for view in (drives.view, driven.view):- directions.addArrangedSubview_(view)- widgets.hug(view, AppKit.NSLayoutPriorityRequired)- column.addArrangedSubview_(directions)++ widgets.add(directions, view, full_width=not self.wide)++ widgets.add(column, directions)+ return column++ def _toggle_directions(self, token):+ if token in self.directions_open:+ self.directions_open.remove(token)+ else:+ self.directions_open.add(token)+ self.refresh()++ def _removal(self, row):+ label = self._shown(row.label)+ if self.removing != row.token:+ return self._chip("Remove", lambda t=row.token: self._ask_to_remove(t), f"Remove {label}", (row.token, "remove"))+ line = widgets.stack(vertical=False, spacing=8)+ words = widgets.note(f"Remove {label}? It stays paired on that machine until you remove this one there too.", ink="ink", reading=False)+ line.addArrangedSubview_(words.view)+ line.addArrangedSubview_(self._chip("Remove", lambda t=row.token: self._remove(t), f"Confirm removing {label}", (row.token, "confirm")))+ line.addArrangedSubview_(self._chip("Keep", self._keep, f"Keep {label}", (row.token, "keep")))+ return line++ def _ask_to_remove(self, token):+ # Focus goes to Keep: pressing Space twice must not remove a machine.+ self.removing = token+ self._focus_after = (token, "keep")+ self.refresh()++ def _keep(self):+ token, self.removing = self.removing, None+ self._focus_after = (token, "remove")+ self.refresh()++ def _remove(self, token):+ self.removing = None+ before = core_ways.way_back_state(self.settings_store.current())+ try:+ removed = self.settings_store.remove_peer(token)+ except Exception as exc:+ self.logger.warning("could not remove a machine: %s", exc)+ self.owner._say(f"Could not remove it: {exc}", "fault")+ self.refresh()+ return+ if removed is not None:+ self.logger.info("removed %s", removed.get("name") or "a machine")+ self.owner.peers_changed()+ after = core_ways.way_back_state(self.settings_store.current())+ changed_peers = [peer for peer, state in after.items() if before.get(peer) != state]+ for peer in changed_peers:+ self.owner._tell(peer)++ def _direction(self, token, **change):+ handler = self.owner.direction_handler+ if handler is not None:+ handler(token, **change)+ self.refresh()++ # The sheet++ def _toggle_sheet(self):+ self.open = not self.open+ if not self.open:+ self._leave_sheet()+ self.refresh()++ def _leave_sheet(self):+ self.code_boxes.clear()+ self.chosen = None+ self._heard_key = None+ self._say("Choose a machine, or type its address, then type the code it shows.")++ def _refresh_sheet(self, hide):+ self._refresh_code(hide)+ self._refresh_heard()+ self.confirm_button.set_enabled(not self.pairing and self._wanted() is not None)++ def invalidate(self):+ """Draw the rows again from the settings on the next refresh."""+ self._rows_key = None++ def stop_showing(self):+ """The window closed: a code nobody can see does not stay up."""+ if self._showing or (self.service is not None and self.service.code is not None):+ self._cancel_code()+ self.open = False++ def _say(self, message, ink="ink_2"):+ self._pair_ink = ink+ self.pair_status.set(self._shown(message), ink=ink)++ # Showing a code++ def _show_code_widgets(self, showing):+ self.show_button.view.setHidden_(showing)- for view in (self.code_label.view, self.code_expiry.view, self.code_address.view, self.qr_view,++ for view in (self.shown_code_boxes.view, self.code_expiry.view, self.code_address.view, self.qr_view,+ self.qr_caption.view, self.cancel_button.view):+ view.setHidden_(not showing)++ def _show_code(self):+ service = self.service+ if service is None:+ return+ try:+ service.begin_pairing()+ except pairing.PairingError as exc:+ self.hosted_status.set(peerlist.pairing_error_text(exc, "this machine"), ink="fault")+ self.hosted_status.view.setHidden_(False)+ return+ self._hosted = None+ self._shown_outcome = None+ self._qr_for = None+ self.hosted_status.set("")+ self.refresh()++ def _cancel_code(self):+ if self.service is not None:+ self.service.cancel_pairing()+ self._showing = False+ self._shown_outcome = None+ self.hosted_status.set("")+ self._show_code_widgets(False)++ def _refresh_code(self, hide):+ service = self.service+ code = service.code if service is not None else None+ if code is not None:+ self._showing = True+ self._show_code_widgets(True)- self.code_label.set(grouped(code))++ for control, digit in zip(self.shown_code_boxes.fields, code):++ control.setStringValue_(digit)+ self.code_expiry.set(seconds(service.seconds_left))+ address = pairing.pairing_address()+ qr_text = service.qr_text(address)+ if hide:+ self.code_address.set(self._shown(f"{address} · port {service.tcp_port}") if address else "")+ self._set_qr(None, "The QR is hidden while addresses are hidden.")+ elif qr_text is None:+ self.code_address.set(f"{address} · port {service.tcp_port}" if address else "No network address found")+ self._set_qr(None, f"No QR: {service.tcp_error}" if service.tcp_error else "No QR while this Mac has no address.")+ else:+ self.code_address.set(f"{address} · port {service.tcp_port}")+ self._set_qr(qr_text, "The same code as a QR, for a phone to scan.")+ self.hosted_status.view.setHidden_(not self.hosted_status.text)+ return+ if self._showing:+ self._showing = False+ self._show_code_widgets(False)+ self._shown_outcome = service.outcome if service is not None else None+ known = service.known if service is not None else None+ text = peerlist.host_outcome_text(self._shown_outcome, self._hosted if self._shown_outcome == "paired" else known)+ ink = "signal" if self._shown_outcome == "paired" else "fault"+ self.hosted_status.set(text, ink=ink)+ self.hosted_status.view.setHidden_(not self.hosted_status.text)++ def _set_qr(self, text, caption):++ if not feature_flags.PAIRING_QR_VISIBLE:++ text, caption = None, ""+ self.qr_caption.set(caption)++ self.qr_caption.view.setHidden_(not caption)+ self.qr_view.setHidden_(text is None)+ if text == self._qr_for:+ return+ self._qr_for = text+ self.qr_view.setImage_(qr.image(text, QR_SIDE) if text is not None else None)++ def hosted_pairing(self, entry):+ """A machine paired with the code this Mac showed (on the main thread, after the entry was stored)."""+ self._hosted = entry+ self.open = False+ self.owner.peers_changed()+ self.owner._say(peerlist.host_outcome_text("paired", entry), "signal")++ # Entering a code++ def _address_text(self):+ field = self.find_secret if self.controller.cfg.hide_addresses else self.find_field+ return field.stringValue().strip()++ def _address_typed(self):+ if self._address_text():+ self.chosen = None+ self._heard_key = None+ self._refresh_heard()+ self.code_boxes.focus(self.owner.window)++ def _wanted(self):+ """What a code would be entered for: the address typed, else the machine chosen, else None."""+ address = self._address_text()+ if address:+ return ("address", address)+ if self.chosen is not None:+ return ("machine", self.chosen)+ return None++ def _refresh_heard(self):+ service = self.service+ heard = service.machines() if service is not None else []+ chosen = self.chosen["address"] if self.chosen is not None else None+ hide = self.controller.cfg.hide_addresses+ key = (chosen, hide, tuple(tuple(sorted((k, str(v)) for k, v in item.items())) for item in heard))+ if key == self._heard_key:+ return+ self._heard_key = key+ self._heard = heard+ current = next((item for item in heard if item["address"] == chosen), None)+ if current is not None and current != self.chosen:+ showed = self.chosen["pair_id"]+ self.chosen = current+ fault = self._pair_ink == "fault"+ if current["pair_id"] != showed and not self.pairing and (current["pair_id"] or not fault):+ self._say_choice()+ for view in list(self.heard_list.arrangedSubviews()):+ self.heard_list.removeArrangedSubview_(view)+ view.removeFromSuperview()+ for index, (item, shared) in enumerate(zip(heard, peerlist.sharing_a_name(heard))):+ self._heard_row(index, item, item["address"] == chosen, shared)+ if service is not None and service.error:+ self.heard_empty.set(f"Beamer cannot look for machines: {service.error}", ink="fault")+ else:+ self.heard_empty.set(+ "Looking for machines running Beamer. Open it on the other machine and it appears here; "+ "across a VPN or on guest Wi-Fi it may not, so type its address below.", ink="ink_2")+ self.heard_frame.setHidden_(not heard)+ self.heard_empty.view.setHidden_(bool(heard))+ if chosen is not None and chosen not in {item["address"] for item in heard}:+ self.chosen = None+ self._heard_key = None++ def _heard_row(self, index, item, picked, shared_name):+ older = item.get("pairing") != pairing.PAIRING_V3+ showing = item["pair_id"] is not None and not older+ row = widgets.pressable(lambda index=index: self._choose(index), "well" if picked else "ground",+ role=AppKit.NSAccessibilityRadioButtonRole)+ row.ring_inset = 1.0+ platform = machines.platform_name(item.get("platform") or "")+ row.setAccessibilityLabel_(self._shown(f"{item['name']}, {item['address']}")+ + (", older Beamer" if older else ", showing a code" if showing else ""))+ line = widgets.stack(vertical=False, spacing=9)+ led = widgets.LED()+ led.set("amber" if older else "signal" if showing else "off")+ line.addArrangedSubview_(led.view)- name = widgets.Label(self._shown(item["name"]), theme.TYPE["note"], 600 if picked else 400)++ name_text = self._shown(item["name"])++ name = widgets.Label(name_text, theme.TYPE["note"], 600 if picked else 400)++ name.view.setToolTip_(name_text)++ name.view.setAccessibilityLabel_(name_text)+ line.addArrangedSubview_(widgets.hug(widgets.squeeze(name.view), AppKit.NSLayoutPriorityDefaultLow))++ name.view.widthAnchor().constraintGreaterThanOrEqualToConstant_(100).setActive_(True)+ # A current machine's row always says where it is; an older one's only where its name is shared.+ where = self._shown(item["address"]) if shared_name or not older else ""+ detail = " · ".join(part for part in ("Older Beamer" if older else platform, where) if part)- line.addArrangedSubview_(widgets.Label(detail, theme.TYPE["small"], mono=True, ink="amber" if older else "ink_3").view)++ detail_label = widgets.Label(detail, theme.TYPE["small"], ink="amber" if older else "ink_3")++ detail_label.view.setToolTip_(detail)++ detail_label.view.setAccessibilityLabel_(detail)++ line.addArrangedSubview_(widgets.squeeze(detail_label.view, AppKit.NSLayoutPriorityDefaultLow))+ row.addSubview_(line)+ widgets.pin(line, row, (7, 10, 7, 10))+ widgets.add(self.heard_list, row)++ def _choose(self, index):+ if not 0 <= index < len(self._heard):+ return+ self.chosen = self._heard[index]+ for box_field in (self.find_field, self.find_secret):+ box_field.setStringValue_("")+ self.code_boxes.clear()+ self.code_boxes.view.setAccessibilityLabel_(self._shown(f"Code shown on {self.chosen['name']}"))+ self._say_choice()+ self._heard_key = None+ self._refresh_heard()+ self.code_boxes.focus(self.owner.window)++ def _say_choice(self):+ chosen = self.chosen+ if chosen.get("pairing") != pairing.PAIRING_V3:+ self._say(peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_VERSION), chosen["name"]), "fault")+ elif chosen["pair_id"] is None:+ self._say(f"{chosen['name']} is not showing a code yet. Show one in Beamer on it first.")+ else:+ self._say(f"Six digits, as shown on {chosen['name']}.")++ def _pair(self):+ wanted = self._wanted()+ service = self.service+ if wanted is None or self.pairing or service is None:+ return+ code = re.sub(r"\D", "", self.code_boxes.value)+ if len(code) != pairing.CODE_DIGITS:+ self._say(f"The code is {pairing.CODE_DIGITS} digits.", "fault")+ return+ kind, target = wanted+ if kind == "machine":+ # The list may have refreshed since the row was chosen; pair with the latest beacon.+ target = next((item for item in self._heard if item["address"] == target["address"]), target)+ name = target["name"]+ if target.get("pairing") != pairing.PAIRING_V3:+ self.chosen = target+ self._say_choice()+ return+ if target["pair_id"] is None:+ self._say(peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_NOT_PAIRING), name), "fault")+ return+ run = lambda: service.pair(target, code)+ else:+ name = "That machine"+ run = lambda: service.pair_by_address(target, code)+ self.pairing = True+ self.confirm_button.set_enabled(False)+ self._say(self._shown(f"Pairing with {name}…" if kind == "machine" else f"Pairing with {target}…"))++ def work():+ try:+ result = run()+ except pairing.PairingError as exc:+ result = exc+ except Exception as exc:+ self.logger.exception("pairing failed")+ result = pairing.PairingError(str(exc))+ AppHelper.callAfter(self._finished, name, result)++ threading.Thread(target=work, name="pair", daemon=True).start()++ def _finished(self, name, result):+ self.pairing = False+ if isinstance(result, pairing.PairingError):+ self._say(self._shown(peerlist.pairing_error_text(result, name)), "fault")+ return+ # The name the exchange proved, not the one a beacon claimed.+ proved = result.get("name") or name+ self.code_boxes.clear()+ for box_field in (self.find_field, self.find_secret):+ box_field.setStringValue_("")+ self.chosen = None+ self._heard_key = None+ self.open = False+ self._say("Choose a machine, or type its address, then type the code it shows.")+ self.owner.peers_changed()+ self.owner._say(f"Paired with {proved}. Connecting…", "signal")+ self.logger.info("paired with %s", proved)diff --cc mac_app/notch_beam.pyindex 243e455,d4cc7ac..1d0008b--- a/mac_app/notch_beam.py+++ b/mac_app/notch_beam.py@@@ -69,6 -69,6 +69,30 @@@ EDGE_SLOW_S = 2.EDGE_FAST_S = 0.8EDGE_FINISH_S = 0.6EDGE_FINISH_TRAVERSE_S = 0.35++EDGE_FALLOFF = ((0.0, 1.0), (0.08, 0.85), (0.3, 0.25), (1.0, 0.0))++++++def mask_edge_falloff(layer, edge, beam):++ """Cut the along-edge mask inward as Windows' live Beam does. Layer coordinates run up."""++ if not beam:++ layer.setMask_(None)++ return++ falloff = layer.mask()++ if falloff is None:++ falloff = Quartz.CAGradientLayer.layer()++ falloff.setLocations_([at for at, _alpha in EDGE_FALLOFF])++ falloff.setColors_([AppKit.NSColor.colorWithWhite_alpha_(1.0, alpha).CGColor()++ for _at, alpha in EDGE_FALLOFF])++ layer.setMask_(falloff)++ falloff.setFrame_(layer.bounds())++ start, end = {++ "left": ((0.0, 0.5), (1.0, 0.5)),++ "right": ((1.0, 0.5), (0.0, 0.5)),++ "top": ((0.5, 1.0), (0.5, 0.0)),++ "bottom": ((0.5, 0.0), (0.5, 1.0)),++ }[edge]++ falloff.setStartPoint_(start)++ falloff.setEndPoint_(end)def palette_values(name):diff --cc mac_app/notices.pyindex a17edd5,0000000..f1b7283mode 100644,000000..100644--- a/mac_app/notices.py+++ b/mac_app/notices.py@@@ -1,82 -1,0 +1,85 @@@+"""Post user alerts through macOS notifications, including source runs outside an app bundle."""++import secrets+++from core.locale import americanise++++def user_notifications():+ """Load the framework only when a notification is requested."""+ import UserNotifications++ return UserNotifications+++_PRESENTER = None+++def _presenter_class():+ """The centre's delegate class, made once: macOS keeps a notice from the app in front out of+ sight unless its delegate asks to show it, and Beamer's window is often in front when a crossing+ from its own page is refused."""+ global _PRESENTER+ if _PRESENTER is None:+ import objc+ from Foundation import NSObject++ try:+ protocols = [objc.protocolNamed("UNUserNotificationCenterDelegate")]+ except Exception:+ protocols = []++ class BeamerNoticePresenter(NSObject, protocols=protocols):+ def userNotificationCenter_willPresentNotification_withCompletionHandler_(self, _centre, _note, handler):+ handler(self.options)++ _PRESENTER = BeamerNoticePresenter+ return _PRESENTER+++class Notices:+ def __init__(self, logger, framework=user_notifications):+ self.logger = logger+ self.framework = framework+ self._asked = False+ # The centre holds its delegate weakly.+ self._presenter = None++ def _module(self):+ return self.framework() if callable(self.framework) else self.framework++ def ask(self):+ if self._asked:+ return+ self._asked = True+ try:+ framework = self._module()+ centre = framework.UNUserNotificationCenter.currentNotificationCenter()+ self._presenter = _presenter_class().alloc().init()+ self._presenter.options = (framework.UNNotificationPresentationOptionBanner+ | framework.UNNotificationPresentationOptionList+ | framework.UNNotificationPresentationOptionSound)+ centre.setDelegate_(self._presenter)+ options = framework.UNAuthorizationOptionAlert | framework.UNAuthorizationOptionSound+ centre.requestAuthorizationWithOptions_completionHandler_(options, lambda *_args: None)+ except Exception:+ self.logger.info("Could not request notification authorisation", exc_info=True)++ def post(self, title, body) -> bool:+ self.ask()+ try:+ framework = self._module()+ centre = framework.UNUserNotificationCenter.currentNotificationCenter()+ content = framework.UNMutableNotificationContent.alloc().init()++ title, body = americanise(title), americanise(body)+ content.setTitle_(title)+ content.setBody_(body)+ content.setSound_(framework.UNNotificationSound.defaultSound())+ request = framework.UNNotificationRequest.requestWithIdentifier_content_trigger_(+ secrets.token_urlsafe(24), content, None+ )+ centre.addNotificationRequest_withCompletionHandler_(request, None)+ return True+ except Exception:+ self.logger.info("Could not show notification %r: %r", title, body, exc_info=True)+ return Falsediff --cc mac_app/pages.pyindex 1b4d790,74670a9..e32d581--- a/mac_app/pages.py+++ b/mac_app/pages.py@@@ -8,40 -8,35 +8,39 @@@ from __future__ import annotationimport re-import effects+from core import effects+from core import peerlist++from core.ways import part_names, parts_phrase, toggle_part# (key, name, SF Symbol, what the page is for), in sidebar order, which is the order a new Mac is# set up in after the Overview; Cmd+1 is the first.PAGES = (("overview", "Overview", "gauge.with.needle",- "Where input is, whether the link is up, and the controls you reach for every day. Pair with a "- "PC here first."),+ "Where input is, whether each link is up, and the controls you reach for every day. Pair your "+ "machines here first."),("permissions", "Permissions", "lock.shield",-- "macOS must allow Beamer to read this keyboard and trackpad before it can send them anywhere."),++ "macOS must allow Beamer to read this Mac's input and to move its pointer and type when another machine drives it."),("crossing", "Crossing", "cursorarrow.motionlines",- "Choose how the pointer or a key moves input to Windows, and how hard the edge pushes back first."),+ "Choose how the pointer or a key moves input to each machine, and how hard the edge pushes back first."),("keyboard", "Keyboard", "keyboard",- "How this Mac's modifier keys arrive on Windows, which keys and buttons stay on this Mac, and "- "how fast the PC's pointer moves here. The switch key is on the Crossing page."),+ "How this Mac's modifier keys arrive on other machines, which keys and buttons stay on this Mac, "+ "and how fast another machine's pointer moves here. The switch key is on the Crossing page."),("design", "Design", "paintpalette","How crossing looks and feels on this Mac: the edge, the corner, the notch and the trackpad."),("connection", "Connection", "network",- "Where the first machine you paired is. Pairing fills these in."),- "Where the PC is and the token this Mac proves itself with. Pairing fills these in."),++ "Local connection details for the first machine you paired. Pair again to change another machine's entry."),)KEYS = tuple(page[0] for page in PAGES)-# Under the purpose on the pages whose settings are this Mac's alone, so nobody looks for the PC's-# on the Mac: each app sets only its own machine, and the PC's are in Beamer on the PC.+# Under the purpose on the pages whose settings are this Mac's alone, so nobody looks for the other+# machine's on the Mac: each app sets only its own machine, and the other's are in Beamer there.SCOPE = {- "crossing": "For this Mac only; every other machine keeps its own. Only which side each machine is on is shared, "- "with that machine. This Mac's resistance is also what its pointer meets at another machine's edge on "- "the way back.",- "design": "For this Mac's screen only; every other machine keeps its own.",- "keyboard": "For this Mac's keyboard only; every other machine keeps its own.",- "crossing": "For this Mac only; the PC keeps its own. Only which side the PC is on is shared. This Mac's "- "resistance is also what its pointer meets at the PC's edge on the way back.",- "design": "For this Mac's screen only; the PC keeps its own.",- "keyboard": "For this Mac's keyboard only; the PC keeps its own.",++ "crossing": "Ways below lead to the selected machine. Its side is shared with that machine. Resistance, drag protection and Shortcut apply to this Mac's input for every destination.",++ "design": "Used on this screen. Shared animation settings may follow another machine; Animate, window appearance, notch and trackpad controls stay on this Mac.",++ "keyboard": "Modifier keys and Stays here belong to this Mac's input. Pointer speed and scrolling belong to this screen when another machine drives it. Every machine keeps its own.",}+# With Same on all machines on, under each row of the shared pages that stays this Mac's own.+OWN_ROW = "This Mac only."+OWN_NOTCH = "The notch is this Mac only."# The window's footer, and the pages where its first sentence would be untrue.FOOTER_APPLIES = "Changes apply as you make them."FOOTER_RUNNING = "Closing this window keeps Beamer running in the menu bar."@@@ -130,10 -118,10 +129,7 @@@ def switch_style_groups(with_effects=Trdef colour_groups(today_colours, with_effects=True):"""[(group, [(colour id, name)])] for the swatches; `today_colours` is crossing.GLOW_COLOURS."""-- groups = [(TODAY, [(name, name.capitalize()) for name in today_colours])]-- for _module, direction, _effects, pack_ids in effects.DIRECTIONS if with_effects else ():-- groups.append((direction, [(pack_id, effects.pack(pack_id)[0]) for pack_id in pack_ids]))-- return groups++ return effects.colour_groups([(name, name.capitalize()) for name in today_colours] + [('aurora', 'Aurora')], with_effects)def notch_style_applies(style):@@@ -141,31 -129,21 +137,14 @@@return style not in effects.EFFECT_IDS--def part_names(edge):-- """The names of return_edge.PARTS along `edge`, as the page shows them: top to bottom on a side-- edge, left to right along the top or bottom."""-- if edge in ("left", "right"):-- return {"start": "Top", "middle": "Middle", "end": "Bottom"}-- return {"start": "Left", "middle": "Middle", "end": "Right"}------def parts_phrase(edge, parts):-- """The chosen thirds in a sentence: "the top and middle of the right edge"."""-- names = part_names(edge)-- # No third, or none known, is never saved, but a sentence must not be what fails on it.-- chosen = [names[part].lower() for part in ("start", "middle", "end") 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 share_sentence(holders, side, name):+ """Name the machines already using the side the chosen machine wants."""+ names = holders[0] if len(holders) == 1 else ", ".join(holders[:-1]) + " and " + holders[-1]+ verb = "crosses" if len(holders) == 1 else "cross"+ # The sentence says what picking a third means: it goes to `name`.+ keep = f"stay with {holders[0]}" if len(holders) == 1 else "stay where they are"+ return (f"{names} already {verb} from the {side} edge of this Mac. The thirds you pick go to {name}; "+ f"the rest {keep}.")# The ways in, in the Crossing page's order.@@@ -182,16 -160,16 +161,7 @@@ def toggle_way(methods, way, on)return [name for name in WAYS if name in chosen]--def toggle_part(parts, part, on):-- """The thirds after `part` is ticked or unticked. The last one cannot be unticked: no thirds-- would be a way in that never crosses; switching Part of the edge off is how to have none."""-- chosen = set(parts) | {part} if on else set(parts) - {part}-- if not chosen:-- chosen = set(parts)-- return [name for name in ("start", "middle", "end") if name in chosen]-----# The Crossing page's diagram: this Mac's screen at 16:10 and the PC's at 16:9, a gap between.+# The Crossing page's diagram: this Mac's screen at 16:10 and the other machine's at 16:9, a gap between.DIAGRAM_THIS = (120.0, 75.0)DIAGRAM_OTHER = (112.0, 63.0)DIAGRAM_GAP = 10.0@@@ -199,145 -177,20 +169,149 @@@ MARK = 3.CORNER_MARK = 12.0+DIAGRAM_SPLIT_GAP = 6.0+DIAGRAM_MARGIN = 12.0+SIDES = ("left", "right", "top", "bottom")+PART_ORDER = ("start", "middle", "end")++def arrangement(width, height, side):- """Where the two screens sit in a diagram `width` by `height`, top left at the origin: (this,- other) as (x, y, w, h), the pair centred with the other screen on `side` of this one."""+ """Where the two screens sit with one machine paired: (this, other) as (x, y, w, h)."""+ this, (other,) = diagram_layout(width, height, [(side, None)])+ return this, other+++def diagram_layout(width, height, machines):+ """Where this Mac and each machine sit in a drawing `width` by `height`, top left at the origin.+ `machines` is (side, first third) per machine: side "" when it is not placed, first third the+ index of its first third when it crosses by Part of the edge, else None. Returns (this, frames),+ a frame (x, y, w, h) or None for each machine. Two or more on one side share it, each as much+ shorter as there are of them, in the order of their thirds when all have some, else of the+ list; the whole is centred, and shrinks to fit only when it must."""tw, th = DIAGRAM_THISow, oh = DIAGRAM_OTHER- if side in ("left", "right"):- left = (width - (tw + DIAGRAM_GAP + ow)) / 2- this_x = left + ow + DIAGRAM_GAP if side == "left" else left- other_x = left if side == "left" else left + tw + DIAGRAM_GAP- return (this_x, (height - th) / 2, tw, th), (other_x, (height - oh) / 2, ow, oh)- top = (height - (th + DIAGRAM_GAP + oh)) / 2- this_y = top + oh + DIAGRAM_GAP if side == "top" else top- other_y = top if side == "top" else top + th + DIAGRAM_GAP- return ((width - tw) / 2, this_y, tw, th), ((width - ow) / 2, other_y, ow, oh)+ placed = [None] * len(machines)+ for side in SIDES:+ at = [index for index, (where, _third) in enumerate(machines) if where == side]+ if at and all(machines[index][1] is not None for index in at):+ at.sort(key=lambda index: machines[index][1])+ count = len(at)+ if not count:+ continue+ w, h = ow / count, oh / count+ upright = side in ("left", "right")+ step = (h if upright else w) + DIAGRAM_SPLIT_GAP+ start = ((th if upright else tw) - (step * count - DIAGRAM_SPLIT_GAP)) / 2+ for order, index in enumerate(at):+ along = start + order * step+ placed[index] = {+ "left": (-DIAGRAM_GAP - w, along), "right": (tw + DIAGRAM_GAP, along),+ "top": (along, -DIAGRAM_GAP - h), "bottom": (along, th + DIAGRAM_GAP),+ }[side] + (w, h)+ frames = [(0.0, 0.0, tw, th)] + [frame for frame in placed if frame is not None]+ left = min(x for x, _y, _w, _h in frames)+ top = min(y for _x, y, _w, _h in frames)+ span_w = max(x + w for x, _y, w, _h in frames) - left+ span_h = max(y + h for _x, y, _w, h in frames) - top+ scale = 1.0+ if span_w > width or span_h > height:+ scale = min((width - 2 * DIAGRAM_MARGIN) / span_w, (height - 2 * DIAGRAM_MARGIN) / span_h)+ dx = (width - span_w * scale) / 2 - left * scale+ dy = (height - span_h * scale) / 2 - top * scale++ def fit(frame):+ x, y, w, h = frame+ return (dx + x * scale, dy + y * scale, w * scale, h * scale)++ return fit(frames[0]), [None if frame is None else fit(frame) for frame in placed]+++def placement(machine):+ """A machine as diagram_layout takes it: its side, and its first third when it crosses by Part+ of the edge."""+ parts = [PART_ORDER.index(part) for part in machine["parts"] if part in PART_ORDER]+ return machine["side"] if machine["side"] in SIDES else "", min(parts) if "part" in machine["methods"] and parts else None+++def diagram_marks(this, machines):+ """What lights on this Mac's screen in the drawing. `machines` are dicts with `key`, `side`,+ `methods`, `parts`, `corner` and `chosen`. Returns (marks, notch): marks maps (key, "edge"),+ (key, "corner") and (key, "part", third) to (frame or None, tone or None), the tone "chosen"+ for the chosen machine's ways, "other" for another's, "track" for a third of the chosen+ machine's edge it does not use and no other machine does, and None for nothing lit; notch is+ the tone of the notch, or None."""+ held = {}+ for machine in machines:+ side, methods = machine["side"], machine["methods"]+ if side in SIDES and ("edge" in methods or "part" in methods):+ for part in PART_ORDER if "edge" in methods else machine["parts"]:+ held.setdefault((side, part), []).append(machine["key"])+ marks = {}+ for machine in machines:+ key, side, methods = machine["key"], machine["side"], machine["methods"]+ tone = "chosen" if machine["chosen"] else "other"+ placed = side in SIDES+ marks[(key, "edge")] = (side_mark(this, side) if placed else None, tone if placed and "edge" in methods else None)+ thirds = third_marks(this, side) if placed else {}+ for part in PART_ORDER:+ lit = None+ if placed and "part" in methods:+ if part in machine["parts"]:+ lit = tone+ elif machine["chosen"] and not held.get((side, part)):+ lit = "track"+ marks[(key, "part", part)] = (thirds.get(part), lit)+ marks[(key, "corner")] = (corner_mark(this, machine["corner"]), tone if "corner" in methods else None)+ notch = [machine["chosen"] for machine in machines if "notch" in machine["methods"]]+ return marks, ("chosen" if any(notch) else "other") if notch else None+++_WHERE = {"left": "to the left of", "right": "to the right of", "top": "above", "bottom": "below"}+++def _joined(names):+ return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]+++def not_placed(machines):+ """The line under the drawing naming the machines with no side yet; "" when every one has one."""+ names = [machine["label"] for machine in machines if machine["side"] not in SIDES]+ return f"Not placed yet: {_joined(names)}" if names else ""+++def arrangement_description(machines, sentence):+ """What VoiceOver reads for the drawing: where every machine is, then the chosen one's ways in."""+ where = [f"{machine['label']} is {_WHERE[machine['side']]} this Mac." if machine["side"] in SIDES+ else f"{machine['label']} is not placed yet." for machine in machines]+ return " ".join(where + [sentence + "." if sentence else "No way in is on."])+++def send_items(peers, on, hide):+ """The menu bar's items for sending input with more than one machine to send to: (id, title)+ for each machine this Mac sends to, "Bring input back" on the one input is on (`on`). [] with+ one or none, where the one Send input item stands as it always has."""+ labels = peerlist.labels(peers)+ targets = [entry for entry in peers if entry.get("id") and entry.get("in_use", True) is True+ and entry.get("send") is True and entry.get("port") != 0]+ if len(targets) < 2:+ return []+ return [(entry["id"], "Bring input back" if entry["id"] == on else redact(f"Send input to {labels[entry['token']]}", hide))+ for entry in targets]+++def where_caption(label):+ """The caption of the side control: today's words with one machine, the chosen one's name with several."""+ return f"Where {label} is" if label else "Where the other machine is"++++def corner_note():++ return "This corner crosses its left or right edge."+++++def shown_side(side, machines):+ """The side the page shows for a machine. With one machine paired, or none, one not placed yet+ shows Right as it always has; with several, nothing, so no two default onto one side."""+ return side or ("right" if machines <= 1 else "")def side_mark(screen, side):@@@ -387,9 -240,12 +361,9 @@@ def crossing_state_sentence(paired, senif not armed:return "Only the shortcut is switched on; there is nothing to pause."if paused:-- return "Paused. Edges, corners and the notch do nothing until you resume; the shortcut still works."++ return "Pauses pointer crossing through this screen, including another machine's pointer. Shortcuts and jump keys still work. Resets when Beamer restarts."if full_screen_app is not None:- return (- f"Off while {full_screen_app} is full screen, so the pointer stays put at "- "the edges; the shortcut still works."- )+ return "Held: an app is full screen."return "On. Pause it to lean on an edge without switching."diff --cc mac_app/previews.pyindex a160b5f,25cb959..2df0f68--- a/mac_app/previews.py+++ b/mac_app/previews.py@@@ -428,17 -428,17 +428,24 @@@ class TileStack(AppKit.NSView)Beam's still, or at the notch, where the notch style plays in their place, that style's ownhosted preview."""++ def layout(self):++ objc.super(TileStack, self).layout()++ if self.shown is not None:++ self.shown.setFrame_(self.bounds())++ self.shown.setNeedsLayout_(True)++@objc.python_methoddef setup(self, children, height=84):self.setTranslatesAutoresizingMaskIntoConstraints_(False)-- self.heightAnchor().constraintEqualToConstant_(height).setActive_(True)++ self.widthAnchor().constraintEqualToAnchor_multiplier_(self.heightAnchor(), 2.0).setActive_(True)self.children = list(children)for child in self.children:child.setTranslatesAutoresizingMaskIntoConstraints_(False)++ AppKit.NSLayoutConstraint.deactivateConstraints_([++ c for c in child.constraints()++ if c.firstItem() == child and c.secondItem() in (None, child)++ ])self.addSubview_(child)-- for a, b in ((child.leadingAnchor(), self.leadingAnchor()), (child.trailingAnchor(), self.trailingAnchor()),-- (child.topAnchor(), self.topAnchor()), (child.bottomAnchor(), self.bottomAnchor())):-- a.constraintEqualToAnchor_(b).setActive_(True)self.shown = Noneself.show(self.children[0])return self@@@ -452,6 -452,6 +459,7 @@@self.shown = childfor other in self.children:other.setHidden_(other is not child)++ self.setNeedsLayout_(True)@objc.python_methoddef current(self):@@@ -481,12 -481,12 +489,13 @@@ class TileHoverdef track(self, tile, preview):owner = _HoverOwner.alloc().init()-- owner.entered = lambda: self.enter(preview)-- owner.exited = lambda: self.leave(preview)++ owner.entered = lambda: (tile.set_tile_state(hovered=True), self.enter(preview))++ owner.exited = lambda: (tile.set_tile_state(hovered=False), self.leave(preview))options = (AppKit.NSTrackingMouseEnteredAndExited | AppKit.NSTrackingActiveInActiveApp| AppKit.NSTrackingInVisibleRect)tile.addTrackingArea_(AppKit.NSTrackingArea.alloc().initWithRect_options_owner_userInfo_(AppKit.NSZeroRect, options, owner, None))++ tile._tile_hover_owner = owner# A tracking area does not keep its owner.self.owners.append(owner)@@@ -551,12 -551,12 +560,12 @@@ def _played(view, still_at)return still_at if since is None else still_at + max(0.0, time.monotonic() - since)-def effect_still(effect_id, colour, logger, height=84, place=lambda: "edge", pace=lambda: 1.0):- """A tile's still frame of `effect_id`, in whatever colour `colour()` names, at the place- `place()` names and the length `pace()` gives, when it draws."""+def effect_still(effect_id, colour, logger, height=84, place=lambda: "edge", pace=lambda: 1.0,+ effect_size=lambda: "medium"):+ """A tile's still frame of `effect_id`, in the selected colour, place, length and size."""view = effects_overlay.EffectsCanvas.alloc().initWithFrame_(AppKit.NSMakeRect(0, 0, 1, 1))view.setTranslatesAutoresizingMaskIntoConstraints_(False)-- view.heightAnchor().constraintEqualToConstant_(height).setActive_(True)++ view.widthAnchor().constraintEqualToAnchor_multiplier_(view.heightAnchor(), 2.0).setActive_(True)view.setWantsLayer_(True)view.layer().setCornerRadius_(theme.RADIUS["field"])view.layer().setMasksToBounds_(True)@@@ -569,10 -569,10 +578,14 @@@fx = effects.preview_effect(effect_id)dark = theme.is_dark()where = place()-- scene = effects.preview_scene(fx, _played(view, STILL_AT_S), where, effects_overlay.palette(colour()), dark=dark,- pace=pace())++ # Beam's comet crosses the cropped pointer at this time; the common still puts it off-tile.++ held_at = 1.45 if effect_id == "beam" and where == "edge" else STILL_AT_S++ scene = effects.preview_scene(fx, _played(view, held_at), where, effects_overlay.palette(colour()), dark=dark,+ pace=pace(), effect_size=effect_size())# A small pointer, so the effect rather than the arrow is what a tile shows.-- effects_overlay.draw_scene(Quartz, ctx, scene, width, height, where, dark, crop=STILL_CROPS[where], pointer=11.0)++ # A desktop-scale thin line would disappear below one pixel in the common crop.++ crop = (730.0, 172.5, 120.0, 60.0) if effect_id == "beam" and where == "edge" else STILL_CROPS[where]++ effects_overlay.draw_scene(Quartz, ctx, scene, width, height, where, dark, crop=crop, pointer=11.0)view.painter = paintreturn viewdiff --cc mac_app/settings_store.pyindex 33c88a4,1aa541c..f915908--- a/mac_app/settings_store.py+++ b/mac_app/settings_store.py@@@ -1,21 -1,7 +1,21 @@@+"""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- peers[0] feeding host and auth_token; settings.json holds the rest (other peers, zones) for the steps++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 jsonimport os+import secretsimport tempfile-from dataclasses import replace+import threading+import timefrom pathlib import Pathimport config as config_module@@@ -152,459 -77,39 +152,466 @@@ 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"}}+ 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 peers[0] standing in for the one PC."""++ """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"])- if settings["peers"]:- peer = settings["peers"][0]++ 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 the values of `cfg` written over it: the pairing fields into peers[0], the rest by name."""++ """`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 peers:- gone = peers.pop(0)++ if at is not None:++ gone = peers.pop(at)+ settings["zones"] = [zone for zone in zones if zone.get("peer") != gone["id"]]- elif not peers or peers[0]["token"] != cfg.auth_token:++ elif peer is None or peer["token"] != cfg.auth_token:+ entry = _entry_from_config(cfg, machine_id)- if peers:- zones = _rename_zones(zones, peers[0]["id"], "")- peers[0] = entry++ 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 != peers[0].get("host"):- peers[0].update(name=cfg.pc_name, hw=cfg.mac_address)- peers[0].update(host=cfg.host, port=cfg.port, send=cfg.send_to_windows, allow_drive=cfg.allow_windows_to_drive)++ 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 (peers and name in MOVED_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."""- if entry.get("port") == 0:- # A phone's entry. The flat settings read the first machine's port, so one of these- # in front would leave them unloadable; phones are the 1.6.0 milestone.- raise SettingsError("a phone cannot be paired with this Mac in this version")+ 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):+ """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."""+ 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")+ 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["hw"] == address:++ 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):+ """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)+ 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."""- first = base["peers"][0]["token"] if base["peers"] else ""++ 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 settings["peers"] else {**config_module.DEFAULT_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"]):++ 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)@@@ -638,60 -146,6 +645,60 @@@except FileNotFoundError:pass+ def _legacy_config(self):+ """1.4.x's config.json as a Config, or None when it is missing, unreadable or not a pairing file.++ 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: nobody chose it, it was what the app shipped+ with, and it moves. A port a user typed is theirs and is left alone.+ """+ try:+ cfg = config_module.load_config(str(self.legacy_path))+ except (config_module.ConfigError, json.JSONDecodeError, OSError, TypeError, ValueError, OverflowError):+ return None+ if cfg.port == protocol.LEGACY_DEFAULT_PORT:+ cfg.port = protocol.DEFAULT_PORT+ return cfg++ def _migrate(self):+ cfg = self._legacy_config() or editable_default_config()+ self._validate(cfg)+ settings = _merge_config(self._fresh(), cfg)+ settings["migrated_token_sha256"] = _sha256(cfg.auth_token)+ settings["port"] = cfg.port+ return self.save_settings(settings)++ def _reimport(self, settings):+ """A pair made again under 1.4.x (a new token in config.json) replaces the migrated entry, once."""+ legacy = self._legacy_config()+ if legacy is None or not legacy.auth_token or _sha256(legacy.auth_token) == settings["migrated_token_sha256"]:+ return settings+ settings = copy.deepcopy(settings)+ settings["migrated_token_sha256"] = _sha256(legacy.auth_token)+ peers = settings["peers"]- at = next((index for index, peer in enumerate(peers) if peer["from_1_4"]), None)++ at = next((index for index, peer in enumerate(peers) if peer["from_1_4"] and peer.get("port") != 0), None)+ taken = {protocol.key_id(peer["token"]) for index, peer in enumerate(peers)+ if index != at and protocol.is_paired_token(peer["token"])}+ token = legacy.auth_token+ try:+ self._validate(legacy)+ except SettingsError:+ legacy = None+ clash = protocol.is_paired_token(token) and protocol.key_id(token) in taken+ if legacy is not None and not clash and (at is not None or len(peers) < MAX_PEERS):+ entry = {**PEER_DEFAULTS, **_entry_from_config(legacy, settings["machine_id"])}+ if at is None:+ peers.append(entry)+ settings["zones"] = _apply_zones(settings["zones"], "", legacy.crossing)+ else:+ settings["zones"] = _rename_zones(settings["zones"], peers[at]["id"], "")+ peers[at] = entry+ try:+ return self.save_settings(settings)+ except SettingsError:+ # The move is retried on the next start; a read-only folder must not stop the app opening.+ return self._complete(settings)+def _validate(self, cfg):if not isinstance(cfg.host, str):raise SettingsError("Windows host must be text")@@@ -733,10 -187,9 +740,10 @@@("haptic_steps", HAPTIC_STEPS),# Today's styles and colours, then every crossing effect and colour pack.("glow_style", GLOW_STYLES + effects.EFFECT_IDS),-- ("glow_colour", GLOW_COLOURS + effects.PACK_IDS),++ ("glow_colour", GLOW_COLOURS + ("aurora",) + effects.PACK_IDS),("shortcut_arrival_style", effects.SWITCH_STYLES),("effect_length", tuple(value for value, _name in effects.LENGTHS)),+ ("effect_size", tuple(value for value, _name in effects.SIZES)),)for name, allowed in choices:if crossing[name] not in allowed:diff --cc mac_app/tests/design_offscreen.pyindex 0000000,0000000..e2ddf39new file mode 100644--- /dev/null+++ b/mac_app/tests/design_offscreen.py@@@ -1,0 -1,0 +1,254 @@@++"""Offscreen-only settings inspection; never activates or orders a window."""++++import json++import math++import statistics++import time++from pathlib import Path++++from mac_app.tests.test_window_geometry import offscreen_control_window, kvm_bridge_app++++AppKit = kvm_bridge_app.AppKit++++++def settle(window):++ from Foundation import NSDate, NSRunLoop++ window.contentView().layoutSubtreeIfNeeded()++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.01))++ window.contentView().layoutSubtreeIfNeeded()++ assert not window.isVisible()++++++def rect_list(rect):++ return [rect.origin.x, rect.origin.y, rect.size.width, rect.size.height]++++++def capture(view):++ bounds = view.bounds()++ rep = view.bitmapImageRepForCachingDisplayInRect_(bounds)++ view.cacheDisplayInRect_toBitmapImageRep_(bounds, rep)++ return bytes(rep.representationUsingType_properties_(AppKit.NSBitmapImageFileTypePNG, {}))++++++def lit_pixels(view):++ rep = view.bitmapImageRepForCachingDisplayInRect_(view.bounds())++ view.cacheDisplayInRect_toBitmapImageRep_(view.bounds(), rep)++ data = bytes(rep.bitmapData())++ channels = rep.samplesPerPixel()++ # Screens and pointer are neutral. Coloured pixels are the effect itself.++ count = 0++ for y in range(rep.pixelsHigh()):++ for x in range(rep.pixelsWide()):++ offset = y * rep.bytesPerRow() + x * channels++ pixel = data[offset:offset + 3]++ count += max(pixel) - min(pixel) > 35 and max(pixel) > 70++ return count++++++def tiles(control):++ return {value: rect_list(tile.convertRect_toView_(tile.bounds(), control.crossing_styles_box))++ for row in control.glow_style_select.rows for value, tile, _name in row.tiles}++++++def view_frames(view, path="content"):++ result = {path: rect_list(view.frame())}++ for index, child in enumerate(view.subviews()):++ name = type(child).__name__.removeprefix("NSKVONotifying_")++ result.update(view_frames(child, f"{path}/{index}:{name}"))++ return result++++++def tile_measurements(control):++ frames = tiles(control)++ rows = {}++ for frame in frames.values():++ rows.setdefault(round(frame[1] + frame[3], 1), []).append(frame)++ gaps = []++ slack = []++ width = control.crossing_styles_box.bounds().size.width++ for row in rows.values():++ row.sort()++ gaps.extend(second[0] - first[0] - first[2] for first, second in zip(row, row[1:]))++ slack.append(width - row[-1][0] - row[-1][2])++ outside = []++ for choices in control.glow_style_select.rows:++ for value, tile, _name in choices.tiles:++ for child in tile.subviews():++ rect = child.convertRect_toView_(child.bounds(), tile)++ if not AppKit.NSContainsRect(tile.bounds(), rect):++ outside.append(value)++ return dict(gaps=gaps, right_slack=slack, tile_content_outside=outside,++ tile_widths=[frame[2] for frame in frames.values()])++++++def panel_overflows(body):++ outside = []++++ def inspect(view, panel, path):++ if view.isHidden():++ return++ rect = view.convertRect_toView_(view.bounds(), panel)++ if not AppKit.NSContainsRect(AppKit.NSInsetRect(panel.bounds(), -.5, -.5), rect):++ outside.append(dict(path=path, frame=rect_list(rect), panel=rect_list(panel.bounds())))++ for index, child in enumerate(view.subviews()):++ inspect(child, panel, f"{path}/{index}:{type(child).__name__}")++++ for index, panel in enumerate(body.arrangedSubviews()[1:]):++ for child_index, child in enumerate(panel.subviews()):++ inspect(child, panel, f"panel-{index}/{child_index}:{type(child).__name__}")++ return outside++++++def interaction_measurements(control):++ def walk(view):++ yield view++ for child in view.subviews():++ yield from walk(child)++++ scroll = control.pages["design"]++ controls = [view for view in walk(scroll) if isinstance(view, kvm_bridge_app.widgets.Pressable)]++ started = time.perf_counter()++ for _ in range(5):++ for view in controls:++ view.resetCursorRects()++ cursor_ms = (time.perf_counter() - started) * 1000++ clip = scroll.contentView()++ maximum = max(0, scroll.documentView().frame().size.height - clip.bounds().size.height)++ times = []++ for index in range(61):++ started = time.perf_counter()++ clip.scrollToPoint_((0, maximum * index / 60))++ scroll.reflectScrolledClipView_(clip)++ control.window.contentView().layoutSubtreeIfNeeded()++ times.append((time.perf_counter() - started) * 1000)++ return dict(controls=len(controls), cursor_reset_passes=5, cursor_reset_ms=cursor_ms,++ scroll_offsets=61, scroll_median_ms=statistics.median(times), scroll_max_ms=max(times),++ scroll_class=type(scroll).__name__, elasticity=scroll.verticalScrollElasticity(),++ predominant_axis=scroll.usesPredominantAxisScrolling(), scroller_style=scroll.scrollerStyle())++++++def resize_measurements(control):++ window = control.window++ frames = []++ changes_after_settling = []++ arrange_times = []++ originals = []++ for choices in (*control.glow_style_select.rows, *control.switch_style_select.rows, *control.glow_colour_select.rows):++ grid = choices.grid++ arrange = grid.arrange++++ def measured_arrange(width, arrange=arrange):++ started = time.perf_counter()++ try:++ return arrange(width)++ finally:++ arrange_times.append((time.perf_counter() - started) * 1000)++++ grid.arrange = measured_arrange++ originals.append((grid, arrange))++ widths = list(range(760, 1901, 20)) + list(range(1900, 759, -20))++ try:++ for index, width in enumerate(widths):++ arrange_start = len(arrange_times)++ pair_before = [pair.orientation() for pair in control.side_by_side]++ started = time.perf_counter()++ window.setFrame_display_(((100000 + index, 100000 + index), (width, 800 + index % 7)), False)++ callback_ms = (time.perf_counter() - started) * 1000++ started = time.perf_counter()++ window.contentView().layoutSubtreeIfNeeded()++ layout_ms = (time.perf_counter() - started) * 1000++ first = view_frames(window.contentView())++ settle(window)++ later = view_frames(window.contentView())++ changed = [dict(path=path, before=frame, after=later.get(path))++ for path, frame in first.items() if later.get(path) != frame]++ if changed:++ changes_after_settling.append(dict(index=index, views=changed))++ frames.append(dict(width=width, milliseconds=callback_ms + layout_ms,++ callback_ms=callback_ms, layout_ms=layout_ms,++ arrange_ms=sum(arrange_times[arrange_start:]),++ columns=control.glow_style_select.rows[0].columns, wide=control.wide,++ pair_flips=[index for index, pair in enumerate(control.side_by_side)++ if pair.orientation() != pair_before[index]]))++ finally:++ for grid, arrange in originals:++ grid.arrange = arrange++ origins = []++ for index in range(20):++ before = view_frames(window.contentView())++ started = time.perf_counter()++ window.setFrameOrigin_((100000 + index * 10, 100000))++ window.contentView().layoutSubtreeIfNeeded()++ origins.append((time.perf_counter() - started) * 1000)++ assert view_frames(window.contentView()) == before++ times = sorted(frame["milliseconds"] for frame in frames)++ return dict(frames=frames, median_ms=statistics.median(times), p95_ms=times[math.ceil(.95 * len(times)) - 1],++ max_ms=max(times), unsettled_frames=changes_after_settling,++ move_ms=origins, move_max_ms=max(origins))++++++def render_all(destination):++ destination = Path(destination)++ destination.mkdir(parents=True, exist_ok=True)++ control = offscreen_control_window()++ control._select_page("design")++ control.glow_style_select.value = "beam"++ control._reflect()++ window = control.window++ report = []++ minimum = window.minSize()++ for width, height in [(760, 900), (900, 900), (1100, 900), (1400, 900), (1900, 900),++ (int(minimum.width), int(minimum.height))]:++ window.setFrame_display_(((100000, 100000), (width, height)), False)++ settle(window)++ scroll = control.pages["design"]++ clip = scroll.contentView()++ page = scroll.documentView()++ body = page.subviews()[0]++ maximum = max(0, page.frame().size.height - clip.bounds().size.height)++ counts = {}++ for row in control.glow_style_select.rows:++ for (value, _tile, _name), preview in zip(row.tiles, row.previews):++ counts[value] = lit_pixels(preview)++ for position, fraction in [("top", 0), ("middle", .5), ("bottom", 1)]:++ clip.scrollToPoint_((0, maximum * fraction))++ scroll.reflectScrolledClipView_(clip)++ settle(window)++ path = destination / f"design-{width}x{height}-{position}.png"++ path.write_bytes(capture(window.contentView()))++ content = window.contentView()++ footer = control.message_label.view.convertRect_toView_(++ control.message_label.view.bounds(), content)++ viewport = scroll.convertRect_toView_(scroll.bounds(), content)++ last = body.arrangedSubviews()[-1]++ last_rect = last.convertRect_toView_(last.bounds(), page)++ fields = {name: rect_list(view.convertRect_toView_(view.bounds(), view.superview()))++ for name, view in (("length-row", control.length_row), ("size-row", control.size_row),++ ("length-options", control.length_select.view),++ ("size-options", control.size_select.view))}++ report.append(dict(path=str(path), window=rect_list(window.frame()),++ position=position, scroll=rect_list(scroll.frame()),++ document=rect_list(page.frame()), clip=rect_list(clip.bounds()),++ grid=rect_list(control.crossing_styles_box.frame()),++ tiles=tiles(control), geometry=tile_measurements(control), lit_pixels=counts,++ fields=fields, footer=rect_list(footer),++ panel_content_outside=panel_overflows(body),++ viewport_footer_gap=viewport.origin.y - footer.origin.y - footer.size.height,++ last_content_bottom_clearance=page.frame().size.height - last_rect.origin.y - last_rect.size.height,++ modules=[rect_list(module.convertRect_toView_(module.bounds(), body))++ for module in body.arrangedSubviews()]))++ path = destination / "measurements.json"++ path.write_text(json.dumps(report, indent=2) + "\n")++ (destination / "resize-measurements.json").write_text(++ json.dumps(resize_measurements(control), indent=2) + "\n")++ (destination / "scroll-measurements.json").write_text(++ json.dumps(interaction_measurements(control), indent=2) + "\n")++ return report++++++if __name__ == "__main__":++ import sys++ records = render_all(sys.argv[1])++ for record in records:++ print(record["path"], "document", record["document"], "clip", record["clip"],++ "Beam lit", record["lit_pixels"]["beam"], flush=True)diff --cc mac_app/tests/fixtures/effects_parity/qt_reference_frames.zipindex 0000000,0000000..74984a4new file mode 100644Binary files differdiff --cc mac_app/tests/profile_settings_resize.pyindex 0000000,0000000..3d93c5enew file mode 100644--- /dev/null+++ b/mac_app/tests/profile_settings_resize.py@@@ -1,0 -1,0 +1,86 @@@++"""Unordered resize profiling, with optional isolated text-layout experiments."""++import cProfile++import json++import sys++import time++import os++import subprocess++from pathlib import Path++++from mac_app.tests.design_offscreen import offscreen_control_window, resize_measurements, settle++from mac_app.tests.test_settings_layout_acceptance import walk++import AppKit++++++def main():++ if '--fonts' in sys.argv:++ from mac_app.tests.design_offscreen import kvm_bridge_app++ kvm_bridge_app.theme.init_fonts()++ control = offscreen_control_window()++ control._select_page('design')++ settle(control.window)++ if '--empty-tiles' in sys.argv:++ for choices in (control.glow_style_select, control.switch_style_select, control.glow_colour_select):++ for row in choices.rows:++ for cell in row.grid.cells:++ for child in list(cell.subviews()):++ child.removeFromSuperview()++ settle(control.window)++ if '--no-tiles' in sys.argv:++ for choices in (control.glow_style_select, control.switch_style_select, control.glow_colour_select):++ for row in choices.rows:++ row.view.removeFromSuperview()++ settle(control.window)++ if '--single-line' in sys.argv:++ for view in walk(control.pages['design']):++ if isinstance(view, AppKit.NSTextField):++ view.cell().setWraps_(False)++ view.cell().setUsesSingleLineMode_(True)++ settle(control.window)++ profiler = cProfile.Profile()++ lines, previous = {}, {}++++ def trace(frame, event, arg):++ if frame.f_code.co_name != 'windowDidResize_':++ return None++ now = time.perf_counter()++ held = previous.get(id(frame))++ if held:++ line, started = held++ lines.setdefault(line, []).append((now - started) * 1000)++ if event == 'return':++ previous.pop(id(frame), None)++ else:++ previous[id(frame)] = (frame.f_lineno, now)++ return trace++++ if '--trace-lines' in sys.argv:++ sys.settrace(trace)++ profiler.enable()++ sampler = None++ if '--sample-native' in sys.argv:++ sampler = subprocess.Popen(['sample', str(os.getpid()), '5', '1', '-file', str(Path(sys.argv[1]).with_suffix('.sample'))],++ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)++ if '--hot-native' in sys.argv:++ for index in range(600):++ width = 760 + (index % 40 if index % 80 < 40 else 79 - index % 80) * 10++ control.window.setFrame_display_(((100000, 100000), (width, 800)), False)++ control.window.contentView().layoutSubtreeIfNeeded()++ result = resize_measurements(control)++ else:++ for _ in range(5 if sampler else 1):++ result = resize_measurements(control)++ if sampler:++ sampler.wait()++ profiler.disable()++ sys.settrace(None)++ destination = Path(sys.argv[1])++ destination.with_suffix('.json').write_text(json.dumps(result, indent=2) + '\n')++ profiler.dump_stats(str(destination.with_suffix('.prof')))++ if lines:++ print({line: {'total_ms': sum(values), 'max_ms': max(values), 'calls': len(values)} for line, values in lines.items()})++ print({key: result[key] for key in ('median_ms', 'p95_ms', 'max_ms')})++++++if __name__ == '__main__':++ main()diff --cc mac_app/tests/settings_layout_offscreen.pyindex 0000000,0000000..f8369a7new file mode 100644--- /dev/null+++ b/mac_app/tests/settings_layout_offscreen.py@@@ -1,0 -1,0 +1,77 @@@++"""Synthetic, unordered AppKit layout measurements and density-controlled renders."""++import json++from pathlib import Path++from unittest import mock++++from mac_app.tests.design_offscreen import AppKit, offscreen_control_window, rect_list, settle++from mac_app.tests.test_settings_layout_acceptance import frame_in, walk++import theme++++++def render(view, density, path=None):++ width, height = view.bounds().size++ bitmap = AppKit.NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(++ None, round(width * density), round(height * density), 8, 4, True, False,++ AppKit.NSDeviceRGBColorSpace, 0, 0)++ bitmap.setSize_((width, height))++ view.cacheDisplayInRect_toBitmapImageRep_(view.bounds(), bitmap)++ if path is not None:++ bitmap.representationUsingType_properties_(AppKit.NSBitmapImageFileTypePNG, {}).writeToFile_atomically_(str(path), True)++ return bitmap++++++def measure(control, key):++ scroll = control.pages[key]++ page = scroll.documentView()++ body = page.subviews()[0]++ children = []++ for child in walk(body):++ rect = frame_in(child, body)++ if rect.origin.x < -1 or rect.origin.x + rect.size.width > body.bounds().size.width + 1:++ children.append(dict(kind=type(child).__name__, text=str(child.stringValue()) if isinstance(child, AppKit.NSTextField) else str(child.accessibilityLabel()),++ rect=rect_list(rect), parent=type(child.superview()).__name__))++ return dict(page=key, frame=rect_list(control.window.frame()), sidebar=rect_list(control.sidebar.view.frame()),++ viewport=rect_list(scroll.contentView().bounds()), document=rect_list(page.frame()),++ column=rect_list(body.frame()), sections=[rect_list(frame_in(child, body)) for child in body.arrangedSubviews() if not child.isHidden()],++ overflows=children, font=str(theme.font(theme.TYPE['body']).fontName()),++ controls={name: rect_list(frame_in(getattr(control, name).view, body)) for name in++ ('length_select', 'size_select', 'appearance_select', 'tick_steps_select', 'style_for_select', 'effect_method_select', 'follow_select') if key == 'design'})++++++def render_all(destination, dark=True):++ destination = Path(destination)++ destination.mkdir(parents=True, exist_ok=True)++ theme.init_fonts()++ with mock.patch.object(theme, 'system_dark', return_value=dark):++ control = offscreen_control_window()++ control.glow_style_select.value = 'flint'++ control._reflect()++ records = []++ for width in (320, 640, 900, 1440, 1920):++ for key in control.pages:++ control._select_page(key)++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ for _ in range(3):++ settle(control.window)++ scroll = control.pages[key]++ clip = scroll.contentView()++ page = scroll.documentView()++ record = measure(control, key)++ maximum = max(0, page.bounds().size.height - clip.bounds().size.height)++ for position, fraction in (('top', 0), ('middle', .5), ('bottom', 1)):++ clip.scrollToPoint_((0, maximum * fraction))++ scroll.reflectScrolledClipView_(clip)++ settle(control.window)++ for density in (1, 2):++ render(control.window.contentView(), density, destination / f'{key}-{width}-{density}x-{position}.png')++ for density in (1, 2):++ render(page, density, destination / f'{key}-{width}-{density}x-document.png')++ records.append(record)++ print(key, width, 'actual', record['frame'][2], 'column', record['column'], 'overflows', record['overflows'], flush=True)++ (destination / 'measurements.json').write_text(json.dumps(records, indent=2) + '\n')++++++if __name__ == '__main__':++ import sys++ for dark, name in ((True, 'dark'), (False, 'light')):++ render_all(Path(sys.argv[1]) / name, dark)diff --cc mac_app/tests/settings_layout_sheets.pyindex 0000000,0000000..d065653new file mode 100644--- /dev/null+++ b/mac_app/tests/settings_layout_sheets.py@@@ -1,0 -1,0 +1,70 @@@++"""Contact sheets retain every document pixel at a logical 1x inspection scale."""++import json++import math++import sys++from pathlib import Path++++from PIL import Image, ImageDraw, ImageFont++++++def make_sheets(root):++ destination = root / 'contact-sheets'++ destination.mkdir(exist_ok=True)++ font = ImageFont.truetype('/System/Library/Fonts/Helvetica.ttc', 16)++ records = json.loads((root / 'measurements.json').read_text())++ index = []++++ def picture(path):++ image = Image.open(path).convert('RGBA')++ ground = '#0e0f0d' if root.name == 'dark' else '#f1f0ea'++ return Image.alpha_composite(Image.new('RGBA', image.size, ground), image).convert('RGB')++++ for record in records:++ page, width = record['page'], round(record['frame'][2])++ cell_width = min(width, 900)++ cell_height = round(872 * cell_width / width)++ sheet = Image.new('RGB', (3 * cell_width, 2 * (cell_height + 28)), '#31312d')++ draw = ImageDraw.Draw(sheet)++ originals = []++ for row, density in enumerate((1, 2)):++ for col, position in enumerate(('top', 'middle', 'bottom')):++ source = root / f'{page}-{width}-{density}x-{position}.png'++ resized = picture(source).resize((cell_width, cell_height), Image.Resampling.LANCZOS)++ x, y = col * cell_width, row * (cell_height + 28)++ sheet.paste(resized, (x, y + 28))++ draw.text((x + 8, y + 5), f'{page} {width} pt {density}x {position}', fill='white', font=font)++ originals.append(source.name)++ name = f'{page}-{width}-viewports.png'++ sheet.save(destination / name)++ index.append({'sheet': name, 'originals': originals})++ logical = Image.open(root / f'{page}-{width}-1x-document.png')++ height = logical.height++ left, _, column_width, _ = record['column']++ left, right = max(0, math.floor(left) - 4), min(logical.width, math.ceil(left + column_width) + 4)++ tile_width = right - left++ for start in range(0, height, 1400):++ chunks = list(range(start, min(height, start + 1400), 700))++ sheet = Image.new('RGB', (len(chunks) * tile_width, 1456), '#31312d')++ draw = ImageDraw.Draw(sheet)++ originals = []++ for row, density in enumerate((1, 2)):++ source = root / f'{page}-{width}-{density}x-document.png'++ original = picture(source)++ for col, top in enumerate(chunks):++ bottom = min(height, top + 700)++ strip = original.crop((left * density, top * density, right * density, bottom * density))++ strip = strip.resize((tile_width, bottom - top), Image.Resampling.LANCZOS)++ x, y = col * tile_width, row * 728++ sheet.paste(strip, (x, y + 28))++ draw.text((x + 5, y + 5), f'{page} {width} pt {density}x y{top}', fill='white', font=font)++ originals.append(source.name)++ name = f'{page}-{width}-document-{start:05}.png'++ sheet.save(destination / name)++ index.append({'sheet': name, 'originals': originals})++ (destination / 'index.json').write_text(json.dumps(index, indent=2) + '\n')++ print(root.name, len(index), 'sheets covering', len({s for entry in index for s in entry['originals']}), 'renders')++++++if __name__ == '__main__':++ for name in ('dark', 'light'):++ make_sheets(Path(sys.argv[1]) / name)diff --cc mac_app/tests/test_appearance_contrast.pyindex 0000000,0000000..43f5643new file mode 100644--- /dev/null+++ b/mac_app/tests/test_appearance_contrast.py@@@ -1,0 -1,0 +1,327 @@@++"""Every page of the settings window, rendered offscreen in Light and in Dark, read back as pixels:++each piece of text against what is behind it, the cards against the palette, and both after the++appearance changes with the window already built (05-10-2026: Light chosen on Design left the++Crossing page's cards dark, because the page was out of the window when the palette switched).++++Never put on screen. BEAMER_RENDERS=<folder> also writes each page at 900 pt in both appearances."""++++import base64++import copy++import json++import logging++import os++import sys++import tempfile++import unittest++from collections import Counter++from pathlib import Path++from unittest import mock++++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++sys.path.insert(0, str(Path(__file__).resolve().parent))++++import AppKit # noqa: E402++import Quartz # noqa: E402++from Foundation import NSDate, NSRunLoop # noqa: E402++++AppKit.NSApplication.sharedApplication()++++import bridge # noqa: E402++import kvm_bridge_app # noqa: E402++import pages # noqa: E402++import settings_store # noqa: E402++import theme # noqa: E402++import tokens # noqa: E402++from bridge_fakes import PAIRED_TOKEN # noqa: E402++from core import protocol # noqa: E402++from fake_link import FakeLink # noqa: E402++from wake import WakingController # noqa: E402++++PEER = protocol.id_text(bytes(range(40, 56)))++WIDTH = 900++++++def _luminance(rgb):++ def channel(value):++ return value / 12.92 if value <= 0.03928 else ((value + 0.055) / 1.055) ** 2.4++ red, green, blue = (channel(value) for value in rgb)++ return 0.2126 * red + 0.7152 * green + 0.0722 * blue++++++def contrast(first, second):++ lighter, darker = sorted((_luminance(first), _luminance(second)), reverse=True)++ return (lighter + 0.05) / (darker + 0.05)++++++def _srgb(colour, view):++ """A system colour such as labelColor resolves against the appearance it is drawn in, which is++ the view's, not this process's."""++ resolved = []++ view.effectiveAppearance().performAsCurrentDrawingAppearance_(++ lambda: resolved.append(colour.colorUsingColorSpace_(AppKit.NSColorSpace.sRGBColorSpace())))++ colour = resolved[0]++ return colour.redComponent(), colour.greenComponent(), colour.blueComponent(), colour.alphaComponent()++++++def _hex_rgb(value):++ return theme.rgb(value)++++++def _shown(view, root):++ alpha = 1.0++ while view is not None and view != root:++ if view.isHidden():++ return None++ alpha *= view.alphaValue()++ view = view.superview()++ return alpha++++++def _walk(view):++ yield view++ for child in view.subviews() or ():++ yield from _walk(child)++++++def _runs(string):++ """(colour, point size, bold) for every run of an attributed string."""++ runs, index, length = [], 0, string.length()++ while index < length:++ attributes, extent = string.attributesAtIndex_effectiveRange_(index, None)++ colour = attributes.get(AppKit.NSForegroundColorAttributeName)++ font = attributes.get(AppKit.NSFontAttributeName)++ if colour is not None and string.string()[index:index + extent.length].replace("\ufffc", "").strip():++ bold = bool(font) and AppKit.NSFontManager.sharedFontManager().weightOfFont_(font) >= 9++ runs.append((colour, font.pointSize() if font else 13.0, bold))++ index += max(extent.length, 1)++ return runs++++++class Bitmap:++ """The content view drawn the way the window draws it, read in points from the top left."""++++ def __init__(self, view):++ self.view = view++ width, height = view.bounds().size++ self.rep = view.bitmapImageRepForCachingDisplayInRect_(view.bounds())++ view.cacheDisplayInRect_toBitmapImageRep_(view.bounds(), self.rep)++ self.scale = self.rep.pixelsWide() / width++ self.height = height++ self.data = bytes(self.rep.bitmapData())++ self.row = self.rep.bytesPerRow()++ self.channels = self.rep.samplesPerPixel()++++ def pixel(self, x, y):++ """Colour at view point (x, y), y measured up as AppKit does."""++ px = min(max(int(x * self.scale), 0), self.rep.pixelsWide() - 1)++ py = min(max(int((self.height - y) * self.scale), 0), self.rep.pixelsHigh() - 1)++ offset = py * self.row + px * self.channels++ return tuple(value / 255 for value in self.data[offset:offset + 3])++++ def ground(self, rect):++ """The commonest colour in `rect`: what text in it is drawn on."""++ (x, y), (width, height) = rect++ counts = Counter()++ steps = 24++ for i in range(steps):++ for j in range(max(4, steps // 3)):++ sample = self.pixel(x + width * (i + 0.5) / steps, y + height * (j + 0.5) / max(4, steps // 3))++ counts[tuple(round(value * 255) for value in sample)] += 1++ return tuple(value / 255 for value in counts.most_common(1)[0][0])++++++def _settle(window):++ for _ in range(3):++ window.contentView().layoutSubtreeIfNeeded()++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.01))++ assert not window.isVisible()++++++class AppearanceContrast(unittest.TestCase):++ maxDiff = None++++ @classmethod++ def setUpClass(cls):++ theme.init_fonts()++ cls.directory = tempfile.TemporaryDirectory()++ path = Path(cls.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, appearance="dark")++ path.write_text(json.dumps(raw))++ store = settings_store.SettingsStore(path)++ settings = copy.deepcopy(store.current())++ secret = base64.urlsafe_b64encode(bytes(range(100, 132))).decode("ascii").rstrip("=")++ settings["peers"] = [{**settings_store.PEER_DEFAULTS, "id": PEER, "name": "Desk PC", "platform": "windows",++ "token": secret, "host": "192.0.2.30", "port": 24820, "paired_at": 1_700_000_000,++ "linked": True, "side": "right", "side_set_at": 100,++ "side_by": settings["machine_id"]}]++ settings["zones"] = [{"peer": PEER, "kind": "edge"}]++ store.save_settings(settings)++ logger = logging.getLogger("test-appearance-contrast")++ book, identity = bridge.links_from_store(store, "1.5.0")++ controller = WakingController(store.load(), logger=logger, book=book, identity=identity, link_factory=FakeLink)++ cls.later = mock.patch.object(kvm_bridge_app.AppHelper, "callLater", lambda _delay, _call: None)++ cls.later.start()++ with mock.patch.object(kvm_bridge_app, "accessibility_granted", return_value=True), \++ mock.patch.object(kvm_bridge_app, "input_monitoring_granted", return_value=True):++ cls.control = kvm_bridge_app.ControlWindow.alloc().initWithController_settingsStore_logger_(++ controller, store, logger)++ cls.control.windows_input = mock.Mock()++ cls.control.windows_input.server.links.return_value = []++ cls.control.window.setFrame_display_(((100000, 100000), (WIDTH, 900)), False)++ cls.renders = os.environ.get("BEAMER_RENDERS")++++ @classmethod++ def tearDownClass(cls):++ cls.control.appearance_watch.stop()++ cls.later.stop()++ theme.set_dark(True)++ cls.directory.cleanup()++++ def _choose(self, choice):++ self.control.appearance_select.value = choice++ self.control._apply_appearance(choice)++++ def _show(self, key):++ """The page at 900 pt, the window tall enough that the whole page is in view."""++ control = self.control++ control._select_page(key)++ window = control.window++ _settle(window)++ page = control.pages[key].documentView()++ chrome = window.frame().size.height - control.pages[key].contentView().bounds().size.height++ window.setFrame_display_(((100000, 100000), (WIDTH, page.frame().size.height + chrome + 2)), False)++ _settle(window)++ return Bitmap(window.contentView())++++ def _texts(self, root):++ for view in _walk(root):++ if isinstance(view, AppKit.NSButton):++ string = view.attributedTitle()++ elif isinstance(view, AppKit.NSTextField) or type(view).__name__ == "_PreviewCaption":++ string = view.attributedStringValue()++ else:++ continue++ if string is None or not str(string.string()).strip():++ continue++ alpha = _shown(view, root)++ # Faded to show it is off, as a switch the Mac does not have: WCAG 1.4.3 exempts an++ # inactive control, and these fade as a whole.++ if alpha is None or alpha < 0.99:++ continue++ if isinstance(view, AppKit.NSControl) and not view.isEnabled():++ continue++ rect = view.convertRect_toView_(view.bounds(), root)++ if rect.size.width < 2 or rect.size.height < 2:++ continue++ yield view, string, rect++++ def _check_text(self, bitmap, label):++ failures, checked = [], 0++ root = self.control.window.contentView()++ for view, string, rect in self._texts(root):++ behind = bitmap.ground(rect)++ for colour, size, bold in _runs(string):++ red, green, blue, alpha = _srgb(colour, view)++ ink = tuple(alpha * value + (1 - alpha) * base for value, base in zip((red, green, blue), behind))++ ratio = contrast(ink, behind)++ needed = 3.0 if size >= 18 or (size >= 14 and bold) else 4.5++ checked += 1++ if ratio < needed:++ failures.append(f"{label}: {str(string.string())[:40]!r} {ratio:.2f} < {needed}")++ return checked, failures++++ def _check_cards(self, bitmap, label):++ """Every tinted layer anywhere in the window, pages out of it included, carries the++ palette in use, and the cards in view measure as `panel` on screen."""++ failures = []++ palette = tokens.PALETTE if theme.is_dark() else tokens.PALETTE_LIGHT++ roots = [self.control.window.contentView(), *self.control.pages.values()]++ for root in roots:++ for view in _walk(root):++ layer = view.layer()++ spec = layer.valueForKey_(theme._KEY + "background") if layer is not None else None++ if not spec:++ continue++ name = str(spec).partition("@")[0]++ red, green, blue = Quartz.CGColorGetComponents(layer.backgroundColor())[:3]++ expected = _hex_rgb(palette[name])++ if max(abs(a - b) for a, b in zip((red, green, blue), expected)) > 1.5 / 255:++ failures.append(f"{label}: {type(view).__name__} {name} is not the {'dark' if theme.is_dark() else 'light'} {name}")++ content = self.control.window.contentView()++ page = self.control.pages[self.control.page]++ panel = _hex_rgb(palette["panel"])++ cards = 0++ for view in _walk(page):++ layer = view.layer()++ if layer is None or str(layer.valueForKey_(theme._KEY + "background") or "") != "panel":++ continue++ if _shown(view, content) is None or view.window() is None:++ continue++ (x, y), (width, height) = view.convertRect_toView_(view.bounds(), content)++ if width < 40 or height < 40:++ continue++ cards += 1++ measured = bitmap.pixel(x + 4, y + height - 4)++ if max(abs(a - b) for a, b in zip(measured, panel)) > 3 / 255:++ failures.append(f"{label}: card at {round(x)},{round(y)} measures {tuple(round(v * 255) for v in measured)}")++ return cards, failures++++ def _sweep(self, appearance):++ checked = cards = 0++ failures = []++ for key in pages.KEYS:++ bitmap = self._show(key)++ label = f"{appearance}/{key}"++ count, text_failures = self._check_text(bitmap, label)++ panels, card_failures = self._check_cards(bitmap, label)++ checked += count++ cards += panels++ failures += text_failures + card_failures++ if self.renders:++ folder = Path(self.renders)++ folder.mkdir(parents=True, exist_ok=True)++ png = bitmap.rep.representationUsingType_properties_(AppKit.NSBitmapImageFileTypePNG, {})++ png.writeToFile_atomically_(str(folder / f"{key}-{appearance}-{WIDTH}.png"), True)++ return checked, cards, failures++++ def test_every_page_reads_in_dark_and_in_light_chosen_from_another_page(self):++ # Toby's path: the window built dark, Light chosen on the Design page, then every other page.++ self._choose("dark")++ self.control._select_page("design")++ self._choose("light")++ self.assertFalse(theme.is_dark())++ checked, cards, failures = self._sweep("light")++ self.assertGreater(checked, 150)++ self.assertGreater(cards, 10)++ self.assertEqual(failures, [])++ self.control._select_page("crossing")++ self._choose("dark")++ checked, cards, failures = self._sweep("dark")++ self.assertGreater(checked, 150)++ self.assertGreater(cards, 10)++ self.assertEqual(failures, [])++++ def test_an_odd_way_out_fills_its_row_instead_of_leaving_a_grey_slot(self):++ self._show("crossing")++ tiles = list(self.control.method_boxes.values())++ last, frame = tiles[-1].view, tiles[-1].view.superview()++ self.assertEqual(len(tiles) % 2, 1)++ self.assertAlmostEqual(last.frame().origin.x + last.frame().size.width, frame.bounds().size.width, delta=0.5)++++ def test_system_switching_while_the_window_exists_repaints_pages_out_of_view(self):++ self._choose("system")++ for dark in (False, True, False):++ self.control._select_page("overview" if dark else "keyboard")++ with mock.patch.object(theme, "system_dark", return_value=dark):++ self.control.appearance_watch.callback()++ self.assertEqual(theme.is_dark(), dark)++ bitmap = self._show("crossing")++ _count, text_failures = self._check_text(bitmap, f"system-{dark}/crossing")++ _cards, card_failures = self._check_cards(bitmap, f"system-{dark}/crossing")++ self.assertEqual(text_failures + card_failures, [])++ self._choose("dark")++++++if __name__ == "__main__":++ unittest.main()diff --cc mac_app/tests/test_beam_live.pyindex 0000000,0000000..96f6953new file mode 100644--- /dev/null+++ b/mac_app/tests/test_beam_live.py@@@ -1,0 -1,0 +1,69 @@@++"""The live Beam's inward fade, through real Core Animation layers with no windows."""++++import sys++import unittest++from pathlib import Path++++sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools"))++++from beam_live_offscreen import live_glow, profile, layer_profile++++++class LiveBeamFalloffTest(unittest.TestCase):++ def test_every_edge_and_size_fades_before_the_panel_ends_at_both_scales(self):++ for size in ("small", "medium", "large"):++ for edge in ("left", "right", "top", "bottom"):++ for scale in (1, 2):++ with self.subTest(size=size, edge=edge, scale=scale):++ values = profile(live_glow(edge, size), edge, scale)++ self.assertGreater(values[0], 20)++ self.assertLessEqual(values[-1], 5)++ self.assertGreater(values[len(values) // 4], values[len(values) // 2])++++ def test_live_falloff_matches_the_windows_live_gradient(self):++ values = profile(live_glow("left", "large"), "left", 2)++ depth = 67.02 * 2++ stops = ((0, 1), (.08, .85), (.3, .25), (1, 0))++ for index, alpha in enumerate(values):++ at = (index + .5) / depth++ expected = 0++ for (a, av), (b, bv) in zip(stops, stops[1:]):++ if a <= at <= b:++ expected = av + (bv - av) * (at - a) / (b - a)++ break++ # The along-edge comet is at its midpoint; mask sampling can round by one alpha unit.++ self.assertAlmostEqual(alpha / values[0], expected / (1 - .15 * .5 / (.08 * depth)), delta=.025)++++ def test_both_corner_walls_fade_inward(self):++ for corner in ("top_left", "top_right", "bottom_left", "bottom_right"):++ glow = live_glow("right", "medium", corner=corner)++ for layer, wall in zip((glow.fill, glow.side), corner.split("_")):++ values = layer_profile(layer, wall, 2)++ with self.subTest(corner=corner, wall=wall):++ self.assertGreater(values[0], 10)++ self.assertLessEqual(values[-1], 2)++++ def test_a_third_keeps_its_along_edge_taper_and_inward_fade(self):++ glow = live_glow("left", "medium", third=True)++ values = profile(glow, "left", 2)++ self.assertGreater(values[0], 200)++ self.assertLessEqual(values[-1], 2)++ from beam_live_offscreen import render++ width, height, rgba = render(glow.panel.contentView().layer(), 2)++ self.assertLess(rgba[3], 5)++ self.assertLess(rgba[((height - 2) * width) * 4 + 3], 5)++++ def test_switching_back_to_glow_removes_the_beam_mask(self):++ glow = live_glow("left", "medium")++ glow.controller.cfg.crossing["glow_style"] = "glow"++ # The real reconfiguration path, held offscreen by OffscreenPanel.++ from unittest import mock++ import kvm_bridge_app++ with mock.patch.object(kvm_bridge_app.time, "monotonic", return_value=100):++ glow._draw()++ values = profile(glow, "left", 2)++ self.assertGreater(values[len(values) // 2], 200)++++++if __name__ == "__main__":++ unittest.main()diff --cc mac_app/tests/test_bridge.pyindex 05887fc,d77cfad..1be8989--- a/mac_app/tests/test_bridge.py+++ b/mac_app/tests/test_bridge.py@@@ -7,13 -3,11 +7,14 @@@ import errnimport loggingimport osimport queue-import struct+import sysimport threading+import timeimport typesimport unittest++from unittest import mock++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))import configimport media_keys@@@ -318,6 -570,6 +319,47 @@@ class ControllerTests(unittest.TestCaseself.assertIs(returned, event)self.assertTrue(self.controller.outbound.empty())++ def test_shortcut_off_passes_the_key_without_switching_in_each_input_state(self):++ for style in ("double_tap", "hold"):++ for state in ("local", "receiving", "redirected"):++ with self.subTest(style=style, state=state):++ cfg = crossing_config(PAIRED_TOKEN, methods=["edge"])++ cfg.trigger_style = style++ controller = make_controller(self.clock, cfg)++ self.addCleanup(controller.stop_event.set)++ bring_up(controller)++ homes = []++ controller.send_peer_home = lambda: homes.append(True) or True++ if state == "receiving":++ controller.receiving = True++ elif state == "redirected":++ redirect_to(controller)++ for flags in (FakeQuartz.kCGEventFlagMaskAlternate, 0) * 2:++ event = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": flags}++ returned = controller._event_tap_callback(None, FakeQuartz.kCGEventFlagsChanged, event, None)++ if state == "redirected":++ self.assertIsNone(returned)++ else:++ self.assertIs(returned, event)++ self.assertEqual(controller.receiving, state == "receiving")++ self.assertEqual(controller.redirecting, state == "redirected")++ self.assertEqual(homes, [])++ messages = drain(controller)++ expected = [{"type": kind, "data": {"key": "alt_r"}}++ for kind in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP) * 2]++ self.assertEqual(messages, expected if state == "redirected" else [])++++ def test_switching_shortcut_off_discards_an_unfinished_double_tap(self):++ bring_up(self.controller)++ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": FakeQuartz.kCGEventFlagMaskAlternate}++ up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}++ self._tap(FakeQuartz.kCGEventFlagsChanged, down)++ self._tap(FakeQuartz.kCGEventFlagsChanged, up)++ self.controller.apply_settings(crossing_config(PAIRED_TOKEN, methods=["edge"]))++ self.controller.apply_settings(crossing_config(PAIRED_TOKEN, methods=["shortcut", "edge"]))++ self.assertIs(self._tap(FakeQuartz.kCGEventFlagsChanged, down), down)++ self.assertFalse(self.controller.redirecting)++def test_redirected_event_is_queued_and_swallowed(self):event = {FakeQuartz.kCGKeyboardEventKeycode: 0x00,@@@ -1316,9 -1909,9 +1358,31 @@@ class CrossingWiringTests(unittest.Testself.assertTrue(self.controller._crossing_failed)event, returned = self._move(1727.0, 558.0, 30)self.assertIs(returned, event)- self.controller.update_config(crossing_config())+ self.controller.update_config(crossing_config(PAIRED_TOKEN))self.assertFalse(self.controller._crossing_failed)++ def test_a_failed_cursor_read_skips_that_event_without_disabling_crossing(self):++ original = FakeQuartz.__dict__["CGEventGetLocation"]++ reads = iter([PermissionError("access denied"), PermissionError("access denied")])++++ def cursor_position(_quartz, event):++ try:++ result = next(reads)++ except StopIteration:++ return event.get("location", FakeQuartz.cursor_pin_location)++ raise result++++ FakeQuartz.CGEventGetLocation = classmethod(cursor_position)++ self.addCleanup(setattr, FakeQuartz, "CGEventGetLocation", original)++ with mock.patch.object(self.controller.logger, "warning") as warning:++ self._move(1727.0, 558.0, 30)++ self._move(1727.0, 558.0, 30)++ _event, returned = self._push(10)++++ self.assertIsNone(returned)++ self.assertTrue(self.controller.redirecting)++ self.assertEqual(warning.call_count, 1)++def test_a_passing_failure_in_the_crossing_path_heals_by_itself(self):self.controller.desktop_bounds = lambda: (_ for _ in ()).throw(RuntimeError("no displays"))self.controller._bounds_cache = None@@@ -1585,5 -2174,61 +1649,58 @@@ class RoundTripTests(unittest.TestCase)self.assertIsNone(self.controller.round_trip_ms)-class FollowingAMovedPcTests(unittest.TestCase):- """The PC's router hands it a new address; it still beacons under the name it paired with."""-- OLD, NEW = "192.0.2.10", "192.0.2.77"-- def make(self, reply_token="synthetic-token", beacons=None):- sock = FakeSocket()- seed_receiver_reply(sock, protocol.welcome_msg(), token=reply_token)- tried = []-- def socket_factory(address, timeout):- tried.append(address[0])- if address[0] == self.OLD:- raise ConnectionRefusedError("nothing there now")- return sock-- controller = KVMController(- dataclasses.replace(make_config(), pc_name="STUDIO-PC"),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=FakeClock(),- socket_factory=socket_factory,- )- found = beacons if beacons is not None else [- {"name": "STUDIO-PC", "address": self.NEW, "port": 51820, "reply_port": 24821, "pair_id": None}]- controller.discovery = types.SimpleNamespace(pcs=lambda: found)- learned = []- controller.on_host_learned = learned.append- return controller, tried, learned-- def test_it_follows_the_pc_and_saves_the_address_once_it_authenticates(self):- controller, tried, learned = self.make()- self.assertFalse(controller._connect_once())- controller._follow_the_pc()- self.assertEqual(tried, [self.OLD, self.NEW])- self.assertEqual(controller.cfg.host, self.NEW)- self.assertEqual(learned, [self.NEW])- self.assertIsNotNone(controller.sock)-- def test_a_beacon_that_cannot_authenticate_changes_nothing(self):- controller, tried, learned = self.make(reply_token="an-impostors-token")- controller._connect_once()- controller._follow_the_pc()- self.assertEqual(tried, [self.OLD, self.NEW])- self.assertEqual(controller.cfg.host, self.OLD)- self.assertEqual(learned, [])-- def test_another_pcs_beacon_is_ignored(self):- controller, tried, learned = self.make(beacons=[- {"name": "SOMEONE-ELSE", "address": self.NEW, "port": 51820, "reply_port": 24821, "pair_id": None}])- controller._connect_once()- controller._follow_the_pc()- self.assertEqual(tried, [self.OLD])- self.assertEqual(learned, [])++class HeldKeyMappingTests(unittest.TestCase):++ def test_key_release_keeps_the_mapping_used_for_its_press(self):++ controller = KVMController.__new__(KVMController)++ controller.cfg = types.SimpleNamespace(key_map=config.KEY_MAP_STYLES["semantic"])++ controller._sent_names = {}++ peer = types.SimpleNamespace(peer_id=b"peer", peer_platform="windows", caps=set())++ press = controller._for_peer(++ {"type": protocol.MSG_KEYDOWN, "data": {"key": "cmd"}}, peer++ )++ controller.cfg = types.SimpleNamespace(key_map=config.KEY_MAP_STYLES["positional"])++ release = controller._for_peer(++ {"type": protocol.MSG_KEYUP, "data": {"key": "cmd"}}, peer++ )++ self.assertEqual(press["data"]["key"], release["data"]["key"])++++ def test_shared_semantic_modifier_stays_down_until_both_physical_keys_release(self):++ controller = KVMController.__new__(KVMController)++ controller.cfg = types.SimpleNamespace(key_map=config.KEY_MAP_STYLES["semantic"])++ controller._sent_names = {}++ peer = types.SimpleNamespace(peer_id=b"peer", peer_platform="windows", caps=set())++ events = []++ for kind, key in (++ (protocol.MSG_KEYDOWN, "ctrl"),++ (protocol.MSG_KEYDOWN, "ctrl_r"),++ (protocol.MSG_KEYUP, "ctrl"),++ ):++ event = controller._for_peer({"type": kind, "data": {"key": key}}, peer)++ if event is not None:++ events.append(event)++ held_on_peer = set()++ for event in events:++ key = event["data"]["key"]++ if event["type"] == protocol.MSG_KEYDOWN:++ held_on_peer.add(key)++ else:++ held_on_peer.discard(key)++ self.assertEqual(held_on_peer, {"cmd"})++ final_release = controller._for_peer(++ {"type": protocol.MSG_KEYUP, "data": {"key": "ctrl_r"}}, peer++ )++ self.assertEqual(final_release["data"]["key"], "cmd")++ held_on_peer.discard(final_release["data"]["key"])++ self.assertEqual(held_on_peer, set())++++ def test_a_dropped_peer_forgets_its_held_key_names(self):++ controller = KVMController.__new__(KVMController)++ controller._sent_names = {(b"peer", "cmd"): "ctrl", (b"other", "cmd"): "ctrl"}++ controller._clip_lock = threading.Lock()++ controller._clip_wait = {}++ controller._forget_held(b"peer")++ self.assertEqual(controller._sent_names, {(b"other", "cmd"): "ctrl"})++if __name__ == "__main__":unittest.main()diff --cc mac_app/tests/test_click_focus.pyindex 0000000,0000000..ba56108new file mode 100644--- /dev/null+++ b/mac_app/tests/test_click_focus.py@@@ -1,0 -1,0 +1,158 @@@++"""Spec section 6: a click never leaves a focus ring; Tab and the arrows show one. Offscreen only."""++import unittest++++from mac_app.tests.design_offscreen import AppKit, kvm_bridge_app, offscreen_control_window, settle++++widgets = kvm_bridge_app.widgets++++++def mouse(window, view, kind):++ bounds = view.bounds()++ point = view.convertPoint_toView_((bounds.size.width / 2, bounds.size.height / 2), None)++ return AppKit.NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_(++ kind, point, 0, 0, window.windowNumber(), None, 0, 1, 1.0)++++++def key(window, characters, code):++ return AppKit.NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_(++ AppKit.NSEventTypeKeyDown, (0, 0), 0, 0, window.windowNumber(), None, characters, characters, False, code)++++++def ring_shown(view):++ while view is not None and not isinstance(view, (widgets.Pressable, widgets._RulerView)):++ view = view.superview()++ if isinstance(view, widgets._RulerView):++ return widgets.keyboard_focus_visible(view)++ return view.ring is not None and not view.ring.isHidden()++++++def visible_pressables(view):++ if view.isHidden():++ return++ if isinstance(view, widgets.Pressable):++ yield view++ for child in view.subviews():++ yield from visible_pressables(child)++++++class ClickFocusTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ kvm_bridge_app.theme.init_fonts()++ cls.control = offscreen_control_window()++ cls.window = cls.control.window++ cls.window.setFrame_display_(((100000, 100000), (1100, 900)), False)++++ def show(self, page):++ self.control._select_page(page)++ settle(self.window)++++ def click(self, view):++ window = self.window++ window.keyboard_navigation = True++ view.scrollRectToVisible_(view.bounds())++ settle(window)++ down = mouse(window, view, AppKit.NSEventTypeLeftMouseDown)++ up = mouse(window, view, AppKit.NSEventTypeLeftMouseUp)++ hit = window.contentView().superview().hitTest_(down.locationInWindow())++ self.assertIsNotNone(hit)++ window.sendEvent_(down)++ # An offscreen window is never key, so AppKit stops short of what it does for a real++ # click: the hit view takes first responder if it accepts it, then gets the click.++ if hit.acceptsFirstResponder():++ window.makeFirstResponder_(hit)++ hit.mouseDown_(down)++ window.sendEvent_(up)++ hit.mouseUp_(up)++ settle(window)++++ def press_key(self, characters, code):++ window = self.window++ window.sendEvent_(key(window, characters, code))++ # Unkeyed, the window never runs its own Tab handling; this is what Tab calls.++ if characters == '\t':++ window.selectNextKeyView_(None)++ settle(window)++++ def assert_no_ring_after_click(self, view, name):++ with self.subTest(control=name):++ self.click(view)++ self.assertFalse(self.window.keyboard_navigation)++ self.assertFalse(ring_shown(view), name)++ responder = self.window.firstResponder()++ self.assertNotIsInstance(responder, AppKit.NSTextView, f"{name}: a click opened the field editor")++ if isinstance(responder, widgets.Pressable):++ self.assertFalse(ring_shown(responder), name)++++ def test_wrapping_labels_are_not_selectable(self):++ label = widgets.Label("Corner", wrap=True)++ self.assertFalse(label.view.isSelectable())++ self.assertFalse(label.view.acceptsFirstResponder())++ self.assertFalse(widgets.note("A note").view.isSelectable())++++ def test_click_on_each_control_type_draws_no_ring(self):++ control = self.control++ self.show('design')++ segment, words = control.length_select.cells[1][1], control.length_select.cells[1][2]++ self.assert_no_ring_after_click(segment, 'segment')++ self.assert_no_ring_after_click(words.view, 'segment label')++ self.assertIsNot(self.window.firstResponder(), words.view)++ self.assert_no_ring_after_click(control.glow_box.view, 'switch')++ self.assert_no_ring_after_click(control.glow_box.words.view, 'switch label')++ tiles = control.notch_style_select.tiles++ tile = tiles[0][1]++ if not tile.isHiddenOrHasHiddenAncestor():++ self.assert_no_ring_after_click(tile, 'tile')++ chips = [view for view in visible_pressables(control.glow_colour_select.rows[0].view)]++ self.assertTrue(chips)++ self.assert_no_ring_after_click(chips[0], 'swatch')++ for view in visible_pressables(control.pages['design'].documentView()):++ if view.accessibilityRole() == AppKit.NSAccessibilityRadioButtonRole:++ self.assert_no_ring_after_click(view, view.accessibilityLabel())++ self.assert_no_ring_after_click(control.sidebar.rows['design'][1], 'sidebar row')++++ def test_click_on_ruler_does_not_light_its_thumb(self):++ control = self.control++ for page in control.pages:++ self.show(page)++ views = [v for v in self._rulers(control.pages[page].documentView())]++ if views:++ self.assert_no_ring_after_click(views[0], 'ruler')++ self.assertIs(self.window.firstResponder(), views[0])++ self.press_key(AppKit.NSRightArrowFunctionKey, 124)++ self.assertTrue(ring_shown(views[0]))++ return++ self.fail('no ruler found')++++ def _rulers(self, view):++ if view.isHidden():++ return++ if isinstance(view, widgets._RulerView):++ yield view++ for child in view.subviews():++ yield from self._rulers(child)++++ def test_other_keys_after_a_click_leave_the_ring_off(self):++ self.show('design')++ segment = self.control.length_select.cells[1][1]++ self.click(segment)++ self.press_key('a', 0)++ self.assertFalse(self.window.keyboard_navigation)++ self.assertFalse(ring_shown(segment))++++ def test_tab_shows_a_ring_and_the_next_click_clears_it(self):++ self.show('design')++ segment = self.control.length_select.cells[1][1]++ self.click(segment)++ self.press_key('\t', 48)++ self.assertTrue(self.window.keyboard_navigation)++ responder = self.window.firstResponder()++ self.assertIsInstance(responder, widgets.Pressable)++ self.assertTrue(ring_shown(responder))++ self.click(segment)++ self.assertFalse(ring_shown(responder))++ self.assertFalse(ring_shown(segment))++++++if __name__ == '__main__':++ unittest.main()diff --cc mac_app/tests/test_colour_pixels.pyindex 0000000,0000000..6a5ff21new file mode 100644--- /dev/null+++ b/mac_app/tests/test_colour_pixels.py@@@ -1,0 -1,0 +1,52 @@@++"""Native colour previews, drawn into bitmaps without displaying a window."""++++import sys++import unittest++from pathlib import Path++++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from tools.render_colour_choices import MacRenderer, NEW_COLOURS, colour_rows, sample++++++class ColourPixelTests(unittest.TestCase):++ def test_ring_arrival_preview_draws_the_new_bright_colour(self):++ renderer = MacRenderer()++ renderer.set_dark(False)++ from tools.render_colour_choices import sample++ _image, pixels = sample(renderer, 'switch:locator', 'citron')++ self.assertGreater(pixels, 0)++++ def test_five_choices_fill_the_existing_swatch_row_without_a_blank_column(self):++ import crossing++ import widgets++ import notch_beam++ renderer = MacRenderer()++ choices = colour_rows('mac')[0][1]++ row = widgets.Swatches([(value, name, notch_beam.palette_values(value)) for value, name in choices],++ columns=len(crossing.GLOW_COLOURS))++ self.assertEqual(len(row.view.arrangedSubviews()), 5)++++ def test_every_colour_group_has_five_choices_and_mono_has_its_own_home(self):++ groups = colour_rows("mac")++ self.assertTrue(NEW_COLOURS <= {value for _group, values in groups for value, _title in values})++ self.assertEqual([values for name, values in groups if name == "Mono"], [[++ ("mono", "White"), ("mono_silver", "Silver"), ("mono_graphite", "Graphite"),++ ("mono_ink", "Ink"), ("mono_warm", "Warm grey")]])++ self.assertTrue(any(name == "Bright" for name, _values in groups))++ for name, values in groups:++ self.assertEqual(len(values), 5, name)++++ def test_every_colour_draws_visible_pixels_in_every_native_preview(self):++ renderer = MacRenderer()++ for dark in (False, True):++ renderer.set_dark(dark)++ for group, values in colour_rows("mac"):++ for colour, _name in values:++ for style in renderer.styles:++ with self.subTest(group=group, colour=colour, style=style, dark=dark):++ _image, changed = sample(renderer, style, colour)++ self.assertGreater(changed, 0)++++++if __name__ == "__main__":++ unittest.main()diff --cc mac_app/tests/test_crossing_matrix.pyindex 1fbf89c,2d636ce..dc5e430--- a/mac_app/tests/test_crossing_matrix.py+++ b/mac_app/tests/test_crossing_matrix.py@@@ -284,7 -253,7 +284,7 @@@ class WhatIsSharedTests(unittest.TestCaline = pages.SCOPE["crossing"]self.assertNotIn("Two are shared", line)- self.assertIn("Only which side each machine is on is shared", line)- self.assertIn("Only which side the PC is on is shared", line)++ self.assertIn("Its side is shared with that machine", line)def pc_at_edge(duo, edge):diff --cc mac_app/tests/test_crossing_page_machines.pyindex c8c9943,0000000..f9249f6mode 100644,000000..100644--- a/mac_app/tests/test_crossing_page_machines.py+++ b/mac_app/tests/test_crossing_page_machines.py@@@ -1,628 -1,0 +1,629 @@@+"""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 = []+ 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_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_design_offscreen.pyindex 0000000,0000000..0e2637anew file mode 100644--- /dev/null+++ b/mac_app/tests/test_design_offscreen.py@@@ -1,0 -1,0 +1,252 @@@++"""Real AppKit regressions without ever ordering or activating a window."""++++import unittest++import time++from unittest import mock++++from mac_app.tests.design_offscreen import (++ AppKit, kvm_bridge_app, lit_pixels, offscreen_control_window, rect_list, resize_measurements, settle, tiles,++)++++widgets = kvm_bridge_app.widgets++++++class LayoutStack(AppKit.NSStackView):++ passes = []++++ def layout(self):++ LayoutStack.passes.append(self.enclosingScrollView())++ kvm_bridge_app.objc.super(LayoutStack, self).layout()++++++def measured_stack(vertical=True, spacing=10):++ view = LayoutStack.alloc().init()++ view.setTranslatesAutoresizingMaskIntoConstraints_(False)++ view.setOrientation_(1 if vertical else 0)++ view.setSpacing_(spacing)++ view.setAlignment_(AppKit.NSLayoutAttributeLeading if vertical else AppKit.NSLayoutAttributeCenterY)++ view.setDistribution_(AppKit.NSStackViewDistributionFill)++ return view++++++def raster(view):++ rep = view.bitmapImageRepForCachingDisplayInRect_(view.bounds())++ view.cacheDisplayInRect_toBitmapImageRep_(view.bounds(), rep)++ return rep++++++def accent_pixels_near_top_edge(view):++ rep = raster(view)++ left, right = int(rep.pixelsWide() * .25), int(rep.pixelsWide() * .75)++ return sum(++ 1 for y in range(2, min(16, rep.pixelsHigh())) for x in range(left, right)++ if (lambda colour: colour.blueComponent() > .55 and++ colour.blueComponent() - colour.redComponent() > .18)(rep.colorAtX_y_(x, y))++ )++++++def raster_difference(a, b):++ if (a.pixelsWide(), a.pixelsHigh()) != (b.pixelsWide(), b.pixelsHigh()):++ return 0++ return sum(x != y for x, y in zip(bytes(a.bitmapData()), bytes(b.bitmapData())))++++++class DesignOffscreenTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ kvm_bridge_app.theme.init_fonts()++++ def test_style_hint_is_present(self):++ control = offscreen_control_window()++ control._select_page("design")++ settle(control.window)++ self.assertEqual(control.style_preview_hint.view.stringValue(), "Hover to preview")++++ def test_selection_marker_is_on_tile_pixels(self):++ control = offscreen_control_window()++ control._select_page("design")++ settle(control.window)++ control.glow_style_select.value = "beam"++ tile = control.glow_style_select.rows[0].tiles[1][1]++ self.assertGreater(accent_pixels_near_top_edge(tile), 0,++ "the selected tile's own raster has no accent marker")++++ def test_hover_state_changes_the_tile_raster(self):++ control = offscreen_control_window()++ control._select_page("design")++ settle(control.window)++ tile = control.glow_style_select.rows[0].tiles[1][1]++ before = raster(tile).colorAtX_y_(int(tile.bounds().size.width / 2), 1)++ owner = getattr(tile, "_tile_hover_owner", None)++ self.assertIsNotNone(owner, "the style tile has no discoverable hover-state handler")++ owner.mouseEntered_(None)++ after = raster(tile).colorAtX_y_(int(tile.bounds().size.width / 2), 1)++ contrast = sum(abs(a - b) for a, b in zip(++ (before.redComponent(), before.greenComponent(), before.blueComponent()),++ (after.redComponent(), after.greenComponent(), after.blueComponent())))++ self.assertGreater(contrast, 0.1, f"hover edge contrast was only {contrast:.3f}")++ self.assertEqual(accent_pixels_near_top_edge(tile), 0)++ owner.mouseExited_(None)++++ def test_style_families_fill_the_panel_at_requested_widths(self):++ control = offscreen_control_window()++ control._select_page("design")++ columns = []++ for width, expected in ((900, 3), (1200, 3), (1500, 3), (1900, 3)):++ with self.subTest(width=width):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ settle(control.window)++ self.assertAlmostEqual(control.window.frame().size.width, width, delta=.5)++ columns.append(control.glow_style_select.rows[0].columns)++ for row in control.glow_style_select.rows:++ self.assertEqual(row.columns, expected)++ group_frames = [rect_list(tile.convertRect_toView_(tile.bounds(), row.view))++ for _, tile, _ in row.tiles]++ group_frames.sort()++ self.assertAlmostEqual(group_frames[0][0], 0, delta=.5)++ self.assertAlmostEqual(group_frames[-1][0] + group_frames[-1][2],++ row.view.bounds().size.width, delta=1)++ for first, second in zip(group_frames, group_frames[1:]):++ self.assertAlmostEqual(second[0] - first[0] - first[2], 12, delta=1)++ for family in control.glow_style_select.rows:++ for preview in family.previews:++ frame = preview.frame()++ self.assertAlmostEqual(frame.size.width / frame.size.height, 2.0, delta=.02)++ self.assertEqual(columns, sorted(columns))++++ def test_continuous_wide_resizing_does_not_layout_hidden_pages(self):++ with mock.patch.object(widgets, "stack", measured_stack):++ control = offscreen_control_window()++ control._select_page("design")++ settle(control.window)++ LayoutStack.passes = []++ control.window.setFrame_display_(((100000, 100000), (1900, 900)), False)++ control.window.contentView().layoutSubtreeIfNeeded()++ hidden = [scroll for scroll in LayoutStack.passes++ if scroll is not None and scroll in control.pages.values() and scroll.isHidden()]++ self.assertEqual(hidden, [])++++ def test_every_effect_still_contains_visible_colour_including_beam(self):++ control = offscreen_control_window()++ control._select_page("design")++ for width in (640, 760, 900, 1100, 1400, 1900):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ settle(control.window)++ for row in control.glow_style_select.rows:++ for (value, _tile, _name), preview in zip(row.tiles, row.previews):++ with self.subTest(effect=value, width=width):++ self.assertGreater(lit_pixels(preview), 30)++++ def test_resize_callbacks_fit_a_frame_budget(self):++ control = offscreen_control_window()++ control._select_page("design")++ settle(control.window)++ measured = resize_measurements(control)++ slow = [(frame["width"], frame["milliseconds"], frame["columns"])++ for frame in measured["frames"] if frame["milliseconds"] >= 16]++ print(f"Design resize: median {measured['median_ms']:.3f} ms, p95 "++ f"{measured['p95_ms']:.3f} ms, max {measured['max_ms']:.3f} ms", flush=True)++ if slow:++ details = [(frame["width"], round(frame["milliseconds"], 3),++ round(frame["callback_ms"], 3), round(frame["layout_ms"], 3),++ round(frame["arrange_ms"], 3), frame["wide"], frame["pair_flips"])++ for frame in measured["frames"] if frame["milliseconds"] >= 16]++ print(f"slow frame breakdown (width, total, callback, layout, arrange, wide, pair flips): "++ f"{details}", flush=True)++ self.assertLess(measured["p95_ms"], 16, "95% of live-resize frames must fit 16 ms")++ self.assertLess(measured["max_ms"], 25, "no live-resize frame may take 25 ms")++ self.assertEqual(measured["unsettled_frames"], [], "resize geometry changed after settling")++++ def test_length_and_size_have_readable_segments_at_minimum_width(self):++ control = offscreen_control_window()++ control._select_page("design")++ control.window.setFrame_display_(((100000, 100000), control.window.minSize()), False)++ settle(control.window)++ for selector in (control.length_select, control.size_select):++ self.assertLessEqual(selector.view.frame().size.width, 240)++ self.assertEqual(selector.layout_columns, 1)++ for _, cell, words in selector.cells:++ self.assertGreaterEqual(cell.bounds().size.height, 28)++ self.assertGreaterEqual(words.view.frame().size.width, words.view.attributedStringValue().size().width)++++ def test_stacked_length_and_size_share_the_field_column(self):++ control = offscreen_control_window()++ control._select_page("design")++ for width in (640, 760, 900):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ settle(control.window)++ for row in (control.length_row, control.size_row):++ self.assertAlmostEqual(row.frame().origin.x, 0, delta=.5)++ self.assertAlmostEqual(row.frame().size.width, control.style_module.body.frame().size.width, delta=1)++++ def test_wide_length_and_size_keep_equal_halves(self):++ control = offscreen_control_window()++ control._select_page("design")++ control.window.setFrame_display_(((100000, 100000), (1900, 900)), False)++ settle(control.window)++ self.assertAlmostEqual(control.length_select.view.frame().size.width, 240, delta=1)++ self.assertAlmostEqual(control.size_select.view.frame().size.width, 240, delta=1)++ self.assertAlmostEqual(control.length_row.frame().size.width, control.size_row.frame().size.width, delta=1)++++ def test_trackpad_options_do_not_truncate_at_any_width(self):++ control = offscreen_control_window()++ control._select_page("design")++ for width in (640, 760, 900, 1100, 1400, 1900):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ settle(control.window)++ for value, _cell, words in control.tick_steps_select.cells:++ with self.subTest(width=width, value=value):++ self.assertGreaterEqual(words.view.frame().size.width,++ words.view.cell().cellSize().width)++++ def test_wide_trackpad_options_fill_the_field_column(self):++ control = offscreen_control_window()++ control._select_page("design")++ control.window.setFrame_display_(((100000, 100000), (1900, 900)), False)++ settle(control.window)++ self.assertAlmostEqual(control.tick_steps_select.view.frame().size.width, 360, delta=1)++ self.assertFalse(control.tick_steps_pair.field_owner.stacked)++++ def test_native_cursor_resets_do_not_stall_scrolling(self):++ control = offscreen_control_window()++ control._select_page("design")++ def walk(view):++ yield view++ for child in view.subviews():++ yield from walk(child)++ controls = [view for view in walk(control.pages["design"])++ if isinstance(view, widgets.Pressable)]++ started = time.perf_counter()++ for _ in range(5):++ for view in controls:++ view.resetCursorRects()++ elapsed = (time.perf_counter() - started) * 1000++ self.assertLess(elapsed, 20, f"five cursor resets: {elapsed:.3f} ms")++++ def test_scroll_changes_no_layout_and_bottom_content_clears_footer(self):++ with mock.patch.object(widgets, "stack", measured_stack):++ control = offscreen_control_window()++ control._select_page("design")++ settle(control.window)++ scroll = control.pages["design"]++ clip = scroll.contentView()++ page = scroll.documentView()++ body = page.subviews()[0]++ maximum = page.frame().size.height - clip.bounds().size.height++ LayoutStack.passes = []++ for index in range(21):++ clip.scrollToPoint_((0, maximum * index / 20))++ scroll.reflectScrolledClipView_(clip)++ control.window.contentView().layoutSubtreeIfNeeded()++ self.assertEqual(LayoutStack.passes, [])++ last = body.arrangedSubviews()[-1].convertRect_toView_(body.arrangedSubviews()[-1].bounds(), clip)++ self.assertLessEqual(last.origin.y + last.size.height, clip.bounds().origin.y + clip.bounds().size.height - 20)++ content = control.window.contentView()++ viewport = scroll.convertRect_toView_(scroll.bounds(), content)++ footer = control.message_label.view.convertRect_toView_(control.message_label.view.bounds(), content)++ self.assertGreater(viewport.origin.y, footer.origin.y + footer.size.height)++ self.assertFalse(scroll.hasHorizontalScroller())++++++if __name__ == "__main__":++ unittest.main()diff --cc mac_app/tests/test_design_tiles.pyindex 0000000,0000000..0e5f4f1new file mode 100644--- /dev/null+++ b/mac_app/tests/test_design_tiles.py@@@ -1,0 -1,0 +1,91 @@@++"""Measure Design tile states without ordering a window."""++++import unittest++++from mac_app.tests.design_offscreen import offscreen_control_window, settle, tiles++from mac_app.tests.test_design_offscreen import raster, accent_pixels_near_top_edge++import theme++++++def luminance(colour):++ colour = colour.colorUsingColorSpace_(theme.AppKit.NSColorSpace.deviceRGBColorSpace())++ rgb = [colour.redComponent(), colour.greenComponent(), colour.blueComponent()]++ linear = [x / 12.92 if x <= .04045 else ((x + .055) / 1.055) ** 2.4 for x in rgb]++ return sum(x * weight for x, weight in zip(linear, (.2126, .7152, .0722)))++++++class DesignTileMeasurements(unittest.TestCase):++ def test_hover_background_brightens_in_both_appearances(self):++ control = offscreen_control_window()++ tile = control.glow_style_select.rows[0].tiles[1][1]++ previous = theme.is_dark()++ try:++ for dark in (True, False):++ theme.set_dark(dark)++ tile.set_tile_state(selected=False, hovered=False)++ rest = theme.AppKit.NSColor.colorWithCGColor_(tile.layer().backgroundColor())++ tile.set_tile_state(hovered=True)++ hovered = theme.AppKit.NSColor.colorWithCGColor_(tile.layer().backgroundColor())++ with self.subTest(dark=dark):++ self.assertGreater(luminance(hovered), luminance(rest))++ theme.set_dark(not dark)++ theme.repaint(tile)++ switched = theme.AppKit.NSColor.colorWithCGColor_(tile.layer().backgroundColor())++ border = theme.AppKit.NSColor.colorWithCGColor_(tile.layer().borderColor())++ with self.subTest(switched_to_dark=not dark):++ self.assertGreater(luminance(switched), luminance(theme.colour("ground")))++ self.assertAlmostEqual(border.alphaComponent(), .18)++ finally:++ theme.set_dark(previous)++++ def test_hover_has_no_accent_and_selection_has_thicker_ring(self):++ control = offscreen_control_window()++ control._select_page("design")++ settle(control.window)++ control.glow_style_select.value = "glow"++ selected, hovered = [item[1] for item in control.glow_style_select.rows[0].tiles[:2]]++ before = tiles(control)++ hovered._tile_hover_owner.mouseEntered_(None)++ self.assertEqual(accent_pixels_near_top_edge(hovered), 0)++ self.assertGreater(accent_pixels_near_top_edge(selected), 0)++ rep = raster(selected)++ x = rep.pixelsWide() // 2++ thickness = sum(rep.colorAtX_y_(x, y).blueComponent() -++ rep.colorAtX_y_(x, y).redComponent() > .18 for y in range(8))++ self.assertGreaterEqual(thickness, 2, f"selected ring: {thickness} pixels")++ self.assertEqual(tiles(control), before)++ hovered._tile_hover_owner.mouseExited_(None)++++ def test_preview_hint_uses_secondary_ink_with_readable_contrast(self):++ control = offscreen_control_window()++ hint = control.style_preview_hint++ self.assertEqual(hint.view.stringValue(), "Hover to preview")++ self.assertEqual(hint.ink, "ink_2")++ for dark in (True, False):++ theme.set_dark(dark)++ a, b = sorted((luminance(theme.colour(hint.ink)), luminance(theme.colour("panel"))))++ self.assertGreaterEqual((b + .05) / (a + .05), 4.5)++++ def test_geometry_is_unchanged_by_hover_or_selection_at_every_width(self):++ control = offscreen_control_window()++ control._select_page("design")++ for width in (900, 1200, 1500, 1900):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ settle(control.window)++ baseline = tiles(control)++ for family in control.glow_style_select.rows:++ frames = [tile.convertRect_toView_(tile.bounds(), family.view) for _, tile, _ in family.tiles]++ self.assertLessEqual(max(f.size.height for f in frames) - min(f.size.height for f in frames), 1)++ self.assertLessEqual(max(f.origin.y for f in frames) - min(f.origin.y for f in frames), 1)++ hover = control.glow_style_select.rows[0].tiles[1][1]._tile_hover_owner++ hover.mouseEntered_(None)++ settle(control.window)++ self.assertEqual(tiles(control), baseline)++ hover.mouseExited_(None)++ control.glow_style_select.value = "beam"++ settle(control.window)++ self.assertEqual(tiles(control), baseline)++++++if __name__ == "__main__":++ unittest.main()diff --cc mac_app/tests/test_effect_parity.pyindex 0000000,0000000..4d5b26bnew file mode 100644--- /dev/null+++ b/mac_app/tests/test_effect_parity.py@@@ -1,0 -1,0 +1,89 @@@++import json++import sys++import unittest++import zlib++from pathlib import Path++from zipfile import ZipFile++++ROOT = Path(__file__).resolve().parents[2]++sys.path.insert(0, str(ROOT))++sys.path.insert(0, str(ROOT / "mac_app"))++++from core.tests import render_effect_parity as parity++++parity.SCALE = 2.0++REFERENCE = Path(__file__).parent / "fixtures" / "effects_parity" / "qt_reference_frames.zip"++++++def effect_region(rgba, width, height):++ left = round((800 - 150) * parity.SCALE)++ right = round((800 + 150) * parity.SCALE)++ stride = width * 4++ return b"".join(rgba[row * stride + left * 4:row * stride + right * 4]++ for row in range(height))++++++def pixel_difference(actual, expected):++ total = over_32 = maximum = 0++ pixels = len(actual) // 4++ for offset in range(0, len(actual), 4):++ difference = max(abs(actual[offset + channel] - expected[offset + channel])++ for channel in range(4))++ total += difference++ over_32 += difference > 32++ maximum = max(maximum, difference)++ return total / pixels, maximum, over_32 / pixels++++++class MacEffectParityTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ cls.references = ZipFile(REFERENCE)++ cls.manifest = json.loads(cls.references.read("manifest.json"))++++ @classmethod++ def tearDownClass(cls):++ cls.references.close()++++ def test_each_effect_matches_its_windows_reference_frame(self):++ for _direction, effect_id, pack_id in parity.catalogue():++ if effect_id == "beam":++ continue++ for dark in (True, False):++ mode = "dark" if dark else "light"++ with self.subTest(effect=effect_id, mode=mode):++ width, height, actual = parity.frame(effect_id, pack_id, 1.78, dark=dark)++ expected = zlib.decompress(++ self.references.read(f"{effect_id}-{mode}-push85.rgba.z")++ )++ mean, maximum, large_pixel_share = pixel_difference(++ effect_region(actual, width, height), effect_region(expected, width, height)++ )++ self.assertLessEqual(mean, 0.5, f"mean pixel difference {mean:.3f}")++ self.assertLessEqual(large_pixel_share, 0.001,++ f"pixels differing by over 32 levels: {large_pixel_share:.4%}")++ self.assertLessEqual(maximum, 100, f"maximum pixel difference {maximum}")++++ def test_beam_edge_alpha_profile_matches_windows_across_every_stage(self):++ scene_width, scene_height = parity.effects.preview_size("edge")++ width, height = round(scene_width * parity.SCALE), round(scene_height * parity.SCALE)++ edge, radius = round(800 * parity.SCALE), round(40 * parity.SCALE)++ start = edge - radius++++ for dark in (True, False):++ mode = "dark" if dark else "light"++ for t, stage in zip(parity.TIMES, parity.STAGES):++ with self.subTest(mode=mode, stage=stage):++ _width, _height, actual = parity.frame("beam", "signal", t, dark=dark, transparent=True)++ expected = zlib.decompress(++ self.references.read(f"beam-{mode}-{stage}-alpha.rgba.z")++ )++ for x in range(start, edge + 1):++ actual_alpha = sum(actual[(y * width + x) * 4 + 3] for y in range(height)) / height++ expected_alpha = sum(expected[(y * width + x) * 4 + 3] for y in range(height)) / height++ self.assertLessEqual(abs(actual_alpha - expected_alpha), 3.0,++ f"Beam alpha differs at x={x} on {mode} {stage}")++++++if __name__ == "__main__":++ unittest.main()diff --cc mac_app/tests/test_follow_banner.pyindex 0000000,0000000..1dc4d07new file mode 100644--- /dev/null+++ b/mac_app/tests/test_follow_banner.py@@@ -1,0 -1,0 +1,57 @@@++"""The follow banner at every width: its words never break mid-word and Stop following keeps its size."""++import unittest++from unittest import mock++++from mac_app.tests.design_offscreen import AppKit, kvm_bridge_app, offscreen_control_window, settle++++PEER = "b" * 32++WIDTHS = (320, 426, 640, 900, 1440, 1920)++++++def follow(control):++ peer = {++ "id": PEER, "name": "Windows workstation", "platform": "windows", "token": "synthetic",++ "host": "192.0.2.30", "port": 24820, "hw": "", "send": True,++ "allow_drive": True, "side": "right", "side_set_at": 100, "side_by": PEER,++ "paired_with": [], "paired_at": 1, "linked": True, "from_1_4": False,++ }++ control.settings_store._cache["peers"] = [peer]++ control.controller.book.data["peers"] = [peer]++ control.controller.cfg.design_follow_peer = PEER++ control.controller.cfg.same_on_both = False++ control._refresh_design_follow()++++++class FollowBannerTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ kvm_bridge_app.theme.init_fonts()++ cls.control = offscreen_control_window()++ follow(cls.control)++ cls.control._select_page("design")++++ def test_text_keeps_whole_words_and_button_its_natural_size(self):++ control = self.control++ label, button = control.follow_banner_label.view, control.stop_follow_button.view++ words = control.follow_banner_label.text.split()++ for width in WIDTHS:++ with self.subTest(width=width):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ for _ in range(3):++ settle(control.window)++ self.assertFalse(control.follow_banner.isHidden())++ column = label.bounds().size.width++ attrs = control.follow_banner_label.view.attributedStringValue()++ widest = max(++ AppKit.NSAttributedString.alloc().initWithString_attributes_(++ word, attrs.attributesAtIndex_effectiveRange_(0, None)[0]).size().width++ for word in words)++ self.assertGreaterEqual(column, widest, "a word is wider than its column")++ natural = control.stop_follow_button.width.constant()++ self.assertAlmostEqual(button.frame().size.width, natural, delta=1)++ self.assertAlmostEqual(button.frame().size.height, 30, delta=1)++ self.assertGreater(label.frame().size.height, 0)++++++if __name__ == "__main__":++ unittest.main()diff --cc mac_app/tests/test_ignored_inputs.pyindex 1e12aaa,673301a..517643e--- a/mac_app/tests/test_ignored_inputs.py+++ b/mac_app/tests/test_ignored_inputs.py@@@ -120,10 -114,10 +120,33 @@@ class TapTests(unittest.TestCase)self.tap(FakeQuartz.kCGEventKeyDown, key_event(KEY_F13))self.configure([ignored.key(KEY_F13)])self.controller._return_local()- self.controller.redirecting = True+ redirect_to(self.controller)+ up = key_event(KEY_F13)+ self.assertIs(self.tap(FakeQuartz.kCGEventKeyUp, up), up)+++ def test_ignored_key_kept_here_stays_local_after_return_and_setting_change(self):++ down = key_event(KEY_F13)++ self.assertIs(self.tap(FakeQuartz.kCGEventKeyDown, down), down)++ self.controller._return_local()++ self.configure([])++ redirect_to(self.controller)+ up = key_event(KEY_F13)+ self.assertIs(self.tap(FakeQuartz.kCGEventKeyUp, up), up)++ self.assertEqual(self.sent(), [])++++ def test_local_release_after_return_clears_the_kept_key_for_its_next_press(self):++ self.tap(FakeQuartz.kCGEventKeyDown, key_event(KEY_F13))++ self.controller._return_local()++ self.tap(FakeQuartz.kCGEventKeyUp, key_event(KEY_F13))++ self.configure([])++ redirect_to(self.controller)++ self.assertIsNone(self.tap(FakeQuartz.kCGEventKeyDown, key_event(KEY_F13)))++ self.assertIsNone(self.tap(FakeQuartz.kCGEventKeyUp, key_event(KEY_F13)))++ self.assertEqual(self.sent(), [++ (protocol.MSG_KEYDOWN, {"key": "f13"}),++ (protocol.MSG_KEYUP, {"key": "f13"}),++ ])+class SettingsTests(unittest.TestCase):def test_the_list_survives_a_save_and_a_load(self):diff --cc mac_app/tests/test_mac_pairing.pyindex 8091708,0000000..89184f9mode 100644,000000..100644--- a/mac_app/tests/test_mac_pairing.py+++ b/mac_app/tests/test_mac_pairing.py@@@ -1,91 -1,0 +1,90 @@@+"""The Mac's settings store behind a real PairingService, both ways, over loopback: the store and+peers the app hands the service are the ones the pairing is checked and kept in."""++import json+import logging- import socket+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++import bridge+import settings_store+from bridge_fakes import PAIRED_TOKEN+from core import pairing- from core.tests.test_pairing_service import Machine, free_port, wait_until++from core.tests.test_pairing_service import Machine, wait_until+from core.tests.test_pairing_v3 import entry++PC_ID = bytes(range(101, 117))+MAC_ID = bytes(range(1, 17))+++class MacPairingTests(unittest.TestCase):+ 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="127.0.0.1", auth_token=PAIRED_TOKEN, pc_name="Old PC")+ path.write_text(json.dumps(raw))+ self.store = settings_store.SettingsStore(path)+ self.store.load()+ self.book, self.identity = bridge.links_from_store(self.store, "1.5.0")+ self.paired = []- udp, tcp = free_port(socket.SOCK_DGRAM), free_port(socket.SOCK_STREAM)- self.tcp_port = tcp+ ident = self.identity()+ logger = logging.getLogger("test-mac-pairing")+ logger.handlers = [logging.NullHandler()]+ self.service = pairing.PairingService(+ ident["name"], bytes(ident["id"]), ident["platform"], lambda: 24820, self.book.peers, self.store.add_peer,- on_paired=self.paired.append, logger=logger, bind_port=udp, tcp_port=tcp,- announce_to=("127.0.0.1", free_port(socket.SOCK_DGRAM)),++ on_paired=self.paired.append, logger=logger, bind_port=0, tcp_port=0,++ announce_to=("127.0.0.1", 0),+ )+ self.service.start()+ self.addCleanup(self.service.stop)- self.pc = Machine(self, "Desk PC", PC_ID, "windows")++ self.assertTrue(wait_until(lambda: self.service.listening_port is not None))++ self.pc = Machine(self, "Desk PC", PC_ID, "windows", peer_udp=self.service.listening_port)++ self.service.announce_to = ("127.0.0.1", self.pc.udp_port)++ def test_a_pairing_this_mac_enters_replaces_the_1_4_entry_at_that_address_in_the_store(self):+ before = self.store.current()["peers"][0]+ self.assertTrue(before["from_1_4"])+ code = self.pc.service.begin_pairing()+ saved = self.service.pair_by_address("127.0.0.1", code, port=self.pc.tcp_port)+ peers = self.store.current()["peers"]+ self.assertEqual([peer["token"] for peer in peers], [saved["token"]])+ self.assertEqual((peers[0]["name"], peers[0]["platform"]), ("Desk PC", "windows"))+ self.assertEqual(self.store.load().auth_token, saved["token"])+ # The machine at the 1.4.x entry's address on its platform takes over its side and zones.+ zones = self.store.current()["zones"]+ self.assertTrue(zones)+ self.assertEqual({zone["peer"] for zone in zones}, {peers[0]["id"]})+ self.assertEqual((peers[0]["side"], peers[0]["side_set_at"]), (before["side"], before["side_set_at"]))+ self.assertTrue(wait_until(lambda: self.pc.paired))++ def test_a_pairing_this_mac_hosts_is_stored_after_the_machines_it_has(self):+ # A 1.4.x entry at the requester's own address would be replaced by it; this one is elsewhere.+ settings = self.store.current()+ settings["peers"][0]["host"] = "192.0.2.20"+ self.store.save_settings(settings)+ code = self.service.begin_pairing()- saved = self.pc.service.pair_by_address("127.0.0.1", code, port=self.tcp_port)++ saved = self.pc.service.pair_by_address("127.0.0.1", code, port=self.service.tcp_port)+ self.assertTrue(wait_until(lambda: self.paired))+ peers = self.store.current()["peers"]+ self.assertEqual([peer["token"] for peer in peers], [PAIRED_TOKEN, saved["token"]])+ self.assertEqual(self.store.load().auth_token, PAIRED_TOKEN)+ self.assertEqual(self.service.outcome, "paired")++ def test_a_machine_already_paired_is_refused_by_this_mac_and_the_store_is_untouched(self):+ self.store.add_peer({**settings_store.PEER_DEFAULTS, **entry(PC_ID, name="Desk PC", paired_at=1_700_000_000), "port": 24820, "host": "192.0.2.77"})+ before = self.store.current()["peers"]+ code = self.pc.service.begin_pairing()+ with self.assertRaises(pairing.AlreadyPaired) as caught:+ self.service.pair_by_address("127.0.0.1", code, port=self.pc.tcp_port)+ self.assertEqual(caught.exception.entry["name"], "Desk PC")+ self.assertEqual(self.store.current()["peers"], before)+++if __name__ == "__main__":+ unittest.main()diff --cc mac_app/tests/test_machines_panel.pyindex 5a7f30f,0000000..2b48d02mode 100644,000000..100644--- a/mac_app/tests/test_machines_panel.py+++ b/mac_app/tests/test_machines_panel.py@@@ -1,719 -1,0 +1,760 @@@+"""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 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_while_none_is_paired_and_follow_the_controls_after(self):++ 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), 3)++ 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):+ 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.code_label.text, "482 913")++ 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())++ 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,+ )- layout = editor.layoutManager()- glyph_range = layout.glyphRangeForCharacterRange_actualCharacterRange_((0, 1), None)[0]- glyph = layout.boundingRectForGlyphRange_inTextContainer_(glyph_range, editor.textContainer())- offset = glyph.origin.x + glyph.size.width / 2 - editor.bounds().size.width / 2- self.assertLessEqual(abs(offset), 0.3, f"the active field editor draws the digit off-centre: {offset}")+ 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 = []- rows = range(int(4 * scale), int((bounds.size.height - 4) * scale), 2)+ for control in boxes.fields:+ box = control.superview()+ frame = box.convertRect_toView_(box.bounds(), view)- # Inside the box's border and corner, on its own ground.- first, last = int((frame.origin.x + 4) * scale), int((frame.origin.x + frame.size.width - 4) * scale)- ground = level(first, int(bounds.size.height * scale / 2))- inked = [x for x in range(first, last) if any(abs(level(x, y) - ground) > 0.6 for y in rows)]++ # 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 = (inked[0] + inked[-1] + 1) / 2 / scale- offsets.append(round(ink - (frame.origin.x + frame.size.width / 2), 2))++ 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()- for offset in self.ink_offsets():- self.assertLessEqual(abs(offset), 0.3, f"digits sit off the middle of their boxes: {self.ink_offsets()}")++ 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/tests/test_notch_beam.pyindex a5dbc13,a5dbc13..c50a9ff--- a/mac_app/tests/test_notch_beam.py+++ b/mac_app/tests/test_notch_beam.py@@@ -65,8 -65,8 +65,8 @@@ class PaletteTest(unittest.TestCase)import crossingimport tokens-- self.assertEqual(crossing.GLOW_COLOURS, tuple(tokens.PALETTES))-- for name in crossing.GLOW_COLOURS:++ self.assertEqual(set(crossing.GLOW_COLOURS) | {'aurora'}, set(tokens.PALETTES))++ for name in tokens.PALETTES:with self.subTest(colour=name):self.assertGreaterEqual(len(notch_beam.palette_colours(name)), 2)closed = notch_beam.palette_colours("colourful", closed=True)diff --cc mac_app/tests/test_notices_mac.pyindex 13faad9,0000000..3d00d83mode 100644,000000..100644--- a/mac_app/tests/test_notices_mac.py+++ b/mac_app/tests/test_notices_mac.py@@@ -1,168 -1,0 +1,187 @@@+"""The Mac's notices go through UNUserNotificationCenter (beta.4 on three machines: a refused crossing+raised one through rumps' NSUserNotificationCenter, deprecated since macOS 11, and nothing showed;+Beamer was never in Notifications settings). Driven against a stand-in framework, so no test asks+this Mac for anything or puts a notification on screen."""++import logging++import sys+import unittest++from pathlib import Path+from unittest import mock+++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+++import rumps++import notices- from kvm_bridge_app import TrayApp++from kvm_bridge_app import TrayApp, _set_tray_title, _tray_item++from core import locale+++class FakeContent:+ def __init__(self):+ self.title = self.body = None+ self.sound = None++ @classmethod+ def alloc(cls):+ return cls()++ def init(self):+ return self++ def setTitle_(self, text):+ self.title = text++ def setBody_(self, text):+ self.body = text++ def setSound_(self, sound):+ self.sound = sound+++class FakeRequest:+ @classmethod+ def requestWithIdentifier_content_trigger_(cls, ident, content, trigger):+ request = cls()+ request.ident, request.content, request.trigger = ident, content, trigger+ return request+++class FakeCenter:+ def __init__(self):+ self.asked = []+ self.added = []+ self.delegate = None++ def setDelegate_(self, delegate):+ self.delegate = delegate++ def requestAuthorizationWithOptions_completionHandler_(self, options, handler):+ self.asked.append(options)+ handler(True, None)++ def addNotificationRequest_withCompletionHandler_(self, request, handler):+ self.added.append(request)+ if handler is not None:+ handler(None)+++class FakeFramework:+ UNAuthorizationOptionAlert = 1 << 2+ UNAuthorizationOptionSound = 1 << 1+ UNNotificationPresentationOptionBanner = 16+ UNNotificationPresentationOptionList = 8+ UNNotificationPresentationOptionSound = 2+ UNMutableNotificationContent = FakeContent+ UNNotificationRequest = FakeRequest++ def __init__(self, center=None, fails=False):+ self.center = center or FakeCenter()+ self.fails = fails++ class Sound:+ @staticmethod+ def defaultSound():+ return "default"++ self.UNNotificationSound = Sound+ framework = self++ class Center:+ @staticmethod+ def currentNotificationCenter():+ if framework.fails:+ # What the real call raises in a process that is not an app bundle (run from source).+ raise RuntimeError("bundleProxyForCurrentProcess is nil")+ return framework.center++ self.UNUserNotificationCenter = Center+++class NoticesTest(unittest.TestCase):+ def setUp(self):+ self.framework = FakeFramework()+ self.notices = notices.Notices(logging.getLogger("test-notices"), framework=lambda: self.framework)++ def test_asking_requests_alerts_and_sound_once(self):+ self.notices.ask()+ self.notices.ask()+ self.assertEqual(self.framework.center.asked,+ [FakeFramework.UNAuthorizationOptionAlert | FakeFramework.UNAuthorizationOptionSound])++ def test_a_notice_shows_while_beamer_is_in_front_too(self):+ # macOS keeps a notice from the app in front out of sight unless its delegate asks to show it,+ # and Beamer's window is usually in front when a crossing is refused from its own page.+ self.notices.ask()+ shown = []+ self.framework.center.delegate.userNotificationCenter_willPresentNotification_withCompletionHandler_(+ self.framework.center, None, shown.append)+ self.assertEqual(shown, [FakeFramework.UNNotificationPresentationOptionBanner+ | FakeFramework.UNNotificationPresentationOptionList+ | FakeFramework.UNNotificationPresentationOptionSound])++ def test_a_notice_is_one_request_with_its_title_body_and_the_default_sound_and_no_trigger(self):+ self.assertTrue(self.notices.post("Can't cross to Laptop-PC", "It is being driven from Desk-PC."))+ self.assertTrue(self.notices.post("Second", "Another."))+ first, second = self.framework.center.added+ self.assertEqual((first.content.title, first.content.body, first.content.sound, first.trigger),+ ("Can't cross to Laptop-PC", "It is being driven from Desk-PC.", "default", None))+ self.assertNotEqual(first.ident, second.ident)+++ def test_us_notice_text_uses_american_spelling(self):++ with mock.patch.object(locale, "is_us_region", return_value=True):++ self.assertTrue(self.notices.post("Cancelled", "Colourful behaviour is a favourite."))++ notice = self.framework.center.added[0].content++ self.assertEqual((notice.title, notice.body),++ ("Canceled", "Colorful behavior is a favorite."))+++ def test_posting_asks_first_when_nothing_has_asked_yet(self):+ self.notices.post("Title", "Body")+ self.assertEqual(len(self.framework.center.asked), 1)++ def test_run_from_source_with_no_bundle_a_notice_is_logged_and_never_raises(self):+ framework = FakeFramework(fails=True)+ quiet = notices.Notices(logging.getLogger("test-notices"), framework=lambda: framework)+ with self.assertLogs("test-notices", level="INFO") as said:+ self.assertFalse(quiet.post("Title", "Body"))+ quiet.ask()+ self.assertTrue(any("Title" in line for line in said.output))++ def test_the_real_framework_is_the_default_and_names_what_the_notices_use(self):+ framework = notices.user_notifications()+ for name in ("UNUserNotificationCenter", "UNMutableNotificationContent", "UNNotificationRequest",+ "UNNotificationSound", "UNAuthorizationOptionAlert", "UNAuthorizationOptionSound"):+ self.assertTrue(hasattr(framework, name), name)+++class _FakeTrayApp:+ _notify_user_main = TrayApp._notify_user_main++ def __init__(self):+ self.logger = logging.getLogger("test-notices-tray")+ self.controller = mock.Mock()+ self.controller.cfg.hide_addresses = True+ self.notices = mock.Mock()+++class TrayNoticeTest(unittest.TestCase):++ def test_tray_menu_titles_use_american_spelling(self):++ with mock.patch.object(locale, "is_us_region", return_value=True):++ item = _tray_item("Minimise", callback=None)++ self.assertEqual(item.title, "Minimize")++ _set_tray_title(item, "Initialising")++ self.assertEqual(item.title, "Initializing")+++ def test_the_tray_app_posts_through_the_notices_not_rumps_with_addresses_hidden_as_set(self):+ fake = _FakeTrayApp()+ with mock.patch.object(rumps, "notification") as old, mock.patch("AppKit.NSBeep"):+ fake._notify_user_main("Can't cross to Bee", "Bee at 192.0.2.30 refused.")+ old.assert_not_called()+ title, body = fake.notices.post.call_args.args+ self.assertEqual(title, "Can't cross to Bee")+ self.assertNotIn("192.0.2.30", body)+++if __name__ == "__main__":+ unittest.main()diff --cc mac_app/tests/test_pages.pyindex 9b57e0f,21d3422..a93ba0c--- a/mac_app/tests/test_pages.py+++ b/mac_app/tests/test_pages.py@@@ -92,24 -88,24 +92,25 @@@ class DesignChoicesTest(unittest.TestCaself.assertEqual(tuple(values), effects.EFFECT_IDS)self.assertEqual(groups[1][1][0][:2], ("skin", "Skin"))-- def test_colours_are_today_then_each_direction_three_packs(self):++ def test_colours_offer_five_per_group_including_mono(self):import crossing- import effects+ from core import effectsgroups = pages.colour_groups(crossing.GLOW_COLOURS)- self.assertEqual(groups[0], ("Light", [(name, name.capitalize()) for name in crossing.GLOW_COLOURS]))- self.assertEqual([group for group, _ in groups[1:]], ["Membrane", "Sparks", "Instrument", "Folio", "Selvedge"])- self.assertEqual(groups[0], ("Classic", [(name, name.capitalize()) for name in crossing.GLOW_COLOURS]))- self.assertEqual([group for group, _ in groups[1:]], ["Membrane", "Sparks", "Instrument"])-- self.assertEqual(tuple(value for _group, choices in groups[1:] for value, _title in choices), effects.PACK_IDS)-- self.assertIn(("sodium", "Sodium"), groups[3][1])++ self.assertEqual([group for group, _ in groups], ['Light', 'Mono', 'Membrane', 'Sparks', 'Instrument', 'Folio', 'Selvedge', 'Bright'])++ self.assertEqual(groups[1][1], [(value, name) for value, (name, _stops) in effects.MONO_PACKS.items()])++ self.assertTrue(all(len(choices) == 5 for group, choices in groups))++ self.assertCountEqual([value for _group, choices in groups[1:] for value, _title in choices], effects.PACK_IDS)++ self.assertIn(("sodium", "Sodium"), groups[4][1])def test_without_the_effects_only_today_is_offered(self):import crossingself.assertIsNone(pages.effects_load_error())- self.assertEqual([group for group, _ in pages.style_groups(False)], ["Classic"])- self.assertEqual([group for group, _ in pages.colour_groups(crossing.GLOW_COLOURS, False)], ["Classic"])+ self.assertEqual([group for group, _ in pages.style_groups(False)], ["Light"])- self.assertEqual([group for group, _ in pages.colour_groups(crossing.GLOW_COLOURS, False)], ["Light"])++ self.assertEqual([group for group, _ in pages.colour_groups(crossing.GLOW_COLOURS, False)], ["Light", "Mono"])from unittest import mock- import effects+ from core import effectswith mock.patch.object(effects, "_load", side_effect=ModuleNotFoundError("fx_ink")):self.assertIsInstance(pages.effects_load_error(), ModuleNotFoundError)@@@ -186,11 -174,11 +187,11 @@@ class CrossingPageRulesTests(unittest.Tdef test_the_crossing_line_gives_the_first_reason_nothing_can_cross(self):line = pages.crossing_state_sentenceself.assertTrue(line(False, False, False, True, False, None).startswith("Not paired yet"))- self.assertTrue(line(True, False, False, True, False, None).startswith("This Mac drives Windows is off"))- self.assertTrue(line(True, True, False, True, False, None).startswith("Not connected to the PC"))+ self.assertTrue(line(True, False, False, True, False, None).startswith("No machine is driven"))+ self.assertTrue(line(True, True, False, True, False, None).startswith("Not connected to any machine"))self.assertEqual(line(True, True, True, False, False, None), "Only the shortcut is switched on; there is nothing to pause.")-- self.assertTrue(line(True, True, True, True, True, None).startswith("Paused."))- self.assertTrue(line(True, True, True, True, False, "Keynote").startswith("Off while Keynote is full screen"))++ self.assertTrue(line(True, True, True, True, True, None).startswith("Pauses pointer crossing"))+ self.assertEqual(line(True, True, True, True, False, "Keynote"), "Held: an app is full screen.")self.assertEqual(line(True, True, True, True, False, None), "On. Pause it to lean on an edge without switching.")def test_a_reason_shows_even_when_only_the_shortcut_is_on(self):diff --cc mac_app/tests/test_pairing.pyindex c0afd6d,4966479..2c2c0d3--- a/mac_app/tests/test_pairing.py+++ b/mac_app/tests/test_pairing.py@@@ -22,14 -22,14 +22,6 @@@ def quiet_logger()return logger--def free_udp_port():-- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)-- sock.bind(("127.0.0.1", 0))-- port = sock.getsockname()[1]-- sock.close()-- return port----def wait_until(predicate, timeout=5.0):deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:@@@ -44,22 -51,22 +36,27 @@@ class LoopbackTests(unittest.TestCase)replaced so nothing leaves this machine."""def setUp(self):-- self.pc_port = free_udp_port()-- self.mac_port = free_udp_port()++ self.pc_port = 0++ self.mac_port = 0self.paired = []self.announcer = Announcer(lambda: 51820,lambda token, name, address: self.paired.append((token, name, address)),logger=quiet_logger(),-- bind_port=self.pc_port,-- announce_to=("127.0.0.1", self.mac_port),++ bind_port=0,++ announce_to=("127.0.0.1", 0),name="TEST-PC",)-- self.discovery = Discovery(logger=quiet_logger(), bind_port=self.mac_port)++ self.discovery = Discovery(logger=quiet_logger(), bind_port=0)self.discovery.start()self.announcer.start()self.addCleanup(self.announcer.stop)self.addCleanup(self.discovery.stop)++ self.assertTrue(wait_until(lambda: self.announcer.listening_port is not None))++ self.assertTrue(wait_until(lambda: self.discovery.listening_port is not None))++ self.pc_port = self.announcer.listening_port++ self.mac_port = self.discovery.listening_port++ self.announcer.announce_to = ("127.0.0.1", self.mac_port)def test_discovers_pairs_and_stores_one_token_each_side(self):self.assertTrue(wait_until(lambda: self.discovery.pcs()))@@@ -169,10 -176,10 +166,10 @@@ class ImpostorTests(unittest.TestCase)self.impostor.bind(("127.0.0.1", 0))self.impostor.settimeout(5.0)self.addCleanup(self.impostor.close)-- self.discovery = Discovery(logger=quiet_logger(), bind_port=free_udp_port())++ self.discovery = Discovery(logger=quiet_logger(), bind_port=0)self.discovery.start()self.addCleanup(self.discovery.stop)-- self.assertTrue(wait_until(lambda: self.discovery._sock is not None))++ self.assertTrue(wait_until(lambda: self.discovery.listening_port is not None))self.real = PairingHost(name="REAL-PC")self.code = self.real.begin()self.pc = {@@@ -262,22 -269,22 +259,24 @@@ class FindTests(unittest.TestCase)"""A PC whose beacons never reach the Mac, found by its address instead."""def setUp(self):-- self.pc_port = free_udp_port()-- self.mac_port = free_udp_port()self.paired = []self.announcer = Announcer(lambda: 51820,lambda token, name, address: self.paired.append((token, name, address)),logger=quiet_logger(),-- bind_port=self.pc_port,-- announce_to=("127.0.0.1", free_udp_port()),++ bind_port=0,++ announce_to=("127.0.0.1", 0),name="FAR-PC",)-- self.discovery = Discovery(logger=quiet_logger(), bind_port=self.mac_port)++ self.discovery = Discovery(logger=quiet_logger(), bind_port=0)self.discovery.start()self.announcer.start()self.addCleanup(self.announcer.stop)self.addCleanup(self.discovery.stop)++ self.assertTrue(wait_until(lambda: self.announcer.listening_port is not None))++ self.assertTrue(wait_until(lambda: self.discovery.listening_port is not None))++ self.pc_port = self.announcer.listening_port++ self.mac_port = self.discovery.listening_portdef test_a_pc_no_beacon_reaches_is_found_by_address_and_pairs(self):self.assertFalse(wait_until(lambda: self.discovery.pcs(), timeout=0.6))@@@ -298,7 -305,7 +297,7 @@@def test_a_name_that_never_resolves_does_not_hold_up_beacons(self):# The beacon below is sent once, so the loop must have its socket before it goes.-- self.assertTrue(wait_until(lambda: self.discovery._sock is not None))++ self.assertTrue(wait_until(lambda: self.discovery.listening_port is not None))resolving = threading.Event()real = socket.getaddrinfodiff --cc mac_app/tests/test_pairing_announcer_error.pyindex 4ba3795,7916a36..3c8b92b--- a/mac_app/tests/test_pairing_announcer_error.py+++ b/mac_app/tests/test_pairing_announcer_error.py@@@ -31,6 -27,6 +31,9 @@@ class _ScriptedSocketself.sent += 1return len(data)++ def getsockname(self):++ return "0.0.0.0", 24821++def recvfrom(self, bufsize):self.calls += 1if self.script:diff --cc mac_app/tests/test_pairing_pixels.pyindex 0000000,0000000..02f426bnew file mode 100644--- /dev/null+++ b/mac_app/tests/test_pairing_pixels.py@@@ -1,0 -1,0 +1,289 @@@++"""Real AppKit pairing views, cached without ordering a window onto the desktop."""++++import json++import os++import sys++import unittest++from pathlib import Path++from types import SimpleNamespace++from unittest import mock++++ROOT = Path(__file__).resolve().parents[2]++sys.path.insert(0, str(ROOT))++sys.path.insert(0, str(ROOT / "mac_app"))++++import AppKit++++import machines++import machines_panel++import kvm_bridge_app++import theme++import widgets++++++def bitmap(view, scale):++ view.layoutSubtreeIfNeeded()++ bounds = view.bounds()++ width, height = round(bounds.size.width), round(bounds.size.height)++ rep = AppKit.NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(++ None, width * scale, height * scale, 8, 4, True, False,++ AppKit.NSCalibratedRGBColorSpace, 0, 0,++ )++ rep.setSize_((width, height))++ view.cacheDisplayInRect_toBitmapImageRep_(bounds, rep)++ return rep++++++def save(rep, path):++ rep.representationUsingType_properties_(AppKit.NSBitmapImageFileTypePNG, {}).writeToFile_atomically_(str(path), True)++++++def colour(rep, x, y):++ c = rep.colorAtX_y_(x, y).colorUsingColorSpace_(AppKit.NSColorSpace.sRGBColorSpace())++ return c.redComponent(), c.greenComponent(), c.blueComponent()++++++def offsets(rep, boxes, scale):++ measured = []++ for field in boxes.fields:++ container = field.superview()++ rect = container.convertRect_toView_(container.bounds(), boxes.view)++ # Bitmap rows run top-down; NSStackView's coordinates run bottom-up.++ x, y, w, h = rect.origin.x, boxes.view.bounds().size.height - rect.origin.y - rect.size.height, rect.size.width, rect.size.height++ left, right = round((x + 4) * scale), round((x + w - 4) * scale)++ top, bottom = round((y + 4) * scale), round((y + h - 4) * scale)++ foreground = theme.rgb(theme.T["ink"])++ ink = [(px, py) for py in range(top, bottom) for px in range(left, right)++ if sum(abs(a - b) for a, b in zip(colour(rep, px, py), foreground)) < 0.45]++ if not ink:++ measured.append(None)++ continue++ lx, rx = min(p[0] for p in ink), max(p[0] for p in ink) + 1++ ty, by = min(p[1] for p in ink), max(p[1] for p in ink) + 1++ measured.append({"digit": field.stringValue(), "dx": round((lx + rx) / 2 - (x + w / 2) * scale, 3),++ "dy": round((ty + by) / 2 - (y + h / 2) * scale, 3),++ "ink": [lx, ty, rx, by], "inner": [(x + 1) * scale, (y + 1) * scale, (x + w - 1) * scale, (y + h - 1) * scale]})++ return measured++++++def atlas(reps, path, columns=1):++ width, height = reps[0].pixelsWide(), reps[0].pixelsHigh()++ rows = (len(reps) + columns - 1) // columns++ combined = AppKit.NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(++ None, width * columns, height * rows, 8, 4, True, False, AppKit.NSCalibratedRGBColorSpace, 0, 0)++ AppKit.NSGraphicsContext.saveGraphicsState()++ AppKit.NSGraphicsContext.setCurrentContext_(AppKit.NSGraphicsContext.graphicsContextWithBitmapImageRep_(combined))++ for index, rep in enumerate(reps):++ image = AppKit.NSImage.alloc().initWithSize_(rep.size())++ image.addRepresentation_(rep)++ image.drawInRect_fromRect_operation_fraction_(((index % columns * width, (rows - index // columns - 1) * height), (width, height)),++ AppKit.NSZeroRect, AppKit.NSCompositingOperationCopy, 1)++ AppKit.NSGraphicsContext.restoreGraphicsState()++ save(combined, path)++++++class PairingPixelsTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ AppKit.NSApplication.sharedApplication()++ theme.init_fonts()++ cls.renders = Path(os.environ.get("BEAMER_PAIRUI_RENDERS", ROOT / "renders"))++ cls.renders.mkdir(parents=True, exist_ok=True)++++ def setUp(self):++ self.window = AppKit.NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(++ AppKit.NSMakeRect(0, 0, 720, 920), AppKit.NSWindowStyleMaskBorderless, AppKit.NSBackingStoreBuffered, False)++ self.window.setReleasedWhenClosed_(False)++ self.window.setAppearance_(theme.appearance_named(True))++ owner = SimpleNamespace(window=self.window, _shown=lambda text: text)++ controller = SimpleNamespace(cfg=SimpleNamespace(hide_addresses=False))++ self.panel = machines_panel.MachinesPanel(controller, mock.Mock(), mock.Mock(), owner)++ self.panel.rows = lambda: []++ self.panel.service = SimpleNamespace(code=None, machines=lambda: [], seconds_left=60, outcome=None,++ known=None, error=None, tcp_error=None, tcp_port=24821,++ qr_text=lambda address: None)++ self.address_patch = mock.patch.object(machines_panel.pairing, "pairing_address", return_value="192.0.2.20")++ self.address_patch.start()++ self.addCleanup(self.address_patch.stop)++ self.body = widgets.stack(spacing=20)++ widgets.add(self.body, self.panel.machines_module.view)++ widgets.add(self.body, self.panel.sheet.view)++ self.window.contentView().addSubview_(self.body)++ content = self.window.contentView()++ AppKit.NSLayoutConstraint.activateConstraints_([++ self.body.topAnchor().constraintEqualToAnchor_constant_(content.topAnchor(), 20),++ self.body.leadingAnchor().constraintEqualToAnchor_constant_(content.leadingAnchor(), 20),++ self.body.trailingAnchor().constraintEqualToAnchor_constant_(content.trailingAnchor(), -20),++ self.body.bottomAnchor().constraintLessThanOrEqualToAnchor_constant_(content.bottomAnchor(), -20),++ ])++ self.panel.refresh()++ self.window.contentView().layoutSubtreeIfNeeded()++++ def tearDown(self):++ self.window.makeFirstResponder_(None)++ self.window.close()++++ def test_digits_are_centred_from_rendered_pixels_at_both_scales(self):++ report = []++ failures = []++ for scale in (1, 2):++ for state in ("typed", "shown"):++ boxes = self.panel.code_boxes if state == "typed" else self.panel.shown_code_boxes++ if state == "shown":++ self.panel.service.code = "012345"++ self.panel.refresh()++ else:++ self.panel.service.code = None++ self.panel.refresh()++ strips = []++ for digit in "0123456789":++ self.window.makeFirstResponder_(None)++ if state == "typed":++ boxes.clear()++ boxes.focus(self.window)++ boxes.fields[0].selectText_(None)++ self.window.firstResponder().insertText_(digit * 6)++ self.assertEqual(boxes.value, digit * 6)++ editor = boxes.fields[-1].currentEditor()++ self.assertIsNotNone(editor)++ editor.setSelectedRange_((1, 0))++ editor.setInsertionPointColor_(AppKit.NSColor.clearColor())++ else:++ self.panel.service.code = digit * 6++ self.panel.refresh()++ self.window.contentView().layoutSubtreeIfNeeded()++ rep = bitmap(boxes.view, scale)++ strips.append(rep)++ rows = offsets(rep, boxes, scale)++ report.append({"scale": scale, "state": state, "digit": digit, "boxes": rows})++ for index, row in enumerate(rows):++ if row is None or abs(row["dx"]) > 1 or abs(row["dy"]) > 1:++ failures.append((scale, state, digit, index, row))++ atlas(strips, self.renders / f"mac-digits-{state}-{scale}x.png")++ if state == "typed":++ self.window.makeFirstResponder_(None)++ for field, digit in zip(boxes.fields, "482913"):++ field.setStringValue_(digit)++ save(bitmap(self.panel.sheet.view, scale), self.renders / f"mac-sheet-typed-{scale}x.png")++ (self.renders / "mac-measurements.json").write_text(json.dumps(report, indent=2))++ self.assertEqual(failures, [], f"ink must centre within one physical pixel ({len(failures)} failures): {failures[:6]}")++ self.assertTrue(hasattr(self.panel, "shown_code_boxes"), "the hosted code must use the same six boxes")++++ def test_pairing_action_leads_the_machines_and_uses_primary_style(self):++ panel = self.panel++ for scale in (1, 2):++ save(bitmap(panel.machines_module.view, scale), self.renders / f"mac-machines-empty-{scale}x.png")++ save(bitmap(panel.sheet.view, scale), self.renders / f"mac-sheet-empty-{scale}x.png")++ order = list(panel.machines_module.body.arrangedSubviews())++ self.assertLess(order.index(panel.pair_button.view.superview()), order.index(panel.list))++ self.assertEqual(panel.pair_button.style, "primary")++ self.assertFalse(panel.pair_button.view.isHidden())++ entry = {"token": "synthetic-test-token", "id": "test-pc", "name": "Studio PC", "platform": "windows",++ "host": "192.0.2.30", "port": 24820, "send": True, "allow_drive": True, "linked": True}++ row = machines.row(entry, "Studio PC", live=True, kind="connected", status="", here=False,++ driving=False, inbound=False, has_link=True)++ panel.rows = lambda: [row]++ panel.refresh()++ for scale in (1, 2):++ save(bitmap(panel.machines_module.view, scale), self.renders / f"mac-machines-filled-{scale}x.png")++++ def test_machine_addresses_use_the_reading_face_without_mono_dot_spacing(self):++ panel = self.panel++ panel.service.code = "482913"++ panel.refresh()++ address_font = panel.code_address.view.attributedStringValue().attribute_atIndex_effectiveRange_(++ AppKit.NSFontAttributeName, 0, None)[0]++ entry = {"token": "synthetic-test-token", "id": "test-pc", "name": "Studio PC",++ "platform": "windows", "host": "192.0.2.30", "port": 24820,++ "send": True, "allow_drive": True, "linked": True}++ row = machines.row(entry, "Studio PC", live=True, kind="connected", status="", here=False,++ driving=False, inbound=False, has_link=True)++ rendered = panel._row_view(row)++ machine_address = rendered.subviews()[0].arrangedSubviews()[1]++ machine_font = machine_address.attributedStringValue().attribute_atIndex_effectiveRange_(++ AppKit.NSFontAttributeName, 0, None)[0]++ heard = {"address": "192.0.2.30", "name": "Studio PC", "platform": "windows",++ "pairing": machines_panel.pairing.PAIRING_V3, "pair_id": None}++ panel._heard_row(0, heard, picked=False, shared_name=True)++ heard_row = panel.heard_list.arrangedSubviews()[-1]++ heard_detail = heard_row.subviews()[0].arrangedSubviews()[-1]++ heard_font = heard_detail.attributedStringValue().attribute_atIndex_effectiveRange_(++ AppKit.NSFontAttributeName, 0, None)[0]++ expected = theme.font(theme.TYPE["small"]).fontName()++ self.assertEqual(address_font.fontName(), expected)++ self.assertEqual(machine_font.fontName(), expected)++ self.assertEqual(heard_font.fontName(), expected)++++ def test_pairing_module_leads_overview_with_and_without_existing_machines(self):++ body = widgets.stack()++ for item in (widgets.label("Overview"), widgets.label("Connection status"), widgets.label("Keyboard and pointer"),++ self.panel.machines_module.view, self.panel.sheet.view):++ body.addArrangedSubview_(item)++ owner = SimpleNamespace(_machines_first=None, overview_body=body, panel=self.panel)++ for empty in (False, True, False):++ kvm_bridge_app.ControlWindow._place_machines(owner, empty)++ self.assertEqual(list(body.arrangedSubviews()).index(self.panel.machines_module.view), 1)++++ def test_shown_boxes_are_read_only_and_empty_boxes_draw_no_ink(self):++ boxes = self.panel.code_boxes++ for scale in (1, 2):++ self.assertEqual(offsets(bitmap(boxes.view, scale), boxes, scale), [None] * 6)++ shown = getattr(self.panel, "shown_code_boxes", None)++ self.assertIsNotNone(shown)++ self.panel.service.code = "482913"++ self.panel.service.qr_text = lambda _address: "beamer://pair?host=192.0.2.20&port=24821&code=482913&k=" + "A" * 22++ self.panel.refresh()++ self.assertEqual(shown.value, "482913")++ self.assertTrue(all(not field.isEditable() for field in shown.fields))++ for scale in (1, 2):++ save(bitmap(self.panel.sheet.view, scale), self.renders / f"mac-sheet-shown-{scale}x.png")++++ def test_pairing_dialog_hides_the_qr_and_caption(self):++ self.panel.service.code = "482913"++ self.panel.service.qr_text = lambda _address: "synthetic pairing payload"++ self.panel.refresh()++ self.assertTrue(self.panel.qr_view.isHidden())++ self.assertTrue(self.panel.qr_caption.view.isHidden())++ for scale in (1, 2):++ save(bitmap(self.panel.sheet.view, scale), self.renders / f"mac-pairing-dialog-{scale}x.png")++++ def test_selected_digits_use_the_same_centred_ink_and_restore_shared_editor_style(self):++ boxes = self.panel.code_boxes++ report, failures = [], []++ for scale in (1, 2):++ strips = []++ for digit in "0123456789":++ self.window.makeFirstResponder_(None)++ boxes.clear()++ boxes.focus(self.window)++ boxes.fields[0].selectText_(None)++ self.window.firstResponder().insertText_(digit * 6)++ for index, field in enumerate(boxes.fields):++ self.window.makeFirstResponder_(field)++ editor = field.currentEditor()++ editor.setSelectedRange_((0, 1))++ rep = bitmap(boxes.view, scale)++ strips.append(rep)++ row = offsets(rep, boxes, scale)[index]++ report.append({"scale": scale, "digit": digit, "slot": index, "selected": row})++ if row is None or abs(row["dx"]) > 1 or abs(row["dy"]) > 1:++ failures.append((scale, digit, index, row))++ atlas(strips, self.renders / f"mac-digits-selected-{scale}x.png", columns=6)++ (self.renders / "mac-selected-measurements.json").write_text(json.dumps(report, indent=2))++ self.assertEqual(failures, [], f"selected ink offsets: {failures[:6]}")++ self.window.makeFirstResponder_(self.panel.find_field)++ self.assertNotEqual(self.panel.find_field.currentEditor().selectedTextAttributes()[AppKit.NSForegroundColorAttributeName],++ AppKit.NSColor.clearColor())++++ def test_leaving_an_empty_box_restores_the_shared_editor_without_typing(self):++ for field in self.panel.code_boxes.fields:++ self.window.makeFirstResponder_(field)++ self.assertIsNotNone(field.currentEditor())++ self.window.makeFirstResponder_(self.panel.find_field)++ attributes = self.panel.find_field.currentEditor().selectedTextAttributes()++ self.assertNotEqual(attributes[AppKit.NSForegroundColorAttributeName], AppKit.NSColor.clearColor())++ self.assertIsNone(field.pair_editor)++++++if __name__ == "__main__":++ unittest.main()diff --cc mac_app/tests/test_phone_settings.pyindex 0000000,0000000..ab91a53new file mode 100644--- /dev/null+++ b/mac_app/tests/test_phone_settings.py@@@ -1,0 -1,0 +1,94 @@@++"""Phone settings use synthetic files only; the flat view belongs to a desktop."""++import copy++import json++import tempfile++import unittest++import sys++from dataclasses import replace++from pathlib import Path++++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++++from core import protocol++from settings_store import SettingsStore, SettingsError, PEER_DEFAULTS, config_to_raw++++++def peer(number, port=24820):++ return {**PEER_DEFAULTS, "id": protocol.id_text(bytes([number]) * 16),++ "token": protocol.id_text(bytes([number]) * 32), "name": f"Peer {number}",++ "platform": "ios" if port == 0 else "windows", "port": port,++ "host": "" if port == 0 else "192.0.2.20", "send": port != 0}++++++class PhoneSettingsTests(unittest.TestCase):++ def setUp(self):++ directory = tempfile.TemporaryDirectory()++ self.addCleanup(directory.cleanup)++ self.path = Path(directory.name) / "settings.json"++ self.store = SettingsStore(self.path)++ self.store.load()++++ def test_phones_first_middle_last_and_alone_round_trip(self):++ phone, first, second = peer(1, 0), peer(2), peer(3)++ for peers in ([phone, first, second], [first, phone, second], [first, second, phone], [phone]):++ with self.subTest(order=[p["port"] for p in peers]):++ settings = self.store.current()++ self.store.save_settings({**settings, "peers": copy.deepcopy(peers), "zones": []})++ before = copy.deepcopy(self.store.current()["peers"])++ cfg = self.store.load()++ desktop = next((p for p in peers if p["port"]), None)++ self.assertEqual(cfg.auth_token, desktop["token"] if desktop else "")++ self.assertGreater(cfg.port, 0)++ self.store.save(config_to_raw(replace(cfg, appearance="dark")))++ again = SettingsStore(self.path)++ again.load()++ self.assertEqual(again.current()["peers"], before)++ self.assertFalse(any(z["peer"] == phone["id"] for z in again.current()["zones"]))++++ def test_flat_pairing_replacement_and_clear_preserve_phone_first(self):++ phone, desktop = peer(1, 0), peer(2)++ self.store.save_settings({**self.store.current(), "peers": [phone, desktop], "zones": []})++ raw = config_to_raw(self.store.load())++ self.store.save({**raw, "auth_token": peer(3)["token"]})++ self.assertEqual(self.store.current()["peers"][0], phone)++ self.store.save({**config_to_raw(self.store.load()), "auth_token": ""})++ self.assertEqual(self.store.current()["peers"], [phone])++++ def test_phone_target_fields_are_cleared_but_permissions_are_preserved(self):++ phone = peer(1, 0)++ phone.update(send=True, host="192.0.2.40", hw="aa:bb:cc:dd:ee:ff", side="left",++ side_set_at=1, side_by=phone["id"], jump_key="ctrl+shift+2", allow_drive=False, in_use=False)++ self.store.save_settings({**self.store.current(), "peers": [phone],++ "zones": [{"peer": phone["id"], "kind": "edge"}],++ "design_follow_peer": phone["id"]})++ saved = self.store.current()++ self.assertEqual(saved["zones"], [])++ self.assertEqual(saved["design_follow_peer"], "")++ phone = saved["peers"][0]++ self.assertFalse(phone["send"])++ self.assertFalse(phone["allow_drive"])++ self.assertFalse(phone["in_use"])++ for name in ("host", "hw", "side", "side_by", "jump_key"):++ self.assertEqual(phone[name], "")++ self.assertEqual(phone["side_set_at"], 0)++++ def test_new_legacy_pairing_is_added_beside_phone_without_replacing_it(self):++ phone = peer(1, 0)++ self.store.add_peer(phone)++ legacy = config_to_raw(self.store.load())++ legacy.update(auth_token=peer(2)["token"], host="192.0.2.20")++ self.path.with_name("config.json").write_text(json.dumps(legacy), encoding="utf-8")++ cfg = SettingsStore(self.path).load()++ self.assertEqual(cfg.auth_token, legacy["auth_token"])++ self.assertEqual(self.store.load_settings()["peers"][0], phone)++++ def test_invalid_peer_or_zone_still_raises_a_settings_error(self):++ for field in ("peers", "zones"):++ with self.subTest(field=field), self.assertRaises(SettingsError):++ self.store.save_settings({**self.store.current(), field: [5]})++++ def test_invalid_phone_identity_still_raises_a_settings_error(self):++ for ident in ([], {}):++ with self.subTest(ident=ident), self.assertRaises(SettingsError):++ self.store.save_settings({**self.store.current(), "peers": [{**peer(1, 0), "id": ident}]})diff --cc mac_app/tests/test_phone_ui.pyindex 0000000,0000000..0cb92c5new file mode 100644--- /dev/null+++ b/mac_app/tests/test_phone_ui.py@@@ -1,0 -1,0 +1,120 @@@++"""Phone presentation and targeting, without constructing a window or capturing input."""++import unittest++import sys++import threading++from pathlib import Path++from types import SimpleNamespace++from unittest import mock++++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++sys.path.insert(0, str(Path(__file__).resolve().parent))++++import kvm_bridge_app++import machines++import pages++from machines_panel import MachinesPanel++from core import protocol++from windows_input import WindowsInput++from bridge import KVMController++from wake import WakingController++from settings_store import editable_default_config++from bridge_fakes import FakeQuartz, FakeClipboard, quiet_logger++from fake_link import FakeLink++from mac_app.tests.test_phone_settings import peer++++++class PhoneUiTests(unittest.TestCase):++ def setUp(self):++ self.phone, self.desktop = peer(1, 0), peer(2)++ self.peers = [self.phone, self.desktop]++ self.book = mock.Mock()++ self.book.peers.return_value = self.peers++++ def test_phone_does_not_affect_same_capability_or_receive_settings(self):++ inbound = WindowsInput.__new__(WindowsInput)++ inbound._controller = SimpleNamespace(book=self.book)++ inbound.server = mock.Mock()++ inbound.server.links.return_value = [protocol.read_id(self.phone["id"])]++ inbound.server.caps_of.return_value = []++ inbound.settings_callback = mock.Mock()++ self.assertIsNone(inbound.peer_settings)++ inbound._on_settings(protocol.read_id(self.phone["id"]), {"on": True})++ inbound.settings_callback.assert_not_called()++++ def test_phone_receives_no_settings_even_if_it_advertises_them(self):++ inbound = WindowsInput.__new__(WindowsInput)++ inbound._controller = SimpleNamespace(book=self.book, _peers_up={})++ inbound.server = mock.Mock()++ inbound.server.links.return_value = [protocol.read_id(self.phone["id"])]++ inbound.server.caps_of.return_value = ["settings", "design_sync"]++ self.assertFalse(inbound.send_settings({"on": True}))++ inbound.server.send.assert_not_called()++++ def test_crossing_diagram_and_match_caps_exclude_phone(self):++ window = SimpleNamespace(settings_store=SimpleNamespace(current=lambda: {"peers": self.peers, "zones": []}),++ edge_select=SimpleNamespace(value="right"), part_boxes={},++ corner_select=SimpleNamespace(value="top_right"), chosen_peer=self.desktop["id"],++ _shown=lambda text: text,++ controller=SimpleNamespace(book=self.book, _peers_up={}), windows_input=mock.Mock())++ window.windows_input.server.links.return_value = [protocol.read_id(self.phone["id"])]++ window.windows_input.server.caps_of.return_value = ["settings", "design_sync"]++ found = kvm_bridge_app.ControlWindow._diagram_machines(window, ["edge"])++ self.assertEqual([m["key"] for m in found], [self.desktop["id"]])++ self.assertEqual(kvm_bridge_app.ControlWindow._design_peer_caps(window), {})++++ def test_bulk_send_toggle_excludes_phone(self):++ tray = SimpleNamespace(controller=SimpleNamespace(book=self.book), _switch=mock.Mock())++ kvm_bridge_app.TrayApp.toggle_send_to_windows(tray, None)++ tray._switch.assert_called_once_with([self.desktop["token"]], send=False)++++ def test_phone_controls_show_in_use_and_remove_without_directions(self):++ row = machines.row(self.phone, "Phone", False, "none", "", False, False, False, False)++ panel = SimpleNamespace(removing=None, wide=True, directions_open={row.token})++ import widgets++ in_use = widgets.Switch("In use")++ disclosure = widgets.label("Directions")++ remove = widgets.label("Remove")++ result = MachinesPanel._controls(panel, row, in_use, disclosure,++ widgets.Switch("This Mac drives it"), widgets.Switch("It drives this Mac"), remove)++ self.assertEqual(len(result.arrangedSubviews()), 1)++ views = list(result.arrangedSubviews()[0].arrangedSubviews())++ self.assertIn(in_use.view, views)++ self.assertIn(remove, views)++ self.assertNotIn(disclosure, views)++++ def test_phone_messages_cannot_set_same_or_match(self):++ window = SimpleNamespace(controller=SimpleNamespace(book=self.book), _design_states={})++ kvm_bridge_app.ControlWindow.apply_same(window, {"on": True}, self.phone["id"])++ kvm_bridge_app.ControlWindow._receive_design(window, {"on": True}, self.phone["id"])++ self.assertEqual(window._design_states, {})++++ def test_phone_is_never_dialled_even_with_a_stale_send_switch(self):++ self.phone["send"] = True++ self.book.zones.return_value = []++ controller = KVMController(editable_default_config(), quartz=FakeQuartz,++ clipboard=FakeClipboard(), logger=quiet_logger(), book=self.book,++ link_factory=FakeLink)++ self.addCleanup(controller.stop)++ self.assertNotIn(self.phone["token"], controller.links)++ self.assertIn(self.desktop["token"], controller.links)++++ def test_phone_never_supplies_a_wake_address(self):++ self.phone.update(hw="aa:bb:cc:dd:ee:ff", host="192.0.2.20")++ controller = SimpleNamespace(book=self.book, _memory=None)++ self.assertEqual(WakingController._wake_address(controller, self.phone["id"]), ("", ""))++++ def test_explicit_phone_wake_is_refused_before_starting_a_worker(self):++ controller = SimpleNamespace(book=self.book, _memory=None, _waking=False,++ _wake_lock=threading.Lock(), _awake=lambda peer: False,++ _wake_worker=mock.Mock())++ with mock.patch("wake.threading.Thread") as worker:++ self.assertFalse(WakingController.wake(controller, self.phone["id"]))++ worker.assert_not_called()++++ def test_phone_is_named_and_has_no_menu_target(self):++ for platform, name in (("ios", "iPhone"), ("android", "Android")):++ row = machines.row({**self.phone, "platform": platform}, "Phone", False, "none", "", False, True, True, False)++ self.assertEqual((row.label, row.platform), ("Phone", name))++ self.assertEqual(row.state.word, "Driving this Mac")++ self.assertEqual(pages.send_items([{**self.phone, "send": True}], None, False), [])diff --cc mac_app/tests/test_same_on_both.pyindex 11ed0c3,0000000..6b596fcmode 100644,000000..100644--- a/mac_app/tests/test_same_on_both.py+++ b/mac_app/tests/test_same_on_both.py@@@ -1,353 -1,0 +1,415 @@@+"""Same on all machines in the real window: the Overview switch, a PC's settings arriving, and a+change here going out. Built as test_appearance builds it, never put on screen; the two links'+sends are recorded instead."""++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++AppKit.NSApplication.sharedApplication()++import kvm_bridge_app # noqa: E402+import pages # noqa: E402+import settings_store # noqa: E402+from bridge_fakes import PAIRED_TOKEN # noqa: E402+from core import protocol, settings_sync # noqa: E402+from fake_link import FakeLink, bring_up # noqa: E402+from wake import WakingController # noqa: E402++PEER = protocol.id_text(bytes(range(1, 17)))+LOW = protocol.id_text(bytes(15) + b"\x01")+HIGH = protocol.id_text(b"\xff" * 16)+++def pc_message(on, set_at, by="", **values):+ base = dict(shortcut=False, resistance_px=60,+ block_while_dragging=False, trigger_key="cmd_r", trigger_style="hold", double_tap_ms=400,+ glow_style="beam", glow_colour="ocean", effect_length="long", shortcut_arrival=False,+ shortcut_arrival_style="locator")+ base.update(values)+ return settings_sync.message_data(on, set_at, base, by=by)+++class SameOnBothTests(unittest.TestCase):+ 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)+ raw["crossing"]["hold_full_screen"] = True+ raw["crossing"]["methods"] = ["shortcut", "edge", "notch"]+ path.write_text(json.dumps(raw))+ self.store = settings_store.SettingsStore(path)+ logger = logging.getLogger("test-same-on-both")+ 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_(- WakingController(self.store.load(), logger=logger, link_factory=FakeLink), self.store, logger++ WakingController(self.store.load(), logger=logger, link_factory=FakeLink, book=self.store.book()), self.store, logger+ )+ self.addCleanup(self.window.appearance_watch.stop)+ self.sent = []+ self.sources = []+ self.window.controller.send_settings = lambda data, source=None: self.sent.append(data) or self.sources.append(source) or True+ self.window._show_same()+++ def pair_sources(self, *ids):++ for ident in ids:++ self.store.add_peer({**settings_store.PEER_DEFAULTS, "id": ident, "token": f"test-{ident}",++ "name": "Paired test PC", "host": "192.0.2.20", "platform": "windows",++ "port": protocol.DEFAULT_PORT})+++ def test_off_by_default_with_each_page_its_own(self):+ self.assertFalse(self.window.same_switch.value)+ self.assertEqual(self.window.scope_labels["design"].text, pages.SCOPE["design"])+ self.assertTrue(all(note.view.isHidden() for note in self.window.own_notes))++ def test_full_screen_hold_switch_names_this_macs_edges(self):+ self.assertEqual(self.window.hold_box.words.text, "Hold this Mac's edges while an app on it is full screen")+ def test_this_machines_design_state_is_sent_even_when_same_is_off(self):+ data = self.window.same_state()++ self.assertFalse(data["on"])+ self.assertEqual(set(data["design_sync"]["values"]), set(settings_sync.DESIGN_KEYS))+ self.assertEqual(data["design_sync"]["values"]["effect_size"], "medium")++ def test_a_followed_machine_changes_this_design_and_this_mac_announces_its_own_state(self):++ self.pair_sources(PEER)+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["design_follow_peer"] = PEER+ self.window.controller.apply_settings(self.store.save(raw))+ received = settings_sync.message_data(+ False, 50, by=PEER,+ design_state={"set_at": 100, "by": PEER,+ "values": {"effect_length": "long", "effect_size": "large"}},+ )++ self.window.apply_same(received, peer=PEER)++ self.assertEqual(self.window.controller.cfg.crossing["effect_length"], "long")+ self.assertEqual(self.window.size_select.value, "large")- self.assertEqual((self.window.controller.cfg.design_set_at, self.window.controller.cfg.design_by),- (100, PEER))++ self.assertGreater(self.window.controller.cfg.design_set_at, 100)++ self.assertEqual(self.window.controller.cfg.design_by, self.window.own_id())+ self.assertTrue(self.sent)+ self.assertEqual(self.sent[-1]["design_sync"]["values"]["effect_length"], "long")+ self.assertEqual((self.sent[-1]["design_sync"]["set_at"], self.sent[-1]["design_sync"]["by"]),- (100, PEER))++ (self.window.controller.cfg.design_set_at, self.window.own_id()))++ def test_a_design_state_in_a_malformed_settings_envelope_is_dropped_whole(self):++ self.pair_sources(PEER)+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["design_follow_peer"] = PEER+ self.window.controller.apply_settings(self.store.save(raw))+ state = {"set_at": 100, "by": PEER, "values": {"effect_length": "long"}}++ for outer in ({"on": "no"}, {"set_at": True}, {"by": "not an id"}):+ data = settings_sync.message_data(False, 50, by=PEER, design_state=state)+ data.update(outer)+ self.window.apply_same(data, peer=PEER)++ self.assertEqual(self.window.controller.cfg.crossing["effect_length"], "normal")+ self.assertNotIn(PEER, self.window._design_states)+ self.assertEqual(self.sent, [])++ def test_follow_accepts_the_leaders_next_change_after_this_mac_reannounces(self):++ self.pair_sources(PEER)+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["design_follow_peer"] = PEER+ raw["design_set_at"] = 50+ raw["design_by"] = PEER+ self.window.controller.apply_settings(self.store.save(raw))++ self.window._receive_design(settings_sync.message_data(+ False, 50, by=PEER,+ design_state={"set_at": 100, "by": PEER, "values": {"effect_length": "long"}},+ ), PEER)+ self.window._receive_design(settings_sync.message_data(+ False, 51, by=PEER,+ design_state={"set_at": 101, "by": PEER, "values": {"effect_length": "short"}},+ ), PEER)++ self.assertEqual(self.window.controller.cfg.crossing["effect_length"], "short")- self.assertEqual((self.window.controller.cfg.design_set_at, self.window.controller.cfg.design_by),- (101, PEER))++ self.assertGreater(self.window.controller.cfg.design_set_at, 101)++ self.assertEqual(self.window.controller.cfg.design_by, self.window.own_id())+ self.assertEqual(self.sent[-1]["design_sync"]["values"]["effect_length"], "short")+ self.assertEqual((self.sent[-1]["design_sync"]["set_at"], self.sent[-1]["design_sync"]["by"]),- (101, PEER))++ (self.window.controller.cfg.design_set_at, self.window.own_id()))++ def test_same_on_design_change_is_announced_with_a_new_local_design_stamp(self):++ self.pair_sources(HIGH)+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["same_on_both"] = True+ raw["same_set_at"] = 10+ raw["same_by"] = PEER+ raw["design_set_at"] = 20+ raw["design_by"] = self.window.own_id()+ raw["crossing"]["effect_length"] = "short"+ self.window.controller.apply_settings(self.store.save(raw))+ incoming = settings_sync.message_data(+ True, 11, values={"effect_length": "long"}, by=HIGH,+ design_state={"set_at": 100, "by": HIGH, "values": {"effect_length": "long"}},+ )++ self.window.apply_same(incoming, peer=HIGH)++ cfg = self.window.controller.cfg+ self.assertEqual(cfg.crossing["effect_length"], "long")+ self.assertGreater(cfg.design_set_at, 100)+ self.assertEqual(cfg.design_by, self.window.own_id())+ self.assertEqual(self.sent[-1]["design_sync"]["set_at"], cfg.design_set_at)+ self.assertNotEqual(self.sent[-1]["design_sync"]["by"], HIGH)++ def test_same_off_from_another_machine_resumes_the_cached_followed_design(self):++ self.pair_sources(PEER, HIGH)+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["same_on_both"] = True+ raw["same_set_at"] = 10+ raw["same_by"] = HIGH+ raw["design_follow_peer"] = PEER+ raw["crossing"]["effect_length"] = "short"+ self.window.controller.apply_settings(self.store.save(raw))+ self.window._design_states[PEER] = {+ "set_at": 100, "by": PEER, "values": {"effect_length": "long"},+ }+ incoming = settings_sync.message_data(False, 11, by=HIGH)++ self.window.apply_same(incoming, peer=HIGH)++ self.assertEqual(self.window.controller.cfg.crossing["effect_length"], "long")+ self.assertEqual(self.sent[-1]["design_sync"]["values"]["effect_length"], "long")+ self.assertEqual((self.sent[-1]["design_sync"]["set_at"], self.sent[-1]["design_sync"]["by"]),- (100, PEER))++ (self.window.controller.cfg.design_set_at, self.window.own_id()))++ def test_same_on_all_machines_takes_precedence_without_clearing_following(self):++ self.pair_sources(PEER)+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw.update(design_follow_peer=PEER, same_on_both=True, same_set_at=100)+ self.window.controller.apply_settings(self.store.save(raw))+ received = settings_sync.message_data(+ True, 101, settings_sync.mac_values(raw), by=PEER,+ design_state={"set_at": 202, "by": PEER, "values": {"effect_length": "long"}},+ )++ self.window.apply_same(received, peer=PEER)++ self.assertEqual(self.window.controller.cfg.crossing["effect_length"], "normal")+ self.assertEqual(self.window.controller.cfg.design_follow_peer, PEER)+- def test_editing_a_design_control_turns_following_off_and_announces_the_edit(self):++ def follow(self, **crossing):++ self.pair_sources(PEER)+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["design_follow_peer"] = PEER++ raw["crossing"].update(crossing)+ self.window.controller.apply_settings(self.store.save(raw))++ self.window._load_shared(raw)++ self.window._refresh_design_follow()++++ def followed_controls(self):++ w = self.window++ return [w.length_select, w.size_select, w.landing_box, *w.glow_style_select.rows,++ *w.switch_style_select.rows, *w.glow_colour_select.rows]++++ def test_following_locks_the_followed_design_controls_under_a_banner(self):++ self.follow()++++ self.assertFalse(any(control.enabled for control in self.followed_controls()))++ self.assertTrue(self.window.glow_box.enabled)++ self.assertFalse(self.window.follow_banner.isHidden())++ self.assertEqual(self.window.follow_banner_label.text, "Following Paired test PC's design")++++ def test_a_click_on_a_locked_control_changes_nothing_and_keeps_following(self):++ self.follow(effect_length="long")+ self.sent.clear()- self.window.length_select.value = "short"++ short = next(cell for value, cell, _words in self.window.length_select.cells if value == "short")+- self.window._apply_settings()++ short.press()++ self.window.landing_box.view.press()+- self.assertEqual(self.window.controller.cfg.design_follow_peer, "")- self.assertEqual(self.sent[-1]["design_sync"]["values"]["effect_length"], "short")++ self.assertEqual(self.window.length_select.value, "long")++ self.assertEqual(self.window.controller.cfg.crossing["effect_length"], "long")++ self.assertEqual(self.window.controller.cfg.design_follow_peer, PEER)++ self.assertEqual(self.sent, [])++++ def test_stop_following_unlocks_the_controls_and_keeps_the_shown_design(self):++ self.follow(effect_length="long", glow_colour="ocean")++++ self.window.stopFollowing_(None)++++ cfg = self.window.controller.cfg++ self.assertEqual(cfg.design_follow_peer, "")++ self.assertTrue(all(control.enabled for control in self.followed_controls()))++ self.assertTrue(self.window.follow_banner.isHidden())++ self.assertEqual((self.window.length_select.value, cfg.crossing["effect_length"]), ("long", "long"))++ self.assertEqual((self.window.glow_colour_select.value, cfg.crossing["glow_colour"]), ("ocean", "ocean"))++ self.assertEqual(self.sent[-1]["design_sync"]["values"]["effect_length"], "long")++ def test_removing_the_followed_machine_resets_the_local_selection(self):+ entry = {**settings_store.PEER_DEFAULTS, "id": PEER, "token": "peer-token", "name": "Peer",+ "platform": "windows", "port": protocol.DEFAULT_PORT}+ self.store.add_peer(entry)+ raw = settings_store.config_to_raw(self.window.controller.cfg)+ raw["design_follow_peer"] = PEER+ self.window.controller.apply_settings(self.store.save(raw))++ self.store.remove_peer("peer-token")+ self.window.peers_changed()++ self.assertEqual(self.window.controller.cfg.design_follow_peer, "")+- def test_a_peer_that_has_not_sent_a_design_state_is_disabled(self):++ def test_a_connected_peer_that_has_not_sent_a_design_state_is_disabled(self):+ entry = {**settings_store.PEER_DEFAULTS, "id": PEER, "token": "peer-token", "name": "Old PC",+ "platform": "windows", "port": protocol.DEFAULT_PORT}+ self.store.add_peer(entry)++ self.window._design_peer_caps = lambda: {PEER: frozenset({"settings", "design_sync"})}++ self.window._refresh_design_follow()+- cell = next(cell for value, cell, _words in self.window.follow_select.cells if value == PEER)- self.assertFalse(cell.enabled)- self.assertIn("Needs beta.6 or later", next(title for value, title in self.window.follow_select.choices if value == PEER))++ cell = next(cell for value, cell in self.window.follow_select.items if value == PEER)++ self.assertFalse(cell.isEnabled())++ self.assertEqual(next(title for value, title in self.window.follow_select.choices if value == PEER), "Old PC")++ self.assertEqual(cell.toolTip(), "Design not available yet: connect to this machine with Beamer 1.5.0 beta.6 or later.")++ self.assertEqual(self.window.follow_note.text, cell.toolTip())++ def test_the_pcs_settings_arrive_and_this_macs_own_stay(self):+ self.window.apply_same(pc_message(True, 100))+ cfg = self.window.controller.cfg+ self.assertTrue(cfg.same_on_both)+ self.assertEqual(cfg.crossing["methods"], ["edge", "notch"])+ self.assertEqual((cfg.crossing["glow_style"], cfg.crossing["effect_length"]), ("beam", "long"))+ self.assertEqual((cfg.trigger_key, cfg.trigger_style, cfg.double_tap_ms), ("cmd_r", "hold", 400))+ self.assertEqual(self.store.load().crossing["glow_colour"], "ocean")+ self.assertEqual(self.window.glow_style_select.value, "beam")+ self.assertEqual(self.window.resistance_ruler.value, 60)+ self.assertTrue(self.window.same_switch.value)+ self.assertEqual(self.window.scope_labels["crossing"].text,- f"Kept the same as {self.window.controller.peer_label}. Change it on any machine.")++ "Resistance, drag protection and Shortcut stay in step. Ways and jump keys below are local; each side is shared with its paired machine.")++ def test_arriving_settings_leave_a_half_typed_address_and_the_pairing_card(self):+ self.window.host_field.setStringValue_("192.0.2.99")+ self.window.panel._say("That code was not accepted.", "fault")+ self.window.apply_same(pc_message(True, 100))+ self.assertEqual(self.window.host_field.stringValue(), "192.0.2.99")+ self.assertEqual(self.window.panel.pair_status.text, "That code was not accepted.")++ def test_the_hold_switch_reaches_the_controller_before_the_debounce(self):+ self.window.hold_box.value = True+ self.window.controller.full_screen_app = "Game"+ self.window.hold_box._toggle()+ self.assertIs(self.window.controller.cfg.crossing["hold_full_screen"], False)+ self.assertIsNone(self.window.controller.full_screen_app)+ self.window.hold_box._toggle()+ self.assertEqual(self.window.controller.full_screen_app, "Game")++ def test_settings_arriving_from_the_pc_leave_the_hold_switch_as_chosen(self):+ self.window.hold_box.value = True+ self.window.hold_box._toggle()+ self.window.apply_same(pc_message(True, 100))+ self.assertFalse(self.window.hold_box.value)+ self.window._apply_settings()+ self.assertFalse(self.store.load().crossing["hold_full_screen"])++ def test_an_older_message_changes_nothing(self):+ self.window.apply_same(pc_message(True, 100))+ self.window.apply_same(pc_message(True, 90, glow_style="glow"))+ self.assertEqual(self.window.controller.cfg.crossing["glow_style"], "beam")++ def test_turning_it_on_here_sends_this_macs_values(self):+ self.window._set_same(True)+ self.assertEqual(len(self.sent), 1)+ self.assertTrue(self.sent[0]["on"])+ self.assertIs(self.sent[0]["crossing"]["shortcut"], True)++ def test_a_change_here_while_on_is_sent_and_one_to_this_macs_own_is_not(self):+ self.window._set_same(True)+ self.sent.clear()+ self.window.notch_after_select.value = 3000+ self.window._apply_settings()+ self.assertEqual(self.sent, [])+ self.window.length_select.value = "short"+ self.window._apply_settings()+ self.assertEqual(len(self.sent), 1)+ self.assertEqual(self.sent[0]["design"]["effect_length"], "short")++ def test_a_design_change_while_off_announces_its_local_design_state(self):+ self.window.length_select.value = "short"+ self.window._apply_settings()+ self.assertEqual(len(self.sent), 1)+ self.assertFalse(self.sent[0]["on"])+ self.assertEqual(self.sent[0]["design_sync"]["values"]["effect_length"], "short")++ def test_changing_size_redraws_the_design_tiles(self):+ from unittest import mock++ stills = [mock.Mock() for _ in self.window.effect_stills]+ self.window.effect_stills = stills+ with mock.patch.object(self.window.previews, "repaint") as repaint:+ self.window.size_select.value = "small"+ self.window._reflect()+ self.assertTrue(stills)+ for still in stills:+ still.setNeedsDisplay_.assert_called_once_with(True)+ repaint.assert_called_once_with()++ def test_an_old_pc_turns_the_switch_off_and_says_why(self):+ self.window._set_same(True)+ bring_up(self.window.controller, caps=("clipboard",))+ self.assertIs(self.window.controller.peer_settings, False)+ self.window._show_same()+ self.assertFalse(self.window.same_switch.value)+ self.assertIn("too old", self.window.same_note.text)++ def test_a_peers_same_state_is_forwarded_with_this_macs_own_design_state(self):++ self.pair_sources(PEER)+ data = pc_message(True, 100, by=PEER)+ self.window.apply_same(data, peer=PEER)+ self.assertEqual(len(self.sent), 1)+ self.assertEqual({key: value for key, value in self.sent[0].items() if key != "design_sync"}, data)+ self.assertNotEqual(self.sent[0]["design_sync"]["by"], PEER)+ self.assertEqual(self.sources, [PEER])++ def test_who_made_the_change_is_kept_with_it(self):++ self.pair_sources(PEER)+ self.window.apply_same(pc_message(True, 100, by=PEER), peer=PEER)+ self.assertEqual(self.window.controller.cfg.same_by, PEER)+ self.assertEqual(self.store.load().same_by, PEER)++ def test_a_change_made_here_says_it_was_made_by_this_mac(self):+ self.window._set_same(True)+ own = self.store.current()["machine_id"]+ self.assertEqual(self.sent[0]["by"], own)+ self.assertEqual(self.window.controller.cfg.same_by, own)++ def test_the_same_second_from_a_larger_id_is_taken_and_from_a_smaller_is_not(self):++ self.pair_sources(PEER, LOW, HIGH)+ self.window.apply_same(pc_message(True, 100, by=PEER, glow_style="beam"), peer=PEER)+ self.window.apply_same(pc_message(True, 100, by=LOW, glow_style="glow"), peer=LOW)+ self.assertEqual(self.window.controller.cfg.crossing["glow_style"], "beam")+ self.window.apply_same(pc_message(True, 100, by=HIGH, glow_style="glow"), peer=HIGH)+ self.assertEqual(self.window.controller.cfg.crossing["glow_style"], "glow")+ self.assertEqual(self.window.controller.cfg.same_by, HIGH)++ def test_the_copy_that_arrives_over_the_second_link_changes_nothing_and_is_not_sent_on(self):++ self.pair_sources(PEER)+ data = pc_message(True, 100, by=PEER)+ self.window.apply_same(data, peer=PEER)+ self.window.apply_same(data, peer=PEER)+ self.assertEqual(len(self.sent), 1)+++ def test_an_unpaired_source_cannot_change_or_forward_settings(self):++ before = settings_store.config_to_raw(self.window.controller.cfg)++ self.window.apply_same(pc_message(True, 100, by=HIGH), peer=HIGH)++ self.assertEqual(settings_store.config_to_raw(self.window.controller.cfg), before)++ self.assertEqual(self.sent, [])++ self.assertNotIn(HIGH, self.window._design_states)++++if __name__ == "__main__":+ unittest.main()diff --cc mac_app/tests/test_settings_behaviour.pyindex 0000000,0000000..634a486new file mode 100644--- /dev/null+++ b/mac_app/tests/test_settings_behaviour.py@@@ -1,0 -1,0 +1,10 @@@++"""Mac settings decisions with in-memory configuration and no AppKit window."""++++from core.tests.settings_behaviour import SettingsBehaviourTests as _SettingsBehaviourTests++++++class MacSettingsBehaviourTests(_SettingsBehaviourTests):++ platform = "mac"++++++del _SettingsBehaviourTestsdiff --cc mac_app/tests/test_settings_layout_acceptance.pyindex 0000000,0000000..faea9b4new file mode 100644--- /dev/null+++ b/mac_app/tests/test_settings_layout_acceptance.py@@@ -1,0 -1,0 +1,342 @@@++"""The corrected 1.5 layout contract, exercised without ordering a window."""++import unittest++++from mac_app.tests.design_offscreen import AppKit, kvm_bridge_app, offscreen_control_window, settle++++widgets = kvm_bridge_app.widgets++WIDTHS = (320, 426, 512, 640, 720, 900, 1100, 1440, 1920)++++++def walk(view):++ yield view++ if isinstance(view, (AppKit.NSTextField, AppKit.NSButton)):++ return++ for child in view.subviews():++ if not child.isHidden():++ yield from walk(child)++++++def frame_in(view, parent):++ rect = view.alignmentRectForFrame_(view.bounds()) if isinstance(view, AppKit.NSTextField) else view.bounds()++ return view.convertRect_toView_(rect, parent)++++++class SettingsLayoutAcceptanceTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ kvm_bridge_app.theme.init_fonts()++ cls.control = offscreen_control_window()++++ def test_all_six_pages_share_the_centred_column_at_every_width_and_density(self):++ from mac_app.tests.settings_layout_offscreen import render++ control = self.control++ for density in (1, 2):++ for width in WIDTHS:++ sidebar = 56 if width < 640 else 144 if width < 800 else 176++ viewport = width - sidebar - 1 - 16++ expected = min(880, viewport - 48)++ for key, scroll in control.pages.items():++ with self.subTest(page=key, width=width, density=density):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ control._select_page(key)++ settle(control.window)++ self.assertFalse(control.window.isVisible())++ self.assertAlmostEqual(control.window.frame().size.width, width, delta=1)++ self.assertAlmostEqual(control.sidebar.view.frame().size.width, sidebar, delta=1)++ page = scroll.documentView()++ body = page.subviews()[0]++ self.assertAlmostEqual(body.frame().size.width, expected, delta=1)++ self.assertAlmostEqual(body.frame().origin.x, (viewport - expected) / 2, delta=1)++ for section in body.arrangedSubviews():++ if section.isHidden():++ continue++ rect = frame_in(section, body)++ self.assertAlmostEqual(rect.origin.x, 0, delta=1)++ self.assertAlmostEqual(rect.size.width, expected, delta=1)++ self.assertLessEqual(page.frame().size.width, scroll.contentView().bounds().size.width + 1)++ self.assertFalse(scroll.hasHorizontalScroller())++ bitmap = render(control.window.contentView(), density)++ self.assertEqual(bitmap.pixelsWide(), width * density)++ self.assertEqual(bitmap.pixelsHigh(), round(control.window.contentView().bounds().size.height * density))++++ def test_controls_labels_and_children_fit_all_six_pages(self):++ control = self.control++ for width in WIDTHS:++ for key, scroll in control.pages.items():++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ control._select_page(key)++ settle(control.window)++ body = scroll.documentView().subviews()[0]++ with self.subTest(page=key, width=width):++ for child in walk(body):++ rect = frame_in(child, body)++ self.assertGreaterEqual(rect.origin.x, -.99, type(child).__name__)++ self.assertLessEqual(rect.origin.x + rect.size.width, body.bounds().size.width + 1,++ type(child).__name__)++ selector = getattr(child, 'segmented_owner', None)++ if selector is not None:++ self.assertLessEqual(child.bounds().size.width, selector.cap + 1)++ for _, cell, _ in selector.cells:++ self.assertLessEqual(cell.bounds().size.width, 120)++ self.assertGreaterEqual(cell.bounds().size.height, 30)++ if isinstance(child, AppKit.NSButton) and not isinstance(child, AppKit.NSPopUpButton):++ self.assertLessEqual(child.bounds().size.width, 241)++ field = getattr(child, 'field_owner', None)++ if field is not None and field.caption is not None and body.bounds().size.width >= 560:++ self.assertAlmostEqual(frame_in(field.words.view, child).size.width, 180, delta=1)++ self.assertLessEqual(field.words.view.bounds().size.height, 20)++++ def test_families_are_horizontal_equal_tiles_and_wrap_by_column_width(self):++ control = self.control++ for width in WIDTHS:++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ control._select_page('design')++ settle(control.window)++ column = control.pages['design'].documentView().subviews()[0].bounds().size.width++ for choices, count, gap in ((control.glow_style_select, 3 if column >= 600 else 2 if column >= 400 else 1, 12),++ (control.glow_colour_select, 5 if column >= 600 else 3 if column >= 400 else 2, 8)):++ for family in choices.rows:++ cells = [tile for _, tile, *_ in getattr(family, 'tiles', getattr(family, 'cells', []))]++ frames = [frame_in(cell, family.view) for cell in cells]++ with self.subTest(width=width, family=family.values):++ self.assertEqual(family.columns, min(count, len(cells)))++ for rect in frames:++ self.assertAlmostEqual(rect.size.width, frames[0].size.width, delta=1)++ self.assertAlmostEqual(rect.size.height, frames[0].size.height, delta=1)++ if choices is control.glow_style_select:++ self.assertAlmostEqual(rect.size.width / rect.size.height, 152 / 116, delta=.015)++ for index in range(1, min(count, len(frames))):++ self.assertAlmostEqual(frames[index].origin.y, frames[0].origin.y, delta=1)++ self.assertAlmostEqual(frames[index].origin.x - frames[index-1].origin.x,++ frames[0].size.width + gap, delta=1)++ self.assertEqual(len(control.glow_colour_select.rows[1].cells), 5)++++ def test_window_minimum_and_resize_constraints_cannot_drive_native_frame(self):++ control = self.control++ self.assertEqual(tuple(control.window.minSize()), (320, 300))++ for key in control.pages:++ control._select_page(key)++ self.assertLess(control.page_width_constraints[key].priority(), 500)++ with self.subTest(page=key):++ control.window.setFrame_display_(((100000, 100000), (320, 300)), False)++ settle(control.window)++ self.assertEqual(tuple(control.window.frame().size), (320, 300))++++ def test_section_padding_and_ordinary_row_spacing_are_shared(self):++ control = self.control++ for key, scroll in control.pages.items():++ control._select_page(key)++ control.window.setFrame_display_(((100000, 100000), (1440, 900)), False)++ settle(control.window)++ for section in scroll.documentView().subviews()[0].arrangedSubviews():++ children = section.subviews()++ if len(children) != 1 or not isinstance(children[0], AppKit.NSStackView):++ continue++ body = children[0]++ with self.subTest(page=key):++ self.assertEqual(body.spacing(), 12)++ self.assertAlmostEqual(body.frame().origin.x, 16, delta=1)++ self.assertAlmostEqual(body.frame().origin.y, 16, delta=1)++ self.assertAlmostEqual(section.bounds().size.width - body.frame().size.width, 32, delta=1)++ self.assertEqual(control.style_module.body.customSpacingAfterView_(control.chosen_box), 12)++++ def test_machine_section_heading_does_not_split_at_the_minimum_width(self):++ control = self.control++ control._select_page('overview')++ control.window.setFrame_display_(((100000, 100000), (320, 900)), False)++ settle(control.window)++ heading = control.panel.pair_button.view.superview().arrangedSubviews()[0]++ self.assertGreaterEqual(heading.bounds().size.width, heading.attributedStringValue().size().width)++++ def test_shortcut_diagram_legend_layers_fit_the_narrow_column(self):++ control = self.control++ control._select_page('crossing')++ control.window.setFrame_display_(((100000, 100000), (320, 900)), False)++ settle(control.window)++ diagram = control.arrangement_diagram++ for layer in (diagram.key, diagram.key_how):++ rect = layer.frame()++ self.assertLessEqual(rect.origin.x + rect.size.width, diagram.bounds().size.width)++ self.assertLessEqual(rect.origin.y + rect.size.height, diagram.bounds().size.height)++++ def test_key_recorders_keep_their_titles_readable_in_the_narrow_column(self):++ control = self.control++ control.window.setFrame_display_(((100000, 100000), (320, 900)), False)++ for key, recorder, label in (('crossing', control.key_recorder, control.key_recorder.key),++ ('keyboard', control.ignored_recorder, control.ignored_recorder.title)):++ control._select_page(key)++ settle(control.window)++ string = label.view.attributedStringValue()++ available = label.view.cell().drawingRectForBounds_(label.view.bounds()).size.width++ if string.size().width > available:++ self.assertTrue(label.wrap)++ full = string.boundingRectWithSize_options_((available, 10000), AppKit.NSStringDrawingUsesLineFragmentOrigin)++ self.assertGreaterEqual(label.view.bounds().size.height + 1, full.size.height)++++ def test_sidebar_selection_and_focus_never_diverge(self):++ control = self.control++ sidebar = control.sidebar++ control.window.keyboard_navigation = False++ control.window.makeFirstResponder_(sidebar.rows['keyboard'][1])++ sidebar._choose('design')++ for _, row, *_ in sidebar.rows.values():++ self.assertTrue(row.ring is None or row.ring.isHidden())++ for action in (lambda: sidebar.step(1), lambda: sidebar.step(-1),++ lambda: control.windowDidBecomeKey_(None)):++ action()++ selected = [key for key, (_, row, *_) in sidebar.rows.items() if row.accessibilityValue() == 1]++ self.assertEqual(selected, [control.page])++ rings = [key for key, (_, row, *_) in sidebar.rows.items() if row.ring and not row.ring.isHidden()]++ self.assertEqual(rings, [control.page])++++ def test_normal_frames_are_clamped_and_tiled_frames_are_not_persisted(self):++ from unittest import mock++ work = AppKit.NSMakeRect(20, 40, 640, 480)++ self.assertEqual(kvm_bridge_app.settings_normal_frame(None, work), (20, 40, 640, 480))++ self.assertEqual(kvm_bridge_app.settings_normal_frame([1000, -200, 500, 400], work), (160, 40, 500, 400))++ self.assertEqual(kvm_bridge_app.settings_normal_frame(['bad'], work), (20, 40, 640, 480))++ window = mock.Mock()++ window.isVisible.return_value = True++ window.isZoomed.return_value = False++ window.styleMask.return_value = 0++ window.frame.return_value = AppKit.NSMakeRect(30, 50, 500, 400)++ window.stringWithSavedFrame.return_value = '30 50 500 400 0 0 640 480'++ self.assertEqual(kvm_bridge_app.ordinary_window_frame(window), [30, 50, 500, 400])++ window.stringWithSavedFrame.return_value += ' {"tilingState":{}}'++ self.assertIsNone(kvm_bridge_app.ordinary_window_frame(window))++ window.stringWithSavedFrame.return_value = ''++ window.styleMask.return_value = AppKit.NSWindowStyleMaskFullScreen++ self.assertIsNone(kvm_bridge_app.ordinary_window_frame(window))++ control = self.control++ held = list(control._normal_frame)++ control._frame_transition = True++ with mock.patch.object(kvm_bridge_app, 'ordinary_window_frame') as ordinary:++ control._remember_normal_frame()++ ordinary.assert_not_called()++ self.assertEqual(control._normal_frame, held)++ control._frame_transition = False++++ def test_tab_enters_the_selected_page_and_pointer_input_clears_all_focus(self):++ control = self.control++ control._select_page('design')++ control.window.makeFirstResponder_(control.window)++ control.window.selectNextKeyView_(None)++ self.assertEqual(control.window.firstResponder(), control.sidebar.rows['design'][1])++ cell = control.length_select.cells[0][1]++ control.window.makeFirstResponder_(cell)++ self.assertFalse(cell.ring.isHidden())++ control.window.keyboard_navigation = False++ control.window.refresh_input_focus()++ self.assertTrue(cell.ring.isHidden())++++ def test_length_size_stay_vertical_and_toggle_targets_remain_usable(self):++ control = self.control++ for width in WIDTHS:++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ control._select_page('design')++ settle(control.window)++ module = control.style_module.view++ length = frame_in(control.length_select.view, module)++ size = frame_in(control.size_select.view, module)++ self.assertGreater(abs(length.origin.y - size.origin.y), 30)++ for switch in (control.glow_box, control.landing_box, control.haptics_box):++ self.assertGreaterEqual(switch.view.bounds().size.height, 30)++++ def test_rail_targets_and_selected_marks_are_explicit(self):++ control = self.control++ control.window.setFrame_display_(((100000, 100000), (320, 900)), False)++ control._select_page('design')++ control.sidebar.set_dots({'overview': 'fault', 'permissions': 'amber'})++ settle(control.window)++ self.assertTrue(control.sidebar.footer_icon.image().isTemplate())++ for _, row, icon, words, _, dot in control.sidebar.rows.values():++ self.assertEqual(tuple(row.bounds().size), (44, 36))++ self.assertTrue(words.view.isHidden())++ self.assertTrue(row.toolTip())++ self.assertEqual(tuple(icon.alignmentRectForFrame_(icon.bounds()).size), (18, 18))++ if not dot.isHidden():++ icon_rect, dot_rect = frame_in(icon, row), frame_in(dot, row)++ self.assertGreaterEqual(dot_rect.origin.x, icon_rect.origin.x + 18 + 2)++ for choices, value in ((control.glow_style_select, 'flint'), (control.glow_colour_select, 'mono')):++ choices.value = value++ family = next(row for row in choices.rows if value in row.values)++ cells = getattr(family, 'tiles', getattr(family, 'cells', []))++ for candidate, cell, *_ in cells:++ self.assertEqual(cell.selection_mark.isHidden(), candidate != value)++ if value == 'mono':++ self.assertEqual(family.ring.inner.borderWidth(), 1)++++ def test_native_machine_menu_complete_bounds_are_capped(self):++ control = self.control++ for width in WIDTHS:++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ control._select_page('design')++ settle(control.window)++ self.assertLessEqual(control.follow_select.view.bounds().size.width, 320)++++ def test_pairing_notch_and_switch_states_fit_at_every_width(self):++ control = self.control++ control.panel.open = True++ control.panel.refresh()++ control.glow_box.value = True++ control.landing_box.value = True++ control.has_notch = True++ control._place_chosen = True++ control.place = 'notch'++ control.glow_style_select.value = 'glow'++ for mode in ('crossing', 'switch'):++ control.style_for_select.value = mode++ control._reflect()++ for width in WIDTHS:++ for key in ('overview', 'design'):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ control._select_page(key)++ settle(control.window)++ body = control.pages[key].documentView().subviews()[0]++ with self.subTest(page=key, mode=mode, width=width):++ for child in walk(body):++ rect = frame_in(child, body)++ self.assertGreaterEqual(rect.origin.x, -1, type(child).__name__)++ self.assertLessEqual(rect.origin.x + rect.size.width, body.bounds().size.width + 1,++ type(child).__name__)++++ def test_breakpoints_reflow_in_both_directions_without_waiting_for_another_resize(self):++ control = self.control++ for dark in (False, True):++ kvm_bridge_app.theme.set_dark(dark)++ widths = (319+1, 519, 520, 521, 638, 639, 640, 641, 767, 768, 769, 770, 798, 799, 800, 801, 839, 840, 841, 842, 1440)++ for width in widths + widths[::-1]:++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ control._select_page('design')++ settle(control.window)++ column = control.pages['design'].documentView().subviews()[0].bounds().size.width++ with self.subTest(dark=dark, width=width):++ for family in control.glow_style_select.rows:++ self.assertEqual(family.columns, 3 if column >= 600 else 2 if column >= 400 else 1)++ self.assertEqual(control.length_row.field_owner.stacked, column < 560)++ self.assertEqual(control.sidebar.rows['design'][3].view.isHidden(), width < 640)++++ def test_long_buttons_grow_in_height_and_machine_names_remain_available(self):++ button = widgets.Button('A longer action whose full label needs several lines in this column', None, None)++ host = widgets.box()++ host.setFrame_(((0, 0), (180, 200)))++ host.addSubview_(button.view)++ AppKit.NSLayoutConstraint.activateConstraints_([++ button.view.leadingAnchor().constraintEqualToAnchor_(host.leadingAnchor()),++ button.view.topAnchor().constraintEqualToAnchor_(host.topAnchor()),++ button.view.widthAnchor().constraintEqualToConstant_(180),++ ])++ host.layoutSubtreeIfNeeded()++ ink = button.view.attributedTitle().boundingRectWithSize_options_(++ (156, 10000), AppKit.NSStringDrawingUsesLineFragmentOrigin)++ self.assertGreater(ink.size.height, 30)++ self.assertGreaterEqual(button.view.bounds().size.height, ink.size.height + 12)++ name = 'A very long machine name kept in full in the native menu'++ menu = widgets.MenuChoice([(None, 'None'), ('synthetic', name)])++ menu.value = 'synthetic'++ self.assertEqual(menu.items[1][1].title(), name)++ self.assertEqual(menu.popup.accessibilityValue(), name)++++++if __name__ == '__main__':++ unittest.main()diff --cc mac_app/tests/test_settings_polish.pyindex 0000000,0000000..ba7fbfanew file mode 100644--- /dev/null+++ b/mac_app/tests/test_settings_polish.py@@@ -1,0 -1,0 +1,254 @@@++"""Text, control grouping and preview geometry in unordered settings windows."""++import unittest++++from mac_app.tests.design_offscreen import AppKit, kvm_bridge_app, offscreen_control_window, settle++from mac_app.tests.test_settings_layout_acceptance import frame_in, walk++++widgets = kvm_bridge_app.widgets++theme = kvm_bridge_app.theme++++++def luminance(colour):++ colour = colour.colorUsingColorSpace_(AppKit.NSColorSpace.sRGBColorSpace())++ values = [colour.redComponent(), colour.greenComponent(), colour.blueComponent()]++ linear = [v / 12.92 if v <= .04045 else ((v + .055) / 1.055) ** 2.4 for v in values]++ return sum(v * w for v, w in zip(linear, (.2126, .7152, .0722)))++++++class SettingsPolishTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ theme.init_fonts()++ cls.control = offscreen_control_window()++++ def test_all_segment_labels_fit_one_line_in_both_appearances(self):++ control = self.control++ for dark in (False, True):++ theme.set_dark(dark)++ for width in (320, 640, 900, 1440, 1920):++ for page in control.pages:++ control._select_page(page)++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ settle(control.window)++ for view in walk(control.pages[page]):++ selector = getattr(view, 'segmented_owner', None)++ if selector is None:++ continue++ for value, _cell, words in selector.cells:++ selector.value = value++ settle(control.window)++ with self.subTest(page=page, width=width, label=words.text, dark=dark):++ text = words.view.attributedStringValue()++ self.assertGreaterEqual(words.view.bounds().size.width + .5, text.size().width)++ foreground = text.attribute_atIndex_effectiveRange_(AppKit.NSForegroundColorAttributeName, 0, None)[0]++ a, b = sorted((luminance(foreground), luminance(theme.colour('ink'))))++ self.assertGreaterEqual((b + .05) / (a + .05), 4.5)++++ def test_field_controls_start_immediately_after_the_label_track(self):++ control = self.control++ for page in control.pages:++ control._select_page(page)++ control.window.setFrame_display_(((100000, 100000), (1440, 900)), False)++ settle(control.window)++ for view in walk(control.pages[page]):++ field = getattr(view, 'field_owner', None)++ if field is not None and field.caption and not field.stacked:++ with self.subTest(page=page, caption=field.caption):++ self.assertAlmostEqual(frame_in(field.control, view).origin.x, 196, delta=1)++++ def test_preview_hint_has_no_disclosure_triangle(self):++ self.assertEqual(self.control.style_preview_hint.text, 'Hover to preview')++++ def test_time_between_taps_value_fits_in_both_appearances_at_every_width(self):++ control = self.control++ control._select_page('crossing')++ figure = control.double_tap_numeral++ original = figure.text++ try:++ for dark in (False, True):++ theme.set_dark(dark)++ for width in (320, 640, 900, 1440, 1920):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ for value in ('300', '2000'):++ figure.set(value)++ settle(control.window)++ with self.subTest(dark=dark, width=width, value=value):++ self.assertGreaterEqual(figure.view.bounds().size.width + .5,++ figure.view.attributedStringValue().size().width)++ self.assertTrue(AppKit.NSContainsRect(control.double_tap_head.bounds(),++ frame_in(figure.view, control.double_tap_head)))++ finally:++ figure.set(original)++++ def test_overview_machine_controls_form_one_group_at_the_right_edge(self):++ control = self.control++ control._select_page('overview')++ control.window.setFrame_display_(((100000, 100000), (900, 900)), False)++ settle(control.window)++ row = control.panel.list.arrangedSubviews()[0]++ controls = [v for v in walk(row) if isinstance(v, widgets.Pressable) and v.accessibilityLabel()]++ in_use = next(v for v in controls if v.accessibilityLabel() == 'In use')++ directions = next(v for v in controls if str(v.accessibilityLabel()).startswith('Show directions'))++ remove = next(v for v in controls if str(v.accessibilityLabel()).startswith('Remove '))++ a, b, c = (frame_in(v, row) for v in (in_use, directions, remove))++ self.assertAlmostEqual(b.origin.x - a.origin.x - a.size.width, 12, delta=1)++ self.assertAlmostEqual(c.origin.x - b.origin.x - b.size.width, 12, delta=1)++ self.assertAlmostEqual(c.origin.x + c.size.width, row.bounds().size.width - 12, delta=1)++++ def test_machine_names_fit_both_crossing_drawings_at_minimum_width(self):++ control = self.control++ control._select_page('crossing')++ control.window.setFrame_display_(((100000, 100000), (320, 900)), False)++ settle(control.window)++ diagram = control.arrangement_diagram++ for layer in (diagram.this_label, *[label for _screen, label in diagram.screens.values()],++ control.push_strip.this_label, control.push_strip.other_label):++ with self.subTest(name=layer.string()):++ self.assertEqual(layer.truncationMode(), kvm_bridge_app.Quartz.kCATruncationNone)++ text = AppKit.NSAttributedString.alloc().initWithString_attributes_(str(layer.string()), {++ AppKit.NSFontAttributeName: layer.font()})++ size = text.boundingRectWithSize_options_((layer.bounds().size.width, 10000), AppKit.NSStringDrawingUsesLineFragmentOrigin).size++ self.assertGreaterEqual(layer.bounds().size.height + 1, size.height)++ self.assertGreaterEqual(control.push_strip.fill.bounds().size.width, 0)++++ def test_narrow_resistance_push_always_moves_towards_the_other_machine(self):++ control = self.control++ control._select_page('crossing')++ control.window.setFrame_display_(((100000, 100000), (320, 900)), False)++ settle(control.window)++ strip = control.push_strip++ strip.show(1)++ self.assertGreaterEqual(strip.pointer.position().x, strip.edge.frame().origin.x)++++ def test_narrow_machine_card_preserves_its_name_and_address(self):++ control = self.control++ control._select_page('overview')++ control.window.setFrame_display_(((100000, 100000), (320, 900)), False)++ settle(control.window)++ row = control.panel.list.arrangedSubviews()[0]++ names = [v for v in walk(row) if isinstance(v, AppKit.NSTextField) and++ v.stringValue() in ('Windows PC', 'Windows 192.0.2.20 · port 24820')]++ self.assertEqual(len(names), 2)++ for label in names:++ text = label.attributedStringValue()++ width = label.cell().drawingRectForBounds_(label.bounds()).size.width++ height = text.boundingRectWithSize_options_((width, 10000), AppKit.NSStringDrawingUsesLineFragmentOrigin).size.height++ self.assertTrue(label.cell().wraps())++ self.assertGreaterEqual(label.bounds().size.height + 1, height)++++ def test_crossing_headers_wrap_complete_machine_names(self):++ control = self.control++ control._select_page('crossing')++ for width in (320, 640, 900, 1440, 1920):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ for heading, text in ((control.ways_heading, 'Ways from this screen to Alex’s Windows gaming machine'),++ (control.jump_heading, 'Jump to Alex’s Windows gaming machine')):++ previous = heading.stringValue()++ heading.setStringValue_(text)++ settle(control.window)++ available = heading.cell().drawingRectForBounds_(heading.bounds()).size.width++ size = heading.attributedStringValue().boundingRectWithSize_options_((available, 10000), AppKit.NSStringDrawingUsesLineFragmentOrigin).size++ with self.subTest(width=width, heading=text):++ self.assertGreaterEqual(heading.bounds().size.height + 1, size.height)++ heading.setStringValue_(previous)++++ def test_preview_captions_fit_without_overlapping_the_picture_or_each_other(self):++ control = self.control++ control._select_page('design')++ control.has_notch = True++ control.place = 'notch'++ control._reflect()++ choices = [control.notch_style_select, *control.glow_style_select.rows,++ *control.switch_style_select.rows]++ for width in (320, 640, 900, 1440, 1920):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ settle(control.window)++ for family in choices:++ for value, tile, name in family.tiles:++ content = tile.tile_content++ with self.subTest(width=width, style=value):++ for label in (content.name, content.detail):++ bounds = label.view.bounds()++ required = label.view.attributedStringValue().boundingRectWithSize_options_(++ (bounds.size.width, 10000), AppKit.NSStringDrawingUsesLineFragmentOrigin).size.height++ self.assertGreaterEqual(bounds.size.height + .5, required)++ self.assertTrue(AppKit.NSContainsRect(tile.bounds(), label.view.frame()))++ self.assertEqual(label.view.accessibilityLabel(), label.view.attributedStringValue().string())++ self.assertGreaterEqual(content.preview.frame().origin.y,++ content.name.view.frame().origin.y + content.name.view.frame().size.height + 5)++ self.assertGreaterEqual(content.name.view.frame().origin.y,++ content.detail.view.frame().origin.y + content.detail.view.frame().size.height + 3)++ self.assertGreaterEqual(content.preview.bounds().size.height, 10)++ for family in control.glow_colour_select.rows:++ for value, cell, chip, name in family.cells:++ with self.subTest(width=width, colour=value):++ required = name.view.attributedStringValue().boundingRectWithSize_options_(++ (name.view.bounds().size.width, 10000), AppKit.NSStringDrawingUsesLineFragmentOrigin).size.height++ self.assertGreaterEqual(name.view.bounds().size.height + .5, required)++ self.assertTrue(AppKit.NSContainsRect(cell.bounds(), name.view.frame()))++ self.assertGreaterEqual(chip.frame().origin.y,++ name.view.frame().origin.y + name.view.frame().size.height + 5)++++ def test_only_the_active_page_is_attached_and_each_document_scrolls_to_its_end(self):++ control = self.control++ for width in (320, 1920):++ control.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ for key, scroll in control.pages.items():++ control._select_page(key)++ settle(control.window)++ self.assertEqual(list(control.page_host.arrangedSubviews()), [scroll])++ page, clip = scroll.documentView(), scroll.contentView()++ self.assertTrue(page.isFlipped())++ maximum = max(0, page.frame().size.height - clip.bounds().size.height)++ clip.scrollToPoint_((0, maximum))++ scroll.reflectScrolledClipView_(clip)++ settle(control.window)++ self.assertAlmostEqual(clip.bounds().origin.y, maximum, delta=1)++ clip.scrollToPoint_((0, 0))++++ def test_hidden_stacked_preview_children_wait_until_they_are_shown(self):++ from previews import TileStack++ children = [AppKit.NSView.alloc().init() for _ in range(3)]++ view = TileStack.alloc().init().setup(children)++ view.setFrame_(((0, 0), (200, 100)))++ view.layout()++ self.assertEqual(children[0].frame().size.width, 200)++ self.assertEqual(children[1].frame().size.width, 0)++ view.show(children[1])++ view.layout()++ self.assertEqual(children[1].frame().size.width, 200)++++ def test_narrow_overview_controls_fit_as_a_trailing_group(self):++ control = self.control++ control._select_page('overview')++ control.window.setFrame_display_(((100000, 100000), (320, 900)), False)++ settle(control.window)++ row = control.panel.list.arrangedSubviews()[0]++ controls = [v for v in walk(row) if isinstance(v, widgets.Pressable) and v.accessibilityLabel()]++ chosen = [next(v for v in controls if v.accessibilityLabel() == 'In use'),++ next(v for v in controls if str(v.accessibilityLabel()).startswith('Show directions')),++ next(v for v in controls if str(v.accessibilityLabel()).startswith('Remove '))]++ frames = [frame_in(v, row) for v in chosen]++ for frame in frames:++ self.assertTrue(AppKit.NSContainsRect(row.bounds(), frame))++ self.assertAlmostEqual(frame.origin.x + frame.size.width, row.bounds().size.width - 12, delta=1)++ for first, second in zip(frames, frames[1:]):++ self.assertFalse(AppKit.NSIntersectsRect(first, second))++++ def test_long_machine_names_stay_inside_the_crossing_visual_slots(self):++ control = self.control++ control._select_page('crossing')++ control.window.setFrame_display_(((100000, 100000), (320, 900)), False)++ settle(control.window)++ diagram = control.arrangement_diagram++ machines = [dict(control._diagram_machines(['edge'])[0], label='Alex’s Windows gaming machine')]++ diagram.show(machines, 'F12', False, 'Synthetic long machine', shortcut=False)++ control.push_strip.show(1, 'Alex’s Windows gaming machine')++ settle(control.window)++ for screen, label in diagram.screens.values():++ self.assertTrue(AppKit.NSContainsRect(screen.frame(), label.frame()))++ self.assertTrue(AppKit.NSContainsRect(control.push_strip.bounds(), control.push_strip.other_label.frame()))++++++if __name__ == '__main__':++ unittest.main()diff --cc mac_app/tests/test_settings_store.pyindex b0afd6d,0dd544e..963feb8--- a/mac_app/tests/test_settings_store.py+++ b/mac_app/tests/test_settings_store.py@@@ -15,6 -12,6 +15,20 @@@ from settings_store import SettingsErroclass SettingsStoreTests(unittest.TestCase):++ def test_all_original_saved_colours_keep_their_id_and_stops(self):++ import notch_beam++ fixture = Path(__file__).resolve().parents[2] / 'core/tests/colour_packs_rc3.json'++ palettes = json.loads(fixture.read_text())++ with tempfile.TemporaryDirectory() as directory:++ store = SettingsStore(Path(directory) / 'settings.json')++ for value, stops in palettes.items():++ with self.subTest(value=value):++ raw = {**self.valid_raw(), 'crossing': {'glow_colour': value}}++ store.save(raw)++ saved = store.load().crossing['glow_colour']++ self.assertEqual(saved, value)++ self.assertEqual(notch_beam.palette_values(saved), stops)++def valid_raw(self):return {"host": "192.0.2.10",@@@ -176,6 -117,6 +190,18 @@@self.assertEqual(loaded.crossing, config_module.DEFAULT_CROSSING)self.assertIsNot(loaded.crossing, config_module.DEFAULT_CROSSING)++ def test_fresh_and_partial_crossing_use_colourful_but_keep_saved_signal(self):++ with tempfile.TemporaryDirectory() as directory:++ path = Path(directory) / "settings.json"++ store = SettingsStore(path)++ fresh = store.save(self.valid_raw())++ self.assertEqual(fresh.crossing["glow_colour"], "colourful")++++ raw = config_to_raw(fresh)++ raw["crossing"]["glow_colour"] = "signal"++ store.save(raw)++ self.assertEqual(SettingsStore(path).load().crossing["glow_colour"], "signal")++def test_showing_where_the_pointer_lands_is_on_for_an_old_config_and_round_trips_off(self):with tempfile.TemporaryDirectory() as directory:path = Path(directory) / "config.json"diff --cc mac_app/tests/test_settings_v6.pyindex 68f0083,0000000..e571861mode 100644,000000..100644--- a/mac_app/tests/test_settings_v6.py+++ b/mac_app/tests/test_settings_v6.py@@@ -1,1093 -1,0 +1,1103 @@@+"""The Mac's settings.json (WIRE.md section 1) and the migration from 1.4.x's config.json.++Every test runs in a temporary folder: nothing here reads or writes the installed app's files.+"""++import base64+import copy+import hashlib+import importlib+import itertools+import json+import os+import sys+import tempfile+import unittest+from dataclasses import replace+from pathlib import Path+from unittest import mock++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import config as config_module+import settings_store+from core import protocol, receiver, ways+from settings_store import SettingsError, SettingsStore, config_to_raw++FIXTURES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")++TOKEN = base64.urlsafe_b64encode(bytes(range(32))).decode("ascii").rstrip("=")+OTHER_TOKEN = base64.urlsafe_b64encode(bytes(range(100, 132))).decode("ascii").rstrip("=")+THIRD_TOKEN = base64.urlsafe_b64encode(bytes(range(200, 232))).decode("ascii").rstrip("=")+PEER_ID = base64.urlsafe_b64encode(bytes(range(1, 17))).decode("ascii").rstrip("=")+OTHER_ID_FOR_TIE = base64.urlsafe_b64encode(bytes(range(60, 76))).decode("ascii").rstrip("=")+SECOND_ID = base64.urlsafe_b64encode(bytes(range(21, 37))).decode("ascii").rstrip("=")+++def legacy_1_4_3():+ """1.4.3's config.json in the shape a real install writes, with the token replaced."""+ return {+ "host": "192.0.2.20",+ "port": 24820,+ "auth_token": TOKEN,+ "trigger_key": "alt_r",+ "double_tap_ms": 300,+ "key_map": "semantic",+ "reconnect_interval_s": 2.0,+ "trigger_style": "double_tap",+ "crossing": {+ "methods": ["shortcut", "edge", "corner"],+ "edge": "left",+ "corner": "top_right",+ "resistance_px": 140,+ "haptics": True,+ "glow": True,+ "notch_style": "beam",+ "notch_after_ms": 1200,+ "haptic_feel": "medium",+ "haptic_steps": "quarters",+ "glow_style": "glow",+ "glow_colour": "signal",+ "block_while_dragging": True,+ "edge_parts": ["start", "end"],+ "shortcut_arrival": True,+ "shortcut_arrival_style": "match",+ "effect_length": "normal",+ "arrangement_set_at": 1790000000,+ },+ "pc_name": "Office PC",+ "mac_address": "02:1a:2b:3c:0d:4e",+ "send_to_windows": True,+ "allow_windows_to_drive": False,+ "check_updates": True,+ "hide_addresses": False,+ "pointer_speed": 1.5,+ "scroll_speed": 1.0,+ "reverse_scroll": False,+ "appearance": "dark",+ "ignored_inputs": [],+ }+++def legacy_before_milestone_2():+ raw = legacy_1_4_3()+ raw["same_on_both"] = True+ raw["same_set_at"] = 1790000100+ return raw+++def sha(text):+ return hashlib.sha256(text.encode("utf-8")).hexdigest()+++class Base(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.dir = Path(self.temp.name)+ self.legacy = self.dir / "config.json"+ self.path = self.dir / "settings.json"+ self.store = SettingsStore(self.path)++ def write_legacy(self, raw):+ self.legacy.write_text(json.dumps(raw, indent=2) + "\n", encoding="utf-8")+ os.utime(self.legacy, (1_700_000_000, 1_700_000_000))++ def settings(self):+ return json.loads(self.path.read_text(encoding="utf-8"))++ def write_settings(self, settings):+ self.path.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8")+++class MigrationTests(Base):+ def test_the_macs_1_4_3_config_becomes_the_settings_the_tables_say(self):+ self.write_legacy(legacy_1_4_3())+ cfg = self.store.load()+ settings = self.settings()+ self.assertEqual(settings["schema"], 6)+ self.assertEqual(settings["port"], 24820)+ self.assertEqual(settings["name"], "")+ self.assertTrue(settings["shortcut"])+ self.assertEqual(settings["migrated_token_sha256"], sha(TOKEN))+ machine_id = settings["machine_id"]+ self.assertEqual(len(base64.urlsafe_b64decode(machine_id + "==")), 16)+ self.assertEqual(settings["peers"], [{+ "id": "",+ "name": "Office PC",+ "platform": "windows",+ "token": TOKEN,+ "host": "192.0.2.20",+ "port": 24820,+ "hw": "02:1a:2b:3c:0d:4e",+ "send": True,+ "allow_drive": False,+ "in_use": True,+ "side": "left",+ "side_set_at": 1790000000,+ "side_by": machine_id,+ "paired_with": [],+ "paired_at": 0,+ "linked": False,+ "from_1_4": True,+ "jump_key": "",+ }])+ self.assertEqual(cfg.host, "192.0.2.20")+ self.assertEqual(cfg.port, 24820)+ self.assertEqual(cfg.auth_token, TOKEN)+ self.assertEqual(cfg.pc_name, "Office PC")+ self.assertEqual(cfg.mac_address, "02:1a:2b:3c:0d:4e")+ self.assertTrue(cfg.send_to_windows)+ self.assertFalse(cfg.allow_windows_to_drive)+ self.assertEqual(cfg.crossing["methods"], ["shortcut", "edge", "corner"])+ self.assertEqual(cfg.crossing["edge"], "left")+ self.assertEqual(cfg.crossing["edge_parts"], ["start", "end"])+ self.assertEqual(cfg.crossing["corner"], "top_right")+ self.assertEqual(cfg.crossing["arrangement_set_at"], 1790000000)+ self.assertEqual(cfg.crossing["resistance_px"], 140)+ self.assertEqual(cfg.pointer_speed, 1.5)+ self.assertEqual(cfg.appearance, "dark")++ def test_every_other_field_keeps_its_1_4_name_and_the_moved_ones_leave_crossing(self):+ self.write_legacy(legacy_1_4_3())+ self.store.load()+ settings = self.settings()+ for name in ("trigger_key", "double_tap_ms", "key_map", "reconnect_interval_s", "trigger_style",+ "check_updates", "hide_addresses", "pointer_speed", "scroll_speed", "reverse_scroll",+ "appearance", "ignored_inputs"):+ self.assertIn(name, settings)+ for name in ("host", "auth_token", "pc_name", "mac_address", "send_to_windows", "allow_windows_to_drive"):+ self.assertNotIn(name, settings)+ for name in ("methods", "edge", "edge_parts", "corner", "arrangement_set_at"):+ self.assertNotIn(name, settings["crossing"])+ self.assertEqual(settings["crossing"]["resistance_px"], 140)++ def test_zones_of_the_migrated_entry_name_the_empty_id(self):+ self.write_legacy(legacy_1_4_3())+ self.store.load()+ self.assertEqual(self.settings()["zones"], [+ {"peer": "", "kind": "edge"},+ {"peer": "", "kind": "part", "parts": ["start", "end"], "off": True},+ {"peer": "", "kind": "corner", "corner": "top_right", "edge": "right"},+ {"peer": "", "kind": "notch", "off": True},+ ])++ def test_a_config_from_main_before_milestone_2_migrates_too(self):+ self.write_legacy(legacy_before_milestone_2())+ cfg = self.store.load()+ self.assertTrue(cfg.same_on_both)+ self.assertEqual(cfg.same_set_at, 1790000100)+ self.assertTrue(self.settings()["same_on_both"])++ def test_never_paired_has_no_peer_and_keeps_the_crossing_choices(self):+ raw = legacy_1_4_3()+ raw.update(auth_token="", host="", pc_name="", mac_address="")+ self.write_legacy(raw)+ cfg = self.store.load()+ settings = self.settings()+ self.assertEqual(settings["peers"], [])+ self.assertEqual(settings["zones"], [])+ self.assertEqual(settings["migrated_token_sha256"], "")+ self.assertEqual(cfg.auth_token, "")+ self.assertEqual(cfg.crossing["methods"], ["shortcut", "edge", "corner"])+ self.assertEqual(cfg.crossing["edge"], "left")+ self.assertEqual(cfg.crossing["edge_parts"], ["start", "end"])++ def test_missing_and_unparseable_config_give_defaults_and_no_peer(self):+ cfg = self.store.load()+ self.assertEqual(cfg.auth_token, "")+ self.assertEqual(self.settings()["peers"], [])+ self.path.unlink()+ self.legacy.write_text("{not json", encoding="utf-8")+ cfg = self.store.load()+ self.assertEqual(cfg.auth_token, "")+ self.assertEqual(self.settings()["peers"], [])+ self.assertEqual(self.legacy.read_text(encoding="utf-8"), "{not json")++ def test_a_second_start_leaves_settings_byte_for_byte_the_same(self):+ self.write_legacy(legacy_1_4_3())+ self.store.load()+ first = self.path.read_bytes()+ stamp = self.path.stat().st_mtime_ns+ SettingsStore(self.path).load()+ self.assertEqual(self.path.read_bytes(), first)+ self.assertEqual(self.path.stat().st_mtime_ns, stamp)++ def test_config_json_is_never_written_again(self):+ self.write_legacy(legacy_1_4_3())+ before = (self.legacy.read_bytes(), self.legacy.stat().st_mtime_ns)+ cfg = self.store.load()+ for change in ({"hide_addresses": True}, {"pointer_speed": 2.0}, {"appearance": "light"}):+ cfg = self.store.save(config_to_raw(replace(cfg, **change)))+ self.assertEqual((self.legacy.read_bytes(), self.legacy.stat().st_mtime_ns), before)++ def test_a_failure_before_the_rename_leaves_no_settings_and_the_next_start_migrates(self):+ self.write_legacy(legacy_1_4_3())+ with mock.patch("settings_store.os.replace", side_effect=OSError("disk full")):+ with self.assertRaises(SettingsError):+ self.store.load()+ self.assertFalse(self.path.exists())+ self.assertEqual([p.name for p in self.dir.iterdir()], ["config.json"])+ cfg = self.store.load()+ self.assertEqual(cfg.auth_token, TOKEN)+ self.assertTrue(self.path.exists())++ def test_1_4_3s_own_loader_reads_the_kept_config_and_gets_the_pairing_back(self):+ self.write_legacy(legacy_1_4_3())+ cfg = self.store.load()+ self.store.save(config_to_raw(replace(cfg, hide_addresses=True)))+ sys.path.insert(0, FIXTURES)+ self.addCleanup(sys.path.remove, FIXTURES)+ for name in ("config_1_4_3", "settings_store_1_4_3"):+ sys.modules.pop(name, None)+ old_store = importlib.import_module("settings_store_1_4_3")+ self.addCleanup(sys.modules.pop, "config_1_4_3", None)+ self.addCleanup(sys.modules.pop, "settings_store_1_4_3", None)+ old = old_store.SettingsStore(self.legacy).load()+ self.assertEqual(old.host, "192.0.2.20")+ self.assertEqual(old.auth_token, TOKEN)+ self.assertEqual(old.pc_name, "Office PC")+ self.assertEqual(old.mac_address, "02:1a:2b:3c:0d:4e")+ self.assertEqual(old.crossing["methods"], ["shortcut", "edge", "corner"])+ self.assertEqual(old.crossing["edge"], "left")+ self.assertFalse(old.hide_addresses)++ def test_the_saved_key_style_survives(self):+ for style in ("semantic", "positional", {"alt": "alt", "cmd": "cmd"}):+ with self.subTest(style=style):+ self.path.unlink(missing_ok=True)+ raw = legacy_1_4_3()+ raw["key_map"] = style+ self.write_legacy(raw)+ cfg = self.store.load()+ again = self.store.save(config_to_raw(cfg))+ self.assertEqual(again.key_map, cfg.key_map)+ self.assertEqual(SettingsStore(self.path).load().key_map, cfg.key_map)+ saved = self.settings()["key_map"]+ self.assertEqual(saved, style if isinstance(style, str) else {**config_module.DEFAULT_KEY_MAP, **style})++ def test_a_typed_token_migrates_and_is_not_a_pairing_token(self):+ raw = legacy_1_4_3()+ raw["auth_token"] = "correct horse battery"+ self.write_legacy(raw)+ cfg = self.store.load()+ self.assertEqual(cfg.auth_token, "correct horse battery")+ self.assertEqual(self.settings()["peers"][0]["token"], "correct horse battery")+ self.assertFalse(protocol.is_paired_token("correct horse battery"))+ self.assertFalse(protocol.is_paired_token(TOKEN[:-1]))+ self.assertFalse(protocol.is_paired_token(TOKEN[:-1] + "="))+ self.assertTrue(protocol.is_paired_token(TOKEN))++ def test_side_by_is_empty_when_the_arrangement_was_never_changed(self):+ raw = legacy_1_4_3()+ raw["crossing"]["arrangement_set_at"] = 0+ self.write_legacy(raw)+ self.store.load()+ peer = self.settings()["peers"][0]+ self.assertEqual((peer["side_set_at"], peer["side_by"]), (0, ""))++ def test_the_legacy_default_port_moves_as_it_always_did(self):+ raw = legacy_1_4_3()+ raw["port"] = 51820+ self.write_legacy(raw)+ self.assertEqual(self.store.load().port, 24820)+++class ZonesFromMethodsTests(Base):+ def test_each_combination_of_methods_gives_its_zones_and_off_flags(self):+ for count in range(6):+ for methods in itertools.combinations(("shortcut", "edge", "part", "corner", "notch"), count):+ with self.subTest(methods=methods):+ self.path.unlink(missing_ok=True)+ raw = legacy_1_4_3()+ raw["crossing"]["methods"] = list(methods)+ self.write_legacy(raw)+ cfg = self.store.load()+ settings = self.settings()+ self.assertEqual(settings["shortcut"], "shortcut" in methods)+ zones = {zone["kind"]: zone for zone in settings["zones"]}+ self.assertEqual(list(zones), ["edge", "part", "corner", "notch"])+ # The whole edge covers its thirds, so with both on the thirds stand down (WIRE.md section 8).+ in_use = [m for m in methods if not (m == "part" and "edge" in methods)]+ for kind in ("edge", "part", "corner", "notch"):+ self.assertEqual(zones[kind].get("off", False), kind not in in_use)+ self.assertEqual(cfg.crossing["methods"], in_use)++ def test_a_corner_crosses_by_its_own_left_or_right_edge_whatever_the_side_as_1_4_x_did(self):+ # crossing.py: the Mac's corner crossing returns the corner's horizontal edge; only the way home uses the side.+ for corner, edge in (("top_right", "right"), ("top_left", "left"), ("bottom_left", "left"), ("bottom_right", "right")):+ for side in ("left", "right", "top", "bottom"):+ with self.subTest(corner=corner, side=side):+ self.path.unlink(missing_ok=True)+ raw = legacy_1_4_3()+ raw["crossing"].update(corner=corner, edge=side)+ self.write_legacy(raw)+ self.store.load()+ zone = [z for z in self.settings()["zones"] if z["kind"] == "corner"][0]+ self.assertEqual(zone["edge"], edge)+++class ReimportTests(Base):+ def migrated(self):+ self.write_legacy(legacy_1_4_3())+ self.store.load()++ def test_a_changed_token_replaces_the_1_4_entry_and_points_its_zones_at_the_empty_id(self):+ self.migrated()+ settings = self.settings()+ settings["peers"][0].update(id=PEER_ID, linked=True, paired_with=[SECOND_ID], paired_at=5)+ for zone in settings["zones"]:+ zone["peer"] = PEER_ID+ self.write_settings(settings)+ raw = legacy_1_4_3()+ raw.update(auth_token=OTHER_TOKEN, host="192.0.2.77", pc_name="New PC")+ self.write_legacy(raw)+ cfg = self.store.load()+ settings = self.settings()+ peer = settings["peers"][0]+ self.assertEqual((peer["id"], peer["linked"], peer["paired_with"]), ("", False, []))+ self.assertEqual((peer["token"], peer["host"], peer["name"], peer["from_1_4"]), (OTHER_TOKEN, "192.0.2.77", "New PC", True))+ self.assertEqual({zone["peer"] for zone in settings["zones"]}, {""})+ self.assertEqual(settings["migrated_token_sha256"], sha(OTHER_TOKEN))+ self.assertEqual((cfg.auth_token, cfg.host), (OTHER_TOKEN, "192.0.2.77"))++ def test_an_unchanged_token_does_nothing_and_peers_added_under_1_5_are_untouched(self):+ self.migrated()+ settings = self.settings()+ added = copy.deepcopy(settings["peers"][0])+ added.update(id=SECOND_ID, token=THIRD_TOKEN, from_1_4=False, name="Laptop")+ settings["peers"].append(added)+ self.write_settings(settings)+ before = self.path.read_bytes()+ self.store.load()+ self.assertEqual(self.path.read_bytes(), before)+ raw = legacy_1_4_3()+ raw["auth_token"] = OTHER_TOKEN+ self.write_legacy(raw)+ self.store.load()+ peers = self.settings()["peers"]+ self.assertEqual(peers[1], added)+ self.assertEqual(peers[0]["token"], OTHER_TOKEN)++ def test_a_migrated_peer_the_user_removed_stays_removed_while_config_is_unchanged(self):+ self.migrated()+ settings = self.settings()+ settings["peers"] = []+ settings["zones"] = []+ self.write_settings(settings)+ for _ in range(3):+ SettingsStore(self.path).load()+ self.assertEqual(self.settings()["peers"], [])++ def test_a_removed_peer_paired_again_under_1_4_comes_back_with_its_zones(self):+ self.migrated()+ settings = self.settings()+ settings["peers"] = []+ settings["zones"] = []+ self.write_settings(settings)+ raw = legacy_1_4_3()+ raw["auth_token"] = OTHER_TOKEN+ self.write_legacy(raw)+ self.store.load()+ settings = self.settings()+ self.assertEqual(len(settings["peers"]), 1)+ self.assertEqual(settings["peers"][0]["token"], OTHER_TOKEN)+ self.assertEqual([zone["kind"] for zone in settings["zones"]], ["edge", "part", "corner", "notch"])++ def test_a_token_whose_key_id_is_another_entrys_is_not_migrated_and_is_not_tried_again(self):+ self.migrated()+ settings = self.settings()+ added = copy.deepcopy(settings["peers"][0])+ added.update(id=SECOND_ID, token=OTHER_TOKEN, from_1_4=False, name="Laptop")+ settings["peers"].append(added)+ self.write_settings(settings)+ raw = legacy_1_4_3()+ raw["auth_token"] = OTHER_TOKEN+ self.write_legacy(raw)+ self.store.load()+ settings = self.settings()+ self.assertEqual(settings["peers"][0]["token"], TOKEN)+ self.assertEqual(len(settings["peers"]), 2)+ self.assertEqual(settings["migrated_token_sha256"], sha(OTHER_TOKEN))++ def test_a_typed_token_is_migrated_even_though_it_has_no_key_id(self):+ self.migrated()+ raw = legacy_1_4_3()+ raw["auth_token"] = "swordfish"+ self.write_legacy(raw)+ self.store.load()+ self.assertEqual(self.settings()["peers"][0]["token"], "swordfish")++ def test_an_emptied_token_is_not_a_migration(self):+ self.migrated()+ raw = legacy_1_4_3()+ raw["auth_token"] = ""+ self.write_legacy(raw)+ before = self.path.read_bytes()+ self.store.load()+ self.assertEqual(self.path.read_bytes(), before)+++class SavingTests(Base):+ def setUp(self):+ super().setUp()+ self.write_legacy(legacy_1_4_3())+ self.cfg = self.store.load()+++ def test_trigger_changes_cannot_overwrite_an_existing_jump_key(self):++ settings = self.settings()++ settings["peers"][0]["jump_key"] = "ctrl+f13"++ self.write_settings(settings)++ before = self.path.read_bytes()++ for key in ("ctrl_r", "f13"):++ with self.subTest(key=key), self.assertRaises(SettingsError):++ self.store.save(config_to_raw(replace(self.cfg, trigger_key=key)))++ self.assertEqual(self.path.read_bytes(), before)+++++ def test_saving_keeps_the_machine_id_and_the_id_of_the_peer_and_writes_privately(self):+ settings = self.settings()+ settings["peers"][0].update(id=PEER_ID, linked=True)+ for zone in settings["zones"]:+ zone["peer"] = PEER_ID+ self.write_settings(settings)+ machine_id = settings["machine_id"]+ saved = self.store.save(config_to_raw(replace(self.cfg, hide_addresses=True)))+ self.assertEqual(saved, self.store.load())+ after = self.settings()+ self.assertEqual(after["machine_id"], machine_id)+ self.assertEqual(after["peers"][0]["id"], PEER_ID)+ self.assertTrue(after["peers"][0]["linked"])+ self.assertEqual({zone["peer"] for zone in after["zones"]}, {PEER_ID})+ self.assertTrue(after["hide_addresses"])+ self.assertEqual(self.path.stat().st_mode & 0o777, 0o600)+ self.assertEqual(self.dir.stat().st_mode & 0o777, 0o700)++ def test_the_save_that_learns_the_peers_id_rewrites_the_zones_naming_the_empty_id(self):+ settings = self.settings()+ settings["peers"][0]["id"] = PEER_ID+ self.store.save_settings(settings)+ self.assertEqual({zone["peer"] for zone in self.settings()["zones"]}, {PEER_ID})++ def test_saving_the_flat_config_updates_peer_zero_and_leaves_the_other_peers_alone(self):+ settings = self.settings()+ added = copy.deepcopy(settings["peers"][0])+ added.update(id=SECOND_ID, token=THIRD_TOKEN, from_1_4=False, name="Laptop", host="192.0.2.30")+ settings["peers"].append(added)+ self.write_settings(settings)+ raw = config_to_raw(self.cfg)+ raw.update(host="192.0.2.99", pc_name="Renamed", send_to_windows=False)+ raw["crossing"]["edge"] = "bottom"+ raw["crossing"]["arrangement_set_at"] = 1790000500+ cfg = self.store.save(raw)+ after = self.settings()+ self.assertEqual(after["peers"][1], added)+ first = after["peers"][0]+ self.assertEqual((first["host"], first["name"], first["send"]), ("192.0.2.99", "Renamed", False))+ # The side is written by set_ways and arrangement only: a flat view read before another+ # machine's arrangement landed must not put the old side back.+ self.assertEqual((first["side"], first["side_set_at"]), ("left", 1790000000))+ self.assertEqual((cfg.host, cfg.crossing["edge"]), ("192.0.2.99", "left"))++ def test_a_flat_save_keeps_a_name_and_hardware_address_learnt_since_the_window_read(self):+ settings = self.settings()+ settings["peers"][0].update(name="Learnt PC", hw="aa:bb:cc:dd:ee:01")+ self.store.save_settings(settings)+ self.store.save(config_to_raw(replace(self.cfg, pointer_speed=2.0)))+ first = self.settings()["peers"][0]+ self.assertEqual((first["name"], first["hw"]), ("Learnt PC", "aa:bb:cc:dd:ee:01"))+ self.assertEqual(self.settings()["pointer_speed"], 2.0)++ def test_a_new_address_clears_what_was_learnt_at_the_old_one(self):+ settings = self.settings()+ settings["peers"][0].update(name="Learnt PC", hw="aa:bb:cc:dd:ee:01")+ self.store.save_settings(settings)+ self.store.save(config_to_raw(replace(self.cfg, host="192.0.2.99", pc_name="", mac_address="")))+ first = self.settings()["peers"][0]+ self.assertEqual((first["host"], first["name"], first["hw"]), ("192.0.2.99", "", ""))++ def with_id(self):+ settings = self.settings()+ settings["peers"][0]["id"] = PEER_ID+ for zone in settings["zones"]:+ zone["peer"] = PEER_ID+ self.write_settings(settings)+ self.store = SettingsStore(self.path)+ return settings++ def test_the_side_stamp_keeps_its_author_until_it_changes(self):+ settings = self.with_id()+ settings["peers"][0].update(side_by=SECOND_ID)+ self.write_settings(settings)+ self.store = SettingsStore(self.path)+ self.store.save(config_to_raw(self.cfg))+ self.assertEqual(self.settings()["peers"][0]["side_by"], SECOND_ID)+ self.assertFalse(self.store.set_ways(PEER_ID, side="left", methods=["edge"], parts=["middle"], corner="top_right"))+ self.assertEqual(self.settings()["peers"][0]["side_by"], SECOND_ID)+ self.assertTrue(self.store.set_ways(PEER_ID, side="top", methods=["edge"], parts=["middle"], corner="top_right"))+ first = self.settings()["peers"][0]+ self.assertEqual((first["side"], first["side_by"]), ("top", self.settings()["machine_id"]))+ self.assertGreater(first["side_set_at"], 1790000000)++ def test_an_arrangement_from_the_peer_is_stamped_with_the_peers_id_not_this_machines(self):+ self.with_id()+ self.assertEqual(self.store.arrangement(PEER_ID, "top", 1790000500, SECOND_ID), (True, []))+ first = self.settings()["peers"][0]+ self.assertEqual((first["side"], first["side_set_at"], first["side_by"]), ("bottom", 1790000500, SECOND_ID))++ def test_a_tie_won_on_the_larger_by_stores_the_winners_by(self):+ settings = self.with_id()+ stamp = settings["peers"][0]["side_set_at"]+ settings["peers"][0].update(side_by=OTHER_ID_FOR_TIE)+ self.write_settings(settings)+ self.store = SettingsStore(self.path)+ self.assertEqual(self.store.arrangement(PEER_ID, "left", stamp, SECOND_ID), (False, []))+ self.assertEqual(self.store.arrangement(PEER_ID, "left", stamp, OTHER_ID_FOR_TIE), (False, []))+ larger = base64.urlsafe_b64encode(bytes(range(200, 216))).decode("ascii").rstrip("=")+ self.assertEqual(self.store.arrangement(PEER_ID, "left", stamp, larger), (True, []))+ self.assertEqual(self.settings()["peers"][0]["side_by"], larger)+ self.assertEqual(self.settings()["peers"][0]["side_set_at"], stamp)++ def test_an_arrangement_for_one_machine_leaves_the_others_side_alone(self):+ settings = self.with_id()+ second = {**copy.deepcopy(settings["peers"][0]), "id": SECOND_ID, "side": "right", "name": "Second"}+ second["token"] = second["token"][::-1]+ settings["peers"].append(second)+ self.write_settings(settings)+ self.store = SettingsStore(self.path)+ self.store.arrangement(SECOND_ID, "right", 1790000900, SECOND_ID)+ after = self.settings()["peers"]+ self.assertEqual((after[0]["side"], after[1]["side"]), ("left", "left"))++ def test_the_store_serves_the_settings_it_holds_to_a_peer_book_and_keeps_them_after_a_save(self):+ book = self.store.book()+ self.assertEqual(book.peers()[0]["token"], TOKEN)+ raw = config_to_raw(self.cfg)+ raw["host"] = "192.0.2.98"+ self.store.save(raw)+ self.assertEqual(book.peers()[0]["host"], "192.0.2.98")+ # The migrated entry never links; as a pairing made on 1.5.0 it does, and what it learns is kept.+ own = protocol.read_id(self.settings()["machine_id"])+ self.assertEqual(book.admit(protocol.key_id(TOKEN), own, protocol.read_id(PEER_ID), {"name": "Learnt"})[0], receiver.GONE)+ settings = self.store.current()+ settings["peers"][0].update(id=PEER_ID, from_1_4=False)+ self.store.save_settings(settings)+ self.assertEqual(book.admit(protocol.key_id(TOKEN), own, protocol.read_id(PEER_ID), {"name": "Learnt"})[0], receiver.ADMITTED)+ self.assertEqual(self.settings()["peers"][0]["name"], "Learnt")+ self.assertEqual(self.store.current()["peers"][0]["name"], "Learnt")++ def test_changing_the_methods_turns_zones_on_and_off(self):+ self.with_id()+ raw = config_to_raw(self.cfg)+ raw["crossing"]["methods"] = ["edge", "corner"]+ self.store.save(raw)+ self.assertFalse(self.settings()["shortcut"])+ self.store.set_ways(PEER_ID, side="left", methods=["part", "notch"], parts=["middle"], corner="top_right")+ zones = {zone["kind"]: zone for zone in self.settings()["zones"]}+ self.assertTrue(zones["edge"]["off"])+ self.assertNotIn("off", zones["part"])+ self.assertEqual(zones["part"]["parts"], ["middle"])+ self.assertNotIn("off", zones["notch"])+ self.assertEqual(self.store.load().crossing["methods"], ["part", "notch"])++ def test_the_corner_zones_edge_follows_the_corner_not_the_side(self):+ self.with_id()+ self.store.set_ways(PEER_ID, side="top", methods=["corner"], parts=["middle"], corner="top_right")+ corner = [z for z in self.settings()["zones"] if z["kind"] == "corner"][0]+ self.assertEqual((corner["corner"], corner["edge"]), ("top_right", "right"))+ self.store.set_ways(PEER_ID, side="top", methods=["corner"], parts=["middle"], corner="bottom_left")+ corner = [z for z in self.settings()["zones"] if z["kind"] == "corner"][0]+ self.assertEqual((corner["corner"], corner["edge"]), ("bottom_left", "left"))++ def test_ways_that_would_clash_with_another_machines_are_refused_with_both_named_and_nothing_written(self):+ settings = self.with_id()+ second = {**copy.deepcopy(settings["peers"][0]), "id": SECOND_ID, "side": "right", "name": "Second"}+ second["token"] = second["token"][::-1]+ settings["peers"].append(second)+ settings["zones"].append({"peer": SECOND_ID, "kind": "edge"})+ self.write_settings(settings)+ self.store = SettingsStore(self.path)+ # On the same side as Second, with no way in yet: turning its edge on would cover Second's.+ self.store.set_ways(PEER_ID, side="right", methods=[], parts=["middle"], corner="top_right")+ before = self.settings()+ with self.assertRaises(SettingsError) as raised:+ self.store.set_ways(PEER_ID, side="right", methods=["edge"], parts=["middle"], corner="top_right")+ self.assertIn("Second", str(raised.exception))+ self.assertIn("right edge of this Mac", str(raised.exception))+ self.assertEqual(self.settings(), before)++ def second_machine(self, side, zones=None):+ settings = self.with_id()+ second = {**copy.deepcopy(settings["peers"][0]), "id": SECOND_ID, "side": side, "name": "Second"}+ second["token"] = second["token"][::-1]+ settings["peers"].append(second)+ if zones is not None:+ settings["zones"] += zones+ self.write_settings(settings)+ self.store = SettingsStore(self.path)++ def test_a_machine_paired_with_no_zone_gets_its_edge_when_the_settings_are_read(self):+ # The rig's beta.3 file of 01-10-2026: a second machine's side set, and no zone to cross by.+ self.second_machine("right")+ self.assertIn({"peer": SECOND_ID, "kind": "edge"}, self.store.current()["zones"])++ def test_one_whose_side_is_taken_gets_its_edge_off_and_the_settings_still_read(self):+ self.second_machine("left")+ self.assertIn({"peer": SECOND_ID, "kind": "edge", "off": True}, self.store.current()["zones"])+ self.assertIn("Second has no way in", ways.blocked_sentence(self.store.current(), SECOND_ID, "this Mac"))++ def test_moving_a_machine_onto_a_taken_side_keeps_the_side_and_turns_its_way_there_off(self):+ self.second_machine("right", [{"peer": SECOND_ID, "kind": "edge"}])+ self.assertTrue(self.store.set_ways(SECOND_ID, side="left", methods=["edge"], parts=["middle"], corner="top_right"))+ second = next(entry for entry in self.settings()["peers"] if entry["id"] == SECOND_ID)+ self.assertEqual(second["side"], "left")+ self.assertIn({"peer": SECOND_ID, "kind": "edge", "off": True}, self.settings()["zones"])++ def test_ways_for_a_machine_no_longer_paired_are_refused(self):+ with self.assertRaises(SettingsError):+ self.store.set_ways(SECOND_ID, side="right", methods=["edge"], parts=["middle"], corner="top_right")++ def test_the_first_machines_port_is_its_own_and_never_moves_this_macs(self):+ raw = config_to_raw(self.cfg)+ raw["port"] = 9000+ self.store.save(raw)+ settings = self.settings()+ self.assertEqual((settings["port"], settings["peers"][0]["port"]), (24820, 9000))++ def test_removing_or_adding_machines_leaves_this_macs_port_where_it_was(self):+ self.store.add_peer({**settings_store.PEER_DEFAULTS, "id": SECOND_ID, "name": "Laptop", "platform": "macos",+ "token": OTHER_TOKEN, "host": "192.0.2.30", "port": 9100, "paired_at": 1_700_000_000})+ self.store.remove_peer(TOKEN)+ self.assertEqual(self.store.load().port, 9100)+ self.assertEqual(self.settings()["port"], 24820)+ self.store.save(config_to_raw(self.store.load()))+ self.assertEqual(self.settings()["port"], 24820)++ def test_clearing_the_token_removes_the_peer_and_its_zones_and_keeps_the_choices(self):+ raw = config_to_raw(self.cfg)+ raw.update(auth_token="", host="", pc_name="", mac_address="")+ cfg = self.store.save(raw)+ settings = self.settings()+ self.assertEqual((settings["peers"], settings["zones"]), ([], []))+ self.assertEqual(cfg.crossing["methods"], ["shortcut", "edge", "corner"])+ self.assertEqual(SettingsStore(self.path).load().crossing["edge_parts"], ["start", "end"])++ def test_pairing_again_after_clearing_makes_a_peer_with_zones_from_the_choices(self):+ raw = config_to_raw(self.cfg)+ raw.update(auth_token="", host="", pc_name="", mac_address="")+ self.store.save(raw)+ raw.update(auth_token=OTHER_TOKEN, host="192.0.2.50", pc_name="Desk")+ self.store.save(raw)+ settings = self.settings()+ peer = settings["peers"][0]+ self.assertEqual((peer["id"], peer["platform"], peer["token"], peer["from_1_4"], peer["linked"]),+ ("", "windows", OTHER_TOKEN, True, False))+ self.assertEqual(peer["side"], "left")+ self.assertEqual([zone["kind"] for zone in settings["zones"]], ["edge", "part", "corner", "notch"])+ self.assertEqual(settings["migrated_token_sha256"], sha(TOKEN))++ def test_a_first_save_with_nothing_on_disk_makes_a_machine(self):+ self.path.unlink()+ self.legacy.unlink()+ cfg = SettingsStore(self.path).save(config_to_raw(settings_store.editable_default_config()))+ self.assertEqual(cfg.auth_token, "")+ self.assertEqual(self.settings()["schema"], 6)+ self.assertTrue(self.settings()["machine_id"])+++class PairedAndRemovedTests(Base):+ """The two writes the window makes to the peers: a pairing stored, a machine removed."""++ def setUp(self):+ super().setUp()+ self.write_legacy(legacy_1_4_3())+ self.cfg = self.store.load()++ def entry(self, ident, token, name="Laptop", **extra):+ return {**settings_store.PEER_DEFAULTS, "id": ident, "name": name, "platform": "macos", "token": token,+ "host": "192.0.2.30", "port": 24820, "paired_at": 1_700_000_000, **extra}++ def test_a_pairing_is_stored_after_the_peers_it_joins_and_the_flat_settings_still_read_the_first(self):+ self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN))+ self.assertEqual([peer["token"] for peer in self.settings()["peers"]], [TOKEN, OTHER_TOKEN])+ self.assertEqual(self.store.load().auth_token, TOKEN)++ def test_the_peer_the_book_serves_is_the_one_just_stored(self):+ self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN))+ self.assertEqual([peer["token"] for peer in self.store.book().peers()], [TOKEN, OTHER_TOKEN])++ def test_a_pairing_replacing_the_1_4_entry_takes_its_place_and_its_zones_go(self):+ self.assertTrue(self.settings()["zones"])+ replaced = copy.deepcopy(self.settings()["peers"][0])+ self.store.add_peer(self.entry(PEER_ID, OTHER_TOKEN, name="Studio"), replaced)+ after = self.settings()+ self.assertEqual([peer["id"] for peer in after["peers"]], [PEER_ID])+ # Only the new machine's own edge, which every machine paired starts with.+ self.assertEqual(after["zones"], [{"peer": PEER_ID, "kind": "edge"}])+ self.assertEqual(self.store.load().auth_token, OTHER_TOKEN)++ def test_a_pairing_that_cannot_be_written_raises_and_changes_nothing(self):+ before = self.path.read_bytes()+ with mock.patch.object(self.store, "_write", side_effect=SettingsError("disk full")):+ with self.assertRaises(SettingsError):+ self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN))+ self.assertEqual(self.path.read_bytes(), before)+ self.assertEqual(len(self.store.current()["peers"]), 1)++ def test_removing_a_machine_takes_its_zones_and_leaves_the_others(self):+ self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN))+ removed = self.store.remove_peer(OTHER_TOKEN)+ self.assertEqual(removed["id"], SECOND_ID)+ self.assertEqual([peer["token"] for peer in self.settings()["peers"]], [TOKEN])+ self.assertTrue(self.settings()["zones"])++ def test_removing_the_first_machine_makes_the_next_the_one_the_flat_settings_read(self):+ self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN))+ self.store.remove_peer(TOKEN)+ self.assertEqual(self.store.load().auth_token, OTHER_TOKEN)+ self.assertEqual(self.settings()["zones"], [{"peer": SECOND_ID, "kind": "edge"}])++ def test_removing_the_only_machine_leaves_this_one_unpaired_and_it_stays_so(self):+ self.store.remove_peer(TOKEN)+ self.assertEqual(self.store.load().auth_token, "")+ self.assertEqual(self.settings()["peers"], [])+ self.assertEqual(SettingsStore(self.path).load().auth_token, "")++ def test_with_nothing_paired_appearance_and_speed_still_save(self):+ self.store.remove_peer(TOKEN)+ cfg = self.store.load()+ saved = self.store.save(config_to_raw(replace(cfg, appearance="dark", pointer_speed=1.5, hide_addresses=True)))+ self.assertEqual((saved.appearance, saved.pointer_speed, saved.hide_addresses), ("dark", 1.5, True))+ self.assertEqual(self.settings()["peers"], [])+ again = SettingsStore(self.path).load()+ self.assertEqual((again.appearance, again.pointer_speed, again.hide_addresses, again.auth_token), ("dark", 1.5, True, ""))++ def test_removing_a_machine_that_is_not_there_is_nothing(self):+ self.assertIsNone(self.store.remove_peer("not-a-token"))+ self.assertEqual(len(self.settings()["peers"]), 1)++ def test_one_machines_directions_are_its_own_switches(self):+ self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN))+ first = self.settings()["peers"][0]+ entry = self.store.set_peer(OTHER_TOKEN, send=False)+ self.assertEqual((entry["send"], entry["allow_drive"]), (False, True))+ peers = self.settings()["peers"]+ self.assertEqual(peers[0], first)+ self.assertEqual((peers[1]["send"], peers[1]["allow_drive"]), (False, True))+ self.store.set_peer(OTHER_TOKEN, allow_drive=False)+ self.assertFalse(self.settings()["peers"][1]["allow_drive"])++ def test_the_first_machines_switches_reach_the_flat_settings(self):+ self.store.set_peer(TOKEN, send=False, allow_drive=False)+ cfg = self.store.load()+ self.assertEqual((cfg.send_to_windows, cfg.allow_windows_to_drive), (False, False))++ def test_only_the_two_switches_can_be_changed_this_way(self):+ with self.assertRaises(SettingsError):+ self.store.set_peer(TOKEN, host="elsewhere")+ with self.assertRaises(SettingsError):+ self.store.set_peer(TOKEN, send="yes")++ def test_a_machine_that_is_not_there_has_no_switches_to_change(self):+ self.assertIsNone(self.store.set_peer("not-a-token", send=False))++ def test_a_save_made_from_settings_read_before_a_pairing_does_not_undo_it(self):+ # The window holds the flat settings it last loaded; a pairing stored from the service's+ # thread changes which machine they describe before the window has read them again.+ stale = config_to_raw(self.cfg)+ self.store.remove_peer(TOKEN)+ self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN))+ self.store.save(dict(stale, hide_addresses=True))+ peers = self.settings()["peers"]+ self.assertEqual([peer["token"] for peer in peers], [OTHER_TOKEN])+ self.assertEqual(peers[0]["name"], "Laptop")+ self.assertTrue(self.settings()["hide_addresses"])++ def test_a_stale_save_with_nothing_paired_does_not_pop_the_machine_just_paired(self):+ self.store.remove_peer(TOKEN)+ empty = config_to_raw(self.store.load())+ self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN))+ self.store.save(dict(empty, hide_addresses=True))+ self.assertEqual([peer["token"] for peer in self.settings()["peers"]], [OTHER_TOKEN])+- def test_a_phone_is_not_paired_on_a_desktop_in_this_version(self):- # A port-0 first peer would make the flat settings, which read its port, unloadable.- with self.assertRaises(SettingsError):- self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN, port=0, host=""))- self.assertEqual(len(self.settings()["peers"]), 1)++ def test_a_phone_can_pair_without_changing_the_flat_desktop_view(self):++ self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN, platform="ios", port=0, host="", send=False))++ self.assertEqual(len(self.settings()["peers"]), 2)++ self.assertEqual(self.store.load().auth_token, TOKEN)+ self.store.load()++ def test_a_replaced_entry_that_has_linked_since_the_pairing_began_is_not_replaced(self):+ replaced = copy.deepcopy(self.settings()["peers"][0])+ settings = self.settings()+ settings["peers"][0].update(id=PEER_ID, linked=True)+ self.store.save_settings(settings)+ with self.assertRaises(SettingsError):+ self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN), replaced)+ self.assertEqual([peer["token"] for peer in self.settings()["peers"]], [TOKEN])++ def test_a_save_that_names_a_new_token_still_replaces_the_first_machine(self):+ raw = config_to_raw(self.cfg)+ self.store.save(dict(raw, auth_token=THIRD_TOKEN))+ self.assertEqual([peer["token"] for peer in self.settings()["peers"]], [THIRD_TOKEN])++ def test_the_book_the_links_read_sees_a_removal_at_once(self):+ book = self.store.book()+ self.store.add_peer(self.entry(SECOND_ID, OTHER_TOKEN))+ self.store.remove_peer(OTHER_TOKEN)+ self.assertEqual([peer["token"] for peer in book.peers()], [TOKEN])+++class ValidationTests(Base):+ def setUp(self):+ super().setUp()+ self.write_legacy(legacy_1_4_3())+ self.store.load()++ def broken(self, change):+ settings = self.settings()+ change(settings)+ self.write_settings(settings)+ with self.assertRaises(SettingsError):+ SettingsStore(self.path).load()++ def test_a_bad_machine_id_is_refused(self):+ self.broken(lambda s: s.update(machine_id="not an id"))+ self.broken(lambda s: s.update(machine_id=base64.urlsafe_b64encode(bytes(16)).decode().rstrip("=")))+ self.broken(lambda s: s.update(machine_id=""))++ def test_two_entries_with_one_id_or_our_own_id_are_refused(self):+ def twin(s):+ s["peers"][0]["id"] = PEER_ID+ s["peers"].append({**s["peers"][0], "token": OTHER_TOKEN, "from_1_4": False})+ self.broken(twin)+ self.broken(lambda s: s["peers"][0].update(id=s["machine_id"]))++ def test_two_entries_with_one_key_id_are_refused(self):+ def same_token(s):+ s["peers"][0]["id"] = PEER_ID+ s["peers"].append({**s["peers"][0], "id": SECOND_ID, "from_1_4": False})+ self.broken(same_token)++ def test_more_than_one_empty_id_or_an_empty_id_that_is_not_from_1_4_is_refused(self):+ self.broken(lambda s: s["peers"].append({**s["peers"][0], "token": OTHER_TOKEN}))+ self.broken(lambda s: s["peers"][0].update(from_1_4=False))++ def test_more_than_thirty_two_peers_are_refused(self):+ def many(s):+ s["peers"] = [{**s["peers"][0], "id": base64.urlsafe_b64encode(bytes([n]) * 16).decode().rstrip("="),+ "token": base64.urlsafe_b64encode(bytes([n, 7]) * 16).decode().rstrip("="),+ "from_1_4": False} for n in range(1, 34)]+ self.broken(many)++ def test_an_unknown_schema_is_refused_rather_than_migrated_over(self):+ self.broken(lambda s: s.update(schema=7))++ def test_a_file_that_does_not_parse_is_refused_and_left_alone(self):+ self.path.write_text("{oops", encoding="utf-8")+ with self.assertRaises(SettingsError):+ SettingsStore(self.path).load()+ self.assertEqual(self.path.read_text(encoding="utf-8"), "{oops")+++class RefusingToStartOverTests(Base):+ """A settings file that exists is never replaced by a fresh one: that would change the machine id."""++ def setUp(self):+ super().setUp()+ self.write_legacy(legacy_1_4_3())+ self.cfg = self.store.load()+ self.machine_id = self.settings()["machine_id"]++ def assert_untouched(self, before):+ self.assertEqual(self.path.read_bytes(), before)+ self.assertEqual([p.name for p in self.dir.iterdir()].count("settings.invalid.json"), 0)++ def test_a_future_schema_is_refused_on_save_and_left_as_it_is(self):+ settings = self.settings()+ settings["schema"] = 7+ self.write_settings(settings)+ before = self.path.read_bytes()+ with self.assertRaises(SettingsError):+ self.store.save(config_to_raw(self.cfg))+ self.assert_untouched(before)++ def test_a_file_without_a_machine_id_is_refused_and_never_given_one(self):+ settings = self.settings()+ del settings["machine_id"]+ self.write_settings(settings)+ before = self.path.read_bytes()+ with self.assertRaises(SettingsError):+ self.store.load()+ with self.assertRaises(SettingsError):+ self.store.save(config_to_raw(self.cfg))+ self.assert_untouched(before)++ def test_a_file_without_peers_or_zones_is_refused(self):+ for name in ("peers", "zones"):+ settings = self.settings()+ del settings[name]+ self.write_settings(settings)+ with self.assertRaises(SettingsError):+ self.store.load()+ self.write_settings({**settings, name: []})++ def test_a_value_that_fails_validation_stops_saves_instead_of_dropping_the_pairing(self):+ settings = self.settings()+ settings["pointer_speed"] = 9+ self.write_settings(settings)+ before = self.path.read_bytes()+ with self.assertRaises(SettingsError):+ self.store.load()+ with self.assertRaises(SettingsError):+ self.store.save(config_to_raw(settings_store.editable_default_config()))+ self.assert_untouched(before)++ def test_infinity_in_the_file_is_a_settings_error(self):+ self.path.write_text(self.path.read_text(encoding="utf-8").replace('"double_tap_ms": 300', '"double_tap_ms": Infinity'), encoding="utf-8")+ with self.assertRaises(SettingsError):+ self.store.load()++ def test_a_failed_write_while_re_importing_does_not_stop_the_app_opening(self):+ raw = legacy_1_4_3()+ raw["auth_token"] = OTHER_TOKEN+ self.write_legacy(raw)+ with mock.patch("settings_store.os.replace", side_effect=OSError("read only")):+ cfg = self.store.load()+ self.assertEqual(cfg.auth_token, OTHER_TOKEN)+ self.assertEqual(self.settings()["machine_id"], self.machine_id)+ self.assertEqual(self.store.load().auth_token, OTHER_TOKEN)+++class ReimportRefusalsTests(Base):+ def setUp(self):+ super().setUp()+ self.write_legacy(legacy_1_4_3())+ self.store.load()++ def test_a_config_that_fails_validation_is_not_migrated_but_is_not_tried_again(self):+ raw = legacy_1_4_3()+ raw["auth_token"] = OTHER_TOKEN+ raw["crossing"]["corner"] = "top"+ self.write_legacy(raw)+ cfg = self.store.load()+ self.assertEqual(cfg.auth_token, TOKEN)+ self.assertEqual(self.settings()["migrated_token_sha256"], sha(OTHER_TOKEN))++ def test_a_thirty_third_peer_is_not_added(self):+ settings = self.settings()+ settings["peers"] = [{**settings["peers"][0], "id": base64.urlsafe_b64encode(bytes([n]) * 16).decode().rstrip("="),+ "token": base64.urlsafe_b64encode(bytes([n, 7]) * 16).decode().rstrip("="),+ "from_1_4": False} for n in range(1, 33)]+ settings["zones"] = []+ self.write_settings(settings)+ raw = legacy_1_4_3()+ raw["auth_token"] = OTHER_TOKEN+ self.write_legacy(raw)+ self.store.load()+ self.assertEqual(len(self.settings()["peers"]), 32)++ def test_a_fractional_arrangement_stamp_migrates(self):+ self.path.unlink()+ raw = legacy_1_4_3()+ raw["crossing"]["arrangement_set_at"] = 1790000000.5+ self.write_legacy(raw)+ self.assertEqual(self.store.load().crossing["arrangement_set_at"], 1790000000)++ def test_a_zone_with_a_bad_corner_or_an_unknown_peer_is_refused(self):+ for change in (lambda s: s["zones"][2].update(corner="top"),+ lambda s: s["zones"][2].update(edge="middle"),+ lambda s: s["zones"][1].update(parts=[]),+ lambda s: s["zones"][0].update(off="yes"),+ lambda s: s["zones"][0].update(peer=PEER_ID)):+ settings = self.settings()+ change(settings)+ self.write_settings(settings)+ with self.assertRaises(SettingsError):+ SettingsStore(self.path).load()+ self.path.unlink()+ self.write_legacy(legacy_1_4_3())+ self.store.load()++ def test_the_id_a_peer_learns_renames_only_the_zones_of_the_entry_with_that_token(self):+ settings = self.settings()+ added = {**settings["peers"][0], "id": SECOND_ID, "token": OTHER_TOKEN, "from_1_4": False}+ settings["peers"].append(added)+ self.write_settings(settings)+ settings["peers"] = [added]+ settings["zones"] = []+ self.store.save_settings(settings)+ self.assertEqual(self.settings()["zones"], [{"peer": SECOND_ID, "kind": "edge"}])+++class OverlapTests(Base):+ def setUp(self):+ super().setUp()+ self.write_legacy(legacy_1_4_3())+ self.store.load()++ def refused(self, change):+ settings = self.settings()+ change(settings)+ self.write_settings(settings)+ with self.assertRaises(SettingsError):+ SettingsStore(self.path).load()++ def test_the_edge_and_its_thirds_in_use_together_are_refused(self):+ self.refused(lambda s: s["zones"][1].pop("off"))++ def test_the_edge_and_the_notch_stay_together_as_1_4_x_let_them(self):+ settings = self.settings()+ settings["zones"][3].pop("off")+ self.write_settings(settings)+ self.assertIn("notch", SettingsStore(self.path).load().crossing["methods"])++ def test_two_part_zones_sharing_a_third_are_refused_and_disjoint_ones_are_not(self):+ def two_parts(s, second):+ s["zones"][0]["off"] = True+ s["zones"][1].pop("off")+ s["zones"].append({"peer": "", "kind": "part", "parts": second})+ self.refused(lambda s: two_parts(s, ["end", "middle"]))+ self.path.unlink()+ self.write_legacy(legacy_1_4_3())+ self.store.load()+ settings = self.settings()+ two_parts(settings, ["middle"])+ self.write_settings(settings)+ SettingsStore(self.path).load()++ def test_two_peers_whose_edges_face_the_same_side_cannot_both_have_the_edge_zone_on(self):+ def second_peer(s):+ s["peers"][0]["id"] = PEER_ID+ s["zones"] = [{**z, "peer": PEER_ID} for z in s["zones"]]+ s["peers"].append({**s["peers"][0], "id": SECOND_ID, "token": OTHER_TOKEN, "from_1_4": False})+ s["zones"].append({"peer": SECOND_ID, "kind": "edge"})+ self.refused(second_peer)++ def test_a_corner_inside_the_edge_is_fine_and_two_of_one_corner_are_not(self):+ settings = self.settings()+ settings["zones"][2]["corner"] = "top_left"+ settings["zones"][2]["edge"] = "left"+ self.write_settings(settings)+ SettingsStore(self.path).load()+ self.refused(lambda s: s["zones"].append({"peer": "", "kind": "corner", "corner": "top_left", "edge": "left"}))++ def test_ways_with_the_edge_and_the_thirds_on_write_the_thirds_off(self):+ self.store.set_ways("", side="left", methods=["edge", "part"], parts=["middle"], corner="top_right")+ self.assertEqual(self.store.load().crossing["methods"], ["shortcut", "edge"])+ zones = {z["kind"]: z for z in self.settings()["zones"]}+ self.assertTrue(zones["part"]["off"])++ def test_two_machines_on_one_notch_are_refused(self):+ def two_notches(s):+ s["peers"][0]["id"] = PEER_ID+ s["zones"] = [{**z, "peer": PEER_ID} for z in s["zones"]]+ s["zones"][3].pop("off", None)+ second = {**copy.deepcopy(s["peers"][0]), "id": SECOND_ID, "side": "right"}+ second["token"] = second["token"][::-1]+ s["peers"].append(second)+ s["zones"].append({"peer": SECOND_ID, "kind": "notch"})+ self.refused(two_notches)+++if __name__ == "__main__":+ unittest.main()diff --cc mac_app/tests/test_titlebar_events.pyindex 0000000,0000000..d544c70new file mode 100644--- /dev/null+++ b/mac_app/tests/test_titlebar_events.py@@@ -1,0 -1,0 +1,95 @@@++import unittest++from unittest import mock++++from mac_app.tests.test_window_geometry import offscreen_control_window, kvm_bridge_app++from mac_app.tests.test_window_resize import settle++++AppKit = kvm_bridge_app.AppKit++++++def double_click(window, point):++ for kind in (AppKit.NSEventTypeLeftMouseDown, AppKit.NSEventTypeLeftMouseUp):++ event = AppKit.NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_(++ kind, point, 0, 0, window.windowNumber(), None, 1, 2, 1.0++ )++ window.sendEvent_(event)++ settle(window)++++++class TitlebarEventTests(unittest.TestCase):++ def test_titlebar_routing_excludes_traffic_lights_and_page_controls(self):++ control = offscreen_control_window()++ window = control.window++ settle(window)++ for kind in (AppKit.NSWindowCloseButton, AppKit.NSWindowMiniaturizeButton, AppKit.NSWindowZoomButton):++ button = window.standardWindowButton_(kind)++ rect = button.convertRect_toView_(button.bounds(), window.contentView().superview())++ point = AppKit.NSMakePoint(AppKit.NSMidX(rect), AppKit.NSMidY(rect))++ self.assertFalse(window.titlebar_background(point))++ self.assertFalse(window.titlebar_background(AppKit.NSMakePoint(450, 200)))++++ def test_explicit_do_nothing_keeps_the_frame_on_all_backgrounds(self):++ control = offscreen_control_window()++ window = control.window++ window.setFrame_display_(((100000, 100000), (900, 700)), False)++ settle(window)++ original = window.frame()++ height = window.contentView().frame().size.height++ with mock.patch.object(kvm_bridge_app, "titlebar_action", return_value=None):++ for point in ((450, height + 10), (450, height - 9), (80, height - 30)):++ double_click(window, point)++ self.assertEqual(window.frame(), original)++++ def test_real_zoom_fills_then_restores_the_previous_frame(self):++ for state in ("initial", "resized"):++ with self.subTest(state=state):++ control = offscreen_control_window()++ window = control.window++ if state == "resized":++ window.setFrame_display_(((100000, 100000), (900, 700)), False)++ settle(window)++ original = window.frame()++ expected = kvm_bridge_app.window_fill_frame(window)++ kvm_bridge_app.perform_titlebar_double_click(window, "Fill")++ settle(window)++ print(f"direct fill ({state}): before={original}, after={window.frame()}, expected={expected}", flush=True)++ self.assertEqual(window.frame(), expected)++ kvm_bridge_app.perform_titlebar_double_click(window, "Fill")++ settle(window)++ self.assertEqual(window.frame(), original)++ self.assertFalse(window.isVisible())++++ def test_titlebar_and_strip_and_sidebar_top_deliver_fill_and_restore(self):++ control = offscreen_control_window()++ window = control.window++ for region in ("native", "strip", "sidebar"):++ window.setFrame_display_(((100000, 100000), (900, 700)), False)++ settle(window)++ original = window.frame()++ expected = kvm_bridge_app.window_fill_frame(window)++ with self.subTest(region=region):++ content_height = window.contentView().frame().size.height++ if region == "native":++ point = (450, content_height + 10)++ elif region == "strip":++ point = (450, content_height - 9)++ else:++ point = (80, content_height - 30)++ hit = window.contentView().superview().hitTest_(point)++ print(f"{region} double-click hit={type(hit).__name__}, point={point}", flush=True)++ # No default is changed on Toby's Mac.++ with mock.patch.object(kvm_bridge_app, "titlebar_action", return_value="fill"):++ double_click(window, point)++ print(f"{region} frame={window.frame()}", flush=True)++ self.assertEqual(window.frame(), expected)++ content_height = window.contentView().frame().size.height++ point = (450, content_height + 10) if region == "native" else (++ (450, content_height - 9) if region == "strip" else (80, content_height - 30)++ )++ double_click(window, point)++ self.assertEqual(window.frame(), original)++ self.assertFalse(window.isVisible())++++++if __name__ == "__main__":++ unittest.main()diff --cc mac_app/tests/test_widgets.pyindex b753297,0000000..9b851afmode 100644,000000..100644--- a/mac_app/tests/test_widgets.py+++ b/mac_app/tests/test_widgets.py@@@ -1,37 -1,0 +1,106 @@@++import gc+import sys+import unittest++import weakref+from pathlib import Path++from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import AppKit++AppKit.NSApplication.sharedApplication()++import theme+import widgets+++class WidthTests(unittest.TestCase):++ def test_figure_renders_its_unit_once(self):++ figure = widgets.Figure('120', theme.TYPE['numeral'], 'px')++ self.assertEqual(figure.view.attributedStringValue().string(), '120 px')++ self.assertEqual(figure.view.accessibilityLabel(), '120 px')++++ def test_us_region_changes_rendered_text_and_accessibility_without_changing_source(self):++ from core import locale++++ with mock.patch.object(locale, "is_us_region", return_value=True):++ label = widgets.Label("Colourful behaviour")++ button = widgets.Button("Minimise", None, None)++++ self.assertEqual(label.view.stringValue(), "Colorful behavior")++ self.assertEqual(label.view.accessibilityLabel(), "Colorful behavior")++ self.assertEqual(label.text, "Colourful behaviour")++ self.assertEqual(button.view.title(), "Minimize")++ self.assertEqual(button.title, "Minimise")++++ def test_nonwrapping_label_updates_full_text_metadata(self):++ label = widgets.Label("Short name")++ full_name = "A very long workstation name with translated length"++ label.view.setFrameSize_((100, 20))++++ label.set(full_name)++++ paragraph = label.view.attributedStringValue().attribute_atIndex_effectiveRange_(++ AppKit.NSParagraphStyleAttributeName, 0, None)[0]++ visible_width = label.view.cell().drawingRectForBounds_(label.view.bounds()).size.width++ self.assertGreater(label.view.attributedStringValue().size().width, visible_width)++ self.assertEqual(paragraph.lineBreakMode(), AppKit.NSLineBreakByTruncatingTail)++ self.assertEqual(label.view.toolTip(), full_name)++ self.assertEqual(label.view.accessibilityLabel(), full_name)++++ def test_nonwrapping_label_update_preserves_explicit_tooltip(self):++ label = widgets.Label("Short name")++ label.view.setToolTip_("Use this explanatory tooltip")++++ label.set("A longer machine name")++++ self.assertEqual(label.view.toolTip(), "Use this explanatory tooltip")++++ def test_nonwrapping_figure_update_keeps_full_text_metadata_when_elided(self):++ figure = widgets.Figure("Short", theme.TYPE["readout"])++ full_name = "A very long workstation name with translated length"++ figure.view.setFrameSize_((100, 30))++++ figure.set(full_name)++++ paragraph = figure.view.attributedStringValue().attribute_atIndex_effectiveRange_(++ AppKit.NSParagraphStyleAttributeName, 0, None)[0]++ visible_width = figure.view.cell().drawingRectForBounds_(figure.view.bounds()).size.width++ self.assertGreater(figure.view.attributedStringValue().size().width, visible_width)++ self.assertEqual(paragraph.lineBreakMode(), AppKit.NSLineBreakByTruncatingTail)++ self.assertEqual(figure.view.toolTip(), full_name)++ self.assertEqual(figure.view.accessibilityLabel(), full_name)++++ def test_ring_overlay_does_not_retain_its_owner(self):++ host = widgets.box()++ ring = widgets.Ring(host, 4)++ overlay = ring.overlay++ owner = weakref.ref(ring)++ del ring++ gc.collect()++ self.assertIsNone(owner())++ overlay.ringPositionChanged_(None)+++ def test_reading_note_stays_capped_inside_a_wider_stack(self):+ parent = widgets.stack()+ note = widgets.note("A note that can wrap.")++ widgets.add(parent, note.view)++ constraints = list(note.view.constraints())+ cap = next(c for c in constraints if c.firstAttribute() == AppKit.NSLayoutAttributeWidth+ and c.relation() == AppKit.NSLayoutRelationLessThanOrEqual)+ reach = next(c for c in parent.constraints() if c.firstItem() == note.view+ and c.secondItem() == parent and c.firstAttribute() == AppKit.NSLayoutAttributeWidth)+ fill_to_cap = next(c for c in note.view.constraints() if c.firstItem() == note.view+ and c.secondItem() is None and c.firstAttribute() == AppKit.NSLayoutAttributeWidth+ and c.relation() == AppKit.NSLayoutRelationEqual)+ self.assertEqual(cap.constant(), theme.READING_WIDTH)+ self.assertEqual(reach.relation(), AppKit.NSLayoutRelationLessThanOrEqual)+ self.assertEqual(fill_to_cap.priority(), 255)+++if __name__ == "__main__":+ unittest.main()diff --cc mac_app/tests/test_window_geometry.pyindex e66ffb7,0000000..7f2f9cbmode 100644,000000..100644--- a/mac_app/tests/test_window_geometry.py+++ b/mac_app/tests/test_window_geometry.py@@@ -1,138 -1,0 +1,282 @@@+import sys+import unittest+import logging+import threading+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import kvm_bridge_app+import settings_store+++def offscreen_control_window():+ AppKit = kvm_bridge_app.AppKit+ AppKit.NSApplication.sharedApplication()+ token = "synthetic-render-only"+ cfg = settings_store.editable_default_config()+ cfg.host = "192.0.2.20"+ cfg.port = 24820+ cfg.auth_token = token+ cfg.pc_name = "Windows PC"+ store = object.__new__(settings_store.SettingsStore)+ store.lock = threading.RLock()+ store._handed_token = token+ store._cache = store._complete({**store._fresh(), "peers": []})+ logger = logging.getLogger("test-window-geometry")+ from wake import WakingController++ controller = WakingController(cfg, logger=logger)+ with mock.patch.object(kvm_bridge_app, "accessibility_granted", return_value=True), mock.patch.object(+ kvm_bridge_app, "input_monitoring_granted", return_value=True+ ):+ return kvm_bridge_app.ControlWindow.alloc().initWithController_settingsStore_logger_(+ controller, store, logger+ )+++class WindowGeometryTests(unittest.TestCase):++ def _assert_side_by_side_layout(self, window, attribute, width, height, expected_orientation):++ AppKit = kvm_bridge_app.AppKit++ from Foundation import NSDate, NSRunLoop++++ window.window.setFrame_display_(((100000, 100000), (width, height)), False)++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.25))++ self.assertEqual(window.window.frame().size.width, width)++ pair = getattr(window, attribute, None)++ self.assertIsNotNone(pair, f"{attribute} was not built")++ self.assertEqual(++ pair.orientation(), expected_orientation,++ f"pair width {pair.bounds().size.width}, threshold {pair.needed()}, window {window.window.frame().size.width}",++ )++ self.assertFalse(pair.isHidden())++ self.assertFalse(pair.first.isHidden())++ self.assertFalse(pair.second.isHidden())++ self.assertEqual(pair.first.superview(), pair.view)++ self.assertEqual(pair.second.superview(), pair.view)++ self.assertEqual(tuple(pair.view.arrangedSubviews()), (pair.first, pair.second))++ return pair+++ def test_resizable_window_keeps_a_requested_full_screen_width(self):+ AppKit = kvm_bridge_app.AppKit+ window = offscreen_control_window()+ # The window takes its largest size from every constraint above WindowSizeStayPut (500),+ # so one page's rigid row or reading-width note used to cap it at 773 to 837 pt.+ screen_width = AppKit.NSScreen.mainScreen().visibleFrame().size.width++ window.window.setFrame_display_(((100000, 100000), (screen_width, 900)), False)+ from Foundation import NSDate, NSRunLoop++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.25))++ self.assertEqual(window.window.frame().size.width, screen_width)+- def test_a_full_screen_page_keeps_its_content_column_centred(self):++ def test_page_column_scales_with_free_width_and_stays_centred(self):+ window = offscreen_control_window()- window.window.setFrame_display_(((100000, 100000), (1728, 900)), False)+ from Foundation import NSDate, NSRunLoop+- NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.25))++ for width in (1366, 1920, 2560, 3440, 7680):++ window.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.25))++ self.assertEqual(window.window.frame().size.width, width)++++ for key, scroll in window.pages.items():++ window._select_page(key)++ window.window.contentView().layoutSubtreeIfNeeded()++ page = scroll.documentView()++ body = page.subviews()[0]++ free = page.frame().size.width++ expected = kvm_bridge_app.page_column_width(free)++ with self.subTest(window_width=width, page=key):++ if key == "design":++ # Its tile grid keeps its intrinsic column width; the Design test checks the rows.++ available = page.frame().size.width - sum(kvm_bridge_app.theme.PAGE_PADDING_NARROW[1::2])++ self.assertLessEqual(body.frame().size.width, available + 1)++ else:++ self.assertAlmostEqual(body.frame().size.width, expected, delta=1)++ left = body.frame().origin.x++ right = page.frame().size.width - left - body.frame().size.width++ self.assertAlmostEqual(left, right, delta=1)++++ def test_crossing_pair_flips_without_reparenting_at_wide_and_narrow_sizes(self):++ AppKit = kvm_bridge_app.AppKit++ window = offscreen_control_window()++ window._select_page("crossing")++ horizontal = AppKit.NSUserInterfaceLayoutOrientationHorizontal++ vertical = AppKit.NSUserInterfaceLayoutOrientationVertical++++ for width, height in ((1366, 900), (1920, 900), (2560, 900), (1440, 3440)):++ with self.subTest(window=(width, height)):++ pair = self._assert_side_by_side_layout(window, "ways_pair", width, height, horizontal)++ self.assertEqual(pair.needed(), 632)++ self.assertEqual(pair.gap, 24)++ self.assertEqual(pair.view.spacing(), 24)++ self.assertGreaterEqual(pair.first.frame().size.width, 254)++ self.assertGreaterEqual(pair.second.frame().size.width, 354)++++ with self.subTest(window=(700, 900)):++ pair = self._assert_side_by_side_layout(window, "ways_pair", 700, 900, vertical)++ self.assertLess(pair.bounds().size.width, pair.needed())++++ def test_design_controls_lead_full_width_responsive_tile_groups(self):++ window = offscreen_control_window()++ window._select_page("design")++ window.landing_box.value = True++ window._reflect()++ self.assertFalse(window.style_for_row.isHidden())++ self.assertFalse(window.effect_method_view.isHidden())++ last_group = window.glow_style_select.rows[-1]++ window.glow_style_select.value = last_group.values[-1]++ from Foundation import NSDate, NSRunLoop++++ for width in (640, 1366, 2560, 1366, 640):++ window.window.setFrame_display_(((100000, 100000), (width, 900)), False)++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.1))++ host = window.style_module.body++ controls = [view.convertRect_toView_(view.bounds(), host)++ for view in (window.style_for_row, window.effect_method_view)]++ tiles = [tile.convertRect_toView_(tile.bounds(), host)++ for row in window.glow_style_select.rows for _value, tile, _name in row.tiles]++ with self.subTest(width=width):++ # NSStackView is unflipped: a row's bottom must be above every tile's top.++ self.assertGreater(min(rect.origin.y for rect in controls),++ max(rect.origin.y + rect.size.height for rect in tiles))++ for rect in controls:++ self.assertAlmostEqual(rect.size.width, host.bounds().size.width, delta=1)++ for rect in tiles:++ self.assertGreaterEqual(rect.size.width, 96)++ first_row = max(rect.origin.y + rect.size.height for rect in tiles)++ count = sum(abs(rect.origin.y + rect.size.height - first_row) < 1 for rect in tiles)++ first_family = max(++ window.glow_style_select.rows,++ key=lambda row: max(tile.convertRect_toView_(tile.bounds(), host).origin.y++ + tile.convertRect_toView_(tile.bounds(), host).size.height++ for _value, tile, _name in row.tiles),++ )++ self.assertEqual(count, first_family.grid.columns)++ for family in window.glow_style_select.rows:++ bounds = family.view.bounds()++ bounds = kvm_bridge_app.AppKit.NSInsetRect(bounds, -1, -1)++ self.assertGreater(bounds.size.width, 0)++ self.assertGreater(bounds.size.height, 0)++ for _value, tile, _name in family.tiles:++ rect = tile.convertRect_toView_(tile.bounds(), family.view)++ self.assertTrue(kvm_bridge_app.AppKit.NSContainsRect(bounds, rect),++ f"tile {rect} outside family row {bounds}")++ selected = next(tile for row in window.glow_style_select.rows++ for value, tile, _name in row.tiles if value == window.glow_style_select.value)++ self.assertIsNone(window.glow_style_select.ring)++ self.assertTrue(selected.tile_selected)++ self.assertEqual(selected.layer().borderWidth(), 2)++++ def test_narrow_page_uses_its_current_padding_for_available_width(self):++ window = offscreen_control_window()++ window._select_page("crossing")++ from Foundation import NSDate, NSRunLoop++++ window.window.setFrame_display_(((100000, 100000), (640, 700)), False)++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.1))++ page = window.pages["crossing"].documentView()++ body = page.subviews()[0]++ padding = kvm_bridge_app.theme.PAGE_PADDING_NARROW if not window.wide else kvm_bridge_app.theme.PAGE_PADDING++ available = page.frame().size.width - padding[1] - padding[3]++ expected = min(++ kvm_bridge_app.page_column_width(page.frame().size.width),++ page.frame().size.width - sum(padding[1::2]),++ )++ self.assertAlmostEqual(body.frame().size.width, expected, delta=1)++++ def test_switch_mode_keeps_long_tile_titles_readable(self):++ window = offscreen_control_window()++ window._select_page("design")++ window.landing_box.value = True++ window.style_for_select.value = "switch"++ window._reflect()++ from Foundation import NSDate, NSRunLoop+- # Every page: one row of a reading-width note and a button, with nothing to take the spare- # width, held Overview's column at 706 pt and Connection's at 684.- for key, page in window.pages.items():- page = page.documentView()- body = page.subviews()[0]- with self.subTest(page=key):- self.assertEqual(body.frame().size.width, kvm_bridge_app.theme.PAGE_CONTENT_WIDTH)- left = body.frame().origin.x- right = page.frame().size.width - left - body.frame().size.width- self.assertAlmostEqual(left, right, delta=1)++ window.window.setFrame_display_(((100000, 100000), (640, 700)), False)++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.1))++ _value, tile, name = next(item for row in window.switch_style_select.rows++ for item in row.tiles if item[0] == "match")++ single_line_height = name.view.attributedStringValue().size().height++ self.assertGreaterEqual(name.view.frame().size.height, single_line_height)++ self.assertGreaterEqual(name.view.frame().size.width, name.view.attributedStringValue().size().width)++ self.assertGreaterEqual(tile.frame().size.width, 96)++ self.assertTrue(kvm_bridge_app.AppKit.NSContainsRect(tile.bounds(),++ name.view.convertRect_toView_(name.view.bounds(), tile)))++ def test_a_full_screen_remove_question_keeps_its_buttons_their_own_width(self):+ from types import SimpleNamespace+ from Foundation import NSDate, NSRunLoop++ window = offscreen_control_window()+ state = SimpleNamespace(word="Connected", led="signal", blink=False, tone="signal", detail="")+ row = SimpleNamespace(label="Windows PC", state=state, token="t1", platform="Windows", address="192.0.2.20",- in_use=True, drives=True, driven=True)++ in_use=True, drives=True, driven=True, phone=False)+ window.panel.removing = "t1"+ window.panel._build_rows([row])+ window.window.setFrame_display_(((100000, 100000), (1728, 900)), False)+ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.25))++ def walk(view):+ yield view+ for sub in view.subviews():+ yield from walk(sub)++ chips = {view.accessibilityLabel(): view for view in walk(window.panel.list)+ if view.accessibilityLabel() in ("Confirm removing Windows PC", "Keep Windows PC")}+ self.assertEqual(len(chips), 2)+ # The question's note stopped at the reading width and the spare width went to Keep.+ for name, chip in chips.items():+ with self.subTest(chip=name):+ self.assertAlmostEqual(chip.frame().size.width, chip.fittingSize().width, delta=1)++ def test_zoom_uses_the_visible_screen_frame(self):+ frame = ((40.0, 24.0), (1440.0, 940.0))+ screen = mock.Mock()+ screen.visibleFrame.return_value = frame+ window = mock.Mock()+ window.screen.return_value = screen+ fill_frame = getattr(kvm_bridge_app, "window_fill_frame", lambda _window: None)++ self.assertEqual(fill_frame(window), frame)++ def test_the_global_titlebar_setting_selects_fill_or_minimise(self):+ action = getattr(kvm_bridge_app, "titlebar_action", lambda _setting: None)+++ self.assertEqual(action(None), "fill")++ self.assertEqual(action(""), "fill")++ self.assertEqual(action("Maximize"), "fill")+ self.assertEqual(action("Fill"), "fill")+ self.assertEqual(action("Zoom"), "fill")+ self.assertEqual(action("Minimise"), "minimise")++ self.assertEqual(action("Minimize"), "minimise")++ self.assertIsNone(action("None"))++ self.assertIsNone(action("Do Nothing"))++ self.assertEqual(action("Unexpected"), "fill")++ def test_double_click_applies_the_selected_titlebar_action(self):+ perform = getattr(kvm_bridge_app, "perform_titlebar_double_click", lambda *_args: None)+ window = mock.Mock()++ perform(window, "Fill")+ window.zoom_.assert_called_once_with(None)++ window.reset_mock()+ perform(window, "Minimise")+ window.miniaturize_.assert_called_once_with(None)++ def test_single_click_on_the_top_strip_starts_a_window_drag(self):+ strip = kvm_bridge_app.TitlebarStrip.alloc().initWithFrame_(((0, 0), (1, 1)))+ event = mock.Mock()+ event.clickCount.return_value = 1++ with mock.patch.object(kvm_bridge_app, "perform_titlebar_drag") as drag:+ strip.mouseDown_(event)++ drag.assert_called_once_with(strip.window(), event)+++if __name__ == "__main__":+ unittest.main()diff --cc mac_app/tests/test_window_resize.pyindex 0000000,0000000..04a7e91new file mode 100644--- /dev/null+++ b/mac_app/tests/test_window_resize.py@@@ -1,0 -1,0 +1,117 @@@++import unittest++from unittest import mock++++from mac_app.tests.test_window_geometry import offscreen_control_window, kvm_bridge_app++++AppKit = kvm_bridge_app.AppKit++widgets = kvm_bridge_app.widgets++objc = kvm_bridge_app.objc++++++class MeasuredStack(AppKit.NSStackView):++ passes = 0++++ def layout(self):++ MeasuredStack.passes += 1++ objc.super(MeasuredStack, self).layout()++++++def measured_stack(vertical=True, spacing=10.0):++ view = MeasuredStack.alloc().init()++ view.setTranslatesAutoresizingMaskIntoConstraints_(False)++ view.setOrientation_(1 if vertical else 0)++ view.setSpacing_(spacing)++ view.setAlignment_(AppKit.NSLayoutAttributeLeading if vertical else AppKit.NSLayoutAttributeCenterY)++ view.setDistribution_(AppKit.NSStackViewDistributionFill)++ return view++++++def settle(window):++ from Foundation import NSDate, NSRunLoop++ window.contentView().layoutSubtreeIfNeeded()++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.01))++ window.contentView().layoutSubtreeIfNeeded()++++++class WindowResizeTests(unittest.TestCase):++ def test_page_breakpoint_jitter_keeps_the_current_typography(self):++ control = offscreen_control_window()++ control._apply_width(700)++ flips = 0++ for width in [599, 601] * 10:++ before = control.wide++ control._apply_width(width)++ flips += control.wide != before++ print(f"page breakpoint jitter: {flips} flips for 20 samples", flush=True)++ self.assertEqual(flips, 0)++ control._apply_width(570)++ self.assertFalse(control.wide)++ control._apply_width(630)++ self.assertTrue(control.wide)++++ def test_resize_notification_at_unchanged_width_does_not_relayout_pages(self):++ control = offscreen_control_window()++ settle(control.window)++ with mock.patch.object(control, "_apply_width", wraps=control._apply_width) as apply_width:++ for _ in range(20):++ control.windowDidResize_(None)++ self.assertEqual(apply_width.call_count, 0)++++ def test_threshold_jitter_does_not_flip_crossing_pair(self):++ pair = widgets.SideBySide(widgets.stack(), widgets.stack(), 254, 354)++ horizontal = AppKit.NSUserInterfaceLayoutOrientationHorizontal++ vertical = AppKit.NSUserInterfaceLayoutOrientationVertical++ pair.view.setFrameSize_((700, 200))++ pair.update_orientation()++ self.assertEqual(pair.orientation(), horizontal)++ flips = 0++ for width in [631, 633] * 20:++ before = pair.orientation()++ pair.view.setFrameSize_((width, 200))++ pair.update_orientation()++ flips += before != pair.orientation()++ print(f"threshold jitter: {flips} flips for 40 samples", flush=True)++ self.assertEqual(flips, 0)++ pair.view.setFrameSize_((600, 200))++ pair.update_orientation()++ self.assertEqual(pair.orientation(), vertical)++++ def test_resize_and_move_sweep_settles_without_layout_feedback(self):++ with mock.patch.object(widgets, "stack", measured_stack):++ control = offscreen_control_window()++ control._select_page("crossing")++ window = control.window++ previous = control.ways_pair.orientation()++ flips = 0++ ambiguous = 0++ MeasuredStack.passes = 0++ widths = list(range(640, 1601, 20)) + list(range(1600, 639, -20))++ for index, width in enumerate(widths):++ window.setFrame_display_(((100000 + index, 100000 + index), (width, 800)), False)++ settle(window)++ orientation = control.ways_pair.orientation()++ flips += orientation != previous++ previous = orientation++ self.assertAlmostEqual(window.frame().size.width, width, delta=1)++ views = (control.pages["crossing"].documentView().subviews()[0],++ control.ways_pair.view, control.ways_pair.first, control.ways_pair.second)++ ambiguous += sum(view.hasAmbiguousLayout() for view in views)++ resize_passes = MeasuredStack.passes++ MeasuredStack.passes = 0++ for index in range(20):++ window.setFrameOrigin_((100000 + index * 10, 100000))++ settle(window)++ move_passes = MeasuredStack.passes++ MeasuredStack.passes = 0++ for _ in range(5):++ settle(window)++ print(f"sweep: {len(widths)} sizes, {resize_passes} stack layouts, {flips} Crossing flips; "++ f"20 moves: {move_passes} layouts; idle: {MeasuredStack.passes}; "++ f"ambiguous Crossing layouts: {ambiguous}", flush=True)++ self.assertLessEqual(flips, 3)++ self.assertEqual(MeasuredStack.passes, 0)++ self.assertEqual(ambiguous, 0)++++++if __name__ == "__main__":++ unittest.main()diff --cc mac_app/wake.pyindex d33f4de,770d693..94dacee--- a/mac_app/wake.py+++ b/mac_app/wake.py@@@ -61,70 -46,39 +61,74 @@@ class WakingController(KVMController)def connection_status(self, value):self._connection_status = value+ def _wake_name(self, peer=None):+ peer = peer or self._in_question()+ name = self._label(lambda entry: entry.get("id") == peer) if peer else None+ return name or self.peer_label or self.cfg.pc_name or self.cfg.host or "the other machine"++ def _wake_address(self, peer):+ """`peer`'s (hardware address, host): its entry's; a Config-built controller's flat settings'."""+ if self._memory is not None:+ return self.cfg.mac_address, self.cfg.host+ entry = next((item for item in self.book.peers() if item.get("id") == peer), None) or {}++ if entry.get("port") == 0:++ return "", ""+ return entry.get("hw") or "", entry.get("host") or ""++ def _awake(self, peer):+ if self._memory is not None:+ return self.connected+ link = self._peers_up.get(peer) if peer else None+ return link is not None and link.live()+@propertydef waking(self) -> bool:return self._waking@propertydef can_wake(self) -> bool:- return bool(self.cfg.mac_address) and not self.connected-- def set_redirecting(self, value, edge=None, offset=None, came_home=True):- if value and not self.redirecting and not self.connected and self.cfg.mac_address and not self._refused():- self.wake()+ """Whether the machine in question (where input is, else where the shortcut would send it)+ is asleep and can be woken."""+ peer = self._in_question()+ return bool(self._wake_address(peer)[0]) and not self._awake(peer)++ def set_redirecting(self, value, edge=None, offset=None, came_home=True, peer=None):+ target = peer or self._shortcut_peer()+ # From home, or on from the machine input is on to another (a menu naming it): one asleep is woken.+ leaving = not self.redirecting or (peer is not None and peer != self.owner.on)+ if (value and leaving and not self._awake(target) and self._wake_address(target)[0]+ and not self._refused(target)):+ self.wake(target)+ return False+ return super().set_redirecting(value, edge, offset, came_home=came_home, peer=peer)++ def _refused(self, peer=None) -> bool:+ """A machine that answered and refused -- the pairing, or the protocol version -- is awake,+ and waking it would hide why; the switch says the refusal instead."""+ link = self._link_of(peer) if peer else None+ kind = link.kind if link is not None else self.status_kind+ return kind in REFUSED_KINDS++ def wake(self, peer=None) -> bool:+ """Sends `peer` (the machine in question when not given) the packet and starts waiting,+ unless a wake is already in flight."""+ peer = peer or self._in_question()++ if self._memory is None and any(entry.get("id") == peer and entry.get("port") == 0 for entry in self.book.peers()):+ return False- return super().set_redirecting(value, edge, offset, came_home=came_home)-- def _refused(self) -> bool:- """A PC that answered and refused -- the token, or the protocol version -- is awake, and- waking it would hide why; the switch says the refusal instead."""- status = self._connection_status or ""- return status == AUTH_FAILED_STATUS or "protocol v" in status or "older Beamer" in status-- def wake(self) -> bool:- """Sends the packet and starts waiting, unless a wake is already in flight."""with self._wake_lock:- if self._waking or self.connected:+ if self._waking or self._awake(peer):return Falseself._waking = True- threading.Thread(target=self._wake_worker, name="wake", daemon=True).start()+ self._waking_peer = peer+ threading.Thread(target=self._wake_worker, args=(peer,), name="wake", daemon=True).start()return True- def _wake_worker(self):+ def _wake_worker(self, peer=None):started = self.clock()+ name = self._wake_name(peer)+ mac, host = self._wake_address(peer)try:- self.wake_sender(self.cfg.mac_address, self.cfg.host)+ self.wake_sender(mac, host)except (OSError, ValueError) as exc:self.logger.warning("wake-on-LAN packet not sent: %s", exc)self._waking = Falsediff --cc mac_app/widgets.pyindex a1d46f5,38dac0e..c4e4ea9--- a/mac_app/widgets.py+++ b/mac_app/widgets.py@@@ -1,7 -1,7 +1,7 @@@"""Vernier's components for the macOS control window, in AppKit.--Everything lays out with Auto Layout constraints and never a frame, so a longer string, a fallback--face or a different display scale reflows instead of clipping. The custom controls draw with the++Page flow uses Auto Layout; preview grids place their cells locally so resizing does not solve++the entire preview tree. Labels keep their measured height. The custom controls draw with thepalette from theme.py; anything clickable takes keyboard focus, answers Space and shows a signalfocus ring."""@@@ -9,17 -9,16 +9,20 @@@from __future__ import annotationsimport math++import weakrefimport AppKit++import CoreTextimport Quartzimport objcimport media_keysimport motionimport theme++from core.locale import americanisefrom ignored_titles import is_modifier_release, recorded_entry-from key_codes import KEY_NAME_TO_CODE, SPECIAL_KEY_NAMES, key_cap, key_title+from key_codes import KEY_NAME_TO_CODE, PRINTABLE_KEY_FALLBACKS, SPECIAL_KEY_NAMES, key_cap, key_title+from core import ways as core_waysdef _autolayout(view):@@@ -38,38 -37,12 +41,100 @@@ def stack(vertical: bool = True, spacinreturn view++class SideBySide:++ """Two blocks in one stack, beside each other when their minimum widths and gap fit."""++++ def __init__(self, first, second, first_minimum, second_minimum, gap=None):++ self.first = first++ self.second = second++ self.first_minimum = first_minimum++ self.second_minimum = second_minimum++ self.gap = theme.tokens.SIDE_BY_SIDE_GAP if gap is None else gap++ self.minimum = first_minimum + second_minimum++ self.view = stack(spacing=self.gap)++ self.view.setAlignment_(AppKit.NSLayoutAttributeWidth)++ self.view.addArrangedSubview_(first)++ self.view.addArrangedSubview_(second)++ for child, minimum in ((first, first_minimum), (second, second_minimum)):++ constraint = child.widthAnchor().constraintGreaterThanOrEqualToConstant_(minimum)++ constraint.setPriority_(AppKit.NSLayoutPriorityDragThatCannotResizeWindow)++ constraint.setActive_(True)++ self.stacked_widths = [child.widthAnchor().constraintEqualToAnchor_(self.view.widthAnchor())++ for child in (first, second)]++ for constraint in self.stacked_widths:++ constraint.setPriority_(1000)++ AppKit.NSLayoutConstraint.activateConstraints_(self.stacked_widths)++ self.view.setIdentifier_("side-by-side")++ self._beside = False++++ def needed(self):++ return self.minimum + self.gap++++ def orientation(self):++ return self.view.orientation()++++ def bounds(self):++ return self.view.bounds()++++ def isHidden(self):++ return self.view.isHidden()++++ def update_orientation(self, width=None):++ width = self.view.bounds().size.width if width is None else width++ # A live resize can alternate rounded widths around the breakpoint. Keep the current++ # layout within a 16pt band rather than rebuilding the stack on every pointer step.++ threshold = self.needed() + (-16 if self._beside else 16)++ beside = width >= threshold++ if beside == self._beside:++ return++ self._beside = beside++ for constraint in self.stacked_widths:++ constraint.setPriority_(1 if beside else 1000)++ self.view.setOrientation_(++ AppKit.NSUserInterfaceLayoutOrientationHorizontal if beside++ else AppKit.NSUserInterfaceLayoutOrientationVertical++ )++ self.view.setAlignment_(++ AppKit.NSLayoutAttributeTop if beside else AppKit.NSLayoutAttributeWidth++ )+++++def _width_cap(view):+ for c in view.constraints():+ if (+ c.firstItem() == view+ and c.secondItem() is None+ and c.firstAttribute() == AppKit.NSLayoutAttributeWidth+ and c.relation() == AppKit.NSLayoutRelationLessThanOrEqual+ ):+ return c.constant()+ return None++def add(parent, view, full_width: bool = True):"""Adds an arranged subview, stretched to the stack's width. NSStackView aligns its children- but does not stretch them, and a control that stops short of the module edge is the giveaway."""+ but does not stretch them, and a control that stops short of the module edge is the giveaway.+ A child with its own maximum width (a note at the reading width) is as wide as the stack up to+ that maximum. Tied to the stack outright, it fixed its whole column at that width, and through+ the column the window: on 1.5.0 the window could not be made wider than 773 to 837 pt."""parent.addArrangedSubview_(view)- if full_width:- view.widthAnchor().constraintEqualToAnchor_(parent.widthAnchor()).setActive_(True)+ if not full_width:+ return view+ cap = _width_cap(view)+ if cap is None:- view.widthAnchor().constraintEqualToAnchor_(parent.widthAnchor()).setActive_(True)++ fill = view.widthAnchor().constraintEqualToAnchor_(parent.widthAnchor())++ # Hidden arranged children retain their external constraints. A required fill links their++ # intrinsic minima back into NSWindow's user-resize limit even while detached by the stack.++ fill.setPriority_(AppKit.NSLayoutPriorityDragThatCannotResizeWindow)++ fill.setActive_(True)+ return view+ view.widthAnchor().constraintLessThanOrEqualToAnchor_(parent.widthAnchor()).setActive_(True)+ # Towards the cap rather than the stack, so the pull never grows with the column. Above the+ # label's own hugging (251), so it fills to the cap; below NSStackView's equal sizing (260),+ # so it cannot unbalance Pairing's two halves.+ reach = view.widthAnchor().constraintEqualToConstant_(cap)+ reach.setPriority_(255)+ reach.setActive_(True)return view@@@ -135,12 -108,12 +200,40 @@@ def attributed(text, size, weight=400,)++def _update_full_text_metadata(view, text, previous):++ if view.toolTip() in (None, previous):++ view.setToolTip_(text)++ if view.accessibilityLabel() in (None, "", previous):++ view.setAccessibilityLabel_(text)++++++class _PreviewCaption(AppKit.NSView):++ text = None++++ @objc.python_method++ def setAttributedStringValue_(self, text):++ self.text = text++ self.setAccessibilityRole_(AppKit.NSAccessibilityStaticTextRole)++ self.setAccessibilityLabel_(text.string())++ self.setNeedsDisplay_(True)++++ @objc.python_method++ def attributedStringValue(self):++ return self.text++++ def isAccessibilityElement(self):++ return True++++ def drawRect_(self, _rect):++ self.text.drawInRect_(self.bounds())++++class Label:"""A label that keeps its style, so the text, colour or size can change without restating it.NSFont has no letter spacing, so tracking is NSKern in the attributed string."""def __init__(self, text="", size=None, weight=400, ink="ink", wrap=False, mono=False, tracking=0.0,-- upper=False, align=None):++ upper=False, align=None, preview=False):self.text = textself.size = size or theme.TYPE["body"]self.weight = weight@@@ -150,8 -123,8 +243,14 @@@self.tracking = trackingself.upper = upperself.align = align++ self._metadata_text = ""maker = AppKit.NSTextField.wrappingLabelWithString_ if wrap else AppKit.NSTextField.labelWithString_-- self.view = _autolayout(maker(""))++ self.view = _autolayout(_PreviewCaption.alloc().init() if preview else maker(""))++ if not preview:++ # wrappingLabelWithString makes a selectable field. A click on one, inside a segment,++ # tile or switch, opened the field editor: I-beam, selected text, and the label redrawn++ # in the editor's own size, alignment and ink.++ self.view.setSelectable_(False)if wrap:squeeze(self.view)self._render()@@@ -166,9 -139,9 +265,14 @@@self._render()def _render(self):++ text = americanise(self.text)self.view.setAttributedStringValue_(attributed(-- self.text, self.size, self.weight, self.ink, self.mono, self.tracking, self.upper, self.align, self.wrap++ text, self.size, self.weight, self.ink, self.mono, self.tracking,++ self.upper, self.align, self.wrap))++ if not self.wrap:++ _update_full_text_metadata(self.view, text, self._metadata_text)++ self._metadata_text = textdef label(text, size=None, weight=400, ink="ink", wrap=False, mono=False):@@@ -176,15 -149,12 +280,15 @@@def eyebrow(text, ink="ink_3"):-- return Label(text, theme.TYPE["eyebrow"], 700, ink, tracking=theme.TRACKING["eyebrow"], upper=True).view++ return Label(text, theme.TYPE["eyebrow"], 700, ink, wrap=True, tracking=theme.TRACKING["eyebrow"], upper=True).view-def note(text="", ink="ink_2", align=None):+def note(text="", ink="ink_2", align=None, reading=True):+ """`reading=False` for a note beside a control in a row: capped there, nothing could take the+ row's spare width, and the row, its module and the page column stopped at note plus control."""label = Label(text, theme.TYPE["note"], ink=ink, wrap=True, align=align)- label.view.widthAnchor().constraintLessThanOrEqualToConstant_(theme.READING_WIDTH).setActive_(True)+ if reading:+ label.view.widthAnchor().constraintLessThanOrEqualToConstant_(theme.READING_WIDTH).setActive_(True)return label@@@ -202,7 -172,7 +306,7 @@@ class Moduleself.view = box("panel")self.body = stack(spacing=spacing)self.view.addSubview_(self.body)-- vertical, horizontal = theme.MODULE_PADDING++ vertical, horizontal = 16, 16AppKit.NSLayoutConstraint.activateConstraints_([self.body.topAnchor().constraintEqualToAnchor_constant_(self.view.topAnchor(), vertical),self.body.leadingAnchor().constraintEqualToAnchor_constant_(self.view.leadingAnchor(), horizontal),@@@ -214,6 -184,6 +318,8 @@@collapse.setActive_(True)def add(self, view, full_width=True):++ if getattr(view, 'segmented_owner', None) is not None:++ view = field_row(None, view)[0]return add(self.body, view, full_width)@@@ -274,20 -244,20 +380,48 @@@ def grid(views, columns)"""Views in equal columns on the `rule` colour, 1pt apart inside a 1pt border, each row as tallas its tallest view."""frame = box("rule")-- rows = stack(spacing=1)-- for start in range(0, len(views), columns):-- row = stack(vertical=False, spacing=1)-- row.setDistribution_(AppKit.NSStackViewDistributionFillEqually)-- row.setAlignment_(AppKit.NSLayoutAttributeTop)-- for view in views[start:start + columns]:-- row.addArrangedSubview_(view)-- view.heightAnchor().constraintEqualToAnchor_(row.heightAnchor()).setActive_(True)-- add(rows, row)++ rows = _autolayout(_ResponsiveView.alloc().init())++ for view in views:++ rows.addSubview_(view)++ rows.owner = FormGrid(rows, views, columns)++ rows.owner.arrange(600)frame.addSubview_(rows)pin(rows, frame, (1, 1, 1, 1))return frame++class FormGrid:++ def __init__(self, view, cells, columns):++ self.view, self.cells, self.columns = view, list(cells), columns++ self.constraints, self.count = [], None++++ def arrange(self, width):++ count = self.columns if width >= 350 else 1++ if self.count == count:++ return++ self.count = count++ AppKit.NSLayoutConstraint.deactivateConstraints_(self.constraints)++ constraints, previous = [], None++ for start in range(0, len(self.cells), count):++ row = self.cells[start:start + count]++ for index, cell in enumerate(row):++ constraints.extend([++ cell.topAnchor().constraintEqualToAnchor_constant_(previous.bottomAnchor() if previous else self.view.topAnchor(), 1 if previous else 0),++ cell.leadingAnchor().constraintEqualToAnchor_constant_(self.view.leadingAnchor() if index == 0 else row[index-1].trailingAnchor(), 0 if index == 0 else 1),++ cell.heightAnchor().constraintEqualToAnchor_(row[0].heightAnchor()),++ ])++ # The last cell of a short row runs to the edge: an empty slot would show the++ # grid's `rule` ground as an odd grey cell.++ if index == len(row) - 1 and len(row) < count:++ constraints.append(cell.trailingAnchor().constraintEqualToAnchor_(self.view.trailingAnchor()))++ else:++ constraints.append(cell.widthAnchor().constraintEqualToAnchor_multiplier_constant_(self.view.widthAnchor(), 1/count, -(count-1)/count))++ previous = row[0]++ constraints.append(self.view.bottomAnchor().constraintEqualToAnchor_(previous.bottomAnchor()))++ self.constraints = constraints++ AppKit.NSLayoutConstraint.activateConstraints_(constraints)++++def flipped(cls):return _autolayout(cls.alloc().init())@@@ -299,6 -269,6 +433,7 @@@ class Figuredef __init__(self, text, size, unit="", unit_size=None, tracking=0.0, ink="ink"):self.text, self.size, self.unit, self.ink, self.tracking = text, size, unit, ink, trackingself.unit_size = unit_size or theme.TYPE["small"]++ self._metadata_text = ""self.view = squeeze(_autolayout(AppKit.NSTextField.labelWithString_("")))self._render()@@@ -312,12 -282,12 +447,15 @@@self._render()def _render(self):++ text = americanise(self.text + (" " + self.unit if self.unit else ""))string = AppKit.NSMutableAttributedString.alloc().initWithAttributedString_(-- attributed(self.text, self.size, ink=self.ink, mono=True, tracking=self.tracking)++ attributed(americanise(self.text), self.size, ink=self.ink, mono=True, tracking=self.tracking))if self.unit:string.appendAttributedString_(attributed(" " + self.unit, self.unit_size, ink="ink_3", mono=True))self.view.setAttributedStringValue_(string)++ _update_full_text_metadata(self.view, text, self._metadata_text)++ self._metadata_text = textclass Readout:@@@ -376,10 -346,10 +514,75 @@@ class LEDlayer.addAnimation_forKey_(animation, "blink")++_NAVIGATION_KEYS = {"\t", "\x19",++ AppKit.NSLeftArrowFunctionKey, AppKit.NSRightArrowFunctionKey,++ AppKit.NSUpArrowFunctionKey, AppKit.NSDownArrowFunctionKey}++++++def is_navigation_key(event):++ """Tab, Shift-Tab and the arrows turn focus rings on (spec section 6). Any other key, a++ shortcut included, leaves them as the last click left them: off."""++ keys = event.charactersIgnoringModifiers()++ return (bool(keys) and keys[0] in _NAVIGATION_KEYS++ and not event.modifierFlags() & AppKit.NSEventModifierFlagCommand)++++++def keyboard_focus_visible(view):++ window = view.window()++ return (window is not None and window.firstResponder() == view++ and bool(getattr(window, 'keyboard_navigation', False)))++++class Pressable(AppKit.NSView):"""A view that acts on a click or Space, the base for every custom control here. A focus ring in`signal` is drawn as its own sublayer, outside the view unless `ring_inset` says inside."""++ # Missing Python attributes on an NSView fall through to expensive Objective-C lookup.++ ring = None++ ring_owner = None++ selection_mark = None++ tile_content = None++ ring_inset = -3.0++ pointer_cursor = False++++ @objc.python_method++ def set_tile_state(self, selected=None, hovered=None):++ if selected is not None:++ self.tile_selected = selected++ if hovered is not None:++ self.tile_hovered = hovered++ if not hasattr(self, "tile_selected"):++ return++ layer = self.layer()++ hover_background = "well" if theme.is_dark() else "panel"++ theme.tint(layer, background=hover_background if self.tile_hovered else "ground",++ border="signal" if self.tile_selected else ("ink", .18) if self.tile_hovered else "rule")++ layer.setBorderWidth_(2 if self.tile_selected else 1)++++ @objc.python_method++ def refresh_colours(self):++ self.set_tile_state()++++ @objc.python_method++ def add_selection_mark(self):++ mark = Quartz.CAShapeLayer.layer()++ path = Quartz.CGPathCreateMutable()++ Quartz.CGPathMoveToPoint(path, None, 1, 6)++ Quartz.CGPathAddLineToPoint(path, None, 4, 3)++ Quartz.CGPathAddLineToPoint(path, None, 10, 10)++ mark.setPath_(path)++ mark.setFillColor_(None)++ mark.setLineWidth_(2)++ mark.setHidden_(True)++ self.layer().addSublayer_(mark)++ self.selection_mark = mark++++ @objc.python_method++ def show_selection_mark(self, selected):++ self.selection_mark.setHidden_(not selected)++ theme.tint(self.selection_mark, stroke='signal')++ self.setNeedsLayout_(True)++def acceptsFirstResponder(self):return getattr(self, "enabled", True) and getattr(self, "callback", None) is not None@@@ -387,7 -357,7 +590,9 @@@return Truedef mouseDown_(self, _event):-- pass++ if self.window() is not None:++ self.window().keyboard_navigation = False++ self._ring(False)def mouseUp_(self, event):point = self.convertPoint_fromView_(event.locationInWindow(), None)@@@ -395,6 -365,6 +600,8 @@@self.press()def keyDown_(self, event):++ if self.window() is not None and is_navigation_key(event):++ self.window().keyboard_navigation = Trueif event.charactersIgnoringModifiers() in (" ", "\r"):self.press()else:@@@ -425,10 -395,10 +632,16 @@@def layout(self):objc.super(Pressable, self).layout()++ content = getattr(self, 'tile_content', None)++ if content is not None:++ content.arrange(self.bounds().size)ring = getattr(self, "ring", None)if ring is not None:inset = getattr(self, "ring_inset", -3.0)ring.setFrame_(AppKit.NSInsetRect(self.bounds(), inset, inset))++ mark = getattr(self, 'selection_mark', None)++ if mark is not None and not mark.isHidden():++ mark.setFrame_(((self.bounds().size.width - 18, self.bounds().size.height - 18), (12, 12)))owner = getattr(self, "ring_owner", None)if owner is not None:owner.follow(self)@@@ -441,6 -411,6 +654,11 @@@@objc.python_methoddef _ring(self, on):++ window = self.window()++ on = on and (window is None or getattr(window, 'keyboard_navigation', False))++ sidebar = getattr(self, 'sidebar_owner', None)++ if sidebar is not None:++ on = on and sidebar.rows[sidebar.selected][1] == selfif getattr(self, "ring", None) is None:self.setWantsLayer_(True)ring = Quartz.CALayer.layer()@@@ -461,19 -431,19 +679,39 @@@ def pressable(callback, fill=None, stroreturn view++class _WrappingButton(AppKit.NSButton):++ def intrinsicContentSize(self):++ natural = objc.super(_WrappingButton, self).intrinsicContentSize()++ width = self.bounds().size.width or min(240, max(64, natural.width))++ ink = self.attributedTitle().boundingRectWithSize_options_(++ (max(1, width - 24), 10000), AppKit.NSStringDrawingUsesLineFragmentOrigin)++ return AppKit.NSMakeSize(natural.width, max(30, math.ceil(ink.size.height) + 12))++++ def setFrameSize_(self, size):++ changed = size.width != self.bounds().size.width++ objc.super(_WrappingButton, self).setFrameSize_(size)++ if changed:++ self.invalidateIntrinsicContentSize()++++class Button:"""A Vernier button. Wraps NSButton rather than subclassing it: its width is recomputed from therendered title on every change, and an AppKit object has nowhere to keep that constraint.Styles are `plain` (well, edge border), `primary` (ink) and `live` (signal)."""-- HEIGHTS = {"small": 24, "regular": 30, "big": 40}++ HEIGHTS = {"small": 30, "regular": 30, "big": 40}def __init__(self, title, target, action, style="plain", scale="regular", full_width=False):-- self.view = _autolayout(AppKit.NSButton.buttonWithTitle_target_action_(title, target, action))++ self.view = _autolayout(_WrappingButton.buttonWithTitle_target_action_(title, target, action))self.view.setBordered_(False)self.view.setWantsLayer_(True)self.view.layer().setCornerRadius_(theme.RADIUS["button"])-- self.view.heightAnchor().constraintEqualToConstant_(self.HEIGHTS[scale]).setActive_(True)++ self.view.heightAnchor().constraintGreaterThanOrEqualToConstant_(self.HEIGHTS[scale]).setActive_(True)++ self.view.widthAnchor().constraintLessThanOrEqualToConstant_(240).setActive_(True)++ self.view.cell().setLineBreakMode_(AppKit.NSLineBreakByWordWrapping)++ self.view.cell().setUsesSingleLineMode_(False)++ self.view.cell().setWraps_(True)++ squeeze(self.view)self.style = styleself.scale = scaleself.full_width = full_width@@@ -506,17 -476,17 +744,15 @@@# disables to the same quiet outline instead.fill, stroke, ink = "panel", "rule", "ink_3"text_size = theme.TYPE["small"] if self.scale == "small" else theme.TYPE["button"]-- title = attributed(self.title, text_size, 600, ink, align=AppKit.NSTextAlignmentCenter)++ title = attributed(americanise(self.title), text_size, 600, ink, align=AppKit.NSTextAlignmentCenter, wrap=True)self.view.setAttributedTitle_(title)paint(self.view, fill, stroke)-- if self.full_width:-- return# Width comes from the rendered title, not a measured pixel, so a longer word or a# fallback face widens the button instead of clipping it.if self.width is not None:self.width.setActive_(False)-- padding = 20 if self.scale == "small" else 26-- self.width = self.view.widthAnchor().constraintEqualToConstant_(math.ceil(title.size().width) + padding)++ self.width = self.view.widthAnchor().constraintEqualToConstant_(min(240, max(64, math.ceil(title.size().width) + 24)))++ self.width.setPriority_(255)self.width.setActive_(True)@@@ -535,38 -505,24 +771,99 @@@ class _Target(AppKit.NSObject)self.callback(sender)-class _CentredCell(AppKit.NSTextFieldCell):- """Text centred in the cell's height, at rest and while typed into, since the field editor lays- itself out in drawingRectForBounds too."""+def callback_target(callback):+ """A target for a control whose action should call `callback()`. The control holds its target+ weakly, so the caller keeps this."""+ return _Target.alloc().initWithCallback_(lambda _sender: callback())+++def action_button(title, callback, **options):+ """A Button that calls `callback()`, for the buttons a window builds as it goes."""+ target = callback_target(callback)+ button = Button(title, target, "fire:", **options)+ button.target = target+ return button++class _CentredCell(AppKit.NSTextFieldCell):- """Text centred in the cell's height, at rest and while typed into, since the field editor lays- itself out in drawingRectForBounds too."""-def drawingRectForBounds_(self, bounds):rect = objc.super(_CentredCell, self).drawingRectForBounds_(bounds)height = self.cellSizeForBounds_(rect).height-- if height >= rect.size.height:-- return rect-- return AppKit.NSMakeRect(rect.origin.x, rect.origin.y + (rect.size.height - height) / 2,-- rect.size.width, height)++ return AppKit.NSMakeRect(rect.origin.x, rect.origin.y + max(0, (rect.size.height - height) / 2),++ rect.size.width, min(height, rect.size.height))++++ def setUpFieldEditorAttributes_(self, editor):++ editor = objc.super(_CentredCell, self).setUpFieldEditorAttributes_(editor)++ control = self.controlView()++ if getattr(control, "pair_editor", None) is None:++ control.pair_editor = editor++ control.pair_selected_attributes = dict(editor.selectedTextAttributes())++ AppKit.NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(++ control, "pairingSelectionChanged:", AppKit.NSTextViewDidChangeSelectionNotification, editor)++ editor.setSelectedTextAttributes_({++ AppKit.NSForegroundColorAttributeName: AppKit.NSColor.clearColor(),++ AppKit.NSBackgroundColorAttributeName: AppKit.NSColor.clearColor(),++ })++ return editor++++++class _DigitInk(AppKit.NSView):++ """Draw above the field editor: its selection compositor can erase an underlying glyph."""++++ def hitTest_(self, _point):++ return None++++ def drawRect_(self, rect):++ control = self.control()++ editor = control.currentEditor()++ text = editor.string() if editor is not None else control.stringValue()++ if not text:++ return++ font = CoreText.CTFontCreateWithName(control.font().fontName(), control.font().pointSize(), None)++ found, glyphs = CoreText.CTFontGetGlyphsForCharacters(font, text[-1], None, 1)++ if not found:++ return++ path = CoreText.CTFontCreatePathForGlyph(font, glyphs[0], None)++ ink = Quartz.CGPathGetBoundingBox(path)++ bounds = self.bounds()++ context = AppKit.NSGraphicsContext.currentContext().CGContext()++ Quartz.CGContextSaveGState(context)++ if editor is not None and editor.selectedRange().length:++ Quartz.CGContextSetFillColorWithColor(context, theme.cg("signal_dim"))++ Quartz.CGContextFillRect(context, bounds)++ Quartz.CGContextTranslateCTM(context, bounds.size.width / 2, bounds.size.height / 2)++ if self.isFlipped():++ Quartz.CGContextScaleCTM(context, 1, -1)++ Quartz.CGContextTranslateCTM(context, -ink.origin.x - ink.size.width / 2, -ink.origin.y - ink.size.height / 2)++ Quartz.CGContextSetFillColorWithColor(context, theme.cg("ink"))++ Quartz.CGContextAddPath(context, path)++ Quartz.CGContextFillPath(context)++ Quartz.CGContextRestoreGState(context)class _CentredField(AppKit.NSTextField):++ """Keep native editing/accessibility while the overlay centres the outline, not the line box."""++@classmethoddef cellClass(cls):return _CentredCell++ def pairingSelectionChanged_(self, _notification):++ self.ink_view.setNeedsDisplay_(True)++++ def becomeFirstResponder(self):++ focused = objc.super(_CentredField, self).becomeFirstResponder()++ if focused:++ self.delegate().owner.begin_editing(self)++ return focused++++ def setStringValue_(self, value):++ objc.super(_CentredField, self).setStringValue_(value)++ self.setNeedsDisplay_(True)++ overlay = getattr(self, "ink_view", None)++ if overlay is not None:++ overlay.setNeedsDisplay_(True)++def field(secure=False, mono=True, cls=None):"""A text input on `ground` with an `edge` border and the text inset off it. Returns@@@ -587,19 -543,19 +884,84 @@@return container, control++class _ResponsiveView(AppKit.NSView):++ owner = None++++ def setFrameSize_(self, size):++ changed = size.width != self.bounds().size.width++ objc.super(_ResponsiveView, self).setFrameSize_(size)++ if changed and self.owner is not None:++ self.setNeedsLayout_(True)++++ def layout(self):++ if self.owner is not None:++ self.owner.arrange(self.bounds().size.width)++ objc.super(_ResponsiveView, self).layout()++++++class FieldRow:++ def __init__(self, caption, control):++ self.view = _autolayout(_ResponsiveView.alloc().init())++ self.view.owner = self++ self.view.field_owner = self++ self.control = control++ self.caption = caption++ self.words = Label(caption or '', theme.TYPE['note'], ink='ink_2', wrap=True)++ self.words.view.setHidden_(caption is None)++ for child in ((self.words.view, control) if caption is not None else (control,)):++ self.view.addSubview_(child)++ self.constraints = []++ self.stacked = None++ if caption is not None and not control.accessibilityLabel():++ control.setAccessibilityLabel_(caption)++ selector = getattr(control, 'segmented_owner', None)++ if selector is not None:++ selector.set_cap({'Length': 240, 'Size': 240, 'This window': 252,++ 'Ticks at': 360, 'Style for': 240, 'Show at': 264}.get(caption, selector.cap))++ self.arrange(640)++++ def arrange(self, width):++ stacked = self.caption is None or width < 528++ selector = getattr(self.control, 'segmented_owner', None)++ if selector is not None:++ selector.set_available_width(max(0, width - (0 if stacked else 196)))++ if stacked == self.stacked:++ return++ self.stacked = stacked++ AppKit.NSLayoutConstraint.deactivateConstraints_(self.constraints)++ label, control, view = self.words.view, self.control, self.view++ if self.caption is None:++ self.constraints = [++ control.topAnchor().constraintEqualToAnchor_(view.topAnchor()),++ control.bottomAnchor().constraintEqualToAnchor_(view.bottomAnchor()),++ control.leadingAnchor().constraintEqualToAnchor_(view.leadingAnchor()),++ control.trailingAnchor().constraintLessThanOrEqualToAnchor_(view.trailingAnchor()),++ ]++ AppKit.NSLayoutConstraint.activateConstraints_(self.constraints)++ return++ constraints = [label.topAnchor().constraintEqualToAnchor_(view.topAnchor()),++ label.leadingAnchor().constraintEqualToAnchor_(view.leadingAnchor()),++ view.bottomAnchor().constraintGreaterThanOrEqualToAnchor_(label.bottomAnchor()),++ view.bottomAnchor().constraintEqualToAnchor_(control.bottomAnchor()),++ control.trailingAnchor().constraintLessThanOrEqualToAnchor_(view.trailingAnchor())]++ if stacked:++ constraints.extend([label.widthAnchor().constraintEqualToAnchor_(view.widthAnchor()),++ control.topAnchor().constraintEqualToAnchor_constant_(label.bottomAnchor(), 8),++ control.leadingAnchor().constraintEqualToAnchor_(view.leadingAnchor())])++ else:++ constraints.extend([label.widthAnchor().constraintEqualToConstant_(180),++ control.topAnchor().constraintEqualToAnchor_(view.topAnchor()),++ control.leadingAnchor().constraintEqualToAnchor_constant_(label.trailingAnchor(), 16)])++ available = control.widthAnchor().constraintEqualToAnchor_constant_(view.widthAnchor(), 0 if stacked else -196)++ available.setPriority_(255)++ constraints.append(available)++ self.constraints = constraints++ AppKit.NSLayoutConstraint.activateConstraints_(constraints)++++def field_row(caption, control):-- """Caption on the left in a fixed column, control filling the rest. Returns (row, caption).-- The caption is also the control's name to VoiceOver, which otherwise reads a group of choices-- or a field with nothing to say what it sets."""-- line = stack(vertical=False, spacing=10)-- words = Label(caption, theme.TYPE["note"], ink="ink_2", wrap=True)-- size(words.view, width=116)-- line.addArrangedSubview_(words.view)-- line.addArrangedSubview_(control)-- hug(control, AppKit.NSLayoutPriorityDefaultLow)-- if not control.accessibilityLabel():-- control.setAccessibilityLabel_(caption)-- return line, words++ row = FieldRow(caption, control)++ return row.view, row.wordsclass _Tick(AppKit.NSView):@@@ -640,7 -596,7 +1002,7 @@@ class WayTileself.view.setAccessibilityLabel_(title)self.view.ring_inset = 1.0self.tick = size(_autolayout(_Tick.alloc().init()), 15, 15)-- self.name = Label(title, theme.TYPE["body"], 600)++ self.name = Label(title, theme.TYPE["body"], 600, wrap=True)self.detail = Label(detail, theme.TYPE["small"], ink="ink_3", wrap=True)# No detail takes no line, so a tile that is only a name stays one line tall.self.detail.view.setHidden_(not detail)@@@ -723,6 -679,6 +1085,7 @@@ class Switchself.view.setAccessibilityLabel_(title)self.track = size(_autolayout(_Track.alloc().init()), 34, 18)self.track.place_knob(False, False)++ self.view.heightAnchor().constraintGreaterThanOrEqualToConstant_(30).setActive_(True)self.words = Label(title, theme.TYPE["body"], wrap=True)line = stack(vertical=False, spacing=12)line.addArrangedSubview_(self.words.view)@@@ -760,6 -716,6 +1123,10 @@@self.on_change(self._value)++class _ControlBox(AppKit.NSView):++ pass++++class Segmented:"""One choice of several, laid out `columns` across in as many rows as it takes. `.value` readsand writes the value rather than the index; a value that is not a choice selects nothing."""@@@ -770,31 -726,31 +1137,79 @@@self._value = Noneself.enabled = Truecolumns = columns or len(self.choices)-- self.view = box("edge", "edge", theme.RADIUS["segment"])++ self.view = box("edge", "edge", theme.RADIUS["segment"], cls=_ControlBox)self.view.layer().setMasksToBounds_(True)# One group to VoiceOver, named by its field_row caption, with the choices inside it.self.view.setAccessibilityElement_(True)self.view.setAccessibilityRole_(AppKit.NSAccessibilityRadioGroupRole)-- grid = stack(spacing=1)-- grid.setDistribution_(AppKit.NSStackViewDistributionFillEqually)++ grid = _autolayout(_ResponsiveView.alloc().init())++ grid.owner = self++ self.grid = grid++ self.columns = columns++ self.layout_columns = None++ self.available_width = None++ self.layout_constraints = []self.cells = []for start in range(0, len(self.choices), columns):-- row = stack(vertical=False, spacing=1)-- row.setDistribution_(AppKit.NSStackViewDistributionFillEqually)for value, title in self.choices[start:start + columns]:cell = pressable(lambda value=value: self._choose(value), "well", role=AppKit.NSAccessibilityRadioButtonRole)cell.setAccessibilityLabel_(title)cell.ring_inset = 2.0-- words = Label(title, theme.TYPE["small"], ink="ink_2", align=AppKit.NSTextAlignmentCenter)++ words = Label(title, theme.TYPE["small"], ink="ink_2", wrap=True, align=AppKit.NSTextAlignmentCenter)squeeze(words.view)cell.addSubview_(words.view)pin(words.view, cell, (6, 4, 6, 4))-- cell.heightAnchor().constraintGreaterThanOrEqualToConstant_(28).setActive_(True)-- row.addArrangedSubview_(cell)++ cell.heightAnchor().constraintGreaterThanOrEqualToConstant_(30).setActive_(True)++ grid.addSubview_(cell)self.cells.append((value, cell, words))-- add(grid, row)self.view.addSubview_(grid)pin(grid, self.view, (1, 1, 1, 1))++ self.view.segmented_owner = self++ measured = max(attributed(title, theme.TYPE['small']).size().width + 24 for _, title in self.choices)++ self.cap_constraint = self.view.widthAnchor().constraintLessThanOrEqualToConstant_(360)++ self.cap_constraint.setActive_(True)++ self.preference = self.view.widthAnchor().constraintEqualToConstant_(360)++ self.preference.setPriority_(255)++ self.preference.setActive_(True)++ self.set_cap(min(120, measured) * columns)++ self.arrange(self.cap - 2)++++ def set_cap(self, width):++ self.cap = min(width, 120 * self.columns, 360)++ self.cap_constraint.setConstant_(self.cap)++ self.preference.setConstant_(self.cap)++++ def set_available_width(self, width):++ self.available_width = width++ cap = self.cap if width >= self.cap else min(120, width)++ if cap != self.cap_constraint.constant():++ self.cap_constraint.setConstant_(cap)++ self.preference.setConstant_(cap)++ self.grid.setNeedsLayout_(True)++++ def arrange(self, width):++ available = self.available_width if self.available_width is not None else width + 2++ columns = self.columns if available >= self.cap else 1++ if self.layout_columns == columns:++ return++ self.layout_columns = columns++ AppKit.NSLayoutConstraint.deactivateConstraints_(self.layout_constraints)++ constraints = []++ rows = [self.cells[start:start + columns] for start in range(0, len(self.cells), columns)]++ previous = None++ for row in rows:++ for index, (_value, cell, _words) in enumerate(row):++ constraints.extend([++ cell.topAnchor().constraintEqualToAnchor_constant_(previous.bottomAnchor() if previous else self.grid.topAnchor(), 1 if previous else 0),++ cell.leadingAnchor().constraintEqualToAnchor_constant_(self.grid.leadingAnchor() if index == 0 else row[index-1][1].trailingAnchor(), 0 if index == 0 else 1),++ cell.widthAnchor().constraintEqualToAnchor_multiplier_constant_(self.grid.widthAnchor(), 1 / columns, -(columns - 1) / columns),++ cell.heightAnchor().constraintEqualToAnchor_(row[0][1].heightAnchor()),++ ])++ previous = row[0][1]++ constraints.append(self.grid.bottomAnchor().constraintEqualToAnchor_(previous.bottomAnchor()))++ self.layout_constraints = constraints++ AppKit.NSLayoutConstraint.activateConstraints_(constraints)++@propertydef value(self):@@@ -831,6 -787,6 +1246,50 @@@self.on_change(value)++class MenuChoice:++ """Native menu keeps full machine names available without growing the column."""++ def __init__(self, choices, on_change=None):++ self.choices = list(choices)++ self.on_change = on_change++ self.view = box()++ self.popup = _autolayout(AppKit.NSPopUpButton.alloc().initWithFrame_pullsDown_(((0, 0), (0, 0)), False))++ self.popup.setFont_(theme.font(theme.TYPE['body']))++ self.popup.setAutoenablesItems_(False)++ self.popup.setAccessibilityLabel_('Match design with')++ self.view.addSubview_(self.popup)++ # Native popup frames extend beyond their alignment rect by seven points.++ pin(self.popup, self.view, (0, 4, 0, 4))++ self.items = []++ for value, title in choices:++ self.popup.addItemWithTitle_(title)++ item = self.popup.lastItem()++ item.setToolTip_(title)++ self.items.append((value, item))++ self.target = _Target.alloc().initWithCallback_(self._changed)++ self.popup.setTarget_(self.target)++ self.popup.setAction_('fire:')++ self.view.widthAnchor().constraintLessThanOrEqualToConstant_(320).setActive_(True)++ preference = self.view.widthAnchor().constraintEqualToConstant_(320)++ preference.setPriority_(255)++ preference.setActive_(True)++ self.view.heightAnchor().constraintGreaterThanOrEqualToConstant_(30).setActive_(True)++ squeeze(self.view)++ squeeze(self.popup)++++ @property++ def value(self):++ return self.choices[self.popup.indexOfSelectedItem()][0]++++ @value.setter++ def value(self, value):++ self.popup.selectItemAtIndex_(next((i for i, pair in enumerate(self.choices) if pair[0] == value), 0))++ self.popup.setAccessibilityValue_(self.popup.titleOfSelectedItem())++++ def _changed(self, _sender):++ if self.on_change is not None:++ self.on_change(self.value)++++class Selector:"""The MAC / WINDOWS indicator: shows where input is, and is not itself a control."""@@@ -943,10 -899,10 +1402,15 @@@ def scale_value(fraction, low, high, scclass _RulerView(_Flipped):TRACK = 30.0TOP = 4.0++ drawn_focus = Falsedef acceptsFirstResponder(self):return self.owner.enabled++ def refresh_keyboard_focus(self):++ if keyboard_focus_visible(self) != self.drawn_focus:++ self.setNeedsDisplay_(True)++def acceptsFirstMouse_(self, _event):return True@@@ -977,7 -933,7 +1441,7 @@@keys = event.charactersIgnoringModifiers()steps = {AppKit.NSLeftArrowFunctionKey: -1, AppKit.NSDownArrowFunctionKey: -1,AppKit.NSRightArrowFunctionKey: 1, AppKit.NSUpArrowFunctionKey: 1}-- direction = steps.get(ord(keys[0])) if keys else None++ direction = steps.get(keys[0]) if keys else Noneif direction is None or not self.owner.enabled:objc.super(_RulerView, self).keyDown_(event)return@@@ -1026,7 -982,7 +1490,10 @@@text_width = text.sizeWithAttributes_(attributes).widthleft = 0 if index == 0 else width - text_width if index == len(owner.labels) - 1 else x - text_width / 2text.drawAtPoint_withAttributes_((left, base + 5), attributes)-- focused = self.window() is not None and self.window().firstResponder() == self++ # A drag makes the ruler first responder so the arrows nudge it next, which is not++ # keyboard navigation: the signal thumb waits for Tab or an arrow.++ focused = keyboard_focus_visible(self)++ self.drawn_focus = focused_fill("panel", ((thumb - 4.5, self.TOP), (9, self.TRACK)))_fill("signal" if focused else "ink", ((thumb - 1.5, self.TOP), (3, self.TRACK)))@@@ -1116,10 -1072,10 +1583,10 @@@ class KeyRecorderface = box("ground", radius=theme.RADIUS["keycap"] - 1)self.view.addSubview_(face)pin(face, self.view, (1, 1, 3, 1))-- self.key = Label(key_title(value), theme.TYPE["keycap"], mono=True, tracking=-0.02)++ self.key = Label(key_title(value), theme.TYPE["keycap"], mono=True, tracking=-0.02, wrap=True)squeeze(self.key.view)-- self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight)-- line = stack(vertical=False, spacing=10)++ self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight, wrap=True)++ line = stack(spacing=8)line.addArrangedSubview_(self.key.view)line.addArrangedSubview_(self.hint.view)hug(self.key.view, AppKit.NSLayoutPriorityDefaultLow)@@@ -1164,98 -1120,6 +1631,98 @@@paint(self.view, "edge")+class JumpKeyRecorder:+ """Records a modifier chord for a peer-specific local jump key."""++ HINT = "Click, then press a key combination"++ def __init__(self, value="", on_change=None, on_arm=None):+ self.value = value or ""+ self.on_change = on_change+ self.on_arm = on_arm+ self.monitor = None+ self.view = pressable(self._clicked, "edge", radius=theme.RADIUS["keycap"])+ self.view.setAccessibilityLabel_("Jump straight here key, " + self._title())+ face = box("ground", radius=theme.RADIUS["keycap"] - 1)+ self.view.addSubview_(face)+ pin(face, self.view, (1, 1, 3, 1))- self.key = Label(self._title(), theme.TYPE["body"], ink="ink_3")++ self.key = Label(self._title(), theme.TYPE["body"], ink="ink_3", wrap=True)+ squeeze(self.key.view)- self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentLeft)++ self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentLeft, wrap=True)+ self.line = stack(spacing=5)+ self.line.addArrangedSubview_(self.key.view)+ self.line.addArrangedSubview_(self.hint.view)+ line = self.line+ face.addSubview_(line)+ pin(line, face, (7, 12, 7, 12))++ def _show_title(self, ink=None):+ has_value = bool(self.value)+ self.key.set(+ self._title(),+ size=theme.TYPE["keycap"] if has_value else theme.TYPE["body"],+ ink=ink or ("ink" if has_value else "ink_3"),+ mono=has_value,+ )++ def _title(self):+ if not self.value:+ return "Choose a key combination"+ names = {"ctrl": "Control", "alt": "Option", "shift": "Shift", "cmd": "Command"}+ return " ".join(names.get(part, key_title(part)) for part in self.value.split("+"))++ def set_value(self, value):+ self.value = value or ""+ self._show_title()+ self.view.setAccessibilityLabel_("Jump straight here key, " + self._title())++ def _clicked(self):+ if self.monitor is not None:+ self._stop()+ return+ self.key.set("Press a key combination…", size=theme.TYPE["body"], ink="signal", mono=False)+ self.hint.set("Click again to cancel")+ paint(self.view, "signal")+ self.monitor = AppKit.NSEvent.addLocalMonitorForEventsMatchingMask_handler_(+ AppKit.NSEventMaskKeyDown | AppKit.NSEventMaskFlagsChanged, self._recorded+ )+ if self.on_arm is not None:+ self.on_arm(True)++ def _recorded(self, event):+ if event.type() != AppKit.NSEventTypeKeyDown:+ return event+ flags = int(event.modifierFlags())+ modifiers = []+ for name, flag in (("ctrl", AppKit.NSEventModifierFlagControl), ("alt", AppKit.NSEventModifierFlagOption),+ ("shift", AppKit.NSEventModifierFlagShift), ("cmd", AppKit.NSEventModifierFlagCommand)):+ if flags & flag:+ modifiers.append(name)+ keycode = int(event.keyCode())+ key = SPECIAL_KEY_NAMES.get(keycode) or PRINTABLE_KEY_FALLBACKS.get(keycode)+ chord = core_ways.jump_chord(modifiers, key)+ if chord is None:+ return None+ self._stop()+ self.set_value(chord)+ if self.on_change is not None:+ self.on_change(chord)+ return None++ def cancel(self):+ self._stop()++ def _stop(self):+ if self.monitor is not None:+ AppKit.NSEvent.removeMonitor_(self.monitor)+ self.monitor = None+ if self.on_arm is not None:+ self.on_arm(False)+ self._show_title()+ self.hint.set(self.HINT)+ paint(self.view, "edge")++class IgnoredRecorder:"""A keycap that records the next key, mouse button or media key as an entry to keep on thisMac while its input is on Windows. Clicking arms it; the left mouse button is never recorded,@@@ -1280,10 -1144,10 +1747,10 @@@pin(face, self.view, (1, 1, 3, 1))# Body size, unlike the shortcut's keycap: this is an action at the foot of a list, and at# keycap size it outweighed the entries above it.-- self.title = Label(self.TITLE, theme.TYPE["body"], 600)++ self.title = Label(self.TITLE, theme.TYPE["body"], 600, wrap=True)squeeze(self.title.view)-- self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight)-- line = stack(vertical=False, spacing=10)++ self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight, wrap=True)++ line = stack(spacing=8)line.addArrangedSubview_(self.title.view)line.addArrangedSubview_(self.hint.view)hug(self.title.view, AppKit.NSLayoutPriorityDefaultLow)@@@ -1347,9 -1211,9 +1814,15 @@@class _CodeDelegate(AppKit.NSObject):++ def controlTextDidBeginEditing_(self, notification):++ self.owner.begin_editing(notification.object())++def controlTextDidChange_(self, notification):self.owner.changed(notification.object())++ def controlTextDidEndEditing_(self, notification):++ self.owner.end_editing(notification.object())++def control_textView_doCommandBySelector_(self, control, _text_view, selector):return self.owner.command(control, selector)@@@ -1358,7 -1222,7 +1831,7 @@@ class CodeBoxes"""Six single-digit boxes for the pairing code. Typing moves on, Backspace in an empty box movesback, pasting the whole code fills every box, and Return submits."""-- def __init__(self, digits, on_submit):++ def __init__(self, digits, on_submit, editable=True):self.on_submit = on_submitself.delegate = _CodeDelegate.alloc().init()self.delegate.owner = self@@@ -1367,11 -1231,10 +1840,22 @@@self.fields = []for index in range(digits):container, control = field(cls=_CentredField)+ control.cell().setScrollable_(False)control.setFont_(theme.mono_font(theme.TYPE["keycap"]))control.setAlignment_(AppKit.NSTextAlignmentCenter)-- # A fixed box the digit centres in, rather than one that hugs the line and leaves the-- # digit sitting on the font's descender room.++ control.setTextColor_(AppKit.NSColor.clearColor())++ control.setEditable_(editable)++ control.setSelectable_(editable)++ overlay = _autolayout(_DigitInk.alloc().init())++ overlay.control = objc.WeakRef(control)++ control.ink_view = overlay++ container.addSubview_(overlay)++ AppKit.NSLayoutConstraint.activateConstraints_([++ overlay.leadingAnchor().constraintEqualToAnchor_(control.leadingAnchor()),++ overlay.trailingAnchor().constraintEqualToAnchor_(control.trailingAnchor()),++ overlay.topAnchor().constraintEqualToAnchor_(control.topAnchor()),++ overlay.bottomAnchor().constraintEqualToAnchor_(control.bottomAnchor()),++ ])container.heightAnchor().constraintEqualToConstant_(48).setActive_(True)control.setDelegate_(self.delegate)control.setAccessibilityLabel_(f"Digit {index + 1}")@@@ -1389,6 -1252,6 +1873,27 @@@def focus(self, window):window.makeFirstResponder_(self.fields[0])++ def begin_editing(self, control):++ editor = control.currentEditor()++ if editor is None:++ return++ editor.setTextColor_(AppKit.NSColor.clearColor())++ editor.setInsertionPointColor_(theme.colour("ink"))++ font = control.font()++ inset = max(0.0, (editor.bounds().size.height - font.capHeight()) / 2 - (font.ascender() - font.capHeight()))++ editor.setTextContainerInset_(AppKit.NSMakeSize(0, inset))++++ def end_editing(self, control):++ editor = getattr(control, "pair_editor", None)++ if editor is not None:++ editor.setTextContainerInset_(AppKit.NSMakeSize(0, 0))++ editor.setSelectedTextAttributes_(control.pair_selected_attributes)++ AppKit.NSNotificationCenter.defaultCenter().removeObserver_name_object_(++ control, AppKit.NSTextViewDidChangeSelectionNotification, editor)++ control.pair_editor = None++ control.setNeedsDisplay_(True)++ control.ink_view.setNeedsDisplay_(True)++def changed(self, control):index = self.fields.index(control)digits = "".join(character for character in control.stringValue() if character.isdigit())@@@ -1419,7 -1282,7 +1924,7 @@@ class _PageList(AppKit.NSView)def keyDown_(self, event):keys = event.charactersIgnoringModifiers()arrows = {AppKit.NSUpArrowFunctionKey: -1, AppKit.NSDownArrowFunctionKey: 1}-- direction = arrows.get(ord(keys[0])) if keys else None++ direction = arrows.get(keys[0]) if keys else Noneif direction is None:objc.super(_PageList, self).keyDown_(event)else:@@@ -1446,7 -1309,7 +1951,7 @@@ class Sidebarcolumn.trailingAnchor().constraintEqualToAnchor_(self.view.trailingAnchor()),])-- link = box()++ link = self.header = box()# The LED sits in a slot one word-line tall, so it centres on the first line when a long# state word wraps onto a second, and wide enough that its glow is not clipped square.slot = size(box(), 16, 20)@@@ -1460,6 -1323,6 +1965,7 @@@self.peer = Label("", theme.TYPE["small"], mono=True, ink="ink_3")squeeze(self.peer.view)words = stack(spacing=3)++ self.link_words = wordsadd(words, self.word.view)add(words, self.peer.view)line = stack(vertical=False, spacing=5)@@@ -1479,11 -1342,11 +1985,18 @@@pin(list_stack, rows)symbol_size = AppKit.NSImageSymbolConfiguration.configurationWithPointSize_weight_(13, AppKit.NSFontWeightRegular)self.rows = {}++ self.row_insets = []++ self.row_widths = []++ self.dot_insets = []for index, (key, name, symbol, *_rest) in enumerate(pages):row = pressable(lambda key=key: self._choose(key), role=AppKit.NSAccessibilityRadioButtonRole)row.setAccessibilityLabel_(name)row.setToolTip_(f"{name} ⌘{index + 1}")row.ring_inset = 2.0++ row.sidebar_owner = self++ row.heightAnchor().constraintEqualToConstant_(36).setActive_(True)++ row_width = row.widthAnchor().constraintEqualToAnchor_(self.view.widthAnchor())++ self.row_widths.append(row_width)icon = size(_autolayout(AppKit.NSImageView.alloc().init()), 18, 18)icon.setImage_(AppKit.NSImage.imageWithSystemSymbolName_accessibilityDescription_(symbol, None))icon.setSymbolConfiguration_(symbol_size)@@@ -1494,9 -1357,9 +2007,21 @@@line = stack(vertical=False, spacing=10)line.addArrangedSubview_(icon)line.addArrangedSubview_(hug(words.view, AppKit.NSLayoutPriorityDefaultLow))-- line.addArrangedSubview_(dot)row.addSubview_(line)-- pin(line, row, (8, 16, 8, 16))++ row.addSubview_(dot)++ dot_inset = row.trailingAnchor().constraintEqualToAnchor_constant_(dot.trailingAnchor(), 8)++ self.dot_insets.append(dot_inset)++ AppKit.NSLayoutConstraint.activateConstraints_([++ dot_inset,++ dot.centerYAnchor().constraintEqualToAnchor_(row.centerYAnchor()),++ ])++ AppKit.NSLayoutConstraint.activateConstraints_([++ line.centerYAnchor().constraintEqualToAnchor_(row.centerYAnchor()),++ line.centerXAnchor().constraintEqualToAnchor_(row.centerXAnchor()),++ ])++ inset = line.widthAnchor().constraintEqualToAnchor_constant_(row.widthAnchor(), -32)++ inset.setActive_(True)++ self.row_insets.append(inset)bar = box()row.addSubview_(bar)AppKit.NSLayoutConstraint.activateConstraints_([@@@ -1508,17 -1371,17 +2033,29 @@@add(list_stack, row)self.rows[key] = (name, row, icon, words, bar, dot)add(column, rows)++ AppKit.NSLayoutConstraint.activateConstraints_(self.row_widths)if footer_text and on_footer is not None:footer = pressable(on_footer)footer.pointer_cursor = Truefooter.setAccessibilityLabel_(footer_label or footer_text)-- footer.setToolTip_(footer_label or footer_text)++ footer.setToolTip_(f'{footer_label or footer_text}\n{footer_text}')footer_label_view = Label(footer_text, theme.TYPE["small"], ink="ink_3", wrap=True)++ self.footer_words = footer_label_viewfooter.addSubview_(footer_label_view.view)# A slim right inset, with nothing beside the text: the address is 144pt of a 180pt# sidebar and wrapped onto a third line at the default window width at 14.pin(footer_label_view.view, footer, (8, 16, 8, 4))++ self.footer_icon = size(_autolayout(AppKit.NSImageView.alloc().init()), 18, 18)++ self.footer_icon.setImage_(AppKit.NSImage.imageWithSystemSymbolName_accessibilityDescription_('arrow.up.right.square', footer_label))++ self.footer_icon.setContentTintColor_(theme.colour('ink_3'))++ self.footer_icon.setHidden_(True)++ footer.addSubview_(self.footer_icon)++ AppKit.NSLayoutConstraint.activateConstraints_([++ self.footer_icon.centerXAnchor().constraintEqualToAnchor_(footer.centerXAnchor()),++ self.footer_icon.centerYAnchor().constraintEqualToAnchor_(footer.centerYAnchor()),++ footer.heightAnchor().constraintGreaterThanOrEqualToConstant_(36),++ ])self.view.addSubview_(footer)AppKit.NSLayoutConstraint.activateConstraints_([footer.leadingAnchor().constraintEqualToAnchor_(self.view.leadingAnchor()),@@@ -1535,14 -1398,14 +2072,43 @@@words.set(ink="ink" if on else "ink_2", weight=600 if on else 400)icon.setContentTintColor_(theme.colour("ink" if on else "ink_3"))row.setAccessibilityValue_(1 if on else 0)++ window = self.view.window()++ responder = window.firstResponder() if window else None++ if window and responder in [values[1] for values in self.rows.values()] and getattr(window, 'keyboard_navigation', False):++ window.makeFirstResponder_(self.rows[key][1])++ self.refresh_focus()++++ def refresh_focus(self):++ window = self.view.window()++ for key, (_name, row, *_rest) in self.rows.items():++ row._ring(bool(window and getattr(window, 'keyboard_navigation', False)++ and key == self.selected and window.firstResponder() == row))++++ def set_collapsed(self, collapsed):++ if collapsed == getattr(self, 'collapsed', None):++ return++ self.collapsed = collapsed++ self.link_words.setHidden_(collapsed)++ for (_name, _row, _icon, words, _bar, dot), inset, width, dot_inset in zip(++ self.rows.values(), self.row_insets, self.row_widths, self.dot_insets):++ words.view.setHidden_(collapsed)++ inset.setConstant_(-26 if collapsed else -32)++ width.setConstant_(-12 if collapsed else 0)++ dot_inset.setConstant_(0 if collapsed else 8)++ if hasattr(self, 'footer_words'):++ self.footer_words.view.setHidden_(collapsed)++ self.footer_icon.setHidden_(not collapsed)def step(self, direction):++ if self.view.window() is not None:++ self.view.window().keyboard_navigation = Trueindex = min(max(self.keys.index(self.selected) + direction, 0), len(self.keys) - 1)key = self.keys[index]self._choose(key)row = self.rows[key][1]if row.window() is not None:row.window().makeFirstResponder_(row)++ self.refresh_focus()def _choose(self, key):self.select(key)@@@ -1552,6 -1415,6 +2118,8 @@@self.led.set(state.led, state.blink)self.word.set(state.word, ink=state.tone)self.peer.set(peer)++ self.header.setAccessibilityLabel_(f'{state.word}, {peer}')++ self.header.setToolTip_(f'{state.word}, {peer}')def set_dots(self, marks):for page, (name, row, _icon, _words, _bar, dot) in self.rows.items():@@@ -1572,11 -1435,11 +2140,17 @@@ class _Overlay(AppKit.NSView)def isAccessibilityElement(self):return False++ def ringPositionChanged_(self, _notification):++ reference = getattr(self, "ring_owner", None)++ owner = reference() if reference is not None else None++ if owner is not None and owner.target is not None:++ owner.follow(owner.target)++class Ring:"""The one ring round a group's chosen tile or chip. It lives over `host`, above what it rings,-- and slides from the old choice to the new; each ringed view's layout calls `follow`, so a-- reflow carries the ring with it instead of leaving it behind."""++ and slides from the old choice to the new. Tile layout and ancestor frame changes both++ carry the ring with a reflow."""def __init__(self, host, radius, inset=0.0):self.overlay = _autolayout(_Overlay.alloc().init())@@@ -1587,22 -1450,22 +2161,39 @@@self.inset = insetself.target = Noneself.enabled = True++ self.overlay.ring_owner = weakref.ref(self)self.layer = Quartz.CALayer.layer()self.layer.setBorderWidth_(2)self.layer.setCornerRadius_(radius)self.layer.setHidden_(True)self.overlay.layer().addSublayer_(self.layer)++ self.inner = Quartz.CALayer.layer()++ self.inner.setBorderWidth_(1)++ self.inner.setCornerRadius_(max(0, radius - 2))++ self.layer.addSublayer_(self.inner)def show(self, target, enabled=True):moving = self.target is not None and target is not None and target != self.targetself.target, self.enabled = target, enabled++ centre = AppKit.NSNotificationCenter.defaultCenter()++ centre.removeObserver_name_object_(self.overlay, AppKit.NSViewFrameDidChangeNotification, None)if target is not None:target.ring_owner = self++ # A group's frame can move without changing its tile's own frame or layout.++ ancestor = target++ while ancestor is not None and ancestor != self.host.superview():++ ancestor.setPostsFrameChangedNotifications_(True)++ centre.addObserver_selector_name_object_(++ self.overlay, "ringPositionChanged:", AppKit.NSViewFrameDidChangeNotification, ancestor++ )++ ancestor = ancestor.superview()motion.transaction(moving and motion.live(self.host))self.layer.setHidden_(target is None)if target is not None:self.layer.setFrame_(self._frame(target))theme.tint(self.layer, border="ink" if enabled else "rule")++ theme.tint(self.inner, border='ground')++ self.inner.setFrame_(AppKit.NSInsetRect(self.layer.bounds(), 2, 2))Quartz.CATransaction.commit()def follow(self, view):@@@ -1610,6 -1473,6 +2201,7 @@@returnmotion.transaction(False)self.layer.setFrame_(self._frame(view))++ self.inner.setFrame_(AppKit.NSInsetRect(self.layer.bounds(), 2, 2))Quartz.CATransaction.commit()def _frame(self, target):@@@ -1617,30 -1480,30 +2209,153 @@@return AppKit.NSInsetRect(rect, self.inset, self.inset)++class ChoiceGrid:++ """Each family wraps within its own equal-width grid; partial rows keep that width."""++ def __init__(self, view, cells, owner, swatches=False):++ self.view, self.cells, self.owner = view, cells, owner++ self.swatches = swatches++ self.columns = None++ self.last_width = None++ self.height = view.heightAnchor().constraintEqualToConstant_(0)++ self.height.setActive_(True)++ for width in (0, 368, 568):++ self.arrange(width)++++ def arrange(self, width):++ column = width + 32++ count = (5 if column >= 600 else 3 if column >= 400 else 2) if self.swatches else (3 if column >= 600 else 2 if column >= 400 else 1)++ count = min(count, len(self.cells))++ if width == self.last_width:++ return++ self.last_width = width++ self.columns = self.owner.columns = count++ gap = 8 if self.swatches else 12++ cell_width = max(0, (width - gap * (count - 1)) / count)++ cell_height = 68 if self.swatches else cell_width * 116 / 152 if self.owner.aspect else 116++ rows = math.ceil(len(self.cells) / count)++ height = rows * cell_height + (rows - 1) * gap++ self.height.setConstant_(height)++ for index, cell in enumerate(self.cells):++ row, column = divmod(index, count)++ cell.setFrame_(((column * (cell_width + gap), height - (row + 1) * cell_height - row * gap),++ (cell_width, cell_height)))++++++class _TileContent:++ """Keep preview geometry out of the page's constraint engine during live resize."""++ def __init__(self, preview, name, detail):++ self.preview, self.name, self.detail = preview, name, detail++ self.last_size = None++ self.measurements = {}++ AppKit.NSLayoutConstraint.deactivateConstraints_([++ c for c in preview.constraints()++ if c.firstItem() == preview and c.secondItem() in (None, preview)++ ])++++ def arrange(self, size):++ dimensions = (size.width, size.height)++ caption = tuple((label.text, label.size, label.weight) for label in (self.name, self.detail))++ if (dimensions, caption) == self.last_size:++ return++ self.last_size = (dimensions, caption)++ width, height = dimensions++ text_width = max(1, width - 16)++ key = (text_width, caption)++ heights = self.measurements.get(key)++ if heights is None:++ heights = [math.ceil(label.view.attributedStringValue().boundingRectWithSize_options_(++ (text_width, 1000), AppKit.NSStringDrawingUsesLineFragmentOrigin).size.height)++ for label in (self.name, self.detail)]++ if len(self.measurements) >= 64:++ self.measurements.clear()++ self.measurements[key] = heights++ name_height, detail_height = heights++ preview_height = max(1, min(text_width / 2, height - name_height - detail_height - 26))++ preview_width = preview_height * 2++ self.preview.setFrame_(((width / 2 - preview_width / 2, height - 8 - preview_height),++ (preview_width, preview_height)))++ self.preview.setNeedsLayout_(True)++ self.name.view.setFrame_(((8, height - 14 - preview_height - name_height),++ (text_width, name_height)))++ self.detail.view.setFrame_(((8, height - 18 - preview_height - name_height - detail_height),++ (text_width, detail_height)))++ self.name.view.setNeedsDisplay_(True)++ self.detail.view.setNeedsDisplay_(True)++++++class _SwatchContent:++ def __init__(self, chip, name):++ self.chip, self.name = chip, name++ self.last_size = None++ AppKit.NSLayoutConstraint.deactivateConstraints_(list(chip.constraints()))++++ def arrange(self, size):++ dimensions = (size.width, size.height)++ if dimensions == self.last_size:++ return++ self.last_size = dimensions++ width, height = dimensions++ self.chip.setFrame_(((3, height - 31), (max(0, width - 6), 28)))++ self.chip.setNeedsLayout_(True)++ self.name.view.setFrame_(((3, 3), (max(0, width - 6), max(0, height - 39))))++ self.name.view.setNeedsDisplay_(True)++++class ChoiceTiles:-- """One of several, as tiles side by side: each a live preview over its name and a line saying-- what it is, the whole tile clickable. The chosen tile takes a 2pt ink border. `.value` reads and-- writes the value rather than the index, like Segmented. `columns` pads a short row with empty-- space so rows of different lengths line up; the Design page's groups need that."""++ """A row or stack of preview cards. Style families use the full-width stacked form."""-- def __init__(self, choices, on_change=None, columns=None):++ def __init__(self, choices, on_change=None, columns=None, tile_width=None, vertical=False, responsive=False, aspect=True):self.on_change = on_changeself._value = Noneself.enabled = Trueself.tiles = []self.values = [choice[0] for choice in choices]self.previews = [choice[3] for choice in choices]-- self.view = stack(vertical=False, spacing=10)-- self.view.setDistribution_(AppKit.NSStackViewDistributionFillEqually)-- self.view.setAlignment_(AppKit.NSLayoutAttributeTop)++ self.vertical = vertical++ self.aspect = aspect++ self.view = _autolayout(_ResponsiveView.alloc().init()) if responsive else stack(vertical=vertical, spacing=8 if vertical else 10)++ if vertical and not responsive:++ self.view.setContentCompressionResistancePriority_forOrientation_(++ AppKit.NSLayoutPriorityDefaultLow, AppKit.NSLayoutConstraintOrientationHorizontal++ )++ if not responsive:++ self.view.setDistribution_(AppKit.NSStackViewDistributionFill if vertical++ else AppKit.NSStackViewDistributionFillEqually)++ self.view.setAlignment_(AppKit.NSLayoutAttributeWidth if vertical else AppKit.NSLayoutAttributeTop)for value, title, detail, preview in choices:tile = pressable(lambda value=value: self._choose(value), "ground", "rule", theme.RADIUS["segment"],role=AppKit.NSAccessibilityRadioButtonRole)++ if vertical:++ tile.tile_selected = False++ tile.tile_hovered = False++ tile.set_tile_state()++ tile.setContentCompressionResistancePriority_forOrientation_(++ AppKit.NSLayoutPriorityDefaultLow, AppKit.NSLayoutConstraintOrientationHorizontal++ )tile.setAccessibilityLabel_(title)++ tile.add_selection_mark()++ if responsive:++ name = Label(title, theme.TYPE["body"], 600, wrap=True, preview=True)++ words = Label(detail, theme.TYPE["small"], ink="ink_3", wrap=True, preview=True)++ for child in (preview, name.view, words.view):++ tile.addSubview_(child)++ tile.tile_content = _TileContent(preview, name, words)++ self.view.addSubview_(tile)++ self.tiles.append((value, tile, name))++ continuecolumn = stack(spacing=6)++ if vertical:++ column.setAlignment_(AppKit.NSLayoutAttributeWidth)++ column.setContentCompressionResistancePriority_forOrientation_(++ AppKit.NSLayoutPriorityDefaultLow, AppKit.NSLayoutConstraintOrientationHorizontal++ )add(column, preview)++ if vertical:++ preview.setContentCompressionResistancePriority_forOrientation_(++ AppKit.NSLayoutPriorityDefaultLow, AppKit.NSLayoutConstraintOrientationHorizontal++ )column.setCustomSpacing_afterView_(10, preview)-- name = Label(title, theme.TYPE["body"], 600)++ name = Label(title, theme.TYPE["body"], 600, wrap=True)words = Label(detail, theme.TYPE["small"], ink="ink_3", wrap=True)# A narrow tile wraps its detail onto more lines; the row grows to fit rather than# squeezing the title or the last line out.@@@ -1651,21 -1514,21 +2366,38 @@@add(column, name.view)add(column, words.view)tile.addSubview_(column)-- # Top-aligned, with the slack below: a tile stretched to its tallest neighbour would-- # otherwise open a gap between its name and its detail.-- AppKit.NSLayoutConstraint.activateConstraints_([-- column.topAnchor().constraintEqualToAnchor_constant_(tile.topAnchor(), 8),-- column.leadingAnchor().constraintEqualToAnchor_constant_(tile.leadingAnchor(), 8),-- tile.trailingAnchor().constraintEqualToAnchor_constant_(column.trailingAnchor(), 8),-- tile.bottomAnchor().constraintGreaterThanOrEqualToAnchor_constant_(column.bottomAnchor(), 12),-- ])-- self.view.addArrangedSubview_(tile)-- tile.heightAnchor().constraintEqualToAnchor_(self.view.heightAnchor()).setActive_(True)++ if vertical:++ self.view.addArrangedSubview_(tile)++ AppKit.NSLayoutConstraint.activateConstraints_([++ tile.leadingAnchor().constraintEqualToAnchor_(self.view.leadingAnchor()),++ tile.trailingAnchor().constraintEqualToAnchor_(self.view.trailingAnchor()),++ column.topAnchor().constraintEqualToAnchor_constant_(tile.topAnchor(), 8),++ column.leadingAnchor().constraintEqualToAnchor_constant_(tile.leadingAnchor(), 8),++ tile.trailingAnchor().constraintEqualToAnchor_constant_(column.trailingAnchor(), 8),++ tile.bottomAnchor().constraintEqualToAnchor_constant_(column.bottomAnchor(), 12),++ ])++ else:++ # Top-aligned, with the slack below so each preview and caption keep the same gap.++ AppKit.NSLayoutConstraint.activateConstraints_([++ column.topAnchor().constraintEqualToAnchor_constant_(tile.topAnchor(), 8),++ column.leadingAnchor().constraintEqualToAnchor_constant_(tile.leadingAnchor(), 8),++ tile.trailingAnchor().constraintEqualToAnchor_constant_(column.trailingAnchor(), 8),++ tile.bottomAnchor().constraintGreaterThanOrEqualToAnchor_constant_(column.bottomAnchor(), 12),++ ])++ if not vertical:++ self.view.addArrangedSubview_(tile)++ if tile_width is not None:++ tile.widthAnchor().constraintEqualToConstant_(tile_width).setActive_(True)++ tile.heightAnchor().constraintEqualToAnchor_(self.view.heightAnchor()).setActive_(True)self.tiles.append((value, tile, name))-- _pad(self.view, columns, len(choices))-- # Linked swaps in one ring for all its rows, so the ring can travel between them.-- self.ring = Ring(self.view, theme.RADIUS["segment"])++ if not vertical:++ _pad(self.view, columns, len(choices))++ self.ring = None if vertical else Ring(self.view, theme.RADIUS["segment"])self.ring_shared = False++ if responsive:++ self.grid = ChoiceGrid(self.view, [tile for _, tile, _ in self.tiles], self)++ self.view.owner = self.grid++ self.grid.arrange(640)@propertydef value(self):@@@ -1677,11 -1540,11 +2409,14 @@@chosen_tile = Nonefor candidate, tile, name in self.tiles:chosen = candidate == value++ tile.show_selection_mark(chosen)if chosen:chosen_tile = tilename.set(ink="ink" if self.enabled else "ink_3")tile.setAccessibilityValue_(1 if chosen else 0)-- if chosen_tile is not None or not self.ring_shared:++ if self.vertical:++ tile.set_tile_state(selected=chosen)++ if self.ring is not None and (chosen_tile is not None or not self.ring_shared):self.ring.show(chosen_tile, self.enabled)def set_enabled(self, enabled):@@@ -1700,6 -1563,6 +2435,8 @@@class _Chip(AppKit.NSView):++ ring_owner = None++def layout(self):objc.super(_Chip, self).layout()gradient = getattr(self, "gradient", None)@@@ -1718,19 -1581,19 +2455,21 @@@ class Swatchesin ink. `.value` reads and writes the palette name. A choice is (name, title), coloured fromtheme.PALETTES, or (name, title, hex colours); `columns` pads as ChoiceTiles does."""-- def __init__(self, choices, on_change=None, columns=None):++ def __init__(self, choices, on_change=None, columns=None, responsive=False):self.on_change = on_changeself._value = Noneself.enabled = Trueself.cells = []self.values = [choice[0] for choice in choices]-- self.view = stack(vertical=False, spacing=8)-- self.view.setDistribution_(AppKit.NSStackViewDistributionFillEqually)++ self.view = _autolayout(_ResponsiveView.alloc().init()) if responsive else stack(vertical=False, spacing=8)++ if not responsive:++ self.view.setDistribution_(AppKit.NSStackViewDistributionFillEqually)for choice in choices:value, title = choice[:2]cell = pressable(lambda value=value: self._choose(value), role=AppKit.NSAccessibilityRadioButtonRole)cell.setAccessibilityLabel_(title)-- chip = size(box(None, "rule", theme.RADIUS["field"], cls=_Chip), height=24)++ cell.add_selection_mark()++ chip = size(box(None, "rule", theme.RADIUS["field"], cls=_Chip), height=28)chip.layer().setMasksToBounds_(True)colours = list(choice[2] if len(choice) > 2 else theme.PALETTES[value])if len(colours) == 1:@@@ -1741,18 -1604,18 +2480,30 @@@gradient.setEndPoint_((1.0, 0.5))chip.layer().insertSublayer_atIndex_(gradient, 0)chip.gradient = gradient-- name = Label(title, theme.TYPE["small"], ink="ink_2", align=AppKit.NSTextAlignmentCenter)++ name = Label(title, theme.TYPE["small"], ink="ink_2", wrap=True,++ align=AppKit.NSTextAlignmentCenter, preview=responsive)squeeze(name.view)-- column = stack(spacing=5)-- add(column, chip)-- add(column, name.view)-- cell.addSubview_(column)-- pin(column, cell, (3, 3, 3, 3))-- self.view.addArrangedSubview_(cell)++ if responsive:++ cell.addSubview_(chip)++ cell.addSubview_(name.view)++ cell.tile_content = _SwatchContent(chip, name)++ self.view.addSubview_(cell)++ else:++ column = stack(spacing=5)++ add(column, chip)++ add(column, name.view)++ cell.addSubview_(column)++ pin(column, cell, (3, 3, 3, 3))++ self.view.addArrangedSubview_(cell)self.cells.append((value, cell, chip, name))-- _pad(self.view, columns, len(choices))++ if not responsive:++ _pad(self.view, columns, len(choices))self.ring = Ring(self.view, theme.RADIUS["field"])self.ring_shared = False++ if responsive:++ self.grid = ChoiceGrid(self.view, [cell for _, cell, _, _ in self.cells], self, swatches=True)++ self.view.owner = self.grid++ self.grid.arrange(640)@propertydef value(self):@@@ -1764,6 -1627,6 +2515,7 @@@chosen_chip = Nonefor candidate, cell, chip, name in self.cells:chosen = candidate == value++ cell.show_selection_mark(chosen)if chosen:chosen_chip = chipname.set(ink="ink" if chosen else "ink_2", weight=600 if chosen else 400)@@@ -1802,13 -1665,13 +2554,14 @@@ class Linkedself._value = None# With a host holding every row, one ring serves them all and slides between rows.self.ring = None-- if host is not None and self.rows:++ if host is not None and self.rows and getattr(self.rows[0], "ring", None) is not None:first = self.rows[0].ringself.ring = Ring(host, first.layer.cornerRadius(), first.inset)for row in self.rows:row.on_change = self._chosenif self.ring is not None:-- row.ring.overlay.removeFromSuperview()++ if row.ring is not None:++ row.ring.overlay.removeFromSuperview()row.ring = self.ringrow.ring_shared = Truediff --cc mac_app/windows_input.pyindex 522627d,4e0f65e..8d1bcdb--- a/mac_app/windows_input.py+++ b/mac_app/windows_input.py@@@ -16,14 -16,12 +16,15 @@@ import logginimport threadingimport clipboard_mac+import crossingimport desktop_mac+import hardware_macimport input_injector_macimport no_unlock-import receiver-import return_edge-from receiver import ReceiverServer, ServerState+from core import protocol++from core import peerlist+from core import receiver+from core.receiver import LinkResponder, ServerStateLOGGER = logging.getLogger("Beamer")@@@ -81,31 -90,30 +82,32 @@@ class WindowsInputdef receiving(self) -> bool:return bool(self._controller.receiving)+ @property+ def peer_settings(self):+ """Whether a machine linked to this Mac keeps Same on all machines; None while none is, or+ none has told."""- known = [self.server.caps_of(peer) for peer in self.server.links()]++ desktops = {protocol.read_id(peer.get("id")) for peer in peerlist.desktops(self._controller.book.peers())}++ known = [self.server.caps_of(peer) for peer in self.server.links() if peer in desktops]+ known = [caps for caps in known if caps is not None]+ return any("settings" in caps for caps in known) if known else None+def sync(self, cfg) -> None:speeds = (cfg.pointer_speed, cfg.scroll_speed, cfg.reverse_scroll)- scale = self.server.input_scale- if scale is None or (scale.pointer, scale.scroll, scale.reverse) != speeds:+ if self.server.input_scale is None or speeds != self._speeds:+ self._speeds = speedsself.server.input_scale = receiver.InputScale(*speeds)- # A change on the Crossing page reaches the PC's pointer while it is here, not at its next- # crossing: the way home is built from these when the PC's input arrives.- ways = tuple((key, str(cfg.crossing.get(key))) for key in ("methods", "edge_parts", "corner"))- if ways != self._ways:- self._ways = ways- self.server.rearm_return()- if not cfg.allow_windows_to_drive:- # Stopping hands back whatever the PC was driving, the same as a dropped link.- with self._lock:- if self._running_for is None:- return- self._running_for = None- self.server.stop()- return- wanted = (cfg.port, cfg.auth_token)+ wanted = self._controller.own_portwith self._lock:if wanted == self._running_for and self.server.listening:+ # Only when the peers or the zones changed: re-arming starts every push over, and+ # this runs on the status tick while another machine may be pushing through a zone.+ held = self._held()+ if held != self._armed_for:+ self._armed_for = held+ self.server.peers_changed()+ self.server.rearm()return- if not cfg.auth_token or not cfg.port:+ if not wanted:returnif self._running_for is not None:self.server.stop()@@@ -130,76 -131,19 +132,80 @@@try:input_injector_mac.release_all()except Exception:- self._logger.exception("Could not release the keys the PC was holding")-- def send_arrangement(self, mac_edge: str, set_at: int) -> bool:- """Tell the PC over the link it opened to this Mac. Returns False when- there is nobody connected, which is not a failure worth reporting.- The hello names this Mac's way home but carries no stamp, so a change- made while nobody was connected reaches the PC only as that."""- return self.server.send_arrangement(mac_edge, int(set_at))-- def _on_arrangement(self, mac_edge, set_at) -> None:+ self._logger.exception("Could not release the keys another machine was holding")++ def _outbound_up(self, peer_id: bytes) -> bool:+ link = self._controller._peers_up.get(protocol.id_text(peer_id))+ return link is not None and link.live()++ def send_arrangement(self, peer: str, mac_edge: str, set_at: int, by=None) -> bool:+ """Tell `peer` (a b64 id) which edge of this Mac faces it, as the controller's send_arrangement+ does, over the link it opened to this Mac, when this Mac has none open to it (WIRE.md section 3,+ "Which link"). False when it has no link here either, which is not a failure worth reporting."""+ ident = protocol.read_id(peer)+ if ident is None or self._outbound_up(ident):+ return False+ author = protocol.read_id(by) or bytes(self._controller.identity()["id"])+ return self.server.send(ident, protocol.arrangement_v6(mac_edge, int(set_at), author,+ way_back=self._controller.way_back(peer),+ way_back_by=protocol.read_id(self._controller.way_back_by(peer))))++ def send_settings(self, data, source=None) -> bool:+ """This Mac's settings state to every machine linked to it that keeps it and that this Mac+ has no link open to, `source` (a b64 id, the machine a newer state came from) excepted."""+ sent = False++ desktops = {protocol.read_id(peer.get("id")) for peer in peerlist.desktops(self._controller.book.peers())}+ for peer in self.server.links():++ if peer not in desktops:++ continue+ caps = self.server.caps_of(peer)+ if protocol.id_text(peer) == source or caps is None or "settings" not in caps or self._outbound_up(peer):+ continue+ sent = self.server.send(peer, protocol.settings_msg(data)) or sent+ return sent++ def _announce(self, peer: bytes):+ """What this Mac tells a machine the moment it links in: where the two sit, its settings+ state, and who else this Mac has, unless this Mac has a link of its own open to it (that+ link carries them)."""+ if self._outbound_up(peer):+ return []+ text = protocol.id_text(peer)+ entry = next((item for item in self._controller.book.peers() if item.get("id") == text), None)+ if entry is None:+ return []+ messages = []- if entry.get("side") in crossing.EDGES:++ if entry.get("port") != 0 and entry.get("side") in crossing.EDGES:+ by = protocol.read_id(entry.get("side_by")) or bytes(self._controller.identity()["id"])+ messages.append(protocol.arrangement_v6(entry["side"], entry.get("side_set_at", 0), by,+ way_back=self._controller.way_back(text),+ way_back_by=protocol.read_id(self._controller.way_back_by(text))))+ caps = self.server.caps_of(peer) or frozenset()- if "settings" in caps:++ if entry.get("port") != 0 and "settings" in caps:+ messages += [m for m in self._controller.announce() if m.get("type") == protocol.MSG_SETTINGS]+ if entry.get("send") is True:+ ids = [protocol.read_id(item.get("id")) for item in self._controller.book.peers() if item.get("id") != text]+ messages.append(protocol.paired_msg([ident for ident in ids if ident is not None][:protocol.MAX_PEERS]))+ return messages++ def _on_arrangement(self, peer, read) -> None:if self._arrangement_callback is None:return- self._arrangement_callback(mac_edge, set_at)+ args = (protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]),+ read.get("way_back"))+ if read.get("way_back_by"):+ args += (protocol.id_text(read["way_back_by"]),)+ self._arrangement_callback(*args)++ def _on_settings(self, peer, data) -> None:- if self.settings_callback is not None:++ desktops = {protocol.read_id(entry.get("id")) for entry in peerlist.desktops(self._controller.book.peers())}++ if peer in desktops and self.settings_callback is not None:+ self.settings_callback(data, protocol.id_text(peer))++ def _on_paired(self, peer, ids) -> None:+ self._controller.book.store_paired(protocol.id_text(peer), [protocol.id_text(ident) for ident in ids])+ if self.paired_callback is not None:+ self.paired_callback(protocol.id_text(peer), [protocol.id_text(ident) for ident in ids])def _on_status(self, state, detail) -> None:self.state = statediff --cc scripts/ui_audit/guarded_tests.pyindex 0000000,0000000..a1b2959new file mode 100644--- /dev/null+++ b/scripts/ui_audit/guarded_tests.py@@@ -1,0 -1,0 +1,29 @@@++"""Run unittest commands while forbidding access to the installed Beamer settings tree."""++++import os++from pathlib import Path++import runpy++import sys++++++def protect_settings():++ roots = [Path.home() / "Library/Application Support/Beamer"]++ roots.extend(Path(os.environ[key]) / "Beamer" for key in ("LOCALAPPDATA", "APPDATA") if key in os.environ)++ roots = [root.resolve() for root in roots]++++ def guard(event, values):++ if event != "open" or not values or not isinstance(values[0], (str, bytes, os.PathLike)):++ return++ path = Path(os.fsdecode(values[0])).resolve()++ if any(path == root or root in path.parents for root in roots):++ raise RuntimeError("Installed Beamer settings access is forbidden during verification")++++ sys.addaudithook(guard)++++++if __name__ == "__main__":++ protect_settings()++ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++ sys.path.insert(0, str(Path.cwd()))++ sys.argv[0] = "unittest"++ runpy.run_module("unittest", run_name="__main__")diff --cc scripts/ui_audit/mac_actions.pyindex 0000000,0000000..068a7a9new file mode 100644--- /dev/null+++ b/scripts/ui_audit/mac_actions.py@@@ -1,0 -1,0 +1,214 @@@++"""Drive Mac controls offscreen with all OS and network effects replaced by fakes."""++import contextlib++import copy++import json++import traceback++from types import SimpleNamespace++from unittest import mock++++from mac_render import ROOT, AppKit, app, fixture, measure, peers, render, render_metadata, settle, widgets, walk++from mac_states import FakePairing, menus++from core import pairing++++++PUBLIC = ("appearance", "check_updates", "hide_addresses", "same_on_both", "trigger_key", "trigger_style", "double_tap_ms", "pointer_speed", "scroll_speed", "reverse_scroll", "key_map", "crossing", "ignored_inputs", "port")++SAVED = {++ "same_switch": "same_on_both", "updates_switch": "check_updates", "hide_switch": "hide_addresses",++ "reverse_scroll_box": "reverse_scroll", "appearance_select": "appearance", "modifier_select": "key_map",++ "style_select": "trigger_style", "hold_box": "crossing.hold_full_screen",++ "dragging_box": "crossing.block_while_dragging", "glow_box": "crossing.glow",++ "landing_box": "crossing.shortcut_arrival", "haptics_box": "crossing.haptics",++ "length_select": "crossing.effect_length", "size_select": "crossing.effect_size",++ "notch_style_select": "crossing.notch_style", "notch_after_select": "crossing.notch_after_ms",++ "tick_steps_select": "crossing.haptic_steps", "glow_style_select": "crossing.glow_style",++ "switch_style_select": "crossing.shortcut_arrival_style", "glow_colour_select": "crossing.glow_colour",++}++++++def public_settings(control):++ raw = control.settings_store.current()++ effective = app.config_to_raw(control.settings_store.load())++ result = {key: copy.deepcopy(effective[key]) for key in PUBLIC if key in effective}++ result["peers"] = [{key: copy.deepcopy(peer[key]) for key in ("id", "name", "in_use", "send", "allow_drive", "side", "jump_key") if key in peer} for peer in raw["peers"]]++ result["zones"] = [{key: copy.deepcopy(zone[key]) for key in ("peer", "kind", "edge", "parts", "corner", "off") if key in zone} for zone in raw.get("zones", [])]++ return result++++++def expected_selection(control, view):++ callback = getattr(view, "callback", None)++ owner = getattr(callback, "__self__", None)++ if owner is None:++ for cell in getattr(callback, "__closure__", None) or ():++ candidate = cell.cell_contents++ if isinstance(candidate, (widgets.Segmented, widgets.ChoiceTiles, widgets.Swatches)):++ owner = candidate++ break++ if isinstance(owner, (widgets.Switch, widgets.WayTile)):++ expected = not owner.value++ elif isinstance(owner, (widgets.Segmented, widgets.ChoiceTiles, widgets.Swatches)):++ defaults = getattr(callback, "__defaults__", None)++ if not defaults:++ return None++ expected = defaults[0]++ else:++ return None++ name = next((key for key, value in control.__dict__.items() if value is owner), None)++ if name is None:++ name = next((key for key, value in control.__dict__.items() if isinstance(value, widgets.Linked) and owner in value.rows), None)++ return owner, name, expected++++++def capture(control, page, output, state):++ document = control.pages[page].documentView()++ geometry = measure(document)++ paths = []++ for target, suffix in ((control.window.contentView(), ""), (document, "-full")):++ path = output / f"{page}{suffix}-640-1x-{state}.png"++ render(target, path, 1)++ paths.append(str(path))++ if geometry["flags"]:++ path = output / f"{page}-full-640-2x-{state}.png"++ render(document, path, 2)++ paths.append(str(path))++ return geometry["flags"], paths++++++def main():++ output = ROOT / "renders/mac"++ output.mkdir(parents=True, exist_ok=True)++ actions = []++ with contextlib.ExitStack() as stack:++ stack.enter_context(mock.patch.object(app, "accessibility_granted", return_value=False))++ stack.enter_context(mock.patch.object(app, "input_monitoring_granted", return_value=False))++ workspace = mock.Mock()++ stack.enter_context(mock.patch.object(AppKit, "NSWorkspace", SimpleNamespace(sharedWorkspace=lambda: workspace)))++ # PyObjC cannot delete a Python replacement for an inherited selector on++ # restoration. These process-local fakes disappear when the runner exits.++ AppKit.NSEvent.addLocalMonitorForEventsMatchingMask_handler_ = mock.Mock(return_value=object())++ AppKit.NSEvent.removeMonitor_ = mock.Mock()++ stack.enter_context(mock.patch.object(app.ApplicationServices, "AXIsProcessTrustedWithOptions", return_value=True))++ stack.enter_context(mock.patch.object(app.Quartz, "CGRequestListenEventAccess", return_value=True))++ stack.enter_context(mock.patch.object(app.subprocess, "Popen"))++ login = {"on": False}++ stack.enter_context(mock.patch.object(app.login_item, "status", side_effect=lambda: app.login_item.ENABLED if login["on"] else app.login_item.NOT_FOUND))++ stack.enter_context(mock.patch.object(app.login_item, "set_enabled", side_effect=lambda on: login.update(on=on)))++ stack.enter_context(mock.patch.object(pairing, "pairing_address", return_value="192.0.2.20"))++ for page in ("overview", "permissions", "crossing", "keyboard", "design", "connection"):++ control = fixture(peers(5), True)++ control.quit_handler = mock.Mock()++ control.haptics = mock.Mock()++ control.update_checker = mock.Mock()++ control.panel.service = FakePairing()++ def direction(token, **changes):++ control.settings_store.set_peer(token, **changes)++ control.panel.refresh()++ control.direction_handler = direction++ control.has_notch = True++ control.controller.notch_range = (100, 200)++ control.controller.event_tap = object()++ control._select_page(page)++ control.window.setContentSize_((640, 540))++ control.windowDidResize_(None)++ control.refresh()++ control._reflect()++ settle(control)++ seen = set()++ for round_number in range(3):++ if page == "design" and round_number:++ control.glow_box.value = True++ control.landing_box.value = True++ control.style_for_select.value = "switch" if round_number == 1 else "crossing"++ control._reflect()++ settle(control)++ views = list(walk(control.pages[page].documentView()))++ for view in views:++ label = str(view.accessibilityLabel() or "")++ if isinstance(view, AppKit.NSButton):++ label = str(view.title())++ action = str(view.action() or "")++ target = view.target()++ if not view.isEnabled() or target is None or not action:++ continue++ callback = lambda view=view, target=target, action=action: getattr(target, action.replace(":", "_"))(view)++ elif isinstance(view, widgets.Pressable) and getattr(view, "enabled", True) and getattr(view, "callback", None):++ callback = view.press++ else:++ continue++ key = (page, id(view))++ if key in seen:++ continue++ seen.add(key)++ row = {"page": page, "label": label, "class": view.className(), "round": round_number}++ selection = expected_selection(control, view)++ row["settings_before"] = public_settings(control)++ redirected_before = control.controller.redirecting++ paused_before = control.controller.crossing_paused++ try:++ callback()++ control._flush()++ settle(control)++ row["result"] = "completed"++ except Exception as exc:++ row["result"] = "exception"++ row["exception"] = repr(exc)++ row["traceback"] = traceback.format_exc()++ row["settings_after"] = public_settings(control)++ row["checks"] = []++ if isinstance(view, AppKit.NSButton) and action == "toggleRedirect:":++ row["checks"].append({"effect": "redirecting", "expected": not redirected_before,++ "actual": control.controller.redirecting, "passed": control.controller.redirecting == (not redirected_before)})++ if isinstance(view, AppKit.NSButton) and action == "togglePause:":++ row["checks"].append({"effect": "crossing_paused", "expected": not paused_before,++ "actual": control.controller.crossing_paused, "passed": control.controller.crossing_paused == (not paused_before)})++ if selection:++ owner, name, expected = selection++ row["checks"].append({"control": name, "expected": expected, "actual": owner.value, "passed": owner.value == expected})++ saved = SAVED.get(name)++ if saved:++ actual = row["settings_after"]++ for part in saved.split("."):++ actual = actual.get(part) if isinstance(actual, dict) else None++ row["checks"].append({"setting": saved, "expected": expected, "actual": actual, "passed": actual == expected})++ if name == "login_switch":++ row["checks"].append({"effect": "login_item.set_enabled", "expected": expected, "actual": login["on"], "passed": login["on"] == expected})++ row["flags"], row["renders"] = capture(control, page, output, f"action-{len(actions):03d}")++ row["render_metadata"] = render_metadata(control)++ actions.append(row)++ for recorder in (control.key_recorder, control.jump_recorder, control.ignored_recorder):++ recorder.cancel()++ print(f"{page}: {sum(r['page'] == page for r in actions)} controls", flush=True)++ control = fixture(peers(5), True)++ control.window.setContentSize_((640, 540))++ control.windowDidResize_(None)++ for ruler_name in ("pointer_ruler", "scroll_ruler", "resistance_ruler", "double_tap_ruler"):++ ruler = getattr(control, ruler_name)++ page = "keyboard" if ruler_name in ("pointer_ruler", "scroll_ruler") else "crossing"++ control._select_page(page)++ for fraction in (0, 0.5, 1):++ row = {"page": page, "label": ruler_name, "fraction": fraction, "round": 0,++ "settings_before": public_settings(control)}++ try:++ ruler.move_to(fraction)++ control._flush()++ settle(control)++ row.update(result="completed", value=ruler.value)++ after = public_settings(control)++ setting = {"pointer_ruler": "pointer_speed", "scroll_ruler": "scroll_speed",++ "resistance_ruler": "crossing.resistance_px", "double_tap_ruler": "double_tap_ms"}[ruler_name]++ actual = after++ for part in setting.split("."):++ actual = actual.get(part) if isinstance(actual, dict) else None++ expected = ruler.value / 100 if ruler_name in ("pointer_ruler", "scroll_ruler") else ruler.value++ row["checks"] = [{"setting": setting, "expected": expected, "actual": actual, "passed": actual == expected}]++ except Exception as exc:++ row.update(result="exception", exception=repr(exc))++ row["settings_after"] = public_settings(control)++ row["flags"], row["renders"] = capture(control, page, output, f"action-{len(actions):03d}")++ row["render_metadata"] = render_metadata(control)++ actions.append(row)++ (output / "actions.json").write_text(json.dumps(actions, indent=2))++ print(json.dumps({"actions": len(actions), "exceptions": sum(r["result"] == "exception" for r in actions), "selection_checks": sum(len(r.get("checks", [])) for r in actions), "mismatches": sum(not check["passed"] for r in actions for check in r.get("checks", []))}))++++++if __name__ == "__main__":++ main()diff --cc scripts/ui_audit/mac_menu_actions.pyindex 0000000,0000000..23759fanew file mode 100644--- /dev/null+++ b/scripts/ui_audit/mac_menu_actions.py@@@ -1,0 -1,0 +1,115 @@@++"""Invoke the production tray callbacks without a status item or OS side effects."""++import contextlib++import json++import logging++from types import SimpleNamespace++from unittest import mock++++from mac_render import ROOT, AppKit, app, fixture, peers, settle++from mac_states import FakePairing++from mac_actions import public_settings++++++def menu_items(menu, prefix="tray"):++ for item in list(menu.values()):++ if getattr(item, "hidden", False) or not hasattr(item, "title"):++ continue++ path = prefix + "/" + str(item.title)++ yield path, item++ if hasattr(item, "values"):++ yield from menu_items(item, path)++++++def main():++ actions = []++ with contextlib.ExitStack() as stack:++ for target, name in ((app.keyboard_layout, "watch"), (app, "GestureOverlay"), (app, "EdgeGlow"),++ (app, "NotchIsland"), (app, "NotchBeam"), (app.effects_overlay, "EffectsOverlay"),++ (app, "Haptics"), (app, "WindowsInput"), (app.updates, "Checker"),++ (app.rumps, "Timer"), (app.notices, "Notices"), (app.rumps, "quit_application"),++ (app, "show_about_panel")):++ stack.enter_context(mock.patch.object(target, name))++ workspace = mock.Mock()++ stack.enter_context(mock.patch.object(AppKit, "NSWorkspace", SimpleNamespace(sharedWorkspace=lambda: workspace)))++ stack.enter_context(mock.patch.object(AppKit, "NSBeep"))++ stack.enter_context(mock.patch.object(app, "LOG_DIRECTORY", ROOT / "renders/mac/synthetic-logs"))++ service = FakePairing()++ service.start, service.stop = mock.Mock(), mock.Mock()++ stack.enter_context(mock.patch.object(app.pairing, "PairingService", return_value=service))++ stack.enter_context(mock.patch.object(app, "accessibility_granted", return_value=True))++ stack.enter_context(mock.patch.object(app, "input_monitoring_granted", return_value=True))++ for count in (0, 1, 3, 5):++ control = fixture(peers(count), True)++ control.controller.stop = mock.Mock()++ tray = app.TrayApp(control.controller, control.settings_store, logging.getLogger("audit-menu"), hidden=True)++ tray.control_window.show = mock.Mock()++ tray.measure_notch = mock.Mock()++ tray.refresh_status(None)++ for menu_path, item in menu_items(tray.menu):++ if not getattr(item, "callback", None):++ continue++ title = item.title++ before = public_settings(tray.control_window)++ paused = tray.controller.crossing_paused++ redirected_before = tray.controller.redirecting++ on_before = tray.controller.owner.on++ expected = None++ if item is tray.send_item:++ chosen = [p for p in before["peers"] if p["send"] or p["side"]]++ expected = ("send", not all(p["send"] is True for p in chosen))++ elif item is tray.receive_item:++ expected = ("allow_drive", not all(p["allow_drive"] is True for p in before["peers"]))++ try:++ item.callback(item)++ settle(tray.control_window)++ after = public_settings(tray.control_window)++ checks = []++ if expected:++ key, value = expected++ applicable = [p for p in after["peers"] if key != "send" or p["side"]]++ checks.append({"setting": key, "expected": value, "actual": [p[key] for p in applicable],++ "passed": all(p[key] == value for p in applicable)})++ if item is tray.pause_item:++ checks.append({"effect": "crossing_paused", "expected": not paused,++ "actual": tray.controller.crossing_paused, "passed": tray.controller.crossing_paused == (not paused)})++ if item is tray.toggle_item and count:++ checks.append({"effect": "redirecting", "expected": not redirected_before,++ "actual": tray.controller.redirecting, "passed": tray.controller.redirecting == (not redirected_before)})++ defaults = getattr(item.callback, "__defaults__", None)++ if defaults and defaults[-1] in {p["id"] for p in before["peers"]}:++ peer = defaults[-1]++ expected_on = app.protocol.id_text(tray.controller.identity()["id"]) if redirected_before and on_before == peer else peer++ checks.append({"effect": "input owner", "expected": expected_on, "actual": tray.controller.owner.on,++ "passed": tray.controller.owner.on == expected_on})++ actions.append({"state": count, "title": title, "path": menu_path, "result": "completed",++ "settings_before": before, "settings_after": after, "checks": checks})++ except Exception as exc:++ actions.append({"state": count, "title": item.title, "result": "exception", "exception": repr(exc)})++ for index, page in enumerate(app.pages.PAGES):++ sender = SimpleNamespace(tag=lambda index=index: index)++ tray.control_window.showPage_(sender)++ actions.append({"state": count, "title": "View/" + page[1], "result": "completed",++ "selected_page": tray.control_window.page})++ for parent in AppKit.NSApp.mainMenu().itemArray():++ for item in parent.submenu().itemArray():++ if item.isSeparatorItem():++ continue++ selector = str(item.action() or "")++ target = item.target()++ if target is not None:++ supported = bool(target.respondsToSelector_(selector))++ else:++ supported = any(obj.respondsToSelector_(selector) for obj in++ (AppKit.NSApp, tray.control_window.window, tray.control_window.host_field))++ actions.append({"state": count, "title": str(parent.title()) + "/" + str(item.title()),++ "selector": selector, "result": "selector-present" if supported else "responder-chain-only",++ "note": "Native Edit/Hide/Close/Minimise effects are not invoked on Toby's desktop."})++ path = ROOT / "renders/mac/menu-actions.json"++ path.write_text(json.dumps(actions, indent=2))++ print(json.dumps({"menu_actions": len(actions), "exceptions": sum(row["result"] == "exception" for row in actions),++ "checks": sum(len(row.get("checks", [])) for row in actions),++ "mismatches": sum(not check["passed"] for row in actions for check in row.get("checks", []))}))++++++if __name__ == "__main__":++ main()diff --cc scripts/ui_audit/mac_render.pyindex 0000000,0000000..100a2b9new file mode 100644--- /dev/null+++ b/scripts/ui_audit/mac_render.py@@@ -1,0 -1,0 +1,277 @@@++"""Offscreen AppKit UI audit; never starts Beamer or orders a window front.++++Run with Beamer's PyObjC interpreter from the repository root. All settings are++in memory. Geometry JSON is a candidate list requiring visual review.++"""++from __future__ import annotations++++import argparse++import builtins++import copy++import json++import logging++from pathlib import Path++import sys++import threading++from types import SimpleNamespace++from unittest import mock++++ROOT = Path(__file__).resolve().parents[2]++sys.path[:0] = [str(ROOT / "mac_app"), str(ROOT)]++import AppKit++from Foundation import NSDate, NSRunLoop++import kvm_bridge_app as app++import settings_store++import widgets++import theme++from wake import WakingController++from core.link import OutboundLink++++AppKit.NSApplication.sharedApplication()++theme.init_fonts()++++++def deny_real_settings(event, args):++ if event == "open" and isinstance(args[0], (str, bytes, Path)):++ path = str(args[0])++ if "/Library/Application Support/Beamer/" in path:++ raise RuntimeError("UI audit blocked a real Beamer settings access")++++++sys.addaudithook(deny_real_settings)++++++def walk(view, hidden=False):++ hidden = hidden or bool(view.isHidden())++ if hidden:++ return++ yield view++ for child in view.subviews():++ yield from walk(child, hidden)++++++def settle(control):++ control.window.contentView().layoutSubtreeIfNeeded()++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.025))++ control.window.contentView().layoutSubtreeIfNeeded()++ if control.window.isVisible():++ raise RuntimeError("Offscreen window unexpectedly became visible")++++++def peers(count):++ names = ["PC", "A very long workstation name with translated length", "Linux", "localhost-live.example.lan", "Phone"]++ return [{**settings_store.PEER_DEFAULTS, "id": settings_store._b64(bytes([i + 1]) * 16),++ "name": names[i][:app.protocol.MAX_NAME_CHARS], "platform": "android" if i == 4 else "windows" if i % 2 == 0 else "linux",++ "token": settings_store._b64(bytes([i + 11]) * 32), "host": "localhost-live.example.lan" if i == 3 else f"192.0.2.{i + 10}",++ "port": 0 if i == 4 else 24820, "send": i != 4, "allow_drive": True,++ "side": ("left", "right", "top", "bottom", "")[i], "linked": True,++ "paired_at": i + 1} for i in range(count)]++++++def fixture(entries, connected, appearance="system"):++ AppKit.NSApplication.sharedApplication()++ store = object.__new__(settings_store.SettingsStore)++ store.lock = threading.RLock()++ store._handed_token = ""++ store._cache = store._complete({**store._fresh(), "name": "Mac audit", "appearance": appearance,++ "machine_id": settings_store._b64(bytes([100]) * 16), "peers": entries,++ "zones": [{"peer": p["id"], "kind": "edge"} for p in entries if p["port"] and p["side"]]})++ store._check(store._cache)++ store.path = ROOT / "renders/mac/synthetic-settings.json"++ store._write = lambda *args, **kwargs: None++ store._read = lambda: copy.deepcopy(store._cache)++ store.load_settings = lambda: copy.deepcopy(store._cache)++ store.load = lambda: store._config(store._cache)++ cfg = store.load()++ store._handed_token = cfg.auth_token++ logger = logging.getLogger("ui-audit")++ book, identity = app.bridge.links_from_store(store, app.VERSION)++ controller = WakingController(cfg, logger=logger, book=book, identity=identity, hardware=lambda _host: "")++ controller.start_input_capture = lambda: None++ controller.peers_changed = lambda: None++ controller._sync_links = lambda: None++ controller.links = {}++ for p in entries:++ if p["port"] == 0:++ continue++ link = OutboundLink(p["token"], controller.book, lambda: {})++ link._live = connected++ link.kind = "connected" if connected else "unreachable"++ link.status = "Connected" if connected else "Disconnected"++ link.peer_id, link.peer_name, link.peer_platform = p["id"], p["name"], p["platform"]++ link.dialled = (p["host"], p["port"])++ link._caps = frozenset(("settings", "design_sync"))++ link.entry = lambda p=p: copy.deepcopy(p)++ link.start = lambda: None++ link.refresh = lambda: None++ link.send = lambda *args, **kwargs: None++ controller.links[p["token"]] = link++ controller._primary_link = next(iter(controller.links.values()), None)++ controller._primary_token = entries[0]["token"] if entries else ""++ controller._peers_up = {link.peer_id: link for link in controller.links.values()} if connected else {}++ controller._accepts = {p["id"]: True for p in entries if p["port"]} if connected else {}++ controller._return_local = lambda *args: None++ def redirect(value, *args, peer=None, **kwargs):++ target = peer or controller._shortcut_peer()++ if value and target is None:++ return False++ controller._redirecting = bool(value)++ controller.receiving = False++ controller.owner.on = target if value else app.protocol.id_text(identity()["id"])++ return True++ controller.set_redirecting = redirect++ controller.event_tap = object()++ controller.retry_capture = lambda *args: None++ controller.send_to_peer = lambda *args: None++ with mock.patch.object(app, "accessibility_granted", return_value=True), mock.patch.object(app, "input_monitoring_granted", return_value=True):++ control = app.ControlWindow.alloc().initWithController_settingsStore_logger_(controller, store, logger)++ control.retry_capture = lambda *args, **kwargs: None++ control.inbound_ids = lambda: {p["id"] for p in store._cache["peers"]} if connected else set()++ control.refresh()++ control.previews = mock.Mock()++ return control++++++def render_metadata(control):++ return {"sans_font": str(theme.font(theme.TYPE["body"]).fontName()),++ "mono_font": str(theme.mono_font(theme.TYPE["small"]).fontName()),++ "appearance": control.appearance_select.value, "dark": bool(theme.is_dark()),++ "backing_scale_factor": float(control.window.backingScaleFactor()),++ "scale_method": "bitmap pixel density; physical display backing scale unchanged"}++++++def rect(value):++ return [round(value.origin.x, 2), round(value.origin.y, 2), round(value.size.width, 2), round(value.size.height, 2)]++++++def measure(root):++ rows, flags = [], []++ for view in walk(root):++ frame = view.convertRect_toView_(view.bounds(), root)++ entry = {"class": view.className(), "frame": rect(frame), "label": str(view.accessibilityLabel() or "")}++ if isinstance(view, AppKit.NSTextField):++ text = str(view.stringValue())++ entry["text"] = text++ attributed = view.attributedStringValue()++ bounds = view.bounds()++ cell_rect = view.cell().drawingRectForBounds_(bounds)++ entry["cell"] = rect(cell_rect)++ required = attributed.boundingRectWithSize_options_((max(1, cell_rect.size.width), 100000),++ AppKit.NSStringDrawingUsesLineFragmentOrigin | AppKit.NSStringDrawingUsesFontLeading)++ entry["required"] = rect(required)++ if text and required.size.height > cell_rect.size.height + 2:++ flags.append({**entry, "kind": "text-height"})++ if text and not view.cell().wraps() and attributed.size().width > cell_rect.size.width + 2:++ paragraph = attributed.attribute_atIndex_effectiveRange_(++ AppKit.NSParagraphStyleAttributeName, 0, None)[0]++ line_break_mode = paragraph.lineBreakMode() if paragraph is not None else view.cell().lineBreakMode()++ tooltip = str(view.toolTip() or "")++ accessibility_text = str(view.accessibilityLabel() or "")++ intentional = (line_break_mode == AppKit.NSLineBreakByTruncatingTail++ and tooltip == text and accessibility_text == text)++ flags.append({**entry, "kind": "text-width",++ "ink_width": round(attributed.size().width, 2),++ "source_ink_width": round(attributed.size().width, 2),++ "visible_width": round(cell_rect.size.width, 2),++ "line_break_mode": int(line_break_mode),++ "tooltip": tooltip, "accessibility_text": accessibility_text,++ "classification": "intentional-tail-elision" if intentional else "review-source-width",++ "intentional_elision": intentional})++ elif isinstance(view, AppKit.NSButton):++ title = view.attributedTitle()++ title_rect = view.cell().titleRectForBounds_(view.bounds())++ entry.update(text=str(view.title()), cell=rect(title_rect),++ ink_width=round(title.size().width, 2), ink_height=round(title.size().height, 2))++ if title.size().width > title_rect.size.width + 2:++ flags.append({**entry, "kind": "button-title-width"})++ if title.size().height > title_rect.size.height + 2:++ flags.append({**entry, "kind": "button-title-height"})++ elif isinstance(view, widgets._RulerView):++ owner = view.owner++ span, base = view.bounds().size.width - 3, view.TOP + view.TRACK++ attributes = {AppKit.NSFontAttributeName: theme.mono_font(theme.TYPE["eyebrow"])}++ entry["drawn_text"] = []++ for index, value in enumerate(owner.labels):++ text = AppKit.NSString.stringWithString_(str(value))++ ink = text.sizeWithAttributes_(attributes)++ x = 1.5 + widgets.scale_fraction(value, owner.low, owner.high, owner.scale) * span++ left = 0 if index == 0 else view.bounds().size.width - ink.width if index == len(owner.labels) - 1 else x - ink.width / 2++ entry["drawn_text"].append({"text": str(value), "left": left, "top": base + 5, "width": ink.width, "height": ink.height})++ if left < -2 or left + ink.width > view.bounds().size.width + 2 or base + 5 + ink.height > view.bounds().size.height + 2:++ flags.append({**entry, "text": str(value), "kind": "drawn-ruler-text"})++ parent = view.superview()++ if parent is not None and not isinstance(parent, AppKit.NSClipView) and view.className() != "NSButtonTextField":++ f, b = view.frame(), parent.bounds()++ if f.size.width > 1 and f.size.height > 1 and (f.origin.x < b.origin.x - 2 or f.origin.x + f.size.width > b.origin.x + b.size.width + 2):++ flags.append({**entry, "kind": "outside-parent-horizontal", "parent": parent.className(), "parent_bounds": rect(b)})++ if isinstance(view, AppKit.NSStackView):++ children = [child for child in view.arrangedSubviews() if not child.isHidden()]++ vertical = view.orientation() == AppKit.NSUserInterfaceLayoutOrientationVertical++ for first, second in zip(children, children[1:]):++ a, b = first.alignmentRectForFrame_(first.frame()), second.alignmentRectForFrame_(second.frame())++ if vertical:++ gap = b.origin.y - a.origin.y - a.size.height if view.isFlipped() else a.origin.y - b.origin.y - b.size.height++ else:++ gap = b.origin.x - a.origin.x - a.size.width++ wanted = view.customSpacingAfterView_(first)++ if abs(wanted) > 100000:++ wanted = view.spacing()++ if gap < -2:++ flags.append({**entry, "kind": "stack-overlap", "actual_gap": round(gap, 2),++ "expected_gap": wanted, "first": first.className(), "second": second.className()})++ elif abs(gap - wanted) > 2 and view.distribution() == AppKit.NSStackViewDistributionFill:++ flags.append({**entry, "kind": "uneven-stack-gap", "actual_gap": round(gap, 2), "expected_gap": wanted})++ rows.append(entry)++ return {"size": [root.bounds().size.width, root.bounds().size.height], "is_flipped": bool(root.isFlipped()), "views": rows, "flags": flags}++++++def render(view, path, scale):++ width, height = view.bounds().size++ bitmap = AppKit.NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(++ None, round(width * scale), round(height * scale), 8, 4, True, False, AppKit.NSDeviceRGBColorSpace, 0, 0)++ bitmap.setSize_((width, height))++ view.cacheDisplayInRect_toBitmapImageRep_(view.bounds(), bitmap)++ data = bitmap.representationUsingType_properties_(AppKit.NSBitmapImageFileTypePNG, {})++ data.writeToFile_atomically_(str(path), True)++++++def main():++ parser = argparse.ArgumentParser()++ parser.add_argument("--quick", action="store_true")++ parser.add_argument("--output", type=Path, default=ROOT / "renders/mac")++ args = parser.parse_args()++ args.output.mkdir(parents=True, exist_ok=True)++ results = []++ counts = [0] if args.quick else [0, 1, 3, 5]++ widths = [900] if args.quick else [int(theme.MIN_WINDOW[0]), 900, 1200, 1600, 1900]++ with mock.patch.object(app, "accessibility_granted", return_value=True), mock.patch.object(app, "input_monitoring_granted", return_value=True):++ for count in counts:++ for connected in ([False] if args.quick else [False, True]):++ control = fixture(peers(count), connected)++ state = f"{count}-{'connected' if connected else 'disconnected'}"++ for width in widths:++ control.window.setContentSize_((width, int(theme.MIN_WINDOW[1]) if width == int(theme.MIN_WINDOW[0]) else 900))++ control.windowDidResize_(None)++ settle(control)++ for page in control.pages:++ control._select_page(page)++ settle(control)++ targets = [(page, control.window.contentView()), (f"{page}-full", control.pages[page].documentView())]++ for name, target in targets:++ measurements = measure(target)++ for scale in ([1] if args.quick else [1, 2]):++ path = args.output / f"{name}-{width}-{scale}x-{state}.png"++ render(target, path, scale)++ results.append({"page": name, "width": width, "scale": scale, "state": state,++ "path": str(path), **render_metadata(control), **measurements})++ print(f"rendered {state} {width}", flush=True)++ (args.output / "measurements.json").write_text(json.dumps(results, indent=2))++ width_flags = [flag for result in results for flag in result["flags"] if flag["kind"] == "text-width"]++ print(json.dumps({"renders": len(results), "flagged": sum(bool(r["flags"]) for r in results),++ "raw_width_flags": len(width_flags),++ "intentional_elisions": sum(flag["intentional_elision"] for flag in width_flags),++ "unclassified_source_width_flags": sum(not flag["intentional_elision"] for flag in width_flags)}))++++++if __name__ == "__main__":++ main()diff --cc scripts/ui_audit/mac_review.pyindex 0000000,0000000..edd2798new file mode 100644--- /dev/null+++ b/scripts/ui_audit/mac_review.py@@@ -1,0 -1,0 +1,61 @@@++"""Contact sheets of every flagged AppKit text crop; PNG originals stay untouched."""++import json++import math++import sys++from pathlib import Path++++from PIL import Image, ImageDraw++++ROOT = Path(__file__).resolve().parents[2]++++++def main():++ folder = ROOT / "renders/mac"++ action_mode = "--actions" in sys.argv++ output = folder / ("action-review" if action_mode else "review")++ output.mkdir(exist_ok=True)++ entries = []++ files = ("actions.json",) if action_mode else ("measurements.json", "state-measurements.json")++ for file in files:++ for row in json.loads((folder / file).read_text()):++ if action_mode:++ if not row.get("renders"):++ continue++ row = {**row, "page": row["page"] + "-full", "width": 640, "scale": 1,++ "path": row["renders"][1], "state": f"{row['label']} round {row['round']}", "is_flipped": True}++ for flag in row["flags"]:++ if flag["class"] == "NSButtonTextField":++ continue++ entries.append((row, flag))++ index = []++ for batch_start in range(0, len(entries), 32):++ batch = entries[batch_start:batch_start + 32]++ sheet = Image.new("RGB", (1600, math.ceil(len(batch) / 4) * 135), "#303030")++ draw = ImageDraw.Draw(sheet)++ for offset, (row, flag) in enumerate(batch):++ image = Image.open(row["path"]).convert("RGB")++ scale = row["scale"]++ x, y, width, height = flag["frame"]++ if not row.get("is_flipped", row["page"].endswith("-full")):++ y = image.height / scale - y - height++ left, top = max(0, x - 15), max(0, y - 15)++ right, bottom = min(image.width / scale, x + width + 15), min(image.height / scale, y + height + 15)++ pos = ((offset % 4) * 400, (offset // 4) * 135)++ if right > left and bottom > top:++ crop = image.crop(tuple(round(v * scale) for v in (left, top, right, bottom)))++ crop.thumbnail((390, 90))++ sheet.paste(crop, (pos[0] + 4, pos[1] + 42))++ else:++ draw.text((pos[0] + 4, pos[1] + 60), "Below visible scroller; inspect -full PNG", fill="white")++ title = f"{batch_start + offset}: {row['page']} {row['width']} {scale}x"++ draw.text((pos[0] + 4, pos[1] + 3), title, fill="white")++ draw.text((pos[0] + 4, pos[1] + 19), row["state"], fill="white")++ index.append({"index": batch_start + offset, "original": row["path"], "flag": flag,++ "sheet": str(output / f"flags-{batch_start // 32:03d}.png")})++ sheet.save(output / f"flags-{batch_start // 32:03d}.png")++ (output / "index.json").write_text(json.dumps(index, indent=2))++ print(f"{len(entries)} flagged crops in {math.ceil(len(entries) / 32)} contact sheets")++++++if __name__ == "__main__":++ main()diff --cc scripts/ui_audit/mac_states.pyindex 0000000,0000000..74b74benew file mode 100644--- /dev/null+++ b/scripts/ui_audit/mac_states.py@@@ -1,0 -1,0 +1,186 @@@++"""Expanded offscreen states and native-menu measurements for mac_render.py."""++import json++from pathlib import Path++from types import SimpleNamespace++from unittest import mock++++from mac_render import ROOT, AppKit, app, fixture, measure, peers, render, render_metadata, settle, settings_store, theme, widgets++from core import pairing++++++class FakePairing:++ def __init__(self, heard=5, code=None):++ self.code, self.seconds_left, self.tcp_port = code, 179, 24820++ self.error, self.tcp_error, self.outcome, self.known = None, None, None, None++ self.heard = [{"name": p["name"], "platform": p["platform"], "address": p["host"],++ "port": 24820, "pairing": pairing.PAIRING_V3, "pair_id": bytes([i + 1]) * 16,++ "id": bytes([i + 1]) * 16} for i, p in enumerate(peers(heard))]++++ def machines(self):++ return self.heard++++ def qr_text(self, address):++ return "beamer://pair?code=123456" if address and not self.tcp_error else None++++ def begin_pairing(self):++ self.code = "123456"++++ def cancel_pairing(self):++ self.code = None++++ def pair(self, *args):++ raise pairing.PairingError(pairing.ERROR_NOT_PAIRING)++++ pair_by_address = pair++++++def capture(control, page, state, results):++ control._select_page(page)++ for width in (int(theme.MIN_WINDOW[0]), 900, 1200, 1600, 1900):++ control.window.setContentSize_((width, int(theme.MIN_WINDOW[1]) if width == int(theme.MIN_WINDOW[0]) else 900))++ control.windowDidResize_(None)++ settle(control)++ for name, view in ((page, control.window.contentView()), (page + "-full", control.pages[page].documentView())):++ measured = measure(view)++ for scale in (1, 2):++ path = ROOT / "renders/mac" / f"{name}-{width}-{scale}x-{state}.png"++ render(view, path, scale)++ results.append({"page": name, "state": state, "width": width, "scale": scale, "path": str(path), **render_metadata(control), **measured})++++++def menus(control):++ import rumps++ tray = object.__new__(app.TrayApp)++ tray.controller, tray.control_window, tray.settings_store = control.controller, control, control.settings_store++ tray._send_keys = []++ tray.toggle_item = rumps.MenuItem(app.TOGGLE_ITEM, callback=lambda _: None)++ tray.send_item = rumps.MenuItem("This Mac drives other machines", callback=lambda _: None)++ tray.receive_item = rumps.MenuItem("Other machines drive this Mac", callback=lambda _: None)++ tray._menu = rumps.rumps.Menu()++ tray.menu = [rumps.MenuItem(f"Beamer {app.VERSION}"), None, rumps.MenuItem(app.link_state.describe(control.controller).word),++ tray.toggle_item, rumps.MenuItem("Resume crossing" if control.controller.crossing_paused else "Pause crossing"), None, tray.send_item,++ tray.receive_item, None, rumps.MenuItem("Settings…"), rumps.MenuItem("Reload configuration"),++ rumps.MenuItem("Open log folder"), None, rumps.MenuItem("About Beamer"), rumps.MenuItem("Quit Beamer")]++ if control.controller.peer_label:++ tray.toggle_item.title = "Return input to Mac" if control.controller.redirecting else f"Send input to {control.controller.peer_label}"++ tray._machine_items()++ tray._direction_items()++ app.install_main_menu(control)++ roots = [("tray", tray.menu._menu), ("main", AppKit.NSApp.mainMenu())]++ output = []++++ def inspect(name, menu):++ menu.update()++ width = menu.size().width++ font = menu.font() or AppKit.NSFont.menuFontOfSize_(0)++ screen = min(s.visibleFrame().size.width for s in AppKit.NSScreen.screens())++ for item in menu.itemArray():++ if item.isSeparatorItem():++ continue++ ink = AppKit.NSAttributedString.alloc().initWithString_attributes_(item.title(), {AppKit.NSFontAttributeName: font}).size().width++ shortcut = str(item.keyEquivalent())++ reserve = 32 + (24 if item.submenu() is not None else 0) + (44 if shortcut else 0)++ output.append({"menu": name, "title": str(item.title()), "ink_width": round(ink, 2),++ "font": str(font.fontName()), "font_size": font.pointSize(),++ "menu_width": width, "minimum_screen_width": screen, "reserve": reserve,++ "submenu": bool(item.submenu()), "overflow_screen": ink + reserve > screen,++ "possible_menu_clip": width > 0 and ink + reserve > width + 2,++ "ellipsis": "…" in str(item.title())})++ if item.submenu() is not None:++ inspect(name + "/" + str(item.title()), item.submenu())++++ for name, menu in roots:++ inspect(name, menu)++ return output++++++def main():++ output = ROOT / "renders/mac"++ output.mkdir(parents=True, exist_ok=True)++ results, menu_results = [], []++ with mock.patch.object(app, "accessibility_granted", return_value=True), mock.patch.object(app, "input_monitoring_granted", return_value=True), mock.patch.object(pairing, "pairing_address", return_value="192.0.2.20"):++ control = fixture(peers(5), True)++ control.panel.directions_open = {p["token"] for p in peers(5)}++ control.panel.refresh()++ capture(control, "overview", "5-directions", results)++ control.panel.removing = peers(5)[1]["token"]++ control.panel.refresh()++ capture(control, "overview", "5-remove-long", results)++ for mode in ("heard", "showing", "no-qr", "error", "older"):++ control = fixture(peers(1), True)++ control.panel.open = True++ service = FakePairing(code="123456" if mode in ("showing", "no-qr") else None)++ if mode == "no-qr":++ service.tcp_error = "Another application is already listening on this port; a very long translated error explanation."++ if mode == "error":++ service.heard, service.error = [], "The local network could not be reached; another application denied multicast service discovery."++ if mode == "older":++ for item in service.heard:++ item["pairing"] = "old"++ control.panel.service = service++ control.panel.refresh()++ capture(control, "overview", "pair-" + mode, results)++ control = fixture(peers(5), True)++ control._machine_picked(peers(5)[1]["id"])++ for tile in control.method_boxes.values():++ tile.value = True++ control.has_notch = True++ control._reflect()++ control.jump_recorder.set_value("ctrl+alt+shift+cmd+f12")++ control._add_ignored("key:122")++ capture(control, "crossing", "all-ways-long-jump", results)++ capture(control, "keyboard", "ignored-added", results)++ control.host_field.setStringValue_("localhost-live.example.lan")++ capture(control, "connection", "long-host", results)++ control.show_update(("1.5.0-rc.999-long-translated-version", "https://example.invalid"))++ capture(control, "overview", "update-long-version", results)++ for count in (0, 1, 3, 5):++ for connected in (False, True):++ control = fixture(peers(count), connected)++ for row in menus(control):++ menu_results.append({"state": f"{count}-{'connected' if connected else 'disconnected'}", **row})++ control = fixture(peers(1), False)++ with mock.patch.object(app, "accessibility_granted", return_value=False), mock.patch.object(app, "input_monitoring_granted", return_value=False):++ control.refresh()++ capture(control, "permissions", "denied", results)++ control.granted_at_launch = False++ control.refresh()++ capture(control, "permissions", "relaunch", results)++ for appearance in ("light", "dark"):++ control = fixture(peers(5), True, appearance=appearance)++ for page in control.pages:++ capture(control, page, "5-" + appearance, results)++ long = peers(1)++ long[0]["name"] = "A very long workstation name with translated length"[:app.protocol.MAX_NAME_CHARS]++ long[0]["host"] = "localhost-live.example.lan"++ control = fixture(long, True)++ for page in ("overview", "crossing", "connection"):++ capture(control, page, "1-long-name-host", results)++ for row in menus(control):++ menu_results.append({"state": "1-long-name-host", **row})++ for mode in ("sending", "receiving", "paused", "token-refused", "older"):++ control = fixture(long, True)++ if mode == "sending":++ control.controller.owner.on = long[0]["id"]++ control.controller.redirecting = True++ elif mode == "receiving":++ control.controller.driver = long[0]["id"]++ control.controller.receiving = True++ elif mode == "paused":++ control.controller.crossing_paused = True++ else:++ link = next(iter(control.controller.links.values()))++ link._live = False++ link.kind = "unauthenticated" if mode == "token-refused" else "older"++ link.status = "That machine refused the connection; remove this pairing and pair it again."++ control.refresh()++ capture(control, "overview", "long-" + mode, results)++ for row in menus(control):++ menu_results.append({"state": "long-" + mode, **row})++ (output / "state-measurements.json").write_text(json.dumps(results, indent=2))++ (output / "menu-measurements.json").write_text(json.dumps(menu_results, indent=2))++ print(json.dumps({"renders": len(results), "flagged": sum(bool(r["flags"]) for r in results), "menu_items": len(menu_results)}))++++++if __name__ == "__main__":++ main()diff --cc scripts/ui_audit/pack_renders.pyindex 0000000,0000000..b216751new file mode 100644--- /dev/null+++ b/scripts/ui_audit/pack_renders.py@@@ -1,0 -1,0 +1,35 @@@++"""Pack completed measurement manifests and their renders for cross-machine review."""++import argparse++import json++from pathlib import Path++import sys++import zipfile++++++def main():++ parser = argparse.ArgumentParser()++ parser.add_argument("root", type=Path)++ parser.add_argument("archive", type=Path)++ parser.add_argument("--platforms", required=True)++ parser.add_argument("--scales", default="1.0,1.25,1.5,2.0")++ args = parser.parse_args()++ destination = sys.stdout.buffer if args.archive == Path("-") else args.archive++ with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_STORED) as archive:++ for platform in args.platforms.split(","):++ folder = args.root / platform++ for scale in args.scales.split(","):++ manifest = folder / f"measurements-{scale}.json"++ records = json.loads(manifest.read_text(encoding="utf-8"))++ paths = {folder / Path(row["path"]).name for row in records}++ paths.add(manifest)++ paths.update(folder.glob(f"*-{scale}.json"))++ for path in sorted(paths):++ archive.write(path, arcname=path.relative_to(args.root).as_posix())++ if args.archive == Path("-"):++ print(json.dumps({"archive": "stdout"}), file=sys.stderr)++ else:++ print(json.dumps({"archive": str(args.archive), "bytes": args.archive.stat().st_size}))++++++if __name__ == "__main__":++ main()diff --cc scripts/ui_audit/qt_actions.pyindex 0000000,0000000..1fb016cnew file mode 100644--- /dev/null+++ b/scripts/ui_audit/qt_actions.py@@@ -1,0 -1,0 +1,304 @@@++"""Drive the real Qt controls after qt_audit has isolated all OS/network effects.++++Only the caller's explicit fixture settings path is read. Reports whitelist public++settings fields, so synthetic pairing credentials never enter an audit report.++"""++++from __future__ import annotations++++import json++from pathlib import Path++import re++import sys++import time++++++def exercise(window, app, output=None, snapshot=None):++ """Return action results; optionally write JSON and call snapshot(name) after each.++++ The caller must neutralise receiver/capture, pairing transport, autostart,++ firewall, update-checker, injector shutdown and QDesktopServices before calling.++ `snapshot` runs on the GUI thread with the current page and control state.++ """++ from PySide6.QtCore import QEvent, QPointF, Qt++ from PySide6.QtGui import QKeyEvent, QMouseEvent++ from PySide6.QtTest import QTest++ from PySide6.QtWidgets import QApplication, QMessageBox, QPushButton++++ import app_config++ import widgets++++ results = []++ signal_errors = []++ previous_hook = sys.excepthook++ public_fields = (++ "appearance", "check_updates", "hold_full_screen", "block_while_dragging",++ "hide_addresses", "same_on_both", "modifier_style", "pointer_speed",++ "scroll_speed", "reverse_scroll", "trigger_key", "trigger_style",++ "double_tap_ms", "crossing_resistance_px", "edge_glow", "shortcut_arrival",++ "shortcut_arrival_style", "glow_style", "glow_colour", "effect_length",++ "effect_size", "design_follow_peer", "ignored_inputs", "port",++ )++++ def exception_hook(kind, value, trace):++ signal_errors.append(f"{kind.__name__}: {value}")++++ def settings():++ data = app_config.load_settings(window.config_path)++ return {key: data.get(key) for key in public_fields}++++ def settle():++ # Slider persistence waits 300ms; animations also alter control geometry.++ deadline = time.monotonic() + 0.36++ while time.monotonic() < deadline:++ app.processEvents()++ QTest.qWait(5)++ window._refresh_window()++ app.processEvents()++++ def run(name, function, expected=None):++ before = settings()++ signal_errors.clear()++ row = {"action": name, "result": "pass"}++ try:++ function()++ settle()++ after = settings()++ row["changed"] = {key: after[key] for key in public_fields if before[key] != after[key]}++ if expected:++ wrong = {key: {"expected": value, "actual": after.get(key)}++ for key, value in expected.items() if after.get(key) != value}++ if wrong:++ row["result"] = "fail"++ row["mismatch"] = wrong++ if signal_errors:++ row["result"] = "fail"++ row["exceptions"] = list(signal_errors)++ if snapshot:++ snapshot(re.sub(r"[^A-Za-z0-9_.-]+", "-", name).strip("-"))++ except Exception as exc:++ row["result"] = "fail"++ row["exception"] = f"{type(exc).__name__}: {exc}"++ results.append(row)++++ def click(name, control, expected=None):++ if not control.isEnabled():++ results.append({"action": name, "result": "disabled"})++ return++ run(name, control.click, expected)++++ def toggle(name, control, field=None):++ initial = control.isChecked()++ for value in (not initial, initial):++ expected = {field: value} if field else None++ click(f"{name}-{str(value).lower()}", control, expected)++++ def choice(name, group, field=None):++ for value, button in list(group._buttons.items()):++ click(f"{name}-{value}", button, {field: value} if field else None)++++ sys.excepthook = exception_hook++ try:++ for key, button in window.sidebar._buttons.items():++ click(f"sidebar-{key}", button)++ if window._page != key:++ results[-1].update(result="fail", mismatch={"selected_page": window._page})++ if isinstance(window.sidebar.foot, QPushButton):++ click("sidebar-website", window.sidebar.foot)++++ window._select_page("overview")++ for name, field in (("updates_switch", "check_updates"),++ ("hold_switch", "hold_full_screen"),++ ("same_switch", "same_on_both"), ("logon_switch", None)):++ toggle(name, getattr(window, name), field)++ click("redirect", window.redirect_button)++ click("redirect-return", window.redirect_button)++ click("pause", window.pause_button)++ click("resume", window.pause_button)++ window._on_update(("9.9.9-audit", "https://example.invalid/audit-release"))++ click("update-download", window.update_button)++ run("tray-update-download", window.header_action.trigger)++ window._on_update(None)++++ window._select_page("crossing")++ choice("crossing-machine", window.machine_choice)++ for value, box in window.way_boxes.items():++ toggle(f"way-{value}", box)++ choice("edge", window.edge_choice)++ choice("corner", window.corner_choice)++ for value, button in window.part_buttons.items():++ toggle(f"part-{value}", button)++ for value, button in window.share_tiles.items():++ if window.share_module.isVisibleTo(window):++ click(f"share-part-{value}", button)++ if window.share_module.isVisibleTo(window):++ click("share-edge", window.share_button)++ toggle("drag-protection", window.dragging_switch, "block_while_dragging")++ for value in (0, 25, window.resistance_slider.maximum()):++ run(f"resistance-{value}", lambda v=value: window.resistance_slider.setValue(v),++ {"crossing_resistance_px": value})++ choice("shortcut-style", window.trigger_style_choice, "trigger_style")++ click("double-tap-enable-for-slider", window.trigger_style_choice._buttons["double_tap"],++ {"trigger_style": "double_tap"})++ for value in (50, 500, 1000):++ run(f"double-tap-{value}", lambda v=value: window.double_tap_slider.setValue(v),++ {"double_tap_ms": value})++ for recorder_name in ("trigger_recorder", "jump_recorder"):++ recorder = getattr(window, recorder_name)++ click(f"{recorder_name}-arm", recorder)++ click(f"{recorder_name}-cancel", recorder)++++ recorder = window.trigger_recorder++ for native, key in ((0x7B, Qt.Key.Key_F12), (0x41, Qt.Key.Key_A)):++ def record_trigger(native=native, key=key):++ recorder.click()++ original = recorder.hook_vk++ recorder.hook_vk = lambda virtual, scan: virtual++ try:++ event = QKeyEvent(QEvent.Type.KeyPress, key, Qt.KeyboardModifier.NoModifier,++ 0, native, 0, "a" if native == 0x41 else "")++ recorder.eventFilter(recorder, event)++ finally:++ recorder.hook_vk = original++ recorder.cancel()++ run(f"shortcut-record-{native}", record_trigger)++ def record_jump():++ window.jump_recorder.click()++ event = QKeyEvent(QEvent.Type.KeyPress, Qt.Key.Key_J,++ Qt.KeyboardModifier.ControlModifier, "j")++ window.jump_recorder.eventFilter(window.jump_recorder, event)++ window.jump_recorder.cancel()++ run("jump-record-ctrl-j", record_jump)++ click("jump-clear", window.jump_clear)++++ window._select_page("keyboard")++ choice("modifier", window.modifier_choice, "modifier_style")++ for field, slider in window.speed_sliders.items():++ for value in (25, 100, 400):++ run(f"{field}-{value}", lambda s=slider, v=value: s.setValue(v), {field: value / 100})++ toggle("reverse-scroll", window.reverse_scroll_switch, "reverse_scroll")++ click("ignored-arm", window.ignored_recorder)++ click("ignored-cancel", window.ignored_recorder)++ def record_mouse():++ recorder = window.ignored_recorder++ recorder.click()++ event = QMouseEvent(QEvent.Type.MouseButtonPress, QPointF(1, 1), QPointF(1, 1),++ Qt.MouseButton.BackButton, Qt.MouseButton.BackButton,++ Qt.KeyboardModifier.NoModifier)++ recorder.eventFilter(recorder, event)++ recorder.cancel()++ run("ignored-record-back-button", record_mouse)++ for index in range(window.ignored_list.count() - 1, -1, -1):++ row_widget = window.ignored_list.itemAt(index).widget()++ if row_widget is not None:++ for button in row_widget.findChildren(QPushButton):++ if button.accessibleName().startswith("Remove "):++ click(f"ignored-{button.accessibleName()}", button)++++ window._select_page("design")++ if not window.glow_toggle.isChecked():++ click("animate-enable-for-controls", window.glow_toggle, {"edge_glow": True})++ toggle("animate", window.glow_toggle, "edge_glow")++ if not window.glow_toggle.isChecked():++ click("animate-enable", window.glow_toggle, {"edge_glow": True})++ toggle("landing", window.landing_toggle, "shortcut_arrival")++ for mode, group, field in (("crossing", window.glow_style_choice, "glow_style"),++ ("switch", window.switch_style_choice, "shortcut_arrival_style")):++ click(f"design-mode-{mode}", window.design_mode_choice._buttons[mode])++ for title, tiles in group.groups.items():++ for value, tile in tiles._tiles.items():++ def tile_press(tile=tile):++ event = QMouseEvent(QEvent.Type.MouseButtonPress, QPointF(4, 4), QPointF(4, 4),++ Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton,++ Qt.KeyboardModifier.NoModifier)++ tile.mousePressEvent(event)++ run(f"{mode}-tile-{value}", tile_press, {field: value})++ choice("preview-place", window.effect_method_choice)++ choice("length", window.length_choice, "effect_length")++ choice("size", window.size_choice, "effect_size")++ for value, swatch in window.glow_colour_choice._swatches.items():++ click(f"colour-{value}", swatch, {"glow_colour": value})++ for index in range(window.design_follow_choice.count()):++ run(f"design-follow-{index}", lambda i=index: window.design_follow_choice.setCurrentIndex(i))++ choice("appearance", window.appearance_choice, "appearance")++++ window._select_page("connection")++ toggle("hide-addresses", window.hide_switch, "hide_addresses")++ original_port = window.port_entry.text()++ for value in ("bad", "0", "65536", "24829", original_port):++ def save_port(value=value):++ window.port_entry.setText(value)++ window.save_button.click()++ run(f"save-port-{value}", save_port,++ {"port": int(value)} if value.isdecimal() and 1 <= int(value) <= 65535 else None)++ click("firewall-action", window.firewall_button)++++ window._select_page("overview")++ for token in list(window.machines.rows):++ row = window.machines.rows.get(token)++ if row is None:++ continue++ # Tokens stay internal: names and numerical row indices are sufficient in reports.++ index = list(window.machines.rows).index(token)++ toggle(f"peer-{index}-in-use", row.in_use)++ if not row._phone:++ toggle(f"peer-{index}-directions", row.directions)++ toggle(f"peer-{index}-send", row.send)++ toggle(f"peer-{index}-allow", row.allow)++ click(f"peer-{index}-remove-confirm", row.remove_button)++ click(f"peer-{index}-keep", row.keep)++++ if not window._pairing_open:++ click("pairing-open", window.machines.pair_button)++ click("pairing-show-code", window.sheet.show_button)++ click("pairing-cancel-code", window.sheet.cancel_button)++ for index, button in enumerate(window.sheet.group.buttons()):++ click(f"pairing-discovery-{index}", button)++ def manual_pair():++ window.sheet.address.setText("localhost-live.example.lan")++ window.sheet._typed_address(window.sheet.address.text())++ window.sheet.code.setText("123456")++ window.sheet._typed_code(window.sheet.code.text())++ window.sheet.pair_button.click()++ run("pairing-manual-address", manual_pair)++ run("pairing-result-error", lambda: window._on_pair_finished(None, ValueError("Audit fixture failure")))++ click("pairing-close", window.machines.pair_button)++++ for index, action in enumerate(list(window.tray_menu.actions())):++ if action.isSeparator():++ continue++ if action.text() == "Quit Beamer":++ continue++ if not action.isEnabled():++ results.append({"action": f"tray-{index}-{action.text()}", "result": "disabled"})++ continue++ run(f"tray-{index}-{action.text()}", action.trigger)++ if action.text() == "About Beamer":++ for box in QApplication.topLevelWidgets():++ if isinstance(box, QMessageBox) and box.windowTitle() == "About Beamer":++ for index, button in enumerate(box.buttons()):++ click(f"about-button-{index}", button)++++ # Destructive to this fixture only, after every other peer-dependent surface.++ for index, token in enumerate(list(window.machines.rows)):++ row = window.machines.rows.get(token)++ if row is not None:++ click(f"peer-{index}-remove-confirm-final", row.remove_button)++ click(f"peer-{index}-remove-final", row.really)++ quit_action = next((a for a in window.tray_menu.actions() if a.text() == "Quit Beamer"), None)++ if quit_action is not None:++ run("tray-quit", quit_action.trigger)++ finally:++ sys.excepthook = previous_hook++ for name in ("trigger_recorder", "jump_recorder", "ignored_recorder"):++ getattr(window, name).cancel()++++ report = {"actions": results, "counts": {kind: sum(row["result"] == kind for row in results)++ for kind in ("pass", "fail", "disabled")}}++ if output is not None:++ path = Path(output)++ if path.suffix != ".json":++ path = path / "actions.json"++ path.parent.mkdir(parents=True, exist_ok=True)++ path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")++ return reportdiff --cc scripts/ui_audit/qt_audit.pyindex 0000000,0000000..71a4969new file mode 100644--- /dev/null+++ b/scripts/ui_audit/qt_audit.py@@@ -1,0 -1,0 +1,620 @@@++"""Offscreen rc.2 UI audit. Run each scale in a fresh Python process.++++Example: QT_QPA_PLATFORM=offscreen QT_SCALE_FACTOR=1.5 python scripts/ui_audit/qt_audit.py++ --platform windows --output renders/windows --actions++No production settings, input hooks, listener, tray icon or desktop window is used.++"""++from __future__ import annotations++++import argparse++import json++import os++from pathlib import Path++import sys++import tempfile++from types import SimpleNamespace++from unittest.mock import patch++++ROOT = Path(__file__).resolve().parents[2]++sys.path.insert(0, str(ROOT))++sys.path.insert(0, str(ROOT / "win_app"))++++++class FakePairing:++ def __init__(self):++ self.code = None++ self.error = ""++ self.seconds_left = 120++ self.tcp_port = 24820++ self.outcome = ""++ self.known = None++ self.discovered = []++++ def machines(self):++ return self.discovered++++ def begin_pairing(self):++ self.code = "123456"++++ def cancel_pairing(self):++ self.code = None++++ def qr_text(self, address):++ return f"beamer://pair?address={address}&port=24820&code=123456"++++ def pair(self, machine, code):++ from core import pairing++ raise pairing.PairingError("wrong_code")++++ def pair_by_address(self, address, code):++ return self.pair(None, code)++++ def stop(self):++ pass++++++def fixtures(count, phone=False, long=False):++ from core import pairing, protocol++ names = ["Studio Mac", "Desk", "Linux", "Office", "Travel"]++ if long:++ names[0] = "Studio MacBook Pro with an exceptionally long machine name"++ names[2] = "Laboratory Linux workstation with the external display"++ peers = []++ for i in range(count):++ entry = pairing.peer_entry(bytes([i + 1]) * 16, names[i][:protocol.MAX_NAME_CHARS], ("macos", "windows", "linux")[i % 3],++ 24820, protocol.id_text(bytes([i + 1]) * 32),++ "localhost-live.example.lan" if i == 0 else f"192.0.2.{10+i}", 1780000000)++ entry.update(send=True, allow_drive=True, in_use=True)++ peers.append(entry)++ if phone:++ entry = pairing.peer_entry(bytes([9]) * 16, "Alex's iPhone with a longer device name", "ios", 0,++ protocol.id_text(bytes([9]) * 32), "", 1780000000)++ entry.update(send=False, allow_drive=True, in_use=True)++ peers.append(entry)++ return peers++++++def visible(widget, root):++ return widget.isVisibleTo(root) and widget.width() > 0 and widget.height() > 0++++++def text_measure(widget):++ from PySide6.QtCore import QRect, Qt++ from PySide6.QtGui import QTextDocument, QImage, QPainter, QColor++ from PySide6.QtWidgets import QLabel, QPushButton, QCheckBox, QStyle, QStyleOptionButton++ import widgets++ source_text = widget.text() if hasattr(widget, "text") else ""++ displayed_text = getattr(widget, "displayed_text", None)++ text = displayed_text() if callable(displayed_text) else source_text++ if not text:++ if not source_text or not callable(displayed_text):++ return None++ rect = widget.contentsRect()++ if isinstance(widget, QPushButton):++ option = QStyleOptionButton()++ option.initFrom(widget)++ rect = widget.style().subElementRect(QStyle.SubElement.SE_PushButtonContents, option, widget)++ return dict(kind="elided-empty", text=text, source_text=source_text,++ available=[rect.width(), rect.height()])++++ def finding(**values):++ result = dict(values)++ if source_text != text:++ result["source_text"] = source_text++ return result++ fm = widget.fontMetrics()++ rect = widget.contentsRect()++ kind = "text"++ if isinstance(widget, widgets.Switch):++ width = widget.width() - widget.TRACK.width() - 14.5++ needed = fm.horizontalAdvance(text)++ return finding(kind="switch-ink", text=text, needed=needed, available=width,++ excess=round(needed - width, 2)) if needed > width + 1 else None++ if isinstance(widget, widgets._Swatch):++ from PySide6.QtGui import QFontMetrics++ metrics = QFontMetrics(widget._face(widget.isChecked()))++ available = widget.height() - widget.chip_rect().bottom() - widget.NAME_GAP++ bounds = metrics.boundingRect(QRect(0, 0, widget.width(), 10000),++ int(Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop), text)++ ink_height = bounds.height() - metrics.height() + metrics.tightBoundingRect(text).height()++ return finding(kind="swatch-ink", text=text, needed=ink_height, available=available,++ excess=ink_height-available) if ink_height > available+2 else None++ if isinstance(widget, QLabel):++ rect.adjust(widget.margin(), widget.margin(), -widget.margin(), -widget.margin())++ indent = widget.indent()++ if indent > 0:++ rect.adjust(indent, 0, 0, 0)++ flags = int(widget.alignment())++ if widget.wordWrap():++ flags |= int(Qt.TextFlag.TextWordWrap)++ if widget.textFormat() == Qt.TextFormat.RichText or "<br" in text or "<a " in text:++ doc = QTextDocument()++ doc.setDefaultFont(widget.font())++ doc.setDocumentMargin(0)++ doc.setHtml(text)++ doc.setTextWidth(rect.width())++ height = doc.size().height()++ return finding(kind="rich-text-height", text=text, needed=height, available=rect.height(),++ excess=round(height - rect.height(), 2)) if height > rect.height() + 2 else None++ bounds = fm.boundingRect(QRect(0, 0, rect.width(), 100000), flags, text)++ excess = max(bounds.height() - rect.height(), bounds.width() - rect.width())++ if excess > 2:++ # QFontMetrics includes leading; only rasterised ink outside the actual++ # text rectangle is a clipping candidate.++ pad = 256++ canvas = QImage(max(1, rect.width()+2*pad), max(1, rect.height()+2*pad), QImage.Format.Format_ARGB32)++ canvas.fill(Qt.GlobalColor.transparent)++ painter = QPainter(canvas)++ painter.setFont(widget.font())++ painter.setPen(QColor("white"))++ painter.drawText(QRect(pad, pad, rect.width(), rect.height()), flags | int(Qt.TextFlag.TextDontClip), text)++ painter.end()++ alpha = canvas.convertToFormat(QImage.Format.Format_Alpha8)++ data = bytes(alpha.constBits())++ stride = alpha.bytesPerLine()++ ink_points = []++ for y in range(alpha.height()):++ line = data[y*stride:y*stride+alpha.width()]++ nz = [x for x, value in enumerate(line) if value > 12]++ if nz:++ ink_points.append((min(nz), max(nz), y))++ if ink_points:++ left = min(p[0] for p in ink_points)-pad++ right = max(p[1] for p in ink_points)-pad++ top = min(p[2] for p in ink_points)-pad++ bottom = max(p[2] for p in ink_points)-pad++ if left < -1 or right >= rect.width()+1 or top < -1 or bottom >= rect.height()+1:++ return finding(kind="label-ink", text=text, ink=[left,top,right,bottom],++ ink_format="inclusive-left-top-right-bottom",++ ink_size=[right-left+1, bottom-top+1],++ available=[rect.width(), rect.height()], excess=excess)++ elif isinstance(widget, (QPushButton, QCheckBox)):++ option = QStyleOptionButton()++ option.initFrom(widget)++ option.text = text++ element = QStyle.SubElement.SE_CheckBoxContents if isinstance(widget, QCheckBox) else QStyle.SubElement.SE_PushButtonContents++ rect = widget.style().subElementRect(element, option, widget)++ needed = max(fm.horizontalAdvance(line.replace("&", "")) for line in text.splitlines())++ if needed > rect.width() + 2:++ return finding(kind="button-ink", text=text, needed=needed, available=rect.width(), excess=needed-rect.width())++ return None++++++def measure(root):++ from PySide6.QtCore import QPoint, QRect++ from PySide6.QtWidgets import QWidget, QScrollArea, QLabel, QAbstractButton++ checks = []++ for w in root.findChildren(QWidget):++ if not visible(w, root):++ continue++ found = text_measure(w)++ origin = w.mapTo(root, QPoint(0, 0))++ info = dict(widget=w.metaObject().className(), name=w.objectName(),++ rect=[origin.x(), origin.y(), w.width(), w.height()])++ if found:++ checks.append(dict(info, **found))++ parent = w.parentWidget()++ if parent and not isinstance(parent, QScrollArea) and parent.objectName() != "qt_scrollarea_viewport":++ box = QRect(w.pos(), w.size())++ outside = box.intersected(parent.rect()) != box++ if outside and w.width() > 2 and w.height() > 2:++ checks.append(dict(info, kind="outside-parent", parent=parent.metaObject().className(),++ parent_size=[parent.width(), parent.height()]))++ for scroll in root.findChildren(QScrollArea):++ if not visible(scroll, root):++ continue++ if scroll.horizontalScrollBar().maximum() > 0:++ checks.append(dict(kind="sideways-scroll", maximum=scroll.horizontalScrollBar().maximum()))++ by_parent = {}++ for child in root.findChildren(QWidget):++ if visible(child, root) and isinstance(child, (QLabel, QAbstractButton)):++ by_parent.setdefault(child.parentWidget(), []).append(child)++ for siblings in by_parent.values():++ for i, first in enumerate(siblings):++ for second in siblings[i+1:]:++ overlap = first.geometry().intersected(second.geometry())++ if overlap.width() > 2 and overlap.height() > 2:++ origin = first.parentWidget().mapTo(root, overlap.topLeft())++ checks.append(dict(kind="sibling-overlap", first=first.text(), second=second.text(),++ overlap=[overlap.x(),overlap.y(),overlap.width(),overlap.height()],++ rect=[origin.x(),origin.y(),overlap.width(),overlap.height()]))++ return checks++++++def layout_snapshot(root, window):++ from PySide6.QtCore import QPoint++ from PySide6.QtWidgets import QWidget, QScrollArea, QGridLayout++++ def size(value):++ return [value.width(), value.height()]++++ def rect(value):++ return [value.x(), value.y(), value.width(), value.height()]++++ def layout_tree(layout):++ if layout is None:++ return None++ children = []++ for index in range(layout.count()):++ item = layout.itemAt(index)++ widget = item.widget()++ child = dict(index=index, geometry=rect(item.geometry()), size_hint=size(item.sizeHint()),++ minimum_size=size(item.minimumSize()), maximum_size=size(item.maximumSize()),++ widget_class=type(widget).__name__ if widget else None,++ object_name=widget.objectName() if widget else None,++ alignment=int(item.alignment()))++ if isinstance(layout, QGridLayout):++ child["grid_position"] = list(layout.getItemPosition(index))++ if item.layout():++ child["layout"] = layout_tree(item.layout())++ children.append(child)++ margins = layout.contentsMargins()++ return dict(class_name=type(layout).__name__, geometry=rect(layout.geometry()),++ size_hint=size(layout.sizeHint()), minimum_size=size(layout.minimumSize()),++ maximum_size=size(layout.maximumSize()), spacing=layout.spacing(),++ margins=[margins.left(), margins.top(), margins.right(), margins.bottom()], children=children)++++ def widget_tree(widget):++ origin = widget.mapTo(window, QPoint())++ policy = widget.sizePolicy()++ record = dict(class_name=type(widget).__name__, object_name=widget.objectName(),++ visible=widget.isVisibleTo(window), geometry=rect(widget.geometry()),++ window_rect=[origin.x(), origin.y(), widget.width(), widget.height()],++ size_hint=size(widget.sizeHint()), minimum_size_hint=size(widget.minimumSizeHint()),++ minimum_size=size(widget.minimumSize()), maximum_size=size(widget.maximumSize()),++ size_policy=[policy.horizontalPolicy().name, policy.verticalPolicy().name],++ has_height_for_width=widget.hasHeightForWidth(),++ height_for_width=widget.heightForWidth(widget.width()), layout=layout_tree(widget.layout()))++ if isinstance(widget, QScrollArea):++ record["scroll"] = dict(viewport=rect(widget.viewport().geometry()),++ horizontal=[widget.horizontalScrollBar().value(), widget.horizontalScrollBar().maximum()],++ vertical=[widget.verticalScrollBar().value(), widget.verticalScrollBar().maximum()])++ record["children"] = [widget_tree(child) for child in widget.children() if isinstance(child, QWidget)]++ return record++++ return widget_tree(root)++++++def main():++ parser = argparse.ArgumentParser()++ parser.add_argument("--platform", choices=["windows", "linux-x11", "linux-wayland"], required=True)++ parser.add_argument("--output", type=Path, required=True)++ parser.add_argument("--quick", action="store_true")++ parser.add_argument("--actions", action="store_true")++ parser.add_argument("--states", help="Comma-separated fixture names; omit for the full matrix")++ parser.add_argument("--sizes", help="Comma-separated logical sizes, e.g. 640x600,1000x800")++ parser.add_argument("--record-layout", action="store_true", help="Include geometry-only Connection layout snapshots")++ args = parser.parse_args()++ if os.environ.get("QT_QPA_PLATFORM") != "offscreen":++ raise SystemExit("Refusing to run without QT_QPA_PLATFORM=offscreen")++ args.output.mkdir(parents=True, exist_ok=True)++ fake_root = args.output / "fixtures"++ fake_root.mkdir(exist_ok=True)++ temporary = tempfile.TemporaryDirectory(prefix="settings-", dir=fake_root)++ settings_path = Path(temporary.name) / "settings.json"++ if args.platform.startswith("linux-"):++ os.environ["XDG_SESSION_TYPE"] = args.platform.removeprefix("linux-")++ os.environ["XDG_CONFIG_HOME"] = str(settings_path.parent / "xdg-config")++ os.environ["XDG_STATE_HOME"] = str(settings_path.parent / "xdg-state")++ def guard(event, values):++ if event in ("socket.connect", "socket.bind", "socket.sendto", "socket.sendmsg"):++ raise RuntimeError(f"Network operation forbidden in UI audit: {event}")++ if event in ("subprocess.Popen", "os.system"):++ raise RuntimeError(f"OS process forbidden in UI audit: {event}")++ if event == "open" and values and isinstance(values[0], (str, bytes, os.PathLike)):++ p = Path(os.fsdecode(values[0]))++ if p.name.lower() in ("settings.json", "config.json"):++ if not p.resolve().is_relative_to(fake_root.resolve()):++ raise RuntimeError(f"Forbidden settings access: {p}")++ sys.addaudithook(guard)++ from PySide6.QtCore import QPoint, QSize, Qt, qVersion, QCoreApplication, QEvent++ from PySide6.QtGui import QDesktopServices, QFontInfo++ from PySide6.QtWidgets import QApplication, QWidget, QSystemTrayIcon, QLabel, QMessageBox, QStyle, QStyleOptionMenuItem++ import app_config++ import kvm_bridge_win as kvm++ import theme++ import motion++ import widgets++ from core import protocol++ from core.receiver import ServerState++ import linux_stand_ins++ app = QApplication.instance() or QApplication([])++ app.setQuitOnLastWindowClosed(False)++ theme.init_fonts()++ app.setFont(theme.font(theme.TYPE["body"]))++ metadata = dict(native_platform=sys.platform, requested_platform=args.platform,++ session_type=os.environ.get("XDG_SESSION_TYPE"), qt_version=qVersion(),++ qt_platform=app.platformName(), qt_scale_factor=os.environ.get("QT_SCALE_FACTOR", "1.0"),++ qt_device_pixel_ratio=app.devicePixelRatio(),++ body_font=dict(requested=app.font().family(), resolved=QFontInfo(app.font()).family(),++ pixel_size=app.font().pixelSize(), point_size=app.font().pointSizeF()),++ sans_font=theme.sans(), mono_font=theme.mono(),++ parts={name: getattr(kvm.platform_parts, name).__name__++ if hasattr(getattr(kvm.platform_parts, name), "__name__") else "stand-in"++ for name in kvm.platform_parts.PARTS})++ branch_platform = "win32" if args.platform == "windows" else "linux"++ kvm.sys = SimpleNamespace(platform=branch_platform, executable=sys.executable, frozen=False)++ kvm.platform_parts.WAYLAND = args.platform == "linux-wayland"++ kvm.OWN_PLATFORM = "windows" if args.platform == "windows" else "linux"++ if args.platform != "windows":++ kvm.firewall_win = linux_stand_ins.firewall++ app_config.default_config_path = lambda: settings_path++ kvm.default_config_path = lambda: settings_path++ kvm.local_address_towards = lambda *_: "192.0.2.1"++ kvm.pairing.local_address_towards = lambda *_: "192.0.2.1"++ kvm.pairing.pairing_address = lambda: "192.0.2.1"++ kvm.hardware_win.hardware_address_towards = lambda *_: ""++ kvm.autostart_win.is_enabled = lambda: False++ kvm.autostart_win.installed_exe = lambda: str(settings_path.parent / "Beamer-audit.exe")++ kvm.platform_parts.injector.stop = lambda: None++ theme.watch_system = lambda *_: None++ motion.fade_from = lambda *_args, **_kw: None++ motion.snapshot = lambda *_: None++ motion.set_shown = lambda w, shown: w.setVisible(shown)++ motion.should_animate = lambda *_: False++ effects_log = []++ kvm.autostart_win.set_enabled = lambda *a: effects_log.append(["autostart", bool(a[0])])++ QDesktopServices.openUrl = lambda url: effects_log.append(["url", url.toString()]) or True++ QSystemTrayIcon.show = lambda *_: None++ QSystemTrayIcon.showMessage = lambda _self, title, message, *_: effects_log.append(["notification", title, message])++ app.beep = lambda: None++ kvm.WindowsApplication._make_pairing = lambda *_: FakePairing()++ kvm.WindowsApplication._apply_title_bar = lambda *_: None++ kvm.WindowsApplication._check_full_screen = lambda *_: None++ kvm.WindowsApplication._run_firewall = lambda *_: effects_log.append(["firewall"])++ kvm.WindowsApplication._run_previews = lambda *_: None++ kvm.WindowsApplication._effect_overlay = lambda *_: None++ kvm.WindowsApplication._switch_overlay = lambda *_: None++ kvm.WindowsApplication._start_receiver = lambda *_: effects_log.append(["receiver"])++ kvm.WindowsApplication._start_sending = lambda *_: effects_log.append(["sender"])++ kvm.WindowsApplication._stop_sending = lambda *_: effects_log.append(["sender-off"])++ kvm.LOG_PATH = settings_path.parent / "Beamer.log"++ sizes = [(640, 600), (1000, 800), (1600, 1000)]++ states = [("none", 0, False, False, False), ("one-short", 1, False, False, False),++ ("one-long", 1, False, True, False), ("three-long", 3, False, True, False),++ ("five-long", 5, False, True, False), ("phone", 1, True, True, False),++ ("three-connected", 3, False, True, True), ("five-connected", 5, False, True, True),++ ("one-light", 1, False, True, False), ("three-all-ways", 3, False, True, True),++ ("five-shared-edge", 5, False, True, True)]++ if args.quick:++ sizes = sizes[:1]++ states = [states[2], states[4]]++ if args.states:++ requested = set(args.states.split(","))++ states = [state for state in states if state[0] in requested]++ if {state[0] for state in states} != requested:++ raise SystemExit("Unrecognised fixture name in --states")++ if args.sizes:++ sizes = [tuple(int(n) for n in value.split("x")) for value in args.sizes.split(",")]++ if any(len(size) != 2 or min(size) <= 0 for size in sizes):++ raise SystemExit("Sizes must be positive WIDTHxHEIGHT values")++ records = []++ scale = os.environ.get("QT_SCALE_FACTOR", "1.0")++ current_case = {}++ metadata.update(selected_wayland=kvm.platform_parts.WAYLAND, sizes=sizes,++ states=[state[0] for state in states], actions=args.actions,++ animations=False, operating_system_effects="mocked", network_effects="mocked")++++ def settle(window):++ for _ in range(5):++ window.layout().activate()++ QCoreApplication.sendPostedEvents(None, QEvent.Type.LayoutRequest)++ app.processEvents()++++ def capture(window, page, size, state, suffix=""):++ settle(window)++ safe_page = "".join(c if c.isalnum() or c in "-_." else "-" for c in page)++ filename = f"{safe_page}-{size[0]}x{size[1]}-{scale}-{state}{suffix}.png"++ path = args.output / filename++ bitmap = window.grab()++ if bitmap.isNull() or not bitmap.save(str(path)):++ raise RuntimeError(f"Could not save offscreen render: {path}")++ flagged = measure(window)++ record = dict(platform=args.platform, page=page, size=list(size), scale=scale, state=state,++ path=str(path), actual_size=[window.width(), window.height()],++ pixels=[bitmap.width(), bitmap.height()], device_pixel_ratio=bitmap.devicePixelRatio(), flags=flagged)++ if args.record_layout and page == "connection":++ record["layout_snapshot"] = layout_snapshot(window.stack.currentWidget(), window)++ records.append(record)++ return path++++ for state, count, phone, long, connected in states:++ entries = fixtures(count, phone, long)++ settings = app_config.migrate(None, machine_id=protocol.id_text(bytes([200])*16))++ settings.update(peers=entries, zones=[], appearance="light" if state.endswith("light") else "dark", hide_addresses=False,++ trigger_key="f13", trigger_style="double_tap", ignored_inputs=["key:135", "button:middle"])++ app_config.write_settings(settings_path, settings)++ if state.endswith("all-ways") or state.endswith("shared-edge"):++ for i, entry in enumerate(entries):++ side = ("right", "left", "top", "bottom", "right")[i]++ if state.endswith("shared-edge") and i == 1:++ side = "right"++ methods = ["part", "corner"] if i < 3 else ["part"]++ app_config.set_ways(settings_path, entry["id"], side=side, methods=methods,++ parts=[("start", "middle", "end")[i%3]],++ corner=("top_right", "top_left", "bottom_left")[i%3])++ app_config.load_config(settings_path, unpaired_ok=True)++ window = kvm.WindowsApplication(settings_path)++ window.refresh_timer.stop()++ window.full_screen_timer.stop()++ window.update_checker.check_now = lambda: effects_log.append(["update-check"])++ window.update_checker.stop = lambda: None++ window.hooks.start = lambda *_: None++ window.hooks.stop = lambda *_: None++ window.sender.start = lambda *_: None++ window.sender.stop = lambda *_: None++ window.sender.refresh = lambda *_: None++ window.sender.links.up = lambda *_: connected++ window.sender.links.status = lambda *_: ""++ window.sender.links.kind = lambda *_: "connected" if connected else "unreachable"++ window.sender.go = lambda peer: effects_log.append(["go", protocol.id_text(peer)]) or True++ window.sender.send_to = lambda *_: True++ window.server.send_to = lambda *_: True++ window.server.peers_changed = lambda *_: None++ window._send_to = lambda *_: True++ window._status = ServerState.CONNECTED if connected else (ServerState.WAITING if entries else ServerState.ERROR)++ window._status_detail = ("Connected to " + entries[0]["name"]) if connected else "Waiting for localhost-live.example.lan"++ window._on_status(window._status, window._status_detail)++ window._host = "localhost-live.example.lan"++ window.host_readout.setText(window._host)++ firewall_status = kvm.firewall_win.FirewallStatus(24820, True, False, ("Private",), ("Private",), True, (), False)++ window._on_firewall(firewall_status)++ if state == "five-shared-edge":++ window._choose_machine(entries[1]["id"])++ window._refresh_window()++ window.show()++ for size in sizes:++ window.resize(*size)++ settle(window)++ for page in kvm.pages_win.KEYS:++ window._select_page(page)++ settle(window)++ scroll = window.stack.currentWidget()++ scroll.verticalScrollBar().setValue(0)++ capture(window, page, size, state)++ maximum = scroll.verticalScrollBar().maximum()++ step = max(1, scroll.viewport().height() - 40)++ for y in range(step, maximum + step, step):++ scroll.verticalScrollBar().setValue(min(y, maximum))++ capture(window, page, size, state, f"-scroll{min(y, maximum)}")++ scroll.verticalScrollBar().setValue(0)++ window._select_page("overview")++ for row in window.machines.rows.values():++ row.directions.setChecked(True)++ row._ask(True)++ capture(window, "remove-confirmation", size, state)++ for row in window.machines.rows.values():++ row._ask(False)++ capture(window, "directions", size, state)++ window._pairing_open = True++ window.sheet.setVisible(True)++ window.machines.set_pairing_open(True)++ window.pairing.discovered = [dict(name=e["name"], address=e.get("host") or "192.0.2.99", platform=e["platform"],++ pairing=kvm.pairing.PAIRING_V3, pair_id="fixture") for e in entries]++ window._refresh_pairing()++ sheet_size = QSize(max(100, window.sheet.width()), max(100, window.sheet.sizeHint().height()))++ window.sheet.resize(sheet_size)++ for mode in ("discovery", "code", "error", "working", "expired", "success"):++ if mode == "code":++ window._show_code()++ elif mode == "error":++ window.sheet.say_pair("The code did not match on localhost-live.example.lan. Show a fresh code there and try again.", "note-fault")++ elif mode == "working":++ window.sheet.busy(True)++ elif mode == "expired":++ window.sheet.busy(False)++ window._cancel_code()++ window.sheet.say_host("That code expired. Show a new code and enter it on the other machine.", "note-amber")++ elif mode == "success":++ paired_name = entries[0]["name"] if entries else "Studio Mac"++ window.sheet.say_pair(f"Paired with {paired_name}.", "note-live")++ settle(window)++ capture(window, f"pairing-{mode}", size, state)++ sheet_path = args.output / f"pairing-{mode}-panel-{size[0]}x{size[1]}-{scale}-{state}.png"++ window.sheet.grab().save(str(sheet_path))++ records.append(dict(platform=args.platform, page=f"pairing-{mode}-panel", size=list(size), scale=scale,++ state=state, path=str(sheet_path), flags=measure(window.sheet)))++ window._pairing_open = False++ window.sheet.setVisible(False)++ window.machines.set_pairing_open(False)++ window.tray_menu.ensurePolished()++ window.tray_menu.adjustSize()++ menu_path = args.output / f"tray-{size[0]}x{size[1]}-{scale}-{state}.png"++ window.tray_menu.grab().save(str(menu_path))++ menu_items = []++ menu_flags = []++ for action in window.tray_menu.actions():++ rect = window.tray_menu.actionGeometry(action)++ option = QStyleOptionMenuItem()++ window.tray_menu.initStyleOption(option, action)++ metrics = option.fontMetrics++ title = action.text().replace("&&", "\0").replace("&", "").replace("\0", "&")++ text_width = metrics.horizontalAdvance(title)++ required = window.tray_menu.style().sizeFromContents(QStyle.ContentsType.CT_MenuItem, option,++ QSize(text_width, metrics.height()), window.tray_menu)++ option.text = ""++ decoration = window.tray_menu.style().sizeFromContents(QStyle.ContentsType.CT_MenuItem, option,++ QSize(0, metrics.height()), window.tray_menu)++ available = max(0, rect.width() - decoration.width())++ item = dict(title=action.text(), rect=[rect.x(), rect.y(), rect.width(), rect.height()],++ text_width=text_width, available_text_width=available, required_width=required.width(),++ decoration_width=decoration.width(), checkable=action.isCheckable(), submenu=action.menu() is not None,++ visible=action.isVisible())++ menu_items.append(item)++ if action.isVisible() and not rect.isEmpty() and not action.isSeparator() and text_width > available + 2:++ menu_flags.append(dict(kind="menu-title-ink", text=action.text(), needed=text_width,++ available=available, rect=item["rect"]))++ screen = app.primaryScreen().availableGeometry()++ if window.tray_menu.width() > screen.width() or window.tray_menu.height() > screen.height():++ menu_flags.append(dict(kind="menu-exceeds-offscreen-screen", menu_size=[window.tray_menu.width(), window.tray_menu.height()],++ screen=[screen.width(), screen.height()]))++ records.append(dict(platform=args.platform, page="tray", size=list(size), scale=scale, state=state,++ path=str(menu_path), menu_size=[window.tray_menu.width(), window.tray_menu.height()],++ screen=[app.primaryScreen().geometry().width(), app.primaryScreen().geometry().height()],++ screen_is_offscreen=True, menu_items=menu_items, flags=menu_flags))++ if state == "five-shared-edge":++ window._select_page("crossing")++ for part, button in window.share_tiles.items():++ if window.share_module.isVisibleTo(window):++ button.click()++ capture(window, f"share-{part}", size, state)++ if window.share_module.isVisibleTo(window) and window.share_button.isEnabled():++ window.share_button.click()++ capture(window, "share-apply", size, state)++ if state == "none":++ window._select_page("connection")++ original_save = kvm.app_config.write_settings++ original_critical = QMessageBox.critical++ dialogs = []++ def critical(parent, title, message):++ dialog = QMessageBox(QMessageBox.Icon.Critical, title, message, QMessageBox.StandardButton.Ok, parent)++ dialog.setWindowModality(Qt.WindowModality.NonModal)++ dialog.show()++ settle(window)++ path = args.output / f"save-failed-{size[0]}x{size[1]}-{scale}-{state}.png"++ dialog.grab().save(str(path))++ records.append(dict(platform=args.platform,page="save-failed",size=list(size),scale=scale,state=state,++ path=str(path),flags=measure(dialog)))++ dialogs.append(dialog)++ return QMessageBox.StandardButton.Ok++ def failed_write(*_args, **_kw):++ raise OSError("Audit fixture: this settings folder is read-only. No settings were changed.")++ QMessageBox.critical = critical++ kvm.app_config.write_settings = failed_write++ try:++ window.save_button.click()++ finally:++ kvm.app_config.write_settings = original_save++ QMessageBox.critical = original_critical++ for dialog in dialogs:++ dialog.close()++ if args.actions and state == "three-long":++ sys.path.insert(0, str(Path(__file__).parent))++ from qt_actions import exercise++ def action_snapshot(name):++ window.resize(*sizes[0])++ settle(window)++ capture(window, name, sizes[0], "action")++ for dialog in app.topLevelWidgets():++ if dialog is not window and isinstance(dialog, QMessageBox):++ dialog_path = args.output / f"dialog-{name}-{scale}.png"++ dialog.grab().save(str(dialog_path))++ records.append(dict(platform=args.platform,page=f"dialog-{name}",size=[dialog.width(),dialog.height()],++ scale=scale,state="action",path=str(dialog_path),flags=measure(dialog)))++ actions = exercise(window, app, snapshot=action_snapshot)++ (args.output / f"actions-{scale}.json").write_text(json.dumps(actions, indent=2), encoding="utf-8")++ window._closing = True++ window.tray.hide()++ window.hide()++ window.deleteLater()++ app.processEvents()++ (args.output / f"measurements-{scale}.json").write_text(json.dumps(records, indent=2), encoding="utf-8")++ (args.output / f"effects-{scale}.json").write_text(json.dumps(effects_log, indent=2), encoding="utf-8")++ (args.output / f"metadata-{scale}.json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")++ print(json.dumps(dict(platform=args.platform, scale=scale, renders=len(records),++ flagged=sum(bool(r["flags"]) for r in records), flags=sum(len(r["flags"]) for r in records))))++ temporary.cleanup()++++++if __name__ == "__main__":++ main()diff --cc scripts/ui_audit/review_sheets.pyindex 0000000,0000000..0ee6221new file mode 100644--- /dev/null+++ b/scripts/ui_audit/review_sheets.py@@@ -1,0 -1,0 +1,186 @@@++"""Build numbered, readable review sheets from every flagged offscreen render.++++Qt measurements use logical coordinates; bitmap crops are normalised to 1x.++Each source remains separately catalogued, including repeated states/scales.++"""++from __future__ import annotations++++import argparse++import json++from pathlib import Path++import re++++from PIL import Image, ImageDraw, ImageFont++++++def font(size):++ for path in ("/System/Library/Fonts/Helvetica.ttc", "C:/Windows/Fonts/arial.ttf",++ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"):++ try:++ return ImageFont.truetype(path, size)++ except OSError:++ pass++ return ImageFont.load_default()++++++def source_path(record, root):++ raw = str(record.get("path") or record.get("render") or "")++ candidate = Path(raw)++ if candidate.is_file():++ return candidate++ basename = re.split(r"[/\\]+", raw)[-1]++ platform = record.get("platform", "")++ for candidate in (root / platform / basename, root / basename):++ if candidate.is_file():++ return candidate++ matches = list(root.rglob(basename))++ return matches[0] if len(matches) == 1 else None++++++def boxes(record, image):++ logical = record.get("size") or record.get("window_size") or list(image.size)++ pixel_size = record.get("pixels") or list(image.size)++ ratio = float(pixel_size[0]) / logical[0] if logical[0] else 1.0++ # Panel/menu images often record their containing window size rather than their++ # own logical size. Their known scale is a safer conversion for those surfaces.++ if "panel" in str(record.get("page", "")) or record.get("page") in ("tray", "dialog"):++ ratio = float(record.get("scale", 1.0))++ width, height = image.width / ratio, image.height / ratio++ seen = set()++ found = []++ omitted = []++ for flag in record.get("flags", []):++ rect = flag.get("rect") or flag.get("bounds") or flag.get("frame")++ if not rect or len(rect) != 4:++ rect = [0, 0, width, min(height, 400)]++ x, y, w, h = (float(value) for value in rect)++ if "frame" in flag and not record.get("is_flipped", True):++ y = height - y - h++ if x + w <= 0 or y + h <= 0 or x >= width or y >= height:++ omitted.append({"reason": "Flagged widget is outside this scrolled bitmap; review its other scroll captures.",++ "flag": flag})++ continue++ if flag.get("kind") == "outside-parent" and flag.get("name") == "page_column":++ parent_size = flag.get("parent_size", [])++ if len(parent_size) == 2 and w <= parent_size[0] + 1 and x <= 190 and h > parent_size[1]:++ omitted.append({"reason": "A vertically scrolled page column is intentionally taller than its scroll document.",++ "flag": flag})++ continue++ left, top = max(0, x - 18), max(0, y - 25)++ right, bottom = min(width, x + w + 18), min(height, y + h + 25)++ if right - left <= 620:++ left = max(left, right - 580)++ # Split large regions rather than shrink the text below its actual 1x size.++ for tile_y in range(int(top), max(int(top) + 1, int(bottom)), 260):++ for tile_x in range(int(left), max(int(left) + 1, int(right)), 560):++ bound = (tile_x, tile_y, min(tile_x + 580, int(right)), min(tile_y + 280, int(bottom)))++ if bound in seen or bound[2] <= bound[0] or bound[3] <= bound[1]:++ continue++ seen.add(bound)++ found.append((bound, flag))++ # Overlapping controls/labels on one row need one contextual crop, while the++ # original flags remain intact in the catalogue.++ merged = []++ for bound, flag in found:++ for index, (held, held_flag) in enumerate(merged):++ union = (min(bound[0], held[0]), min(bound[1], held[1]),++ max(bound[2], held[2]), max(bound[3], held[3]))++ overlap = min(bound[2], held[2]) > max(bound[0], held[0]) and min(bound[3], held[3]) > max(bound[1], held[1])++ if overlap and union[2] - union[0] <= 590 and union[3] - union[1] <= 280:++ merged[index] = (union, held_flag)++ break++ else:++ merged.append((bound, flag))++ return ratio, merged, omitted++++++def build(inputs, root, output, platform=None):++ records = []++ for path in inputs:++ content = json.loads(path.read_text(encoding="utf-8"))++ if isinstance(content, dict):++ content = content.get("renders", content.get("records", []))++ for record in content:++ record_platform = record.get("platform") or path.parent.name++ if record.get("flags") and (platform is None or record_platform == platform):++ record = dict(record, platform=record_platform)++ records.append((path, record))++ output.mkdir(parents=True, exist_ok=True)++ catalogue = []++ missing = []++ sheets = []++ page = Image.new("RGB", (1200, 1800), "#ececec")++ draw = ImageDraw.Draw(page)++ title_font = font(12)++ y_positions = [12, 12]++ crops_on_page = 0++ sheet_number = 1++++ def flush():++ nonlocal page, draw, y_positions, crops_on_page, sheet_number++ if not crops_on_page:++ return++ name = f"sheet-{sheet_number:04d}.png"++ page.save(output / name)++ sheets.append({"path": str(output / name), "crops": crops_on_page})++ sheet_number += 1++ page = Image.new("RGB", (1200, 1800), "#ececec")++ draw = ImageDraw.Draw(page)++ y_positions = [12, 12]++ crops_on_page = 0++++ for number, (measurement, record) in enumerate(records, 1):++ path = source_path(record, root)++ if path is None:++ missing.append({"number": number, "path": record.get("path"), "measurement": str(measurement)})++ continue++ with Image.open(path) as source:++ ratio, regions, omitted = boxes(record, source)++ entry = {"number": number, "path": str(path), "measurement": str(measurement),++ "platform": record.get("platform"), "page": record.get("page"),++ "state": record.get("state"), "size": record.get("size"),++ "scale": record.get("scale"), "flags": record.get("flags"),++ "omitted": omitted, "crops": []}++ for region_number, (bounds, flag) in enumerate(regions, 1):++ pixel_box = tuple(round(v * ratio) for v in bounds)++ crop = source.crop(pixel_box).convert("RGB")++ crop = crop.resize((bounds[2] - bounds[0], bounds[3] - bounds[1]), Image.Resampling.LANCZOS)++ column = min(range(2), key=lambda i: y_positions[i])++ need = crop.height + 55++ if y_positions[column] + need > 1790 or crops_on_page >= 20:++ flush()++ column = 0++ x, y = 10 + 600 * column, y_positions[column]++ label = f"{number}.{region_number} {record.get('page')} {record.get('size')} {record.get('scale')} {record.get('state')}"++ draw.text((x, y), label[:90], fill="#111111", font=title_font)++ draw.text((x, y + 15), path.name[:90], fill="#333333", font=title_font)++ draw.text((x, y + 30), str(flag.get("kind", "flag")), fill="#a02020", font=title_font)++ page.paste(crop, (x, y + 48))++ draw.rectangle((x, y + 48, x + crop.width, y + 48 + crop.height), outline="#888888")++ entry["crops"].append({"id": f"{number}.{region_number}", "sheet": f"sheet-{sheet_number:04d}.png",++ "bounds_logical": list(bounds), "kind": flag.get("kind")})++ y_positions[column] += need++ crops_on_page += 1++ catalogue.append(entry)++ flush()++ report = {"flagged_renders": len(records), "catalogued_renders": len(catalogue), "missing": missing,++ "sheets": sheets, "renders": catalogue}++ (output / "catalogue.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")++ print(json.dumps({"flagged_renders": len(records), "catalogued_renders": len(catalogue),++ "missing": len(missing), "sheets": len(sheets),++ "crops": sum(s["crops"] for s in sheets)}))++ return report++++++def main():++ parser = argparse.ArgumentParser()++ parser.add_argument("measurements", nargs="+", type=Path)++ parser.add_argument("--renders", type=Path, required=True)++ parser.add_argument("--output", type=Path, required=True)++ parser.add_argument("--platform")++ args = parser.parse_args()++ build(args.measurements, args.renders, args.output, args.platform)++++++if __name__ == "__main__":++ main()diff --cc scripts/ui_audit/run_qt_matrix.pyindex 0000000,0000000..389802cnew file mode 100644--- /dev/null+++ b/scripts/ui_audit/run_qt_matrix.py@@@ -1,0 -1,0 +1,47 @@@++"""Run isolated offscreen processes; scaling must be fixed before QApplication exists."""++import argparse++import json++import os++from pathlib import Path++import subprocess++import sys++++++def main():++ parser = argparse.ArgumentParser()++ parser.add_argument("--output", type=Path, required=True)++ parser.add_argument("--platforms", required=True, help="windows,linux-x11,linux-wayland on the rig; Linux modes on Linux")++ parser.add_argument("--scales", default="1.0,1.25,1.5,2.0")++ parser.add_argument("--actions", action="store_true")++ parser.add_argument("--states")++ parser.add_argument("--sizes")++ args = parser.parse_args()++ args.output.mkdir(parents=True, exist_ok=True)++ results = []++ for platform in args.platforms.split(","):++ for scale in args.scales.split(","):++ environment = dict(os.environ, QT_QPA_PLATFORM="offscreen", QT_SCALE_FACTOR=scale)++ if platform.startswith("linux-"):++ environment["XDG_SESSION_TYPE"] = platform.removeprefix("linux-")++ command = [sys.executable, str(Path(__file__).with_name("qt_audit.py")),++ "--platform", platform, "--output", str(args.output / platform)]++ if args.actions:++ command.append("--actions")++ for name in ("states", "sizes"):++ value = getattr(args, name)++ if value:++ command.extend(["--"+name, value])++ log = args.output / f"{platform}-{scale}.log"++ with log.open("w", encoding="utf-8") as stream:++ run = subprocess.run(command, env=environment, stdout=stream, stderr=subprocess.STDOUT)++ row = dict(platform=platform, scale=scale, exit_code=run.returncode, log=str(log))++ results.append(row)++ print(json.dumps(row), flush=True)++ if run.returncode:++ raise SystemExit(run.returncode)++ manifest = "matrix-" + "-".join(args.platforms.split(",")) + ".json"++ (args.output / manifest).write_text(json.dumps(results, indent=2), encoding="utf-8")++++++if __name__ == "__main__":++ main()diff --cc tokens.pyindex e10a308,dbb5b81..a1ecd5b--- a/tokens.py+++ b/tokens.py@@@ -96,6 -96,6 +96,7 @@@ PALETTES ="ocean": ("#288cff", "#6446ff", "#1eb9aa", "#3c6eff"),"sunset": ("#ff7828", "#ff3264", "#ffb43c", "#f03278"),"mono": ("#ebebeb", "#969696", "#ebebeb"),++ "aurora": ("#53dc91", "#9572eb", "#43c5b4"),}# Letter spacing as a fraction of the font size, for the uppercase tracked labels.@@@ -115,8 -115,6 +116,18 @@@ RADIUS =MODULE_PADDING = (14.0, 16.0)RACK_GAP = 1.0MIN_WINDOW = {"mac": (640, 540), "windows": (640, 600)}+READING_WIDTH = 560.0+PAGE_CONTENT_WIDTH = 960.0++# The page column is this share of the free width (window minus sidebar), clamped between the++# minimum and the maximum, centred, and never wider than the free width itself.++PAGE_CONTENT_MIN = 960.0++PAGE_CONTENT_MAX = 1600.0++PAGE_CONTENT_SHARE = 0.75++SIDE_BY_SIDE_GAP = 24.0++CROSSING_ARRANGEMENT_MIN_WIDTH = 254.0++CROSSING_WAYS_MIN_WIDTH = 354.0++DESIGN_TILE_SETS_MIN_WIDTH = 258.0++DESIGN_STYLE_CONTROLS_MIN_WIDTH = 240.0# Mass-spring parameters (mass 1) for everything that moves. The notch island integrates two of# these, width and depth; a trackpad tick adds `tick_velocity` points per second to the width.diff --cc tools/beam_live_offscreen.pyindex 0000000,0000000..7573141new file mode 100644--- /dev/null+++ b/tools/beam_live_offscreen.py@@@ -1,0 -1,0 +1,235 @@@++"""Measure live Beam layers without creating an NSWindow or reading app settings."""++++import argparse++import json++import logging++import math++import sys++from pathlib import Path++from types import SimpleNamespace++from unittest import mock++++ROOT = Path(__file__).resolve().parents[1]++sys.path[:0] = [str(ROOT), str(ROOT / "mac_app")]++++import AppKit++import Quartz++++import crossing++import desktop_mac++import kvm_bridge_app++import effects_overlay++from core import effects++++++class OffscreenPanel:++ """Only an NSView and its live layer tree; ordering a window is an error."""++++ @classmethod++ def alloc(cls):++ return cls()++++ def initWithContentRect_styleMask_backing_defer_(self, rect, *_args):++ self.rect = rect++ return self++++ def setContentView_(self, view):++ self.view = view++++ def contentView(self):++ return self.view++++ def setFrame_display_(self, rect, _display):++ self.rect = rect++ self.view.setFrame_(AppKit.NSMakeRect(0, 0, rect.size.width, rect.size.height))++ self.view.layer().setFrame_(self.view.bounds())++++ def frame(self):++ return self.rect++++ def orderFrontRegardless(self):++ raise AssertionError("offscreen probe must never show a window")++++ def __getattr__(self, name):++ if name.startswith("set"):++ return lambda *_args: None++ raise AttributeError(name)++++++def live_glow(edge, size, *, pressure=1.0, corner=None, third=False, style="beam"):++ width, height = 1728.0, 1117.0++ controller = SimpleNamespace(++ cfg=SimpleNamespace(crossing=dict(crossing.DEFAULT_CROSSING, glow_style=style,++ glow_colour="signal", effect_size=size)),++ crossing_pressure_now=lambda: pressure,++ _current_desktop_bounds=lambda: (0.0, 0.0, width, height),++ )++ glow = kvm_bridge_app.EdgeGlow(controller, logging.getLogger("beam-offscreen"))++ glow.timer = mock.Mock()++ glow.dark_appearance = lambda: False++ glow.mac_edge = edge++ if corner is not None:++ glow.region = (width - 8 if "right" in corner else 0,++ height - 8 if "bottom" in corner else 0, 8, 8)++ elif edge in ("left", "right"):++ glow.region = (width - 1 if edge == "right" else 0, height / 3 if third else 0,++ 1, height / 3 if third else height)++ else:++ glow.region = (width / 3 if third else 0, height - 1 if edge == "bottom" else 0,++ width / 3 if third else width, 1)++ with mock.patch.object(AppKit, "NSPanel", OffscreenPanel):++ glow._ensure_panel()++ # _draw still performs all frame, palette, mask and opacity updates, but cannot order a panel.++ glow.visible = True++ glow.centre = 0.5++ with mock.patch.object(desktop_mac, "monitors", return_value=[]), \++ mock.patch.object(kvm_bridge_app, "menu_bar_height", return_value=0), \++ mock.patch.object(kvm_bridge_app.time, "monotonic", return_value=100.0):++ glow._draw()++ if glow.disabled:++ raise AssertionError("live layer drawing disabled the effect")++ return glow++++++def render(layer, scale, space=None):++ bounds = layer.bounds()++ width, height = math.ceil(bounds.size.width * scale), math.ceil(bounds.size.height * scale)++ data = bytearray(width * height * 4)++ space = space or AppKit.NSScreen.screens()[0].colorSpace().CGColorSpace()++ ctx = Quartz.CGBitmapContextCreate(data, width, height, 8, width * 4, space,++ Quartz.kCGImageAlphaPremultipliedLast | Quartz.kCGBitmapByteOrder32Big)++ # Align the layer's top to the first memory row; fractional panel depths otherwise leave++ # a partially covered extra row at the top of the enclosing integer-pixel bitmap.++ Quartz.CGContextTranslateCTM(ctx, 0, height - bounds.size.height * scale)++ Quartz.CGContextScaleCTM(ctx, scale, scale)++ layer.renderInContext_(ctx)++ return width, height, bytes(data)++++++def layer_profile(layer, edge, scale, space=None):++ width, height, rgba = render(layer, scale, space)++ if edge in ("left", "right"):++ values = [rgba[((height // 2) * width + x) * 4 + 3]++ for x in range(math.floor(layer.bounds().size.width * scale))]++ else:++ values = [rgba[(y * width + width // 2) * 4 + 3]++ for y in range(math.floor(layer.bounds().size.height * scale))]++ # CGBitmapContext's memory rows run from the top, although CALayer coordinates run up.++ if edge in ("right", "bottom"):++ values.reverse()++ return values++++++def profile(glow, edge, scale, space=None):++ return layer_profile(glow.panel.contentView().layer(), edge, scale, space)++++++def canvas_parity(profiles):++ """The actual EffectsCanvas.drawRect/_paint, cropped as _show crops a per-display panel.++++ Beam normally bypasses this canvas. Replaying the recorded preview here tests whether++ the live NSView context, output colour space or panel clipping would damage its alpha.++ """++ times = dict(zip(("push10", "push45", "push85", "threshold", "give", "arrival", "settle"),++ (.92, 1.35, 1.78, 2.18, 2.27, 2.44, 2.7)))++ results = []++ for source in profiles:++ scale = len(source["x"][:-1]) / 40++ for size, _label in effects.SIZES:++ scene = effects.preview_scene(effects.preview_effect("beam"), times[source["stage"]],++ "edge", kvm_bridge_app.notch_beam.palette_values("signal"),++ dark=source["mode"] == "dark", effect_size=size)++ pens = scene["pens"]++ for pen in pens:++ pen.clip = (0, 0, 800, 450)++ boxes = [effects_overlay.padded(pen, 2) for pen in pens]++ left = math.floor(min(b[0] for b in boxes))++ top = math.floor(min(b[1] for b in boxes))++ right = math.ceil(max(b[2] for b in boxes))++ bottom = math.ceil(max(b[3] for b in boxes))++ view = effects_overlay.EffectsCanvas.alloc().initWithFrame_(++ AppKit.NSMakeRect(0, 0, right - left, bottom - top))++ view.painter = lambda ctx, _w, _h: effects_overlay.EffectsOverlay._paint(ctx, pens, (left, top))++ width, height = round((right - left) * scale), round((bottom - top) * scale)++ measured = []++ for space in (Quartz.CGColorSpaceCreateWithName(Quartz.kCGColorSpaceSRGB),++ AppKit.NSScreen.screens()[0].colorSpace().CGColorSpace()):++ data = bytearray(width * height * 4)++ ctx = Quartz.CGBitmapContextCreate(data, width, height, 8, width * 4, space,++ Quartz.kCGImageAlphaPremultipliedLast++ | Quartz.kCGBitmapByteOrder32Big)++ Quartz.CGContextTranslateCTM(ctx, 0, height)++ Quartz.CGContextScaleCTM(ctx, scale, -scale)++ graphics = AppKit.NSGraphicsContext.graphicsContextWithCGContext_flipped_(ctx, True)++ AppKit.NSGraphicsContext.saveGraphicsState()++ try:++ AppKit.NSGraphicsContext.setCurrentContext_(graphics)++ view.drawRect_(view.bounds())++ finally:++ AppKit.NSGraphicsContext.restoreGraphicsState()++ if view.painter is None:++ raise AssertionError("EffectsCanvas failed to paint offscreen")++ values = []++ for x in source["x"]:++ local = x - round(left * scale)++ values.append(round(sum(data[(y * width + local) * 4 + 3] for y in range(height)) / height, 3)++ if 0 <= local < width else 0.0)++ measured.append(values)++ delta = [abs(a - b) for a, b in zip(measured[0], source["mac"])]++ colour_delta = max(abs(a - b) for a, b in zip(*measured))++ results.append({"size": size, "stage": source["stage"], "mode": source["mode"],++ "scale": scale, "panel_points": [right - left, bottom - top],++ "alpha_profile": measured[0], "screen_colour_space_alpha_max_difference": colour_delta,++ "parity_mac_alpha_max_difference": max(delta),++ "parity_windows_alpha_max_difference": max(abs(a - b) for a, b in++ zip(measured[0], source["windows"]))})++ return results++++++def measure():++ rows = []++ for size, _label in effects.SIZES:++ for edge in ("left", "right", "top", "bottom"):++ for scale in (1, 2):++ glow = live_glow(edge, size)++ values = profile(glow, edge, scale)++ rows.append({"size": size, "edge": edge, "scale": scale,++ "frame": [glow.panel.frame().size.width, glow.panel.frame().size.height],++ "depth_points": effects.edge_depth(1728, 1117, size),++ "alpha_edge_to_interior": values,++ "inner_over_outer": round(values[-1] / max(1, values[0]), 4),++ "at_tenth_half_nine_tenths": [values[int((len(values) - 1) * f)] for f in (.1, .5, .9)]})++ return rows++++++if __name__ == "__main__":++ parser = argparse.ArgumentParser(description=__doc__)++ parser.add_argument("--output", type=Path, required=True)++ parser.add_argument("--parity-profiles", type=Path, nargs="+")++ parser.add_argument("--without-inward-mask", action="store_true",++ help="reproduce the pre-fix live layers by removing only the new inward mask")++ args = parser.parse_args()++ with mock.patch.object(kvm_bridge_app.notch_beam, "mask_edge_falloff",++ (lambda layer, _edge, _beam: layer.setMask_(None))++ if args.without_inward_mask else kvm_bridge_app.notch_beam.mask_edge_falloff):++ rows = measure()++ sample = live_glow("left", "medium")++ view = sample.panel.contentView()++ surface = {"view_opaque": bool(view.isOpaque())}++ for name, layer in (("view", view.layer()), ("fill", sample.fill), ("comet", sample.comet)):++ surface[name] = {"opaque": bool(layer.isOpaque()), "opacity": layer.opacity(),++ "background_colour": str(layer.backgroundColor()),++ "compositing_filter": str(layer.compositingFilter()), "contents_scale": layer.contentsScale()}++ result = {"live_layers": rows, "without_inward_mask": args.without_inward_mask,++ "surface": surface,++ "colour_space": str(AppKit.NSScreen.screens()[0].colorSpace()),++ "format": "RGBA8 premultiplied-last, big-endian; NSView/CALayer renderInContext"}++ if args.parity_profiles:++ profiles = [profile for path in args.parity_profiles for profile in json.loads(path.read_text())]++ if any(not any(row["mac"]) or not any(row["windows"]) for row in profiles):++ raise ValueError("all-zero reference profile: check raw frame geometry before comparing")++ result["canvas_parity"] = canvas_parity(profiles)++ result["preview_parity_profiles"] = profiles++ args.output.write_text(json.dumps(result, indent=2) + "\n")++ print(f"Measured {len(rows)} live layer profiles; inner/outer alpha "++ f"{min(r['inner_over_outer'] for r in rows):.4f}..{max(r['inner_over_outer'] for r in rows):.4f}")diff --cc tools/build_flatpak.shindex 0000000,0000000..a65f10enew file mode 100755--- /dev/null+++ b/tools/build_flatpak.sh@@@ -1,0 -1,0 +1,32 @@@++#!/usr/bin/env bash++set -euo pipefail++root="$(cd "$(dirname "$0")/.." && pwd)"++cd "$root"++for tool in flatpak flatpak-builder; do++ command -v "$tool" >/dev/null || { echo "$tool is required" >&2; exit 2; }++done++arch="${1:-$(flatpak --default-arch)}"++case "$arch" in++ x86_64|aarch64) ;;++ *) echo "Supported architectures: x86_64, aarch64" >&2; exit 2 ;;++esac++if [ "$arch" != "$(flatpak --default-arch)" ]; then++ echo "Run this native build on a $arch machine; this script does not cross-compile." >&2++ exit 2++fi++flatpak --version++flatpak-builder --version++if [ "$(flatpak --version)" = "Flatpak 1.18.2" ]; then++ echo "Flatpak 1.18.2 cannot copy a BaseApp on Fedora's SELinux filesystem (upstream #6818). Use 1.18.3 or later." >&2++ exit 2++fi++version="$(tr -d '\r\n' < VERSION)"++output="$root/dist/flatpak/$arch"++mkdir -p "$output"++flatpak-builder --user --arch="$arch" --install-deps-from=flathub --assumeyes \++ --disable-rofiles-fuse --force-clean --repo="$output/repo" "$output/build" "$root/uk.co.kalkman.beamer.json"++bundle="$output/Beamer-$version-$arch.flatpak"++flatpak build-bundle --arch="$arch" --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo \++ "$output/repo" "$bundle" uk.co.kalkman.beamer master++printf 'Bundle: %s\nBytes: ' "$bundle"++wc -c < "$bundle"diff --cc tools/flatpak-proof/observerindex 0000000,0000000..efb1974new file mode 100755--- /dev/null+++ b/tools/flatpak-proof/observer@@@ -1,0 -1,0 +1,5 @@@++#!/usr/bin/env bash++set -euo pipefail++exec flatpak-spawn --host --directory="$BEAMER_FLATPAK_PROOF_TOOLS" \++ --env="WAYLAND_DISPLAY=$BEAMER_PROOF_WAYLAND_DISPLAY" --env=XDG_SESSION_TYPE=wayland \++ /usr/bin/python3 "$BEAMER_FLATPAK_PROOF_TOOLS/wayland_observer.py" "${@:2}"diff --cc tools/flatpak-proof/pythonindex 0000000,0000000..3184555new file mode 100755--- /dev/null+++ b/tools/flatpak-proof/python@@@ -1,0 -1,0 +1,14 @@@++#!/usr/bin/env bash++set -euo pipefail++# Flatpak renames the socket to wayland-0 inside; external peers need the compositor's host name.++exec flatpak run --command=python3 \++ --talk-name=org.gnome.Mutter.RemoteDesktop --talk-name=org.freedesktop.Flatpak \++ --filesystem="$BEAMER_PROOF_DIR" --filesystem="$BEAMER_FLATPAK_PROOF_TOOLS:ro" \++ --env="BEAMER_PROOF_DIR=$BEAMER_PROOF_DIR" \++ --env="BEAMER_FLATPAK_PROOF_TOOLS=$BEAMER_FLATPAK_PROOF_TOOLS" \++ --env="BEAMER_PROOF_WAYLAND_DISPLAY=$WAYLAND_DISPLAY" \++ --env="WAYLAND_DISPLAY=$WAYLAND_DISPLAY" --env=XDG_SESSION_TYPE=wayland \++ --env="XDG_STATE_HOME=$BEAMER_PROOF_DIR/state" \++ --env="OBSERVER_PYTHON=$BEAMER_FLATPAK_PROOF_TOOLS/flatpak-proof/observer" \++ --env="PATH=$BEAMER_FLATPAK_PROOF_TOOLS/flatpak-proof:/app/bin:/usr/bin" \++ uk.co.kalkman.beamer /app/share/beamer/tools/wayland_proof.py "${@:2}"diff --cc tools/flatpak-proof/wl-copyindex 0000000,0000000..6736b59new file mode 100755--- /dev/null+++ b/tools/flatpak-proof/wl-copy@@@ -1,0 -1,0 +1,4 @@@++#!/usr/bin/env bash++set -euo pipefail++exec flatpak-spawn --host --directory="$BEAMER_FLATPAK_PROOF_TOOLS" \++ --env="WAYLAND_DISPLAY=$BEAMER_PROOF_WAYLAND_DISPLAY" wl-copy "$@"diff --cc tools/flatpak-proof/wl-pasteindex 0000000,0000000..27c6612new file mode 100755--- /dev/null+++ b/tools/flatpak-proof/wl-paste@@@ -1,0 -1,0 +1,4 @@@++#!/usr/bin/env bash++set -euo pipefail++exec flatpak-spawn --host --directory="$BEAMER_FLATPAK_PROOF_TOOLS" \++ --env="WAYLAND_DISPLAY=$BEAMER_PROOF_WAYLAND_DISPLAY" wl-paste "$@"diff --cc tools/flatpak_import_probe.pyindex 0000000,0000000..b1b2337new file mode 100644--- /dev/null+++ b/tools/flatpak_import_probe.py@@@ -1,0 -1,0 +1,31 @@@++"""Import the installed Linux app without creating a window or reading settings."""++import ctypes++import ctypes.util++import importlib++import os++from pathlib import Path++++ROOT = Path("/app/share/beamer")++WINDOWS_ONLY = {++ "autostart_win", "capture_win", "clipboard_win", "desktop_win", "firewall_win",++ "input_injector", "touchpad_injector", "unlock_win",++}++names = ["core"] + sorted(f"core.{p.stem}" for p in (ROOT / "core").glob("*.py") if p.stem != "__init__")++names += sorted(p.stem for p in (ROOT / "win_app").glob("*.py") if p.stem not in WINDOWS_ONLY)++for name in names:++ module = importlib.import_module(name)++ path = Path(module.__file__).resolve()++ if not path.is_relative_to(ROOT):++ raise RuntimeError(f"{name} loaded outside the installed app: {path}")++ print(f"ok {name} {path}", flush=True)++for name in ("ei", "xkbcommon", "xkbcommon-x11", "xcb"):++ path = ctypes.util.find_library(name)++ if not path:++ raise RuntimeError(f"lib{name} is missing")++ ctypes.CDLL(path)++ print(f"ok native {name} {path}", flush=True)++import platform_parts++expected = "x11" if os.environ.get("XDG_SESSION_TYPE") == "x11" else "wayland"++if platform_parts.WAYLAND != (expected == "wayland"):++ raise RuntimeError(f"Wrong platform back ends for {expected}")++print(f"passed: {len(names)} installed modules, 4 native libraries, {expected} back ends", flush=True)diff --cc tools/flatpak_wayland_proof.shindex 0000000,0000000..8c5189fnew file mode 100755--- /dev/null+++ b/tools/flatpak_wayland_proof.sh@@@ -1,0 -1,0 +1,7 @@@++#!/usr/bin/env bash++# Only the test harness can reach Mutter and launch the host's GTK observer. The app's manifest++# keeps both names filtered. Beamer's back ends and Python dependencies run from the installed app.++set -euo pipefail++here="$(cd "$(dirname "$0")" && pwd)"++export BEAMER_FLATPAK_PROOF_TOOLS="$here"++PYTHON="$here/flatpak-proof/python" bash "$here/wayland_proof.sh"diff --cc tools/import_probe.pyindex 0000000,0000000..0666b5fnew file mode 100644--- /dev/null+++ b/tools/import_probe.py@@@ -1,0 -1,0 +1,91 @@@++"""Imports every module of a built Beamer inside the build itself, and fails on the first that will++not load: each module of the app's own folder and of core/, by name, from the bundle and never++from this source tree.++++ python3 tools/import_probe.py mac mac_app/dist/Beamer.app [--arch x86_64]++ python tools/import_probe.py win win_app/dist/Beamer.exe++++The Mac bundle carries its own python, which runs this file again inside the bundle (`--arch`++runs it under Rosetta). The Windows build is one windowed exe with no interpreter to lend, so it++runs its own `--import-probe` switch (kvm_bridge_win.py), which writes each outcome to a file.++Neither starts the app, opens a window or touches its config.++"""++++import argparse++import importlib++import os++import subprocess++import sys++import tempfile++from pathlib import Path++++REPO = Path(__file__).resolve().parent.parent++# The entry scripts run as __main__ in a build and are not importable by name there.++APPS = {++ "mac": ("mac_app", {"kvm_bridge_app", "setup"}, ["theme", "tokens"]),++ "win": ("win_app", {"kvm_bridge_win"}, []),++}++++++def module_names(platform: str) -> list:++ folder, entry, extra = APPS[platform]++ own = sorted(path.stem for path in (REPO / folder).glob("*.py") if path.stem not in entry)++ core = sorted(f"core.{path.stem}" for path in (REPO / "core").glob("*.py") if path.stem != "__init__")++ return ["core"] + core + own + extra++++++def inside(bundle: str, names: list) -> int:++ """Run by the bundle's own python: nothing may come from outside the bundle."""++ root = os.path.realpath(bundle)++ for name in names:++ try:++ module = importlib.import_module(name)++ except BaseException as exc:++ print(f"FAIL {name}: {type(exc).__name__}: {exc}", flush=True)++ raise++ where = getattr(module, "__file__", None)++ if where and not os.path.realpath(where).startswith(root):++ print(f"FAIL {name} came from {where}, outside the bundle", flush=True)++ return 1++ print(f"ok {name}", flush=True)++ return 0++++++def probe_mac(app: Path, names: list, arch: str) -> int:++ python = app / "Contents" / "MacOS" / "python"++ command = ([f"/usr/bin/arch", f"-{arch}"] if arch else []) + [str(python), str(Path(__file__).resolve()), "--inside", str(app), *names]++ environment = {"HOME": os.environ["HOME"], "PATH": "/usr/bin:/bin", "PYTHONHOME": str(app / "Contents" / "Resources")}++ with tempfile.TemporaryDirectory() as cwd:++ return subprocess.run(command, env=environment, cwd=cwd).returncode++++++def probe_win(exe: Path, names: list) -> int:++ with tempfile.TemporaryDirectory() as cwd:++ out = Path(cwd) / "probe.txt"++ code = subprocess.run([str(exe), "--import-probe", str(out), *names], cwd=cwd).returncode++ result = out.read_text(encoding="utf-8") if out.exists() else "FAIL the exe wrote no result\n"++ print(result, end="")++ loaded = [line.split(" ", 2) for line in result.splitlines() if line.startswith("ok ")]++ outside = [name for _, name, where in loaded if where.startswith(str(REPO))]++ if outside:++ print(f"FAIL loaded from the source tree, not the exe: {', '.join(outside)}")++ return 1 if code or outside or len(loaded) != len(names) else 0++++++def main() -> int:++ if sys.argv[1:2] == ["--inside"]:++ return inside(sys.argv[2], sys.argv[3:])++ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])++ parser.add_argument("platform", choices=sorted(APPS))++ parser.add_argument("build", type=Path, help="Beamer.app on the Mac, Beamer.exe on Windows")++ parser.add_argument("--arch", default="", help="Mac only: run the bundle's python as this architecture")++ arguments = parser.parse_args()++ names = module_names(arguments.platform)++ build = arguments.build.resolve()++ code = probe_mac(build, names, arguments.arch) if arguments.platform == "mac" else probe_win(build, names)++ print(f"{'passed' if code == 0 else 'FAILED'}: {len(names)} modules probed in {build}")++ return code++++++if __name__ == "__main__":++ sys.exit(main())diff --cc tools/measure_colour_packs.pyindex 0000000,0000000..a0c6a92new file mode 100644--- /dev/null+++ b/tools/measure_colour_packs.py@@@ -1,0 -1,0 +1,117 @@@++"""Write the palette proposal from measured sRGB stops and the pinned baseline."""++import colorsys++import json++import math++from pathlib import Path++import subprocess++import sys++++ROOT = Path(__file__).resolve().parents[1]++sys.path.insert(0, str(ROOT))++from core import effects++import tokens++++++def rgb(value):++ return tuple(int(value[i:i + 2], 16) / 255 for i in (1, 3, 5))++++++def linear(value):++ return tuple(c / 12.92 if c <= .04045 else ((c + .055) / 1.055) ** 2.4 for c in rgb(value))++++++def luminance(value):++ return sum(c * w for c, w in zip(linear(value), (.2126, .7152, .0722)))++++++def contrast(a, b):++ lo, hi = sorted((luminance(a), luminance(b)))++ return (hi + .05) / (lo + .05)++++++def lab(value):++ r, g, b = linear(value)++ xyz = ((r * .4124564 + g * .3575761 + b * .1804375) / .95047,++ r * .2126729 + g * .7151522 + b * .0721750,++ (r * .0193339 + g * .1191920 + b * .9503041) / 1.08883)++ x, y, z = (v ** (1 / 3) if v > .008856 else 7.787 * v + 16 / 116 for v in xyz)++ return 116 * y - 16, 500 * (x - y), 200 * (y - z)++++++def distance(a, b):++ return math.dist(lab(a), lab(b))++++++def baseline():++ def source(path):++ return subprocess.check_output(['git', 'show', f'4370f9b:{path}'], cwd=ROOT, text=True)++ namespace = {}++ exec(source('tokens.py'), namespace)++ old = {'Light': {key: (key.capitalize(), list(stops)) for key, stops in namespace['PALETTES'].items()}}++ for module, title, _styles, _ids in effects.DIRECTIONS:++ namespace = {'__name__': f'core.{module}', '__package__': 'core'}++ exec(source(f'core/{module}.py'), namespace)++ old[title] = namespace['PACKS']++ return old++++++def main():++ old = baseline()++ groups = effects.colour_groups([(key, key.capitalize()) for key in tokens.PALETTES])++ old_ids = {value for choices in old.values() for value in choices}++ old_stops = [stop for choices in old.values() for _name, stops in choices.values() for stop in stops]++ lines = ['# Beamer colour proposal', '', '05-10-2026 · colours · baseline 4370f9b', '',++ 'Keep every existing id and stop. Offer five chromatic choices in Light, Membrane, Sparks, Instrument, Folio and Selvedge. Add Bright with five vivid packs. Put the unchanged Mono choice in a separate Neutral row immediately after Light, available with every style. A single neutral row avoids duplicating the same selected id across seven groups and stops implying Mono belongs only to Light.', '',++ '## Current sets', '', '| Group | Count | Choices |', '| --- | ---: | --- |']++ for title, choices in old.items():++ lines.append(f'| {title} | {len(choices)} | ' + '; '.join(f'{name} (`{value}`): ' + ', '.join(stops) for value, (name, stops) in choices.items()) + ' |')++ lines += ['', 'Ink and Warp are deliberately hidden; their legacy mappings remain unchanged. Colour packs are independent of styles: each colour works with every style.', '',++ '## Proposed sets', '', '| Group | Five choices (or one neutral) |', '| --- | --- |']++ for title, choices in groups:++ lines.append(f'| {title} | ' + ', '.join(name + (' **new**' if value not in old_ids else '') for value, name in choices) + ' |')++ lines += ['', '## New stops and measurements', '',++ 'Ratios below use opaque sRGB stops. Raw references are #161714 (dark panel) and #ffffff (white); rendered references are the actual preview wells, #1f201c (dark) and #e5e4dc (light). White is a reference, not the weakest possible light background. Hue is HSV in degrees for the first, characteristic stop; spacing is the smallest circular distance to a sibling’s first stop, ignoring achromatic stops. ΔE76 compares that stop with every original stop: larger means more separated in CIELAB. Gradients, bloom and opacity change final pixel contrast; these figures describe solid colour, not a claim that every antialiased pixel meets WCAG.', '',++ '| Group / new colour | All raw stops | Hue / nearest sibling spacing | Nearest old stop ΔE76 | Minimum raw dark panel / white contrast | Minimum rendered dark / light well contrast |',++ '| --- | --- | --- | ---: | --- | --- |']++ records = []++ for title, choices in groups:++ palettes = {value: list(tokens.PALETTES[value]) if value in tokens.PALETTES else effects.pack(value)[1] for value, _name in choices}++ for value, name in choices:++ if value in old_ids:++ continue++ stops = palettes[value]++ hue = colorsys.rgb_to_hsv(*rgb(stops[0]))[0] * 360++ sibling_hues = [colorsys.rgb_to_hsv(*rgb(p[0]))[0] * 360 for key, p in palettes.items()++ if key != value and colorsys.rgb_to_hsv(*rgb(p[0]))[1] > .1]++ spacing = min(min(abs(hue - h), 360 - abs(hue - h)) for h in sibling_hues)++ raw = [min(contrast(stop, bg) for stop in stops) for bg in ('#161714', '#ffffff')]++ rendered = [min(contrast(stop, bg) for stop in effects.legible(stops, dark, effects.effect('crease')))++ for dark, bg in ((True, tokens.PALETTE['well']), (False, tokens.PALETTE_LIGHT['well']))]++ delta = min(distance(stops[0], stop) for stop in old_stops)++ lines.append(f'| {title} / {name} (`{value}`) | ' + ', '.join(stops) +++ f' | {hue:.1f}° / {spacing:.1f}° | {delta:.1f} | {raw[0]:.2f}:1 / {raw[1]:.2f}:1 | {rendered[0]:.2f}:1 / {rendered[1]:.2f}:1 |')++ records.append(dict(group=title, id=value, hue=hue, spacing=spacing, delta_e=delta, raw=raw, rendered=rendered))++ lines += ['', 'Membrane adds cool mineral Opal and green Sea glass; Sparks adds blue electrical Arc and violet Magnesium; Instrument adds red Ruby and blue Cobalt; Folio adds muted plant Moss and purple Plum; Selvedge adds dyed Woad and golden Saffron. Aurora adds a cool green/violet/teal sweep to Light.', '',++ 'Bright uses narrow saturated hue bands rather than multicolour rainbow sweeps. Its characteristic hues are separated by at least %.1f°. Existing packs already span the entire hue wheel, so exclusive new hues are impossible; distinctness comes from hue, saturation, lightness and the complete ordered stop signature. No new stop duplicates an existing stop.' % min(r['spacing'] for r in records if r['group'] == 'Bright'), '',++ 'A concrete limit: high luminance and 3:1 against white cannot coexist above relative luminance 0.30. Bright therefore uses the luminous raw stops on dark screens. All sixteen new choices have explicit hue-preserving darker stops on light screens, at least 3:1 on the actual preview wells and 4.2:1 on white. Five new shadow stops are also lifted slightly so every new colour exceeds 3:1 on the dark well. This does not alter older colours. Names and selection rings remain the non-colour cues.', '',++ '| New colour | All light-screen stops |', '| --- | --- |']++ for title, choices in groups:++ for value, name in choices:++ if value not in old_ids:++ stops = tokens.PALETTES[value] if value in tokens.PALETTES else effects.pack(value)[1]++ lines.append(f'| {name} | ' + ', '.join(effects.legible(stops, False)) + ' |')++ bright_stops = [stop for _name, stops in effects.BRIGHT_PACKS.values() for stop in stops]++ lines += ['', 'Across all fifteen Bright stops: HLS saturation is 100%%; relative luminance ranges from %.3f to %.3f; the nearest original stop is ΔE76 %.1f away. These are measurements in specified colour spaces, not a guarantee of separation for every form of colour-vision deficiency.' %++ (min(map(luminance, bright_stops)), max(map(luminance, bright_stops)),++ min(distance(stop, old_stop) for stop in bright_stops for old_stop in old_stops))]++ lines += ['', '## Compatibility and merge boundary', '',++ 'Colours travel by stable id in settings.design.glow_colour and design_sync.values.glow_colour. The origin/release/1.5.0 peer (00c92e8) discards unsupported individual fields, retains its current colour, and applies supported fields. Its links do not fail. Runtime palette resolvers fall back to Signal if handed an unknown id directly. Keep these semantics; a new id must not force an arbitrary old colour onto an older peer.', '',++ 'The shared catalogue lives in core/effects.py; adapters are mac_app/pages.py and win_app/pages_win.py. No layout, hover or selection code changes in the six files owned by design2. New light-screen remapping happens in the shared legible() path used by both native renderers. The Mac retains the legacy five-entry GLOW_COLOURS tuple because its existing swatch code derives the column count from it; Aurora is offered by pages.py and separately admitted by settings_store.py, avoiding an empty sixth column without changing layout code.']++ (ROOT / 'proposal.md').write_text('\n'.join(lines) + '\n')++ (ROOT / 'colour-measurements.json').write_text(json.dumps(records, indent=2) + '\n')++ for record in records:++ print(f"{record['id']}: hue {record['hue']:.1f}, spacing {record['spacing']:.1f}, old ΔE {record['delta_e']:.1f}, rendered {record['rendered']}")++++++if __name__ == '__main__':++ main()diff --cc tools/older_peer_check.pyindex 0000000,0000000..6d91f06new file mode 100644--- /dev/null+++ b/tools/older_peer_check.py@@@ -1,0 -1,0 +1,95 @@@++"""Beamer 1.4.x and this build refuse each other, both ways, in words each side shows (WIRE.md++section 2, Versions; docs/wire-v6-tests.md, "Older peers": the live check). Everything runs on++loopback on this machine, on spare ports; nothing is installed, and no Beamer config is read or++written.++++The 1.4.x side is a 1.4.x source tree run with its own code (tools/older_peer_side.py): its++responder, and its Mac's and PC's initiators. This side is core.receiver.LinkResponder and++core.link.OutboundLink, each holding the peer as a 1.4.x pairing carried into 1.5.0 would be held++(no id yet, `from_1_4`). The token is generated per run and goes to the other process on stdin.++++ git archive acead88 | tar -x -C <dir> # 1.4.3's source++ python3 tools/older_peer_check.py <dir>++++Exit status 0 when every side refused and said so."""++++import base64++import json++import os++import subprocess++import sys++import time++++_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))++sys.path.insert(0, _ROOT)++++from core import receiver # noqa: E402++from core.link import OutboundLink # noqa: E402++from core.tests.responder_harness import Machine, Settings, entry, ident, wait_for # noqa: E402++++++def free_port():++ import socket++ with socket.socket() as probe:++ probe.bind(("127.0.0.1", 0))++ return probe.getsockname()[1]++++++def migrated(name, token, port=24820):++ """A 1.4.x pairing as 1.5.0 carries it over: no id until the peer says it."""++ return entry("", name, token=token, host="127.0.0.1", port=port, linked=False, from_1_4=True, platform="")++++++def main(old_tree):++ token = base64.urlsafe_b64encode(os.urandom(32)).decode("ascii").rstrip("=")++ here = Machine([migrated("Old Beamer", token)], own=ident(7), name="New").start()++ old_port = free_port()++ side = subprocess.Popen(++ [sys.executable, os.path.join(_ROOT, "tools", "older_peer_side.py"), old_tree, str(old_port), str(here.port)],++ stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True,++ )++ side.stdin.write(token + "\n")++ side.stdin.flush()++ seen = {}++ assert json.loads(side.stdout.readline())["part"] == "ready", "the 1.4.x side did not start"++++ # This build dials the 1.4.x listener.++ settings = Settings([migrated("Old PC", token, old_port)], own=ident(9))++ book = receiver.PeerBook(settings.load, settings.save)++ states = []++ link = OutboundLink(++ token, book,++ lambda: {"id": ident(9), "name": "New", "platform": "macos", "app": "1.5.0", "caps": [], "port": 24820},++ state=lambda link_, up, text: states.append((up, text)), reconnect_seconds=0.5,++ )++ link.start()++ wait_for(lambda: states, timeout=5)++ time.sleep(1.5)++ link.stop()++ seen["1.5.0 initiator, dialling 1.4.x"] = " | ".join(dict.fromkeys(text for _, text in states))++++ side.stdin.write("go\n")++ side.stdin.flush()++ for line in side.stdout:++ part = json.loads(line)++ if part["part"] == "done":++ break++ seen[part["part"]] = part.get("text", "") + ("" if part.get("connected") is not True else " [CONNECTED]")++ side.wait(timeout=10)++ seen["1.5.0 responder, dialled by 1.4.x"] = " | ".join(dict.fromkeys(f"{state.value}: {detail}" for state, detail in here.statuses))++ here.stop()++++ for part, text in seen.items():++ print(f"{part}:\n {text}")++ refused = (++ "Update Beamer on Old PC" in seen["1.5.0 initiator, dialling 1.4.x"]++ and "Old Beamer" in seen["1.5.0 responder, dialled by 1.4.x"]++ and not any("[CONNECTED]" in text for text in seen.values())++ and all("v6" in seen.get(part, "") for part in ("1.4.3 Mac, dialling version 6", "1.4.3 PC, dialling version 6", "1.4.3 PC's listener, dialled by version 6"))++ )++ print("refused both ways, in words" if refused else "NOT AS EXPECTED")++ return 0 if refused else 1++++++if __name__ == "__main__":++ sys.exit(main(os.path.abspath(sys.argv[1])))diff --cc tools/older_peer_side.pyindex 0000000,0000000..500e1denew file mode 100644--- /dev/null+++ b/tools/older_peer_side.py@@@ -1,0 -1,0 +1,82 @@@++"""The 1.4.x half of tools/older_peer_check.py, run with a 1.4.x source tree's own code and never++this tree's: that tree's ReceiverServer (the PC's) listens on one port, and its two initiators, the++Mac's KVMController and the PC's MacSender, dial this tree's responder, each built the way that++tree's mac_app/tests/two_machines.py builds them, with only the platform edges faked.++++ python older_peer_side.py <1.4.x tree> <port to listen on> <version 6 responder's port>++++The token comes on stdin, never the command line. Prints one JSON object per line: what each part++showed, then "done"."""++++import json++import os++import sys++import time++++OLD, LISTEN, DIAL = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])++TOKEN = sys.stdin.readline().strip()++for path in (os.path.join(OLD, "mac_app"), os.path.join(OLD, "mac_app", "tests")):++ sys.path.insert(0, path)++for path in (os.path.join(OLD, "win_app"), os.path.join(OLD, "win_app", "tests")):++ sys.path.append(path)++++import app_config # noqa: E402++import receiver # noqa: E402++import sender as pc_sender_module # noqa: E402++from bridge import KVMController # noqa: E402++from fakes import FakeClipboard, FakeDesktop, FakeInjector # noqa: E402++from return_edge import Rect # noqa: E402++from test_bridge import FakeClock, FakeQuartz, crossing_config, quiet_logger # noqa: E402++from two_machines import NoUnlock # noqa: E402++++++def say(**fields):++ print(json.dumps(fields), flush=True)++++++def settle(read, seconds=3.0):++ """What `read()` shows once it has stopped changing, or after `seconds`."""++ deadline = time.monotonic() + seconds++ last, since = read(), time.monotonic()++ while time.monotonic() < deadline:++ time.sleep(0.05)++ now = read()++ if now != last:++ last, since = now, time.monotonic()++ elif time.monotonic() - since > 1.0:++ break++ return last++++++statuses = []++server = receiver.ReceiverServer(++ status_callback=lambda state, detail: statuses.append(f"{state.value}: {detail}"),++ clipboard=FakeClipboard(),++ unlock=NoUnlock(),++ desktop=FakeDesktop([Rect(0, 0, 1920, 1080)], cursor=(900, 500)),++ injector=FakeInjector(),++ focus_callback=lambda target: None,++)++server.start(app_config.Config(host="127.0.0.1", port=LISTEN, auth_token=TOKEN))++say(part="ready")++sys.stdin.readline()++++cfg = crossing_config()++cfg.host, cfg.port, cfg.auth_token = "127.0.0.1", DIAL, TOKEN++cfg.reconnect_interval_s = 0.2++mac = KVMController(cfg, logger=quiet_logger(), quartz=FakeQuartz, clock=FakeClock(), desktop_bounds=lambda: (0, 0, 1728, 1117))++mac.on_user_alert = lambda title, message: say(part="1.4.3 Mac alert", text=f"{title}: {message}")++mac.start()++time.sleep(0.5)++say(part="1.4.3 Mac, dialling version 6", text=settle(lambda: mac.connection_status), connected=bool(mac.connected))++mac.stop()++++pc = pc_sender_module.MacSender(desktop=FakeDesktop([Rect(0, 0, 1920, 1080)]), clipboard=FakeClipboard(), is_local=lambda host: False)++pc.start(app_config.Config(host="127.0.0.1", port=DIAL, auth_token=TOKEN, mac_host="127.0.0.1"))++time.sleep(0.5)++say(part="1.4.3 PC, dialling version 6", text=settle(lambda: pc.status), connected=bool(pc.connected))++pc.stop()++++say(part="1.4.3 PC's listener, dialled by version 6", text=" | ".join(dict.fromkeys(statuses)))++server.stop()++say(part="done")diff --cc tools/phone_vectors.jsonindex 0000000,0000000..7fc0513new file mode 100644--- /dev/null+++ b/tools/phone_vectors.json@@@ -1,0 -1,0 +1,2823 @@@++{++ "$comment": "Generated by beamer/tools/phone_vectors.py. The protocol_version, preamble, derive_key, frames, pairing and messages sections (wire version 5 and pairing version 2) were written by 1.4.x's code and are carried over untouched; v6 and pairing_v3 are made from core/protocol.py and core/pairing.py. Every value is fixed, not random -- rerunning this script must reproduce this file byte for byte until the wire format changes.",++ "protocol_version": 5,++ "preamble": {++ "protocol_version": 5,++ "wire_magic_ascii": "BEAMY",++ "nonce_prefix_hex": "0102030405060708",++ "preamble_hex": "4245414d59050102030405060708"++ },++ "derive_key": {++ "token": "vector-derive-key-token-1",++ "salt_ascii": "beamer-link-v5",++ "info_label_ascii": "beamer-frames",++ "sender_prefix_hex": "1112131415161718",++ "receiver_prefix_hex": "2122232425262728",++ "key_hex": "375170b83750f70d7137cbbc82c5b59b2f8f4f3491e0fb001078d9bcbe2d13d3"++ },++ "frames": {++ "token": "vector-frame-token-1",++ "sender_prefix_hex": "1112131415161718",++ "receiver_prefix_hex": "2122232425262728",++ "frames": [++ {++ "direction": "a_to_b",++ "counter": 1,++ "plaintext": {++ "type": "hello",++ "data": {++ "version": 5++ }++ },++ "frame_hex": "0000003d0000000155323653ac7dd02321cbec63dabdced30ad7f3f69b841d98b5c5b71b60f0b8bb78165486e538e5e61119e9e8263907cd3602812928773f3176"++ },++ {++ "direction": "b_to_a",++ "counter": 1,++ "plaintext": {++ "type": "welcome",++ "data": {++ "version": 5++ }++ },++ "frame_hex": "0000003f0000000140067e5e49a785b19954f9331b3910855d3a3724fae7b1fc09615f215af4aaf898322743a4e3d660eb73b38dfcec7acbf6e5e740d532b4c678f162"++ },++ {++ "direction": "a_to_b",++ "counter": 2,++ "plaintext": {++ "type": "mousemove",++ "data": {++ "dx": 12,++ "dy": -7++ }++ },++ "frame_hex": "0000004700000002ab3af75a2d76f690a8a67a12952825f4c114f3dde5129fbe078bb8697e7431fb87cf80cc29f81e13e7b9362465aad14ab9da5dd3c323ac00063444c8967b457b60ea0c"++ },++ {++ "direction": "b_to_a",++ "counter": 2,++ "plaintext": {++ "type": "ack",++ "data": {++ "seq": 3++ }++ },++ "frame_hex": "0000003700000002735a8dea0c001239acb6102889a0e4019c90e1c741d5bb76330e57e6df357b5a907368dd2557f1d1add9740a71e7eafa47bb82"++ },++ {++ "direction": "a_to_b",++ "counter": 3,++ "plaintext": {++ "type": "keydown",++ "data": {++ "key": "a"++ }++ },++ "frame_hex": "0000003d00000003e30b36c07340b022676aed58f84ba531a84b8b02c773e823be02d54825a5a0d59bb8e5a1a72199f447a817908f735f4f4cd1b9c70faeb173fd"++ }++ ]++ },++ "pairing": {++ "$comment": "Hex is bytes in wire order, except the two elligator2 fields, which are integers printed big-endian as RFC 9380 prints them. Messages are shown before the \"beamy\": 1 every datagram adds.",++ "suite": "CPACE-X25519-SHA512, draft-irtf-cfrg-cpace-21, initiator-responder, key confirmation per section 10.4",++ "specification": "PAIRING.md",++ "pairing_version": 2,++ "constants": {++ "dsi_ascii": "CPace255",++ "channel_ascii": "beamer-pair-v2",++ "role_requester_ascii": "requester",++ "role_host_ascii": "host",++ "token_info_ascii": "beamer-pair-token-v2",++ "done_label_ascii": "beamer-pair-done",++ "nonce_bytes": 16,++ "max_name_chars": 48,++ "max_identity_bytes": 32++ },++ "cpace_draft": {++ "prs_ascii": "Password",++ "ci_hex": "0b415f696e69746961746f720b425f726573706f6e646572",++ "sid_hex": "7e4b4791d6a8ef019b936c79fb7f2c57",++ "generator_hex": "d04bf6d41f6a289632a2e929fa29bebd51092512a7829fdde7d314b62f05a73f",++ "ada_ascii": "ADa",++ "ya_scalar_hex": "21b4f4bd9e64ed355c3eb676a28ebedaf6d8f17bdc365995b319097153044080",++ "ya_hex": "1d13c89278cdadd826f6d8d7f887701430f8380ddc17611cdd6dc989ce0c9f32",++ "adb_ascii": "ADb",++ "yb_scalar_hex": "848b0779ff415f0af4ea14df9dd1d3c29ac41d836c7808896c4eba19c51ac40a",++ "yb_hex": "248cccf6d5cdc3646f0ad593f9e6cef4e69d4945f8372e623512ecea32185623",++ "k_hex": "5b067effbdc0b2a0e1d907b21ebb25cfedb96a852179a847c37e43ee71322c6b",++ "isk_hex": "6e19b875f7a561d6b3ca3dbb9ef42ac55de3e717881018204b8922b4d5e53bb2aa82c300bea7b65d2b671da71922ddf6472301b79bc270adfa8bf413285f2263"++ },++ "elligator2": [++ {++ "field_element_hex_be": "608d892b641f0328523802a6603427c26e55e6f27e71a91a478148d45b5093cd",++ "u_hex_be": "51125222da5e763d97f3c10fcc92ea6860b9ccbbd2eb1285728f566721c1e65b"++ },++ {++ "field_element_hex_be": "46f5b22494bfeaa7f232cc8d054be68561af50230234d7d1d63d1d9abeca8da5",++ "u_hex_be": "7d56d1e08cb0ccb92baf069c18c49bb5a0dcd927eff8dcf75ca921ef7f3e6eeb"++ },++ {++ "field_element_hex_be": "235fe40c443766ce7e18111c33862d66c3b33267efa50d50f9e8e5d252a40aaa",++ "u_hex_be": "3fbe66b9c9883d79e8407150e7c2a1c8680bee496c62fabe4619a72b3cabe90f"++ },++ {++ "field_element_hex_be": "001e92a544463bda9bd04ddbe3d6eed248f82de32f522669efc5ddce95f46f5b",++ "u_hex_be": "227e0bb89de700385d19ec40e857db6e6a3e634b1c32962f370d26f84ff19683"++ },++ {++ "field_element_hex_be": "1a68a1af9f663592291af987203393f707305c7bac9c8d63d6a729bdc553dc19",++ "u_hex_be": "3bcd651ee54d5f7b6013898aab251ee8ecc0688166fce6e9548d38472f6bd196"++ }++ ],++ "low_order_shares": {++ "scalar_hex": "af46e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449aff",++ "must_refuse": [++ "0000000000000000000000000000000000000000000000000000000000000000",++ "0100000000000000000000000000000000000000000000000000000000000000",++ "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",++ "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800",++ "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157",++ "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",++ "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"++ ],++ "must_give": [++ {++ "share_hex": "daffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",++ "product_hex": "d8e2c776bbacd510d09fd9278b7edcd25fc5ae9adfba3b6e040e8d3b71b21806"++ },++ {++ "share_hex": "dbffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",++ "product_hex": "c85c655ebe8be44ba9c0ffde69f2fe10194458d137f09bbff725ce58803cdb38"++ },++ {++ "share_hex": "d9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",++ "product_hex": "db64dafa9b8fdd136914e61461935fe92aa372cb056314e1231bc4ec12417456"++ },++ {++ "share_hex": "cdeb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b880",++ "product_hex": "e062dcd5376d58297be2618c7498f55baa07d7e03184e8aada20bca28888bf7a"++ },++ {++ "share_hex": "4c9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7",++ "product_hex": "993c6ad11c4c29da9a56f7691fd0ff8d732e49de6250b6c2e80003ff4629a175"++ }++ ]++ },++ "exchanges": [++ {++ "comment": "1.4.3: no machine ids yet, so both identities are empty",++ "code": "482913",++ "pair_id": "eb6cf2ee3c1c8cbd2161b67b41be3003",++ "requester": {++ "name": "Vector Mac",++ "id_hex": "",++ "nonce_hex": "edad1eba42ed11cfd8ba0daba74a4bc8",++ "scalar_hex": "842bca52bbbdc727263dfa19a0c2851f18862e0c31e7a1b706d6ce9d1934c604"++ },++ "host": {++ "name": "VECTOR-PC",++ "id_hex": "",++ "scalar_hex": "a2fa23319131feac78653467b4863a444f5da2af0158d1d5e1e239710d691580"++ },++ "sid_hex": "20656236636632656533633163386362643231363162363762343162653330303310edad1eba42ed11cfd8ba0daba74a4bc8",++ "ada_hex": "09726571756573746572000a566563746f72204d6163",++ "adb_hex": "04686f73740009564543544f522d5043",++ "generator_string_hex": "084350616365323535063438323931336f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6265616d65722d706169722d76323220656236636632656533633163386362643231363162363762343162653330303310edad1eba42ed11cfd8ba0daba74a4bc8",++ "generator_hex": "1a750835aae9d408194e8e1393132e02c2495de72b6f265184749f056130ca10",++ "ya_hex": "2649f89325b72e646000fa5dc7c4221bf869de4938a88fecedbda398cbf34150",++ "yb_hex": "2d0dc754bb17865b276c39ba6ff00c0954b4804371a46742c3a2287c04e01347",++ "k_hex": "796f912ddb354ceba9a7642244ed553149bfc23f22f374bff3ad8315df817b2b",++ "isk_hex": "7dc167e8b761b5808f8e873878556f5dd1c52bdd62f3c348ea60a60512ea4294e19f6e72a0c54dacf5656a8debd79bf9615bee6fe5a59bbc98be15cf3b0bd077",++ "mac_key_hex": "8c619a26e16124af43935ba791b7de2b733ee32f13bae3c0943d574dbbbf1a0b6cd32997bf518db4b33a513f306c85ed9ac595806c3fc298488922660cce9f9c",++ "ta_hex": "630c08e363d467fa00c19d741672d4eac8bc9676c2b52bdb9f4939d842b12686c4d27c8ab900a85a411977042a9f4e97be520d9e64eeeeb59038a0330aec8f5d",++ "tb_hex": "1eeaafd522d6884f57057475a3bde52e3e14debcd79088aae52c5aa1edb858bdb12c4fb02a5427c42c46fdec565b43fd9a1c45b8b22d91ff733d43ac14396919",++ "td_hex": "cad8b6dd3af2c1f1b78c16c6eb86fdf897bb4f1b69f5559461491722a845ac83b5332c48433b5c4228accb93b3f177e264acbef9be9f4e21b985c165cea3dc2e",++ "token": "4xGHJR0vazj3INjxHjXpkTzLvzDEtxKZ8TiQQp8QhCw",++ "messages": {++ "pair_start": {++ "type": "pair_start",++ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",++ "v": 2,++ "nonce": "7a0eukLtEc_Yug2rp0pLyA",++ "share": "Jkn4kyW3LmRgAPpdx8QiG_hp3kk4qI_s7b2jmMvzQVA",++ "name": "Vector Mac",++ "id": ""++ },++ "pair_answer": {++ "type": "pair_answer",++ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",++ "ok": true,++ "share": "LQ3HVLsXhlsnbDm6b_AMCVS0gENxpGdCw6IofATgE0c",++ "tag": "Huqv1SLWiE9XBXR1o73lLj4U3rzXkIiq5Sxaoe24WL2xLE-wKlQnxCxG_exWW0P9mhxFuLItkf9zPUOsFDlpGQ",++ "name": "VECTOR-PC",++ "id": ""++ },++ "pair_confirm": {++ "type": "pair_confirm",++ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",++ "tag": "YwwI42PUZ_oAwZ10FnLU6si8lnbCtSvbn0k52EKxJobE0nyKuQCoWkEZdwQqn06XvlINnmTu7rWQOKAzCuyPXQ"++ },++ "pair_done": {++ "type": "pair_done",++ "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",++ "ok": true,++ "tag": "yti23TrywfG3jBbG64b9-Je7Txtp9VWUYUkXIqhFrIO1MyxIQztcQiisy5Oz8XfiZKy--b6fTiG5hcFlzqPcLg"++ }++ }++ },++ {++ "comment": "The wire v6 shape: a 16-byte id each side, and a name with characters outside ASCII and outside the BMP",++ "code": "007045",++ "pair_id": "d397348abeb0691c3292a1f36093d950",++ "requester": {++ "name": "Zo\u00eb\u2019s \ud835\udd39eamer Mac",++ "id_hex": "74f70aa0e96f874c9866b11545950f8b",++ "nonce_hex": "e979b12f908a2f0ad16eb37876b5f0b5",++ "scalar_hex": "85b6b2942677e61db3636c9e6faea4586cc708ac4051afc481e17810a672266a"++ },++ "host": {++ "name": "VECTOR-PC",++ "id_hex": "ee3e1ebd5eacd2c487f2403bac611cdb",++ "scalar_hex": "4ee3c8b532aca27be39b1ac34ea82bd4084684dbd0e54987b192b5cd30541dbc"++ },++ "sid_hex": "20643339373334386162656230363931633332393261316633363039336439353010e979b12f908a2f0ad16eb37876b5f0b5",++ "ada_hex": "097265717565737465721074f70aa0e96f874c9866b11545950f8b165a6fc3abe280997320f09d94b965616d6572204d6163",++ "adb_hex": "04686f737410ee3e1ebd5eacd2c487f2403bac611cdb09564543544f522d5043",++ "generator_string_hex": "084350616365323535063030373034356f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6265616d65722d706169722d76323220643339373334386162656230363931633332393261316633363039336439353010e979b12f908a2f0ad16eb37876b5f0b5",++ "generator_hex": "73b80492ce8c3d166117a405dc4bc62d593149cda94e53f3012d102fb539c069",++ "ya_hex": "46d1977042bd7aabd494df39930b1f6efb83078fe7cf605ffcf1580c8613d005",++ "yb_hex": "5fdbb545d4175d7f1e83613994e2abfdff7f7f46fb62e5c9b3f74c08e0ab8147",++ "k_hex": "f94259fbe1b827b22fc38e9beed8c77501ceca3373fe2abcc79e03ab0b245a77",++ "isk_hex": "9010d318e53253ad83ae8c3354e7d32229b7427d144d99fdba9681482a3ca81c4edc4ef433d1c2253949288c22464ff4b61b66158e983910b9c088de2826bf30",++ "mac_key_hex": "5d539ab7dd2da83e6411669bb70f95578cc61ed2f7f55462352953e3a687edcf8ea0b08bc5737d1ed2dd285cf61968efaed83d4e5acdb9136b7056f03a9681f4",++ "ta_hex": "d084e7d4b3e4d3008f2082cfeb9f421496fd1ea514717eb6f1fabb9e951deb88f734c2806c0a7153914cf5ed37635fa40dd46295c5ff0b7e8dd942f103504a41",++ "tb_hex": "2e636a9a44c7dde48f4d2dee732bd556abf31b4ba2e97121e0af076e1eb6d8297c0d4ad517513caef69c111e46c4097b940740f38e4251c10bc0a03da9b4d556",++ "td_hex": "f3ab76e44dca6d3aad881499c4941f6b5a5cd7e95971b75d0163b1f127fbb6785e728d53863a1d5e7c7ba96c8247a629f106833397415f73eb223febc28272fd",++ "token": "RG0uipRsvpPDZlGTPq3dXODw6X-a1M5f2QnB9jPcldo",++ "messages": {++ "pair_start": {++ "type": "pair_start",++ "pair": "d397348abeb0691c3292a1f36093d950",++ "v": 2,++ "nonce": "6XmxL5CKLwrRbrN4drXwtQ",++ "share": "RtGXcEK9eqvUlN85kwsfbvuDB4_nz2Bf_PFYDIYT0AU",++ "name": "Zo\u00eb\u2019s \ud835\udd39eamer Mac",++ "id": "dPcKoOlvh0yYZrEVRZUPiw"++ },++ "pair_answer": {++ "type": "pair_answer",++ "pair": "d397348abeb0691c3292a1f36093d950",++ "ok": true,++ "share": "X9u1RdQXXX8eg2E5lOKr_f9_f0b7YuXJs_dMCOCrgUc",++ "tag": "LmNqmkTH3eSPTS3ucyvVVqvzG0ui6XEh4K8Hbh622Cl8DUrVF1E8rvacER5GxAl7lAdA845CUcELwKA9qbTVVg",++ "name": "VECTOR-PC",++ "id": "7j4evV6s0sSH8kA7rGEc2w"++ },++ "pair_confirm": {++ "type": "pair_confirm",++ "pair": "d397348abeb0691c3292a1f36093d950",++ "tag": "0ITn1LPk0wCPIILP659CFJb9HqUUcX628fq7npUd64j3NMKAbApxU5FM9e03Y1-kDdRilcX_C36N2ULxA1BKQQ"++ },++ "pair_done": {++ "type": "pair_done",++ "pair": "d397348abeb0691c3292a1f36093d950",++ "ok": true,++ "tag": "86t25E3KbTqtiBSZxJQfa1pc1-lZcbddAWOx8Sf7tnheco1ThjodXnx7qWyCR6Yp8QaDM5dBX3PrIj_rwoJy_Q"++ }++ }++ }++ ],++ "wrong_code": {++ "host_code": "482913",++ "requester_code": "482914",++ "pair_id": "6bc698c0065affb622fff9fb87cac02a",++ "requester": {++ "name": "Vector Mac",++ "id_hex": "",++ "nonce_hex": "d90bf42db9e188ff2f817cd143f514f2",++ "scalar_hex": "5318fc1f72d7f28d4053a37001e4b96339c154095161d9e3686d068e993cd2a5"++ },++ "pair_start": {++ "type": "pair_start",++ "pair": "6bc698c0065affb622fff9fb87cac02a",++ "v": 2,++ "nonce": "2Qv0LbnhiP8vgXzRQ_UU8g",++ "share": "Qq9Jel7gwUBo6te3H1ucksTPo9W9_KNE3wS6H1i8IFY",++ "name": "Vector Mac",++ "id": ""++ },++ "pair_answer": {++ "type": "pair_answer",++ "pair": "6bc698c0065affb622fff9fb87cac02a",++ "ok": true,++ "share": "CAKZVA2Yp_gG6soy4krssop3x0uLbG4BIPWF2JQLCxA",++ "tag": "EDuxWV1wqH2EdQtuQCC4DyFXZb9kibeRaxATuacSQv0hr3hVqhsBkS8bt90zJirBrkZWRSBWaRWNemqnNfu31g",++ "name": "VECTOR-PC",++ "id": ""++ },++ "requester_must": "refused",++ "pair_confirm_abort": {++ "type": "pair_confirm",++ "pair": "6bc698c0065affb622fff9fb87cac02a",++ "tag": ""++ }++ },++ "name_cut": {++ "name": "\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e",++ "code_points": 60,++ "sent": "\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e",++ "sent_code_points": 48++ }++ },++ "messages": {++ "hello": {++ "type": "hello",++ "data": {++ "version": 5,++ "settings": 1,++ "return_edge": "left",++ "resistance_px": 120++ }++ },++ "welcome": {++ "type": "welcome",++ "data": {++ "version": 5,++ "settings": 1++ }++ },++ "welcome_version_mismatch": {++ "type": "welcome",++ "data": {++ "version": 5,++ "settings": 1,++ "error": "version_mismatch"++ }++ },++ "ping": {++ "type": "ping",++ "data": {}++ },++ "ack": {++ "type": "ack",++ "data": {++ "seq": 42++ }++ },++ "ack_locked": {++ "type": "ack",++ "data": {++ "seq": 42,++ "locked": true++ }++ },++ "mousemove": {++ "type": "mousemove",++ "data": {++ "dx": 8,++ "dy": -3++ }++ },++ "mousedown_left": {++ "type": "mousedown",++ "data": {++ "button": "left"++ }++ },++ "mouseup_left": {++ "type": "mouseup",++ "data": {++ "button": "left"++ }++ },++ "mousedown_right": {++ "type": "mousedown",++ "data": {++ "button": "right"++ }++ },++ "mouseup_right": {++ "type": "mouseup",++ "data": {++ "button": "right"++ }++ },++ "scroll_pixel": {++ "type": "scroll",++ "data": {++ "dy": -14.5,++ "dx": 0.0,++ "mode": "pixel"++ }++ },++ "scroll_line": {++ "type": "scroll",++ "data": {++ "dy": 1,++ "dx": 0,++ "mode": "line"++ }++ },++ "keydown_letter": {++ "type": "keydown",++ "data": {++ "key": "a"++ }++ },++ "keyup_letter": {++ "type": "keyup",++ "data": {++ "key": "a"++ }++ },++ "keydown_special": {++ "type": "keydown",++ "data": {++ "key": "cmd"++ }++ },++ "keyup_special": {++ "type": "keyup",++ "data": {++ "key": "cmd"++ }++ },++ "keydown_media": {++ "type": "keydown",++ "data": {++ "key": "media_play_pause"++ }++ },++ "gesture_names": [++ "pinch",++ "spread",++ "swipe_down",++ "swipe_left",++ "swipe_right",++ "swipe_up"++ ],++ "gesture": {++ "type": "gesture",++ "data": {++ "name": "swipe_left"++ }++ },++ "focus_from_crossing": {++ "type": "focus",++ "data": {++ "target": "windows",++ "edge": "left",++ "offset": 0.42,++ "return_edge": "right",++ "resistance_px": 120++ }++ },++ "focus_from_manual_switch": {++ "type": "focus",++ "data": {++ "target": "mac"++ }++ },++ "switch_plain": {++ "type": "switch",++ "data": {++ "target": "mac"++ }++ },++ "switch_with_position": {++ "type": "switch",++ "data": {++ "target": "windows",++ "edge": "top",++ "offset": 0.75++ }++ },++ "arrangement": {++ "type": "arrangement",++ "data": {++ "mac_edge": "right",++ "set_at": 1758975600++ }++ }++ },++ "v6": {++ "$comment": "Wire version 6 (WIRE.md). Hex is bytes in wire order. Generated from core/protocol.py and checked against HKDF, X25519 and ChaCha20-Poly1305 written apart from it.",++ "constants": {++ "version": 6,++ "salt_ascii": "beamer-link-v6",++ "key_id_info_ascii": "beamer-key-id",++ "frame_info_label_ascii": "beamer-frames",++ "key_id_bytes": 16,++ "preamble_bytes": 62,++ "short_reply_bytes": 14,++ "min_frame_bytes": 21,++ "first_frame_max_bytes": 4096++ },++ "key_id": {++ "$comment": "A token made by pairing is the b64 of 32 bytes in its one spelling. A typed token has no key id and never links.",++ "cases": [++ {++ "token": "ZlLgvTLc4DGZaKE90HvBM3syIVscP_40UCQxQIXAZJw",++ "key_id_hex": "563fcce238f33a62db0c2477e8cf8d83"++ },++ {++ "token": "TGlx9eccM8GfzffKhQ--OFTUKTc-0htCVDOQWoYtvbE",++ "key_id_hex": "ef62b05945926e757427bfb9918304ab"++ },++ {++ "token": "jdbb2tZc4xZvk3W-8K9CDPBrKPI5CKJjfdvOVMgNkUI",++ "key_id_hex": "aa67a6af2c5f8d896907027b508a4633"++ }++ ],++ "typed_tokens": [++ "hunter2",++ "ZlLgvTLc4DGZaKE90HvBM3syIVscP_40UCQxQIXAZJB",++ "ZlLgvTLc4DGZaKE90HvBM3syIVscP_40UCQxQIXAZJw=",++ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"++ ]++ },++ "preamble": {++ "token": "9Suyotys6fLcUmAkESPE_3qV71dADd7RngvKAVrIXsE",++ "prefix_hex": "5ceca4f7d61aee01",++ "key_id_hex": "6da7e3a4a107e4061473461dd45339a9",++ "secret_hex": "edf28845a58fda5e0cf7865131591d7ba7d8ae837bc9c506fbf521cde9735351",++ "share_hex": "33e2ce325442f38ac1bca48fbfcbbcc110999702868872242e8d3ee51099f159",++ "preamble_hex": "4245414d59065ceca4f7d61aee016da7e3a4a107e4061473461dd45339a933e2ce325442f38ac1bca48fbfcbbcc110999702868872242e8d3ee51099f159"++ },++ "short_reply": {++ "prefix_hex": "19c72d818ab184cf",++ "reply_hex": "4245414d590619c72d818ab184cf"++ },++ "derive_key": {++ "$comment": "info_i and key_i are for direction 0x01, the frames the initiator seals; info_r and key_r for 0x02. The second case gives the same two machines' prefixes and secrets the opposite roles: the shared secret is the same and every key changes.",++ "cases": [++ {++ "comment": "A initiates, B responds",++ "token": "KFX5cT76a4uBbZ-k66SlHbJJiHqvMrPcHqOVZl_v3Mo",++ "key_id_hex": "7dd820d674da2b465292b2a5456ff756",++ "prefix_i_hex": "220ca92180d4505b",++ "prefix_r_hex": "4ed33c9398f8d412",++ "secret_i_hex": "553ed8446b237ba96d54d931ea20db6068889999f84a4697620053bce5448d2a",++ "secret_r_hex": "54555b4c654ed3274fd8c80bd13ec2a2b584921135988e83afcd7efc3074b910",++ "share_i_hex": "0d5297c17a85a9a09d4bbaaacd973d9a171068c7f108f4169297cd84847dee3b",++ "share_r_hex": "b6c7450905c00ca9a4a5e6d0ed892c8deea001da3b4c3073963da9ab40e7c608",++ "shared_hex": "e42730a125f0a5d698205c7263739f082f56ba90bce85a06535f43157190c958",++ "ikm_hex": "4b4658356354373661347542625a2d6b3636536c48624a4a694871764d72506348714f565a6c5f76334d6fe42730a125f0a5d698205c7263739f082f56ba90bce85a06535f43157190c958",++ "info_i_hex": "6265616d65722d6672616d6573067dd820d674da2b465292b2a5456ff756220ca92180d4505b4ed33c9398f8d4120d5297c17a85a9a09d4bbaaacd973d9a171068c7f108f4169297cd84847dee3bb6c7450905c00ca9a4a5e6d0ed892c8deea001da3b4c3073963da9ab40e7c60801",++ "info_r_hex": "6265616d65722d6672616d6573067dd820d674da2b465292b2a5456ff756220ca92180d4505b4ed33c9398f8d4120d5297c17a85a9a09d4bbaaacd973d9a171068c7f108f4169297cd84847dee3bb6c7450905c00ca9a4a5e6d0ed892c8deea001da3b4c3073963da9ab40e7c60802",++ "key_i_hex": "56f347a5c2e2e7ea00674155bd179e73f5a36c07dedbc1e5df54c240e081141c",++ "key_r_hex": "3fdcd429dd860e6868b0d7a13d47495e4ba4f22b604c354d88a23030fc69b8a4"++ },++ {++ "comment": "the roles swapped: B initiates, A responds",++ "token": "KFX5cT76a4uBbZ-k66SlHbJJiHqvMrPcHqOVZl_v3Mo",++ "key_id_hex": "7dd820d674da2b465292b2a5456ff756",++ "prefix_i_hex": "4ed33c9398f8d412",++ "prefix_r_hex": "220ca92180d4505b",++ "secret_i_hex": "54555b4c654ed3274fd8c80bd13ec2a2b584921135988e83afcd7efc3074b910",++ "secret_r_hex": "553ed8446b237ba96d54d931ea20db6068889999f84a4697620053bce5448d2a",++ "share_i_hex": "b6c7450905c00ca9a4a5e6d0ed892c8deea001da3b4c3073963da9ab40e7c608",++ "share_r_hex": "0d5297c17a85a9a09d4bbaaacd973d9a171068c7f108f4169297cd84847dee3b",++ "shared_hex": "e42730a125f0a5d698205c7263739f082f56ba90bce85a06535f43157190c958",++ "ikm_hex": "4b4658356354373661347542625a2d6b3636536c48624a4a694871764d72506348714f565a6c5f76334d6fe42730a125f0a5d698205c7263739f082f56ba90bce85a06535f43157190c958",++ "info_i_hex": "6265616d65722d6672616d6573067dd820d674da2b465292b2a5456ff7564ed33c9398f8d412220ca92180d4505bb6c7450905c00ca9a4a5e6d0ed892c8deea001da3b4c3073963da9ab40e7c6080d5297c17a85a9a09d4bbaaacd973d9a171068c7f108f4169297cd84847dee3b01",++ "info_r_hex": "6265616d65722d6672616d6573067dd820d674da2b465292b2a5456ff7564ed33c9398f8d412220ca92180d4505bb6c7450905c00ca9a4a5e6d0ed892c8deea001da3b4c3073963da9ab40e7c6080d5297c17a85a9a09d4bbaaacd973d9a171068c7f108f4169297cd84847dee3b02",++ "key_i_hex": "a52f673491a53fd46e3fce9594c36e7f2cebaa2ce44b8341266eea36f49c5dec",++ "key_r_hex": "b065ffebf100b92677a67eee87dfe518ee38e8afab27762e652b271036ec3822"++ }++ ]++ },++ "low_order": {++ "$comment": "X25519 shares of low order, including the non-canonical spellings (u = p and p + 1, and each with bit 255 set, which X25519 ignores). Every one gives 32 zero bytes whatever the secret; a side that gets that result, or whose X25519 refuses the share, ends the handshake and sends nothing.",++ "secret_hex": "fbc88820911dfe5ad3a997933f2a714212cc62ec7db14d71764a4e15c9fadcd2",++ "shares": [++ {++ "comment": "00000000..., bit 255 as listed",++ "share_hex": "0000000000000000000000000000000000000000000000000000000000000000",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "00000000..., bit 255 set",++ "share_hex": "0000000000000000000000000000000000000000000000000000000000000080",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "01000000..., bit 255 as listed",++ "share_hex": "0100000000000000000000000000000000000000000000000000000000000000",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "01000000..., bit 255 set",++ "share_hex": "0100000000000000000000000000000000000000000000000000000000000080",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "ecffffff..., bit 255 as listed",++ "share_hex": "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "ecffffff..., bit 255 set",++ "share_hex": "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "e0eb7a7c..., bit 255 as listed",++ "share_hex": "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "e0eb7a7c..., bit 255 set",++ "share_hex": "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b880",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "5f9c95bc..., bit 255 as listed",++ "share_hex": "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "5f9c95bc..., bit 255 set",++ "share_hex": "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "edffffff..., bit 255 as listed",++ "share_hex": "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "edffffff..., bit 255 set",++ "share_hex": "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "eeffffff..., bit 255 as listed",++ "share_hex": "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ },++ {++ "comment": "eeffffff..., bit 255 set",++ "share_hex": "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",++ "result_hex": "0000000000000000000000000000000000000000000000000000000000000000"++ }++ ]++ },++ "frames": {++ "$comment": "Preambles and frames of scripted links, in order. `message` is the object sealed, `plaintext_json` its exact bytes as text (compact, UTF-8, keys in this order), `frame_hex` the whole frame as it crosses the wire: length, counter, ciphertext and tag. Each side counts its own frames from 1. A link's `initiator` and `responder` give the fixed prefix and ephemeral secret that made its keys.",++ "links": [++ {++ "name": "main",++ "comment": "One pair, scripted end to end: the handshake frames, announcements, a take that lands at an edge, the clipboard and input, an acknowledgement, the responder sending the owner on, and the owner letting go.",++ "token": "d29iG0O2IkW4GJvmmx4kRpgfPagOP8ghvKYxgUvSVQ0",++ "initiator": {++ "id_hex": "ce4b2ccf368aa44030114869407a1ece",++ "prefix_hex": "c5c3f7ed79d4e12c",++ "secret_hex": "fe8a413c1306dd7bbd26986e0280fa135ccd38356beebac8783dbc9aa5116b0f"++ },++ "responder": {++ "id_hex": "9555d20d2b689d2c5bf8685fbb7b3f12",++ "prefix_hex": "605aa2530bd47072",++ "secret_hex": "eb4ec40c13fb7820f32e721a91d6ccf235cabec6a2b756070f7dafcf7a03063a"++ },++ "preamble_i_hex": "4245414d5906c5c3f7ed79d4e12cdbe5d310859156474e1f2ebf2340d195e682c6ca79e54ef902baa846ae032b0838891c3581615710e39a88e150191f20",++ "preamble_r_hex": "4245414d5906605aa2530bd47072dbe5d310859156474e1f2ebf2340d1958a191ad26988c74fd4c5afe515da2c701991cb58e022d6bbf12bd0b16899d501",++ "frames": [++ {++ "direction": "initiator_to_responder",++ "counter": 1,++ "message": {++ "type": "hello",++ "data": {++ "version": 6,++ "id": "zksszzaKpEAwEUhpQHoezg",++ "name": "Zo\u00eb\u2019s \ud835\udd39eamer Mac",++ "platform": "macos",++ "app": "1.5.0",++ "caps": [++ "clipboard",++ "clipboard_image",++ "gestures",++ "media_keys",++ "text",++ "settings"++ ],++ "hw": "02:00:5e:10:00:01",++ "port": 24820++ }++ },++ "plaintext_json": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Zo\u00eb\u2019s \ud835\udd39eamer Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"clipboard_image\",\"gestures\",\"media_keys\",\"text\",\"settings\"],\"hw\":\"02:00:5e:10:00:01\",\"port\":24820}}",++ "frame_hex": "0000010f000000019d8e521f5109a56876d829db5ddaf5b206a033f29c830351a488889adcc5948fb4b5ce476283fbb9e6d93ef6937a270c88b7780d078a2e2b00cf5968b7daf225baacfc5a6229f1596b1ccf80ea5d25d94b4c90be19707e5be53a2e5913062ee37a524c2780eceee6d04cf67de999a3a4c8d9b2581038e8c440dd83f966103706a0a20fad71ce6b0f1f9778c23afaf4927c2fa732983db37b48a3b2cf6f281fa3504785fda0251df91cf4aea8157b8aea164e78104511096fabafaae0da2c177a194237cdf3b08208b07ad8a915d7ca4a64be48c04f566f405998cb1678edbf3076b9863ae583411b418bd2bb89fb18b083af3adf1716665ece318700e37d90c7c8fd13508f3dd5670b1c90"++ },++ {++ "direction": "responder_to_initiator",++ "counter": 1,++ "message": {++ "type": "welcome",++ "data": {++ "version": 6,++ "id": "lVXSDStonSxb-Ghfu3s_Eg",++ "name": "VECTOR-PC",++ "platform": "windows",++ "app": "1.5.0",++ "caps": [++ "clipboard",++ "clipboard_image",++ "gestures",++ "media_keys",++ "text",++ "settings"++ ],++ "hw": "02:00:5e:10:00:02",++ "accepts": true++ }++ },++ "plaintext_json": "{\"type\":\"welcome\",\"data\":{\"version\":6,\"id\":\"lVXSDStonSxb-Ghfu3s_Eg\",\"name\":\"VECTOR-PC\",\"platform\":\"windows\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"clipboard_image\",\"gestures\",\"media_keys\",\"text\",\"settings\"],\"hw\":\"02:00:5e:10:00:02\",\"accepts\":true}}",++ "frame_hex": "00000108000000016576d825fdf4783e905e01465424997d0b6553233cb2e36df6e04b6e2ba3dfccbc58836ef781a9bad7040a1ce35d9467e62b110961080b97a93745f70f9b51e43d01adabcd34a021be1ce7c593c9b920562686d75f93bd92d0915bb257ce6fd78dff15303357f1bd990dff8bdd8ec1f12c40a0c0805ef8cfc367b70f4d6993b5f3584efc0fedfe3d7c388e74555497dd264c5e57d07b087ec61f4b32f5980d96aef4a7ef2ac08cb62620707a01c751be5889fcd062173158ba7f0c72c214af479377c310086448e990eeb31551e04d7f56a73351b6d5048a3e9f038256ef8a3b76d80b2636508739f9562c7eb32988a8d4c4448d129b03cbf946775543959398668db819"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 2,++ "message": {++ "type": "paired",++ "data": {++ "ids": [++ "Jn0hacrGB0cVCWudQUQKuA"++ ]++ }++ },++ "plaintext_json": "{\"type\":\"paired\",\"data\":{\"ids\":[\"Jn0hacrGB0cVCWudQUQKuA\"]}}",++ "frame_hex": "0000004f00000002a6871f9b4ff9df8e456bd4f2c12d1fc56d1030acdda7810c5b014977dabd28252fe1d72e6e11146dd42852a076d642cbb1fc487bc981babe7f60be955e03fec2b3c701dc23d154f2125351"++ },++ {++ "direction": "responder_to_initiator",++ "counter": 2,++ "message": {++ "type": "paired",++ "data": {++ "ids": [++ "Jn0hacrGB0cVCWudQUQKuA"++ ]++ }++ },++ "plaintext_json": "{\"type\":\"paired\",\"data\":{\"ids\":[\"Jn0hacrGB0cVCWudQUQKuA\"]}}",++ "frame_hex": "0000004f000000028b09368f5e74591efc9585588a16e4fdf92109054f5ed6b0979d52074f2bb8b670293d4d68abab9f0d95b93db1cd74d79253e87ba74f15a77c97588071f443b76a5e94e0d02c6f499033d0"++ },++ {++ "direction": "responder_to_initiator",++ "counter": 3,++ "message": {++ "type": "arrangement",++ "data": {++ "edge": "left",++ "set_at": 1789999400,++ "by": "lVXSDStonSxb-Ghfu3s_Eg"++ }++ },++ "plaintext_json": "{\"type\":\"arrangement\",\"data\":{\"edge\":\"left\",\"set_at\":1789999400,\"by\":\"lVXSDStonSxb-Ghfu3s_Eg\"}}",++ "frame_hex": "0000007300000003e426356323c86a3889051f2f14b4537377163a18e5b4d71b00c0085f60e9e5edff905d673cd3fc1b60a4f75bbf91313fe3ef821ef59d20c1ba0200415c98b9ab86b73b5343a16fe9c77eb2477ee681b7d146b92e4397ddc2ea7bd243986f89c732d04b5281055a337235c9e0703abe"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 3,++ "message": {++ "type": "focus",++ "data": {++ "route": 1,++ "target": "lVXSDStonSxb-Ghfu3s_Eg",++ "edge": "left",++ "offset": 0.42,++ "resistance_px": 120,++ "reach": [++ "Jn0hacrGB0cVCWudQUQKuA"++ ]++ }++ },++ "plaintext_json": "{\"type\":\"focus\",\"data\":{\"route\":1,\"target\":\"lVXSDStonSxb-Ghfu3s_Eg\",\"edge\":\"left\",\"offset\":0.42,\"resistance_px\":120,\"reach\":[\"Jn0hacrGB0cVCWudQUQKuA\"]}}",++ "frame_hex": "000000ac00000003a3057fbcfc3e92098fa251288b41d028478b9b9b5835598ba6832816cf8f47adc78aef7b463115c191452fa26fb4ac354b55946534511197981dd149a0a6fe3d7901d295d296ec4657d538afc9168e186dd13cb757ba5d8dabbd1ccc5a0cd3a3b1787225fcd8c368a2fd9c8a5fc68d0daf171d4dd6003ca9e1f2742d2aaa6bfc7e7c381ac314c2cef48f0ad6d3267843aca43b7d8eb507f2efa834fe7aa951126d23c21df8e07724"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 4,++ "message": {++ "type": "clipboard",++ "data": {++ "text": "copied on the Mac"++ }++ },++ "plaintext_json": "{\"type\":\"clipboard\",\"data\":{\"text\":\"copied on the Mac\"}}",++ "frame_hex": "0000004c0000000452f5f1c94336db922478f292d9f7550e222175057f629682881eb1bfa102c8b3db539db342732b449193b70ee0ab0a20e2a93592f622d2f07199896aacc89c8af075d67005f53089"++ },++ {++ "direction": "responder_to_initiator",++ "counter": 4,++ "message": {++ "type": "accept",++ "data": {++ "route": 1++ }++ },++ "plaintext_json": "{\"type\":\"accept\",\"data\":{\"route\":1}}",++ "frame_hex": "0000003800000004c8dac67507deefdf4f7b8e35f98e3f3c55864d6dc894dbedc6d5483f6d19e965ab5d6822979ec8bb70443d76a48ae1778c41d887"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 5,++ "message": {++ "type": "mousemove",++ "data": {++ "dx": 12,++ "dy": -7,++ "seq": 1++ }++ },++ "plaintext_json": "{\"type\":\"mousemove\",\"data\":{\"dx\":12,\"dy\":-7,\"seq\":1}}",++ "frame_hex": "00000049000000051d4cf791dec65c49026221cf2ed6c09deb8fd89cd596db954633d6490f7c77c4f0371a26c14f796300876305ec959864ef34024fab8f59acc1a2d57b922ab72feb3882dede"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 6,++ "message": {++ "type": "keydown",++ "data": {++ "key": "a",++ "us": "a",++ "seq": 2++ }++ },++ "plaintext_json": "{\"type\":\"keydown\",\"data\":{\"key\":\"a\",\"us\":\"a\",\"seq\":2}}",++ "frame_hex": "0000004a0000000666bc213750e7b1e83b663550258b8b99fc9dcb8f602af5915a672b993668f7494f396607247411c410d4414319b213b4bd7049c17718102a4a215df047ba136db420e2fa6b2c"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 7,++ "message": {++ "type": "keyup",++ "data": {++ "key": "a",++ "us": "a",++ "seq": 3++ }++ },++ "plaintext_json": "{\"type\":\"keyup\",\"data\":{\"key\":\"a\",\"us\":\"a\",\"seq\":3}}",++ "frame_hex": "000000480000000733d109669480605fb22c7a39ab25d657815206d84002726212da70eec54175a731cdb4f262c99b7bef1db1cfdb2666e79f7d0bb239de24920c24124b38a5c032ebb1c5f1"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 8,++ "message": {++ "type": "text",++ "data": {++ "text": "caf\u00e9 \ud83d\ude00",++ "seq": 4++ }++ },++ "plaintext_json": "{\"type\":\"text\",\"data\":{\"text\":\"caf\u00e9 \ud83d\ude00\",\"seq\":4}}",++ "frame_hex": "0000004800000008e31bee6bad87639b502adb23e12dbd4504b6e5027ca661d7f5bb1b0cdb70d5d52caa5f61602a5540d5f9409576cf301720100095b90a9f0f4a1083c5e4902c26bf8822e4"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 9,++ "message": {++ "type": "mousedown",++ "data": {++ "button": "left",++ "seq": 5++ }++ },++ "plaintext_json": "{\"type\":\"mousedown\",\"data\":{\"button\":\"left\",\"seq\":5}}",++ "frame_hex": "000000490000000975e2ef1ca60f462c7d32fd9d666bc56e19c00e5dab059a36bc80745d965dddc1595a498b812890dfb88928e2372dfd4a59f03d6cf20e754eead6877c4b0039499d5552c36e"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 10,++ "message": {++ "type": "mouseup",++ "data": {++ "button": "left",++ "seq": 6++ }++ },++ "plaintext_json": "{\"type\":\"mouseup\",\"data\":{\"button\":\"left\",\"seq\":6}}",++ "frame_hex": "000000470000000a50c170db55401acfce9757876f53a11000c879e4247102f4d81cc6793eab8db88cdd3ace697a881413f0c0475ecf949b27deb066e1c155e054b902bc37abd00583cd4c"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 11,++ "message": {++ "type": "scroll",++ "data": {++ "dy": -14.5,++ "dx": 0,++ "mode": "pixel",++ "seq": 7++ }++ },++ "plaintext_json": "{\"type\":\"scroll\",\"data\":{\"dy\":-14.5,\"dx\":0,\"mode\":\"pixel\",\"seq\":7}}",++ "frame_hex": "000000570000000b8a5f54b155cfd6e7d0c4eb3c1a45ad8571bf5ab90aa1b6f013879406889d82b031b565da596d7a0930553ea72fe2e0676e3064ca2dc5842a0b924abc4b19fd00834175b02f2a09ffca2d79b9d36d698ba74a0e"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 12,++ "message": {++ "type": "gesture",++ "data": {++ "name": "swipe_left",++ "seq": 8++ }++ },++ "plaintext_json": "{\"type\":\"gesture\",\"data\":{\"name\":\"swipe_left\",\"seq\":8}}",++ "frame_hex": "0000004b0000000cd244598b570490f0fa01cf1fe2e0350157a2efa3672221fdf5aecbe14ed5bd9054e2cbb06c17309556c65d75be485b5fda450ad1bc0583041f616626476e4c94340f0ef9db830f"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 13,++ "message": {++ "type": "ping",++ "data": {}++ },++ "plaintext_json": "{\"type\":\"ping\",\"data\":{}}",++ "frame_hex": "0000002d0000000da02f62310d52b03292f14777394159c9367339c680fabfa33f99d33b62ce6d80a0ff8370a68f34197b"++ },++ {++ "direction": "responder_to_initiator",++ "counter": 5,++ "message": {++ "type": "accepts",++ "data": {++ "accepts": true++ }++ },++ "plaintext_json": "{\"type\":\"accepts\",\"data\":{\"accepts\":true}}",++ "frame_hex": "0000003e0000000599b393084eb2eae70848e3c7e743cc3f5faae07184dfc1761042bab70013692024983d89bef8000a6901db4de6b90b511f5717e298544ba1d187"++ },++ {++ "direction": "responder_to_initiator",++ "counter": 6,++ "message": {++ "type": "ack",++ "data": {++ "seq": 8,++ "held_us": 1830++ }++ },++ "plaintext_json": "{\"type\":\"ack\",\"data\":{\"seq\":8,\"held_us\":1830}}",++ "frame_hex": "0000004200000006e611a99b032eda628686253980746bddef3d45b7c6c328e91f52316254be42c5daf80c84e033abf0bbd56bda71add51f57d83373e270712926095b696390"++ },++ {++ "direction": "responder_to_initiator",++ "counter": 7,++ "message": {++ "type": "switch",++ "data": {++ "route": 1,++ "next": "Jn0hacrGB0cVCWudQUQKuA",++ "edge": "right",++ "offset": 0.5++ }++ },++ "plaintext_json": "{\"type\":\"switch\",\"data\":{\"route\":1,\"next\":\"Jn0hacrGB0cVCWudQUQKuA\",\"edge\":\"right\",\"offset\":0.5}}",++ "frame_hex": "0000007400000007f808d11519327258bddc308b5a9de58953e969ccab30cac544fa280832aea062588b3eb0f8cd835da0124ce7881132b2989fd34668f0ed24b76b4d9ff988ed70e7c87f664e0a3e9c01cd87160e8e2b80837a0805c101ad9baa15246274fabe979926ebc14c164a00dc0407b653fdfc73"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 14,++ "message": {++ "type": "focus",++ "data": {++ "route": 2,++ "target": "Jn0hacrGB0cVCWudQUQKuA"++ }++ },++ "plaintext_json": "{\"type\":\"focus\",\"data\":{\"route\":2,\"target\":\"Jn0hacrGB0cVCWudQUQKuA\"}}",++ "frame_hex": "000000590000000ed1c84c550417d1be3bb8e9eb8845d5aa1f37cb3522e7dcec619ba0fcd166f5474bbcb0c6521f4395848dd738236a4c1d00fb82d19fce75c2a1291f0976a2e4ffe3c9c572f5c654b488fc92a76bae289e674a1cdc86"++ }++ ]++ },++ {++ "name": "second_link_refuse",++ "comment": "Another machine's link to the same responder while the first owns it: its take is refused as owned.",++ "token": "JJFjICwLZafZiBuondxFwOjUj_UIEH-OldoT_rTAIG4",++ "initiator": {++ "id_hex": "267d2169cac6074715096b9d41440ab8",++ "prefix_hex": "1a2615b21c40c84d",++ "secret_hex": "e0cbc164f5af9c97b0a327d8116c456270d5c8d39fabd0a224c172db5be0a098"++ },++ "responder": {++ "id_hex": "9555d20d2b689d2c5bf8685fbb7b3f12",++ "prefix_hex": "784ad556f2a5cba6",++ "secret_hex": "c066580cfa3fbe16348d6451d99d5bbdb2f1f8a5ca91a5bcaee0d1b82bcebfa9"++ },++ "preamble_i_hex": "4245414d59061a2615b21c40c84d8492d0f3347a2df328167e8d9f7236f679c614403fffe59cdc41feb5fb791f1785022b17974107869c2cc46ee606ef1a",++ "preamble_r_hex": "4245414d5906784ad556f2a5cba68492d0f3347a2df328167e8d9f7236f648c64982e242b1fb668871100142da127e7cad213c76febdd31be82eae80872f",++ "frames": [++ {++ "direction": "initiator_to_responder",++ "counter": 1,++ "message": {++ "type": "hello",++ "data": {++ "version": 6,++ "id": "Jn0hacrGB0cVCWudQUQKuA",++ "name": "Vector Linux",++ "platform": "linux",++ "app": "1.5.0",++ "caps": [++ "text"++ ],++ "port": 24820++ }++ },++ "plaintext_json": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"Jn0hacrGB0cVCWudQUQKuA\",\"name\":\"Vector Linux\",\"platform\":\"linux\",\"app\":\"1.5.0\",\"caps\":[\"text\"],\"port\":24820}}",++ "frame_hex": "000000ab00000001c4ba3b8c0126062fb13075f5c71de0c282aca36e3dc48f93487b4b70463d206d44805f8ab984cfa7751757df78b9decf5b8ad21c93b0d7366ea41ad5965d48a9a26a7cff2ef8ad8772c2d54cf8f9e08e7128550d588f44956392fcff70ddc1e2c67b3372bfdf3adddf8f37ba5694dc3002ec93c93f4281df194430dd74cf4368d93a5cd06c9dfe140710e17348abc0b94725f0a4aae570b0d7d5d90323e5774b6bb5aa5816091f"++ },++ {++ "direction": "responder_to_initiator",++ "counter": 1,++ "message": {++ "type": "welcome",++ "data": {++ "version": 6,++ "id": "lVXSDStonSxb-Ghfu3s_Eg",++ "name": "VECTOR-PC",++ "platform": "windows",++ "app": "1.5.0",++ "caps": [++ "clipboard",++ "clipboard_image",++ "gestures",++ "media_keys",++ "text",++ "settings"++ ],++ "accepts": true++ }++ },++ "plaintext_json": "{\"type\":\"welcome\",\"data\":{\"version\":6,\"id\":\"lVXSDStonSxb-Ghfu3s_Eg\",\"name\":\"VECTOR-PC\",\"platform\":\"windows\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"clipboard_image\",\"gestures\",\"media_keys\",\"text\",\"settings\"],\"accepts\":true}}",++ "frame_hex": "000000ef00000001af092c709c7fbd25b8d36fea2b33c52b88279a82e46f41f45088294961a87979432a320fa92b75c22cd7e5951aba5e8dc4b2c33e1e8b5482f0774eae6ad61e7c1de7d7e5d806e99830e47c87269caa125f50ae5d912fdbb9fa404c376b6cff57ae2b84ae13012eed4a24f273bd92e115e25495e1f722b67f5ffc2146c0f0b41fdf37795e73c7f112f3ecb6174607047ff906ec6fe29080153615f9eb4b8784ac747efaf5d286b54591d456b70e5908a1e605c96abaa16859c203461ed0f2ecc9855fdf843717dd140130547c8db2737455dfb6f0da4b9ee0d32073e788c50c20b95c90c609e8d26860c8bf"++ },++ {++ "direction": "initiator_to_responder",++ "counter": 2,++ "message": {++ "type": "focus",++ "data": {++ "route": 1,++ "target": "lVXSDStonSxb-Ghfu3s_Eg",++ "edge": "right",++ "offset": 0.1,++ "resistance_px": 120,++ "reach": []++ }++ },++ "plaintext_json": "{\"type\":\"focus\",\"data\":{\"route\":1,\"target\":\"lVXSDStonSxb-Ghfu3s_Eg\",\"edge\":\"right\",\"offset\":0.1,\"resistance_px\":120,\"reach\":[]}}",++ "frame_hex": "000000940000000251f37e820ea254ead726a137ce40e73c1107cd3d1f5c673ea3c361ee5c2d4c3eded71d0e25e0a4805f15f937394af9abf67b3de8900328bce14bca61cc95f9017109f9385411ebce3009c92191765d62b53e35500ecd59884f1fb210696aa42c41b6e128a8fbd467e486c71ca6951d00596ff2e61333465a2f91a0319711c1810ab59461f783ed9fb425e90dd49be910"++ },++ {++ "direction": "responder_to_initiator",++ "counter": 2,++ "message": {++ "type": "refuse",++ "data": {++ "route": 1,++ "why": "owned"++ }++ },++ "plaintext_json": "{\"type\":\"refuse\",\"data\":{\"route\":1,\"why\":\"owned\"}}",++ "frame_hex": "0000004600000002096c632f95185455690c25ac05a2eeb5451d1a08459e22a52e13a806dbc00b0a206e75f8c52cb19b6949d8c9b3a6abfabe12ee2506a63acade0d0347bcf1b1d2346a"++ }++ ]++ },++ {++ "name": "invalid_hello",++ "comment": "A first frame that opens but is not a hello is answered with welcome carrying only version and error invalid_hello; the link then closes.",++ "token": "W9KV7C3NXUDKK_x6TNdudEriSq-SGZW23jt3H8ZnI60",++ "initiator": {++ "id_hex": "ce4b2ccf368aa44030114869407a1ece",++ "prefix_hex": "d50d5c6c63fe3a4e",++ "secret_hex": "33337ef2076e7ee274f2f79ccd15b8d1a056f82dc4f2cc2f483c67405ee7a72c"++ },++ "responder": {++ "id_hex": "9555d20d2b689d2c5bf8685fbb7b3f12",++ "prefix_hex": "31f49eeefa1a2c0c",++ "secret_hex": "63bb1a8be5def55ac28f0bfff8db6e5d80654277afab193c6dec4cd3aa417faf"++ },++ "preamble_i_hex": "4245414d5906d50d5c6c63fe3a4e19e1585cf1c9acb8eb7edf1ba8ce0c24a1f6c4d9be95fd931788eb9d3bc9e895bf90e5f7c15ba7bd09dacae715d3cb62",++ "preamble_r_hex": "4245414d590631f49eeefa1a2c0c19e1585cf1c9acb8eb7edf1ba8ce0c2401d1985943dabcf2e907d71c80046a930726833024d627b40b1bcf16cb7b9152",++ "frames": [++ {++ "direction": "initiator_to_responder",++ "counter": 1,++ "message": {++ "type": "ping",++ "data": {}++ },++ "plaintext_json": "{\"type\":\"ping\",\"data\":{}}",++ "frame_hex": "0000002d00000001155b51b387a13972cd4a7b86964d1c513f2cc57c3982e0a15584aacb5c06de898b47e019bbe9ccdf06"++ },++ {++ "direction": "responder_to_initiator",++ "counter": 1,++ "message": {++ "type": "welcome",++ "data": {++ "version": 6,++ "error": "invalid_hello"++ }++ },++ "plaintext_json": "{\"type\":\"welcome\",\"data\":{\"version\":6,\"error\":\"invalid_hello\"}}",++ "frame_hex": "0000005300000001b705e1aaa9270a4a035fd38d0bb4b43884ff098ffe10b9604abb14693e1c9e694470ab5e311c5d47631b05b6323679393c4ee2505a80048580df7ce01cde518b8093b589a3c66886e7220fbb8b1e67"++ }++ ]++ },++ {++ "name": "wrong_id",++ "comment": "A well-formed hello whose id is not the one the responder holds for this pair is answered with welcome carrying only version and error wrong_id.",++ "token": "WGMao3L3hwvO3EX60mvxck2GjKtFMH2laq6IpM4v6nA",++ "initiator": {++ "id_hex": "ce4b2ccf368aa44030114869407a1ece",++ "prefix_hex": "beead5deac3f4b87",++ "secret_hex": "f9ba84df4e1c8ba2214663941631ed6d2d700b5f2f4f0b01431dd6a06ce80b95"++ },++ "responder": {++ "id_hex": "9555d20d2b689d2c5bf8685fbb7b3f12",++ "prefix_hex": "312580750bbcd085",++ "secret_hex": "0423f1839d6babf78f9c7daf5fe17254b7401f26e1c9204e27ecdfa4a8e5eaf5"++ },++ "preamble_i_hex": "4245414d5906beead5deac3f4b879e9bd4ee287885019bc02ec20cdb08c4977e757f406758ce95be25eaced26ef23bf52800ab0df9ce0900b1ed8f645a0d",++ "preamble_r_hex": "4245414d5906312580750bbcd0859e9bd4ee287885019bc02ec20cdb08c47431f522394d9b2153dcc53ad88ca6aac3fa72b6043108ab307b2859e19c7e51",++ "frames": [++ {++ "direction": "initiator_to_responder",++ "counter": 1,++ "message": {++ "type": "hello",++ "data": {++ "version": 6,++ "id": "8FBlxLFvgwCi51Lrwo3i_g",++ "name": "Not the paired machine",++ "platform": "macos",++ "app": "1.5.0",++ "caps": [++ "clipboard",++ "clipboard_image",++ "gestures",++ "media_keys",++ "text",++ "settings"++ ],++ "port": 24820++ }++ },++ "plaintext_json": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"8FBlxLFvgwCi51Lrwo3i_g\",\"name\":\"Not the paired machine\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"clipboard_image\",\"gestures\",\"media_keys\",\"text\",\"settings\"],\"port\":24820}}",++ "frame_hex": "000000f6000000019e27e5e544a4c753d5237054484603d59926a6200d6e2e02fe338ca02cdf0a9cc35aa6428e5b026159f6ff7db8a0765600893a785db5e16c21bd5b7fdbc21c7e3e7d0085d8c8b523a58575457d8c3bea7e681c29ab30a8c9d5d50246deca02cece8b44a17cbfd591ed93233f602c5779ab88e7f5983415428df469fd6a2862e0c60a6f1a1daa86cc9cea77917809d1e8fe9bcdc2fb07e65691100a4ad75380b4c27cf3c34a5b5261405fb8021e3af1a63299d0a6c66d8e39edd655a360fee0763c42e7c3af2d34185e6ca6dc2b79b1a08112325dbeb7df96edaa1140bbec9986d1c417bdd74b1da1cd99f3b3f70b5de93a1b"++ },++ {++ "direction": "responder_to_initiator",++ "counter": 1,++ "message": {++ "type": "welcome",++ "data": {++ "version": 6,++ "error": "wrong_id"++ }++ },++ "plaintext_json": "{\"type\":\"welcome\",\"data\":{\"version\":6,\"error\":\"wrong_id\"}}",++ "frame_hex": "0000004e00000001caa4c615aa97b5c59f6cdabb9cf21ba1768d0d3ca880be843d2fe2a4b044854e0938eaedbd863b9a2fca37b096d21e0b01bf915356faa5d0886618918977b6ec26490f762ebf6c40149c"++ }++ ],++ "wrong_id_hello_id_hex": "f05065c4b16f8300a2e752ebc28de2fe"++ }++ ]++ },++ "bad_frames": {++ "$comment": "Each case is offered to a responder that has accepted nothing yet; it must end the link without sending a byte. `good_frame_hex` is the untouched first frame the cases are made from.",++ "link": {++ "name": "bad_frames",++ "token": "IjioTbViP1kHl1gukLz7GcTOFand1k4XTsSA-DhOsfY",++ "initiator": {++ "id_hex": "ce4b2ccf368aa44030114869407a1ece",++ "prefix_hex": "256a5372d069b984",++ "secret_hex": "f3bdb5ab7657f74c0c5a9d732774d48a6399c284ffa8e17a775ed9cf2e82a26d"++ },++ "responder": {++ "id_hex": "9555d20d2b689d2c5bf8685fbb7b3f12",++ "prefix_hex": "8724b439eab12036",++ "secret_hex": "6f65ce0958ed710c7443ef34bf78a8e8891feceb7ff1a0a2bcf25ac8c80b67c3"++ },++ "preamble_i_hex": "4245414d5906256a5372d069b9848b279bca95deb36543f1c9d126da65cc3bf8204d02aa88975f62d0ff8667e7161fbdb8b0beb2946bc8a095ddd082c30a",++ "preamble_r_hex": "4245414d59068724b439eab120368b279bca95deb36543f1c9d126da65cc85076dbb7587f8d1e44378f3783c60fadbd24fc4d6af89553c4af2a356539316"++ },++ "good_message": {++ "type": "hello",++ "data": {++ "version": 6,++ "id": "zksszzaKpEAwEUhpQHoezg",++ "name": "Vector Mac",++ "platform": "macos",++ "app": "1.5.0",++ "caps": [++ "text"++ ],++ "port": 24820++ }++ },++ "good_frame_hex": "000000a900000001ae2c9c3e4c81ff61fda7b1bcbf59580ae7b7757e6217750ffee65c144956f722240dee7d6d426e8e780bb9a007243d46f57890d494af15b01e7a0471c04e0f3cf97c743edb8f2daffdeb872d7fca46f22e4dafd10a6a0be38e41ef561d924bccd0ab10249899448a09c65162e5c012b8395114dc1612e1bc103d3d1940f50859c2f578e5ad3b445d3a01e9294c9bf7f6345533549b628f818cece55116a8cf1ab5644280b0",++ "cases": [++ {++ "comment": "the last tag byte flipped",++ "receiver": "responder",++ "frame_hex": "000000a900000001ae2c9c3e4c81ff61fda7b1bcbf59580ae7b7757e6217750ffee65c144956f722240dee7d6d426e8e780bb9a007243d46f57890d494af15b01e7a0471c04e0f3cf97c743edb8f2daffdeb872d7fca46f22e4dafd10a6a0be38e41ef561d924bccd0ab10249899448a09c65162e5c012b8395114dc1612e1bc103d3d1940f50859c2f578e5ad3b445d3a01e9294c9bf7f6345533549b628f818cece55116a8cf1ab5644280b1",++ "must": "close_without_reply"++ },++ {++ "comment": "a skipped counter: a valid hello sealed as counter 2, offered as the first frame",++ "receiver": "responder",++ "frame_hex": "000000a9000000022c6e825c24d7151aa9ee61ba7e86c0476eea67da477089082bb3b906fe9e5c3fbf7b61568f7607badfe06fac7ab45ff144f65de64dc315af6c366383b204057469aed3c26c8f6b6fdd7bd3f43ad14e565c6c50c29fb877f0d1df2ed3b31478754f430da52a37e8fd7be8097dd196fd25ac49479715b74dc435525498e464a9858f8bd4a377abaadabb127342cb596f7dc8179e784cf89013e217e6c8fb52dae1697ff78168",++ "must": "close_without_reply"++ },++ {++ "comment": "sealed in the wrong direction: a frame the responder sealed, offered to the responder",++ "receiver": "responder",++ "frame_hex": "0000002d00000001677c0a6bf1da5f56ab82ed5b41c1294bbb928ed80769e4fb782635b95a6bb4d5437b8b4f51f0a0fd24",++ "must": "close_without_reply"++ }++ ]++ },++ "ids": {++ "$comment": "A machine id is 16 bytes in JSON as URL-safe base64 without padding, 22 characters, in its one spelling: decode, encode again, refuse the text if it differs.",++ "cases": [++ {++ "id_hex": "447bc174a9c1124cfdc36e239ebea541",++ "b64": "RHvBdKnBEkz9w24jnr6lQQ"++ },++ {++ "id_hex": "0c9416bd1e4476edbeca782cc83d0e7f",++ "b64": "DJQWvR5Edu2-yngsyD0Ofw"++ },++ {++ "id_hex": "fbffbf11111111111111111111111111",++ "b64": "-_-_EREREREREREREREREQ"++ }++ ],++ "refused": [++ {++ "kind": "non_canonical",++ "comment": "padding added",++ "text": "RHvBdKnBEkz9w24jnr6lQQ==",++ "id_hex": "447bc174a9c1124cfdc36e239ebea541"++ },++ {++ "kind": "non_canonical",++ "comment": "the standard alphabet, + and / for - and _",++ "text": "+/+/EREREREREREREREREQ",++ "id_hex": "fbffbf11111111111111111111111111"++ },++ {++ "kind": "non_canonical",++ "comment": "the last character changed in its unused bits",++ "text": "RHvBdKnBEkz9w24jnr6lQR",++ "id_hex": "447bc174a9c1124cfdc36e239ebea541"++ },++ {++ "kind": "all_zero",++ "comment": "sixteen zero bytes are never an id",++ "text": "AAAAAAAAAAAAAAAAAAAAAA"++ },++ {++ "kind": "wrong_length",++ "comment": "15 bytes",++ "text": "RHvBdKnBEkz9w24jnr6l"++ },++ {++ "kind": "wrong_length",++ "comment": "17 bytes",++ "text": "RHvBdKnBEkz9w24jnr6lQQc"++ },++ {++ "kind": "whitespace",++ "comment": "a leading space",++ "text": " RHvBdKnBEkz9w24jnr6lQQ"++ },++ {++ "kind": "non_ascii",++ "comment": "a character outside ASCII",++ "text": "RHvBdKnBEkz9w24jnr6lQ\u00e9"++ }++ ]++ },++ "malformed": {++ "$comment": "Message bodies a receiver must not act on, and what a desktop does with each: `end_link` ends the link, `ignore` drops the message and the link goes on, `answer_invalid_hello` is a first frame answered with welcome carrying error invalid_hello (and the link closed). `reader` says which validator a desktop reads it with: a hello or welcome as the first frame each way, an ack, or any other message. `also_acceptable` is for a text a JSON parser may refuse outright (WIRE.md, Encodings): ending the link instead of ignoring it is allowed. `well_formed_hello` is accepted, so the refusals around it mean something.",++ "well_formed_hello": {++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}"++ },++ "cases": [++ {++ "comment": "an integer written 1.0 (dx)",++ "hex": "7b2274797065223a226d6f7573656d6f7665222c2264617461223a7b226478223a312e302c226479223a302c22736571223a317d7d",++ "text": "{\"type\":\"mousemove\",\"data\":{\"dx\":1.0,\"dy\":0,\"seq\":1}}",++ "reader": "input",++ "action": "ignore"++ },++ {++ "comment": "an integer written 1e0 (seq)",++ "hex": "7b2274797065223a226d6f7573656d6f7665222c2264617461223a7b226478223a312c226479223a302c22736571223a3165307d7d",++ "text": "{\"type\":\"mousemove\",\"data\":{\"dx\":1,\"dy\":0,\"seq\":1e0}}",++ "reader": "input",++ "action": "ignore"++ },++ {++ "comment": "a boolean for an integer (seq)",++ "hex": "7b2274797065223a226d6f7573656d6f7665222c2264617461223a7b226478223a312c226479223a302c22736571223a747275657d7d",++ "text": "{\"type\":\"mousemove\",\"data\":{\"dx\":1,\"dy\":0,\"seq\":true}}",++ "reader": "input",++ "action": "ignore"++ },++ {++ "comment": "a boolean for an integer (dx)",++ "hex": "7b2274797065223a226d6f7573656d6f7665222c2264617461223a7b226478223a66616c73652c226479223a302c22736571223a317d7d",++ "text": "{\"type\":\"mousemove\",\"data\":{\"dx\":false,\"dy\":0,\"seq\":1}}",++ "reader": "input",++ "action": "ignore"++ },++ {++ "comment": "NaN in a number",++ "hex": "7b2274797065223a227363726f6c6c222c2264617461223a7b226479223a4e614e2c226478223a302c226d6f6465223a226c696e65222c22736571223a317d7d",++ "text": "{\"type\":\"scroll\",\"data\":{\"dy\":NaN,\"dx\":0,\"mode\":\"line\",\"seq\":1}}",++ "reader": "input",++ "action": "ignore",++ "also_acceptable": "end_link"++ },++ {++ "comment": "Infinity in a number",++ "hex": "7b2274797065223a227363726f6c6c222c2264617461223a7b226479223a496e66696e6974792c226478223a302c226d6f6465223a226c696e65222c22736571223a317d7d",++ "text": "{\"type\":\"scroll\",\"data\":{\"dy\":Infinity,\"dx\":0,\"mode\":\"line\",\"seq\":1}}",++ "reader": "input",++ "action": "ignore",++ "also_acceptable": "end_link"++ },++ {++ "comment": "a byte order mark before the object",++ "hex": "efbbbf7b2274797065223a226d6f7573656d6f7665222c2264617461223a7b226478223a312c226479223a302c22736571223a317d7d",++ "text": "\ufeff{\"type\":\"mousemove\",\"data\":{\"dx\":1,\"dy\":0,\"seq\":1}}",++ "reader": "input",++ "action": "ignore",++ "also_acceptable": "end_link"++ },++ {++ "comment": "a lone surrogate in a string",++ "hex": "7b2274797065223a2274657874222c2264617461223a7b2274657874223a225c7564383030222c22736571223a317d7d",++ "text": "{\"type\":\"text\",\"data\":{\"text\":\"\\ud800\",\"seq\":1}}",++ "reader": "input",++ "action": "ignore",++ "also_acceptable": "end_link"++ },++ {++ "comment": "not an object: an array",++ "hex": "5b312c325d",++ "text": "[1,2]",++ "reader": "message",++ "action": "end_link"++ },++ {++ "comment": "not an object: a number",++ "hex": "37",++ "text": "7",++ "reader": "message",++ "action": "end_link"++ },++ {++ "comment": "not UTF-8",++ "hex": "fffe7b7d",++ "text": null,++ "reader": "message",++ "action": "end_link"++ },++ {++ "comment": "no type",++ "hex": "7b2264617461223a7b7d7d",++ "text": "{\"data\":{}}",++ "reader": "message",++ "action": "ignore"++ },++ {++ "comment": "a type that is not a string",++ "hex": "7b2274797065223a352c2264617461223a7b7d7d",++ "text": "{\"type\":5,\"data\":{}}",++ "reader": "message",++ "action": "ignore"++ },++ {++ "comment": "data that is not an object",++ "hex": "7b2274797065223a2270696e67222c2264617461223a5b5d7d",++ "text": "{\"type\":\"ping\",\"data\":[]}",++ "reader": "message",++ "action": "ignore"++ },++ {++ "comment": "hello: hw in upper case",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35453a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5E:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: hw too short",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a3565227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: app empty",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: app over 32 characters",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22787878787878787878787878787878787878787878787878787878787878787878222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: app outside printable ASCII",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e305c7530306539222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\\u00e9\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: caps not a list",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a22636c6970626f617264222c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":\"clipboard\",\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: more than 16 caps",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b2263617030222c2263617031222c2263617032222c2263617033222c2263617034222c2263617035222c2263617036222c2263617037222c2263617038222c2263617039222c226361703130222c226361703131222c226361703132222c226361703133222c226361703134222c226361703135222c226361703136225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"cap0\",\"cap1\",\"cap2\",\"cap3\",\"cap4\",\"cap5\",\"cap6\",\"cap7\",\"cap8\",\"cap9\",\"cap10\",\"cap11\",\"cap12\",\"cap13\",\"cap14\",\"cap15\",\"cap16\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: an empty cap",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b2274657874222c22225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"text\",\"\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: a cap that is not a string",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b2274657874222c355d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"text\",5],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: platform with a space",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a224d6163204f53222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"Mac OS\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: platform over 16 characters",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226161616161616161616161616161616161222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"aaaaaaaaaaaaaaaaa\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: name empty",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: name of 49 code points",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a226e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e6e222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: id of sixteen zero bytes",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a2241414141414141414141414141414141414141414141222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"AAAAAAAAAAAAAAAAAAAAAA\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: id of the wrong length",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f65222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoe\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: version 5",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a352c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a32343832302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":5,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":24820,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: port above 65535",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a36353533362c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":65536,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: port as a string",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a223234383230222c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":\"24820\",\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "hello: port written 1.0",++ "hex": "7b2274797065223a2268656c6c6f222c2264617461223a7b2276657273696f6e223a362c226964223a227a6b73737a7a614b704541774555687051486f657a67222c226e616d65223a22566563746f72204d6163222c22706c6174666f726d223a226d61636f73222c22617070223a22312e352e30222c2263617073223a5b22636c6970626f617264222c2274657874225d2c22706f7274223a312e302c226877223a2230323a30303a35653a31303a30303a3031227d7d",++ "text": "{\"type\":\"hello\",\"data\":{\"version\":6,\"id\":\"zksszzaKpEAwEUhpQHoezg\",\"name\":\"Vector Mac\",\"platform\":\"macos\",\"app\":\"1.5.0\",\"caps\":[\"clipboard\",\"text\"],\"port\":1.0,\"hw\":\"02:00:5e:10:00:01\"}}",++ "reader": "hello",++ "action": "answer_invalid_hello"++ },++ {++ "comment": "welcome: accepts as a string",++ "hex": "7b2274797065223a2277656c636f6d65222c2264617461223a7b2276657273696f6e223a362c226964223a226c5658534453746f6e5378622d4768667533735f4567222c226e616d65223a22564543544f522d5043222c22706c6174666f726d223a2277696e646f7773222c22617070223a22312e352e30222c2263617073223a5b2274657874225d2c2261636365707473223a2274727565227d7d",++ "text": "{\"type\":\"welcome\",\"data\":{\"version\":6,\"id\":\"lVXSDStonSxb-Ghfu3s_Eg\",\"name\":\"VECTOR-PC\",\"platform\":\"windows\",\"app\":\"1.5.0\",\"caps\":[\"text\"],\"accepts\":\"true\"}}",++ "reader": "welcome",++ "action": "end_link"++ },++ {++ "comment": "welcome: accepts missing",++ "hex": "7b2274797065223a2277656c636f6d65222c2264617461223a7b2276657273696f6e223a362c226964223a226c5658534453746f6e5378622d4768667533735f4567222c226e616d65223a22564543544f522d5043222c22706c6174666f726d223a2277696e646f7773222c22617070223a22312e352e30222c2263617073223a5b2274657874225d7d7d",++ "text": "{\"type\":\"welcome\",\"data\":{\"version\":6,\"id\":\"lVXSDStonSxb-Ghfu3s_Eg\",\"name\":\"VECTOR-PC\",\"platform\":\"windows\",\"app\":\"1.5.0\",\"caps\":[\"text\"]}}",++ "reader": "welcome",++ "action": "end_link"++ },++ {++ "comment": "welcome: an error that is not one of the two",++ "hex": "7b2274797065223a2277656c636f6d65222c2264617461223a7b2276657273696f6e223a362c226572726f72223a22676f5f61776179227d7d",++ "text": "{\"type\":\"welcome\",\"data\":{\"version\":6,\"error\":\"go_away\"}}",++ "reader": "welcome",++ "action": "end_link"++ },++ {++ "comment": "welcome: id of sixteen zero bytes",++ "hex": "7b2274797065223a2277656c636f6d65222c2264617461223a7b2276657273696f6e223a362c226964223a2241414141414141414141414141414141414141414141222c226e616d65223a22564543544f522d5043222c22706c6174666f726d223a2277696e646f7773222c22617070223a22312e352e30222c2263617073223a5b2274657874225d2c2261636365707473223a747275657d7d",++ "text": "{\"type\":\"welcome\",\"data\":{\"version\":6,\"id\":\"AAAAAAAAAAAAAAAAAAAAAA\",\"name\":\"VECTOR-PC\",\"platform\":\"windows\",\"app\":\"1.5.0\",\"caps\":[\"text\"],\"accepts\":true}}",++ "reader": "welcome",++ "action": "end_link"++ },++ {++ "comment": "welcome: version 5",++ "hex": "7b2274797065223a2277656c636f6d65222c2264617461223a7b2276657273696f6e223a352c226964223a226c5658534453746f6e5378622d4768667533735f4567222c226e616d65223a22564543544f522d5043222c22706c6174666f726d223a2277696e646f7773222c22617070223a22312e352e30222c2263617073223a5b2274657874225d2c2261636365707473223a747275657d7d",++ "text": "{\"type\":\"welcome\",\"data\":{\"version\":5,\"id\":\"lVXSDStonSxb-Ghfu3s_Eg\",\"name\":\"VECTOR-PC\",\"platform\":\"windows\",\"app\":\"1.5.0\",\"caps\":[\"text\"],\"accepts\":true}}",++ "reader": "welcome",++ "action": "end_link"++ },++ {++ "comment": "ack: seq written 1.0",++ "hex": "7b2274797065223a2261636b222c2264617461223a7b22736571223a312e302c2268656c645f7573223a307d7d",++ "text": "{\"type\":\"ack\",\"data\":{\"seq\":1.0,\"held_us\":0}}",++ "reader": "ack",++ "action": "end_link"++ },++ {++ "comment": "ack: held_us negative",++ "hex": "7b2274797065223a2261636b222c2264617461223a7b22736571223a312c2268656c645f7573223a2d317d7d",++ "text": "{\"type\":\"ack\",\"data\":{\"seq\":1,\"held_us\":-1}}",++ "reader": "ack",++ "action": "end_link"++ },++ {++ "comment": "ack: held_us above 2^31 - 1",++ "hex": "7b2274797065223a2261636b222c2264617461223a7b22736571223a312c2268656c645f7573223a323134373438333634387d7d",++ "text": "{\"type\":\"ack\",\"data\":{\"seq\":1,\"held_us\":2147483648}}",++ "reader": "ack",++ "action": "end_link"++ },++ {++ "comment": "ack: held_us missing",++ "hex": "7b2274797065223a2261636b222c2264617461223a7b22736571223a317d7d",++ "text": "{\"type\":\"ack\",\"data\":{\"seq\":1}}",++ "reader": "ack",++ "action": "end_link"++ },++ {++ "comment": "ack: locked false",++ "hex": "7b2274797065223a2261636b222c2264617461223a7b22736571223a312c2268656c645f7573223a302c226c6f636b6564223a66616c73657d7d",++ "text": "{\"type\":\"ack\",\"data\":{\"seq\":1,\"held_us\":0,\"locked\":false}}",++ "reader": "ack",++ "action": "end_link"++ },++ {++ "comment": "accept: route 0",++ "hex": "7b2274797065223a22616363657074222c2264617461223a7b22726f757465223a307d7d",++ "text": "{\"type\":\"accept\",\"data\":{\"route\":0}}",++ "reader": "accept",++ "action": "ignore"++ },++ {++ "comment": "accept: route as a string",++ "hex": "7b2274797065223a22616363657074222c2264617461223a7b22726f757465223a2231227d7d",++ "text": "{\"type\":\"accept\",\"data\":{\"route\":\"1\"}}",++ "reader": "accept",++ "action": "ignore"++ },++ {++ "comment": "refuse: no route",++ "hex": "7b2274797065223a22726566757365222c2264617461223a7b22776879223a226f776e6564227d7d",++ "text": "{\"type\":\"refuse\",\"data\":{\"why\":\"owned\"}}",++ "reader": "refuse",++ "action": "ignore"++ },++ {++ "comment": "switch: next of sixteen zero bytes",++ "hex": "7b2274797065223a22737769746368222c2264617461223a7b22726f757465223a312c226e657874223a2241414141414141414141414141414141414141414141227d7d",++ "text": "{\"type\":\"switch\",\"data\":{\"route\":1,\"next\":\"AAAAAAAAAAAAAAAAAAAAAA\"}}",++ "reader": "switch",++ "action": "ignore"++ },++ {++ "comment": "switch: edge without offset",++ "hex": "7b2274797065223a22737769746368222c2264617461223a7b22726f757465223a312c226e657874223a224a6e30686163724742306356435775645155514b7541222c2265646765223a226c656674227d7d",++ "text": "{\"type\":\"switch\",\"data\":{\"route\":1,\"next\":\"Jn0hacrGB0cVCWudQUQKuA\",\"edge\":\"left\"}}",++ "reader": "switch",++ "action": "ignore"++ },++ {++ "comment": "switch: an edge that is not one",++ "hex": "7b2274797065223a22737769746368222c2264617461223a7b22726f757465223a312c226e657874223a224a6e30686163724742306356435775645155514b7541222c2265646765223a226d6964646c65222c226f6666736574223a302e357d7d",++ "text": "{\"type\":\"switch\",\"data\":{\"route\":1,\"next\":\"Jn0hacrGB0cVCWudQUQKuA\",\"edge\":\"middle\",\"offset\":0.5}}",++ "reader": "switch",++ "action": "ignore"++ }++ ],++ "implementation_defined": [++ {++ "comment": "a repeated key: a receiver may refuse the message or keep the last value (WIRE.md, Encodings); a desktop ignores it, and a correct sender never sends one",++ "hex": "7b2274797065223a226d6f7573656d6f7665222c2264617461223a7b226478223a312c226478223a322c226479223a302c22736571223a317d7d",++ "text": "{\"type\":\"mousemove\",\"data\":{\"dx\":1,\"dx\":2,\"dy\":0,\"seq\":1}}",++ "reader": "input",++ "desktop_action": "ignore"++ }++ ]++ },++ "qr": {++ "$comment": "The text a pairing QR holds: four keys in order, lower case, each once, nothing else. `k` is the code's 16-byte QR secret as 22 characters of b64.",++ "good": [++ {++ "text": "beamer://pair?host=192.168.0.7&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "host": "192.168.0.7",++ "port": 24821,++ "code": "482913",++ "secret_hex": "6ebbd1aaed8cca13a16d964c027a9f5a"++ },++ {++ "text": "beamer://pair?host=192.168.1.20&port=24821&code=007045&k=1K4lYhJOxhk3Ka_ys0hZag",++ "host": "192.168.1.20",++ "port": 24821,++ "code": "007045",++ "secret_hex": "d4ae2562124ec6193729aff2b348596a"++ }++ ],++ "bad": [++ {++ "comment": "the wrong scheme",++ "text": "beamerx://pair?host=192.168.0.7&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a slash before the query",++ "text": "beamer://pair/?host=192.168.0.7&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "no k",++ "text": "beamer://pair?host=192.168.0.7&port=24821&code=482913",++ "error": "bad_qr"++ },++ {++ "comment": "an extra key",++ "text": "beamer://pair?host=192.168.0.7&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg&x=1",++ "error": "bad_qr"++ },++ {++ "comment": "the keys in another order",++ "text": "beamer://pair?port=24821&host=192.168.0.7&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "an upper-case key",++ "text": "beamer://pair?Host=192.168.0.7&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a repeated key",++ "text": "beamer://pair?host=192.168.0.7&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a host with a leading zero octet",++ "text": "beamer://pair?host=192.168.0.07&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a host that is a name",++ "text": "beamer://pair?host=beamer.example&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a host of five octets",++ "text": "beamer://pair?host=192.168.0.7.5&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a host octet above 255",++ "text": "beamer://pair?host=192.168.0.256&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "port 0",++ "text": "beamer://pair?host=192.168.0.7&port=0&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "port 65536",++ "text": "beamer://pair?host=192.168.0.7&port=65536&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a port with a leading zero",++ "text": "beamer://pair?host=192.168.0.7&port=024821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a port with a sign",++ "text": "beamer://pair?host=192.168.0.7&port=+24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a port with a digit percent-encoded: the text is read as it is",++ "text": "beamer://pair?host=192.168.0.7&port=%32%34821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a code of five digits",++ "text": "beamer://pair?host=192.168.0.7&port=24821&code=48291&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a code with a letter",++ "text": "beamer://pair?host=192.168.0.7&port=24821&code=48291a&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "a code in full-width digits",++ "text": "beamer://pair?host=192.168.0.7&port=24821&code=\uff14\uff18\uff12\uff19\uff11\uff13&k=brvRqu2MyhOhbZZMAnqfWg",++ "error": "bad_qr"++ },++ {++ "comment": "k of 21 characters",++ "text": "beamer://pair?host=192.168.0.7&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfW",++ "error": "bad_qr"++ },++ {++ "comment": "k with padding",++ "text": "beamer://pair?host=192.168.0.7&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWg==",++ "error": "bad_qr"++ },++ {++ "comment": "k in a non-canonical spelling: its last character changed in its unused bits",++ "text": "beamer://pair?host=192.168.0.7&port=24821&code=482913&k=brvRqu2MyhOhbZZMAnqfWh",++ "error": "bad_qr"++ },++ {++ "comment": "k in the standard alphabet, + and / for - and _",++ "text": "beamer://pair?host=192.168.0.7&port=24821&code=482913&k=+/+/AAAAAAAAAAAAAAAAAA",++ "error": "bad_qr"++ }++ ]++ },++ "key_table": {++ "$comment": "WIRE.md section 7's table. `sender` is the family of the machine whose key was pressed (mac: macos and ios; pc: every other platform, an unknown one included); `physical` is the key on that machine's own keyboard; the columns are the name it travels as to a peer of the same family and across families under each saved style. `evdev` maps a Linux sender's key codes to physical names; a code not in it is a character key.",++ "mac_platforms": [++ "ios",++ "macos"++ ],++ "unknown_platform_is": "pc",++ "rows": [++ {++ "key": "Mac Control",++ "sender": "mac",++ "physical": "ctrl",++ "same_family": "ctrl",++ "across_semantic": "cmd",++ "across_positional": "ctrl",++ "across_mac_layout": "\u2014"++ },++ {++ "key": "Mac right Control",++ "sender": "mac",++ "physical": "ctrl_r",++ "same_family": "ctrl_r",++ "across_semantic": "cmd",++ "across_positional": "ctrl",++ "across_mac_layout": "\u2014"++ },++ {++ "key": "Mac Command",++ "sender": "mac",++ "physical": "cmd",++ "same_family": "cmd",++ "across_semantic": "ctrl",++ "across_positional": "cmd",++ "across_mac_layout": "\u2014"++ },++ {++ "key": "Mac right Command",++ "sender": "mac",++ "physical": "cmd_r",++ "same_family": "cmd_r",++ "across_semantic": "ctrl",++ "across_positional": "cmd",++ "across_mac_layout": "\u2014"++ },++ {++ "key": "Mac Option",++ "sender": "mac",++ "physical": "alt",++ "same_family": "alt",++ "across_semantic": "alt",++ "across_positional": "alt",++ "across_mac_layout": "\u2014"++ },++ {++ "key": "Mac right Option",++ "sender": "mac",++ "physical": "alt_r",++ "same_family": "alt_r",++ "across_semantic": "alt",++ "across_positional": "alt",++ "across_mac_layout": "\u2014"++ },++ {++ "key": "PC Control",++ "sender": "pc",++ "physical": "ctrl",++ "same_family": "ctrl",++ "across_semantic": "cmd",++ "across_positional": "ctrl",++ "across_mac_layout": "ctrl"++ },++ {++ "key": "PC right Control",++ "sender": "pc",++ "physical": "ctrl_r",++ "same_family": "ctrl_r",++ "across_semantic": "cmd_r",++ "across_positional": "ctrl_r",++ "across_mac_layout": "ctrl_r"++ },++ {++ "key": "PC Windows or Super",++ "sender": "pc",++ "physical": "cmd",++ "same_family": "cmd",++ "across_semantic": "ctrl",++ "across_positional": "cmd",++ "across_mac_layout": "alt"++ },++ {++ "key": "PC right Windows or Super",++ "sender": "pc",++ "physical": "cmd_r",++ "same_family": "cmd_r",++ "across_semantic": "ctrl_r",++ "across_positional": "cmd_r",++ "across_mac_layout": "alt_r"++ },++ {++ "key": "PC Alt",++ "sender": "pc",++ "physical": "alt",++ "same_family": "alt",++ "across_semantic": "alt",++ "across_positional": "alt",++ "across_mac_layout": "cmd"++ },++ {++ "key": "PC right Alt or AltGr",++ "sender": "pc",++ "physical": "alt_r",++ "same_family": "alt_r",++ "across_semantic": "alt_r",++ "across_positional": "alt_r",++ "across_mac_layout": "cmd_r"++ }++ ],++ "names": [++ "alt",++ "alt_r",++ "backspace",++ "browser_back",++ "browser_forward",++ "caps_lock",++ "cmd",++ "cmd_r",++ "ctrl",++ "ctrl_r",++ "delete",++ "down",++ "end",++ "enter",++ "esc",++ "f1",++ "f10",++ "f11",++ "f12",++ "f13",++ "f14",++ "f15",++ "f16",++ "f17",++ "f18",++ "f19",++ "f2",++ "f20",++ "f21",++ "f22",++ "f23",++ "f24",++ "f3",++ "f4",++ "f5",++ "f6",++ "f7",++ "f8",++ "f9",++ "home",++ "insert",++ "left",++ "media_next",++ "media_play_pause",++ "media_prev",++ "media_stop",++ "menu",++ "num_lock",++ "page_down",++ "page_up",++ "pause",++ "print_screen",++ "right",++ "scroll_lock",++ "shift",++ "shift_r",++ "space",++ "tab",++ "up",++ "volume_down",++ "volume_mute",++ "volume_up"++ ],++ "evdev": {++ "1": "esc",++ "14": "backspace",++ "15": "tab",++ "28": "enter",++ "29": "ctrl",++ "42": "shift",++ "54": "shift_r",++ "56": "alt",++ "57": "space",++ "58": "caps_lock",++ "59": "f1",++ "60": "f2",++ "61": "f3",++ "62": "f4",++ "63": "f5",++ "64": "f6",++ "65": "f7",++ "66": "f8",++ "67": "f9",++ "68": "f10",++ "69": "num_lock",++ "70": "scroll_lock",++ "87": "f11",++ "88": "f12",++ "96": "enter",++ "97": "ctrl_r",++ "99": "print_screen",++ "100": "alt_r",++ "102": "home",++ "103": "up",++ "104": "page_up",++ "105": "left",++ "106": "right",++ "107": "end",++ "108": "down",++ "109": "page_down",++ "110": "insert",++ "111": "delete",++ "113": "volume_mute",++ "114": "volume_down",++ "115": "volume_up",++ "119": "pause",++ "125": "cmd",++ "126": "cmd_r",++ "127": "menu",++ "158": "browser_back",++ "159": "browser_forward",++ "163": "media_next",++ "164": "media_play_pause",++ "165": "media_prev",++ "166": "media_stop",++ "183": "f13",++ "184": "f14",++ "185": "f15",++ "186": "f16",++ "187": "f17",++ "188": "f18",++ "189": "f19",++ "190": "f20",++ "191": "f21",++ "192": "f22",++ "193": "f23",++ "194": "f24"++ }++ },++ "ack": {++ "$comment": "sample_us = max(0, (arrived_at_us - sent_at_us) - held_us): the round trip with the responder's holding time taken out, for an ack whose seq is higher than the last. `held_us_asked` is what a sender has, `held_us_on_wire` what it sends.",++ "cases": [++ {++ "comment": "an ordinary acknowledgement",++ "seq": 5,++ "sent_at_us": 1000000,++ "arrived_at_us": 1012400,++ "held_us_asked": 1830,++ "held_us_on_wire": 1830,++ "sample_us": 10570,++ "message": {++ "type": "ack",++ "data": {++ "seq": 5,++ "held_us": 1830++ }++ }++ },++ {++ "comment": "held longer than the round trip: the sample is clamped to 0",++ "seq": 6,++ "sent_at_us": 2000000,++ "arrived_at_us": 2000900,++ "held_us_asked": 1500,++ "held_us_on_wire": 1500,++ "sample_us": 0,++ "message": {++ "type": "ack",++ "data": {++ "seq": 6,++ "held_us": 1500++ }++ }++ },++ {++ "comment": "held_us asked above the limit is sent as 2^31 - 1",++ "seq": 7,++ "sent_at_us": 10000000,++ "arrived_at_us": 13000000000,++ "held_us_asked": 5000000000,++ "held_us_on_wire": 2147483647,++ "sample_us": 10842516353,++ "message": {++ "type": "ack",++ "data": {++ "seq": 7,++ "held_us": 2147483647++ }++ }++ },++ {++ "comment": "a negative held_us is sent as 0",++ "seq": 8,++ "sent_at_us": 500,++ "arrived_at_us": 4500,++ "held_us_asked": -5,++ "held_us_on_wire": 0,++ "sample_us": 4000,++ "message": {++ "type": "ack",++ "data": {++ "seq": 8,++ "held_us": 0++ }++ }++ }++ ]++ },++ "clipboard_images": {++ "$comment": "Clipboard images judged from their bytes before anything decodes them (WIRE.md section 3). `fits` false drops the image part of a clipboard message and keeps its text. Pixel data is not real past 1 by 1: nothing here decodes it.",++ "cases": [++ {++ "comment": "a 1 by 1 image",++ "png_hex": "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c48900000010494441547801010500faff000000000000050001647895380000000049454e44ae426082",++ "fits": true++ },++ {++ "comment": "an 8K screen's header, 7680 by 4320",++ "png_hex": "89504e470d0a1a0a0000000d4948445200001e00000010e00806000000b69114930000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",++ "fits": true++ },++ {++ "comment": "16384 by 2048, exactly 2^25 pixels",++ "png_hex": "89504e470d0a1a0a0000000d4948445200004000000008000806000000de2c2b9a0000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",++ "fits": true++ },++ {++ "comment": "bytes after IEND are ignored",++ "png_hex": "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c48900000010494441547801010500faff000000000000050001647895380000000049454e44ae426082747261696c696e67",++ "fits": true++ },++ {++ "comment": "zTXt inflating to exactly 4 MiB",++ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b000068417a545874436f6d6d656e74000078014b4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c1c05a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1280000e9966bd03978c9330000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",++ "fits": true++ },++ {++ "comment": "a side of 16385",++ "png_hex": "89504e470d0a1a0a0000000d4948445200004001000000010806000000c95ddd660000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",++ "fits": false++ },++ {++ "comment": "6000 by 6000, past 2^25 pixels",++ "png_hex": "89504e470d0a1a0a0000000d4948445200001770000017700806000000e35487430000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",++ "fits": false++ },++ {++ "comment": "IHDR not the first chunk",++ "png_hex": "89504e470d0a1a0a0000000374455874610062dc49a23b0000000d49484452000000010000000108060000001f15c48900000010494441547801010500faff000000000000050001647895380000000049454e44ae426082",++ "fits": false++ },++ {++ "comment": "no IEND",++ "png_hex": "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c48900000010494441547801010500faff00000000000005000164789538",++ "fits": false++ },++ {++ "comment": "a second IHDR",++ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b0000000d49484452000186a0000186a00806000000a8520bc80000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",++ "fits": false++ },++ {++ "comment": "an APNG acTL",++ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b000000086163544c0000000000000000894dc0100000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",++ "fits": false++ },++ {++ "comment": "zTXt inflating to 4 MiB and one byte",++ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b000068427a545874436f6d6d656e74000078014b4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c1c05a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c128000055d66c31d393054f0000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",++ "fits": false++ },++ {++ "comment": "zTXt whose zlib stream is cut short",++ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b000000f27a545874436f6d6d656e74000078014b4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c1c05a36014e766143a0000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",++ "fits": false++ },++ {++ "comment": "iTXt with a compression flag of 2",++ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b0000000e695458744b6579000200656e0000746578748fa003e70000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",++ "fits": false++ }++ ]++ }++ },++ "pairing_v3": {++ "$comment": "Pairing version 3 (WIRE.md section 6). Hex is bytes in wire order. Every exchange shows every intermediate value and all four messages. The host of a typed exchange still draws a QR secret when it shows a code, which nothing uses, so its `qr_secret_hex` is null. `beacon` is the host's beacon while the code is up.",++ "constants": {++ "pairing_version": 3,++ "pair_start_v": 3,++ "dsi_ascii": "CPace255",++ "channel_ascii": "beamer-pair-v3",++ "token_info_ascii": "beamer-pair-token-v3",++ "done_label_ascii": "beamer-pair-done",++ "role_requester_ascii": "requester",++ "role_host_ascii": "host",++ "id_bytes": 16,++ "qr_secret_bytes": 16,++ "max_peers": 32,++ "nonce_bytes": 16,++ "max_name_chars": 48,++ "tcp_port": 24821,++ "link_key_id_info_ascii": "beamer-key-id"++ },++ "exchanges": [++ {++ "comment": "Desktop to desktop with the code typed; the requester's name is 48 code points outside ASCII and the BMP, 177 bytes, so its length in ADa takes two LEB128 bytes",++ "code": "482913",++ "qr_secret_hex": null,++ "prs_hex": "343832393133",++ "wall": 1790000000,++ "pair_id": "6b1a17a072cddecd660c7e94f007ed5c",++ "requester": {++ "name": "Zo\u00eb\u2019s \ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39",++ "id_hex": "7f1a2715e76636bc63a54bd739c172ae",++ "platform": "macos",++ "port": 24820,++ "nonce_hex": "6cf2cf66a42563eb3f6006864fb0191f",++ "scalar_hex": "15923d653efd46f0053e88b1ffc6a1056ba4ec696e5f0afe5cb89d8852f2a975"++ },++ "host": {++ "name": "VECTOR-PC",++ "id_hex": "f092b8d69193df6d5fc72f7728b586e5",++ "platform": "windows",++ "port": 24820,++ "scalar_hex": "efe1b90d899464d39cd9debb10aac2c1844f4d68dfc60d32514f61fbf0f8272a"++ },++ "sid_hex": "203662316131376130373263646465636436363063376539346630303765643563106cf2cf66a42563eb3f6006864fb0191f",++ "ada_hex": "09726571756573746572107f1a2715e76636bc63a54bd739c172aeb1015a6fc3abe280997320f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9f09d94b9056d61636f730260f4",++ "adb_hex": "04686f737410f092b8d69193df6d5fc72f7728b586e509564543544f522d50430777696e646f77730260f4",++ "generator_string_hex": "084350616365323535063438323931336f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6265616d65722d706169722d763332203662316131376130373263646465636436363063376539346630303765643563106cf2cf66a42563eb3f6006864fb0191f",++ "generator_hex": "38fcfaec3a9b04ea43ed77aae6def40c1647d49e3250e64ce7a75f6afa27f47e",++ "ya_hex": "b88597b640460d1bfc4b71edf60ccf1f51cc72886823608b83cc04549b1bd402",++ "yb_hex": "af819c42049c95eb2cad943caaa5cc41088395735fb9a2fbbf78dc1eed532b05",++ "k_hex": "7cb66d16be514e2b1d237bf302c078d27dac3ad3f6e1c3b536e26672d8009251",++ "isk_hex": "11b5d74f9d45fe210e6549f68bc7090520650051e59a8f39afcf620e862b031981a123f552c79c021775c821e4605b4542ea532320da766f4f2f4a123546fe21",++ "mac_key_hex": "d1d304cc077c480a21f16115253bc33ac97f2d7c1b5ebf53a108f84fe094c8df8ae97bd6cd1032abfa56d98d14b1b4d8fefc88aec798d12f4f630e45267fee47",++ "ta_hex": "9a633f11139bafd2e6418c9b635403691a273727ee5eb0bd14f243b8482576bc4de4a1515ac68e8683572e3ce1e50112b0118da958c30557924c938da55fd469",++ "tb_hex": "0bb2ac485c17c9cff049c04c880483dd1d416ae4146119278242a23814e7f8530ebfe9112f32f6c66e08fce3faac2b7760d29746a1211c331b5ebdea9b13ae6b",++ "td_hex": "d887825c70d762e318bc12a59f15b84c0a2ec7a975b9ad2eebad2f6c156958ae8a2ece6a6d5025cb5793dfa31985f704156b3203db4787ec28e0569ef39febb8",++ "token": "LHEBqJlZwOS2QO7xBT4I4pgmRcsXRdXD3Pik1dvYr9g",++ "key_id_hex": "bd4028e4171970c7648554b603ae08a7",++ "beacon": {++ "type": "beacon",++ "name": "VECTOR-PC",++ "port": 24820,++ "pairing": 3,++ "platform": "windows",++ "pair": "6b1a17a072cddecd660c7e94f007ed5c",++ "id": "8JK41pGT321fxy93KLWG5Q"++ },++ "messages": {++ "pair_start": {++ "type": "pair_start",++ "pair": "6b1a17a072cddecd660c7e94f007ed5c",++ "v": 3,++ "nonce": "bPLPZqQlY-s_YAaGT7AZHw",++ "share": "uIWXtkBGDRv8S3Ht9gzPH1HMcohoI2CLg8wEVJsb1AI",++ "name": "Zo\u00eb\u2019s \ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39\ud835\udd39",++ "id": "fxonFedmNrxjpUvXOcFyrg",++ "platform": "macos",++ "port": 24820++ },++ "pair_answer": {++ "type": "pair_answer",++ "pair": "6b1a17a072cddecd660c7e94f007ed5c",++ "ok": true,++ "share": "r4GcQgSclessrZQ8qqXMQQiDlXNfuaL7v3jcHu1TKwU",++ "tag": "C7KsSFwXyc_wScBMiASD3R1BauQUYRkngkKiOBTn-FMOv-kRLzL2xm4I_OP6rCt3YNKXRqEhHDMbXr3qmxOuaw",++ "name": "VECTOR-PC",++ "id": "8JK41pGT321fxy93KLWG5Q",++ "platform": "windows",++ "port": 24820++ },++ "pair_confirm": {++ "type": "pair_confirm",++ "pair": "6b1a17a072cddecd660c7e94f007ed5c",++ "tag": "mmM_ERObr9LmQYybY1QDaRonNyfuXrC9FPJDuEgldrxN5KFRWsaOhoNXLjzh5QESsBGNqVjDBVeSTJONpV_UaQ"++ },++ "pair_done": {++ "type": "pair_done",++ "pair": "6b1a17a072cddecd660c7e94f007ed5c",++ "ok": true,++ "tag": "2IeCXHDXYuMYvBKlnxW4TAoux6l1ua0u660vbBVpWK6KLs5qbVAly1eT36MZhfcEFWsyA9tHh-wo4Fae85_ruA"++ }++ }++ },++ {++ "comment": "A phone pairing by QR: port 0, qr 1, and a 22-byte password",++ "code": "007045",++ "qr_secret_hex": "84cbf854f707c846c7983bc925720e43",++ "prs_hex": "30303730343584cbf854f707c846c7983bc925720e43",++ "wall": 1790000000,++ "pair_id": "560a79d5d80bd38bb9cba7feab676f5a",++ "requester": {++ "name": "Zo\u00eb\u2019s \ud835\udd39Phone",++ "id_hex": "7351f4c520f23e274386518b04263b45",++ "platform": "ios",++ "port": 0,++ "nonce_hex": "a52fb4c89aeb3c4d852e72d968716615",++ "scalar_hex": "6bcdc467211ecb43070f4b56545b3f449b857c4cf31638ac6077d382487af241"++ },++ "host": {++ "name": "Vector Mac",++ "id_hex": "f97993aa97b7e46d94b3ea908385496f",++ "platform": "macos",++ "port": 24820,++ "scalar_hex": "da2749702debfa5a82c0b79c76babc40a2075010d1b82d55ea9f42550f5f71eb"++ },++ "sid_hex": "20353630613739643564383062643338626239636261376665616236373666356110a52fb4c89aeb3c4d852e72d968716615",++ "ada_hex": "09726571756573746572107351f4c520f23e274386518b04263b45125a6fc3abe280997320f09d94b950686f6e6503696f73020000",++ "adb_hex": "04686f737410f97993aa97b7e46d94b3ea908385496f0a566563746f72204d6163056d61636f730260f4",++ "generator_string_hex": "0843506163653235351630303730343584cbf854f707c846c7983bc925720e435f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6265616d65722d706169722d76333220353630613739643564383062643338626239636261376665616236373666356110a52fb4c89aeb3c4d852e72d968716615",++ "generator_hex": "c4436fa1dd38fa76d517649079fb0383b896fd8424e80d7afd03d1228e18c60c",++ "ya_hex": "16123bf4a050b8d6108fdbfb34603070c4bb889bbb519da871762f3c24541a3d",++ "yb_hex": "18fd0ab7b04495afddf97045e803daca7c6e5ed3b5b58222662a1adb473ea10f",++ "k_hex": "88eb95e6c99e858e88c4505f3bcdda28fdc5e8466e833f1a91db2be20cc0c170",++ "isk_hex": "bc4e441e77b82a5c103c30b894a85cf727041202189fc217b900e6b1e69712304bd715cec81c7906bddca2a278eeb40908631fbc767d0db19f2473fb7f130c83",++ "mac_key_hex": "108600fbfd30bf469c531d510d7cd3d01903e9a7c10afb0202cc72b8f7fefe001c76044506f14e221ebb88e2cb2b87f8d05abcb49c62afca6df030ee83ada661",++ "ta_hex": "b37c62139dabe7fd5fe9d28bfc903646fd51ed7e6f0bdb60bd79f400b20753e3fb8fe7b3b4ec58f18e6225efb7f07b94718d001410bfe6639a901b64401c6d70",++ "tb_hex": "a27aedac2b0b34527b6b18403ef924e86f4ee41512781dcf2a591a17398876e4254d8b4f8115e121e3e297b5654de0dee5b266abff4d1881bb0e641740c8b188",++ "td_hex": "1d71124282af1f69b57bbd5b7d7ce9ad5301d383c7ff571dbb2121df746ab0fd768a2c7e73d7345c163aca190fc141af6a72af6871f1e6125703554c0b630ded",++ "token": "C8JiSxEGfm05PG-nyz4LUdNUj1JdXuGb2a40GzaP6Hs",++ "key_id_hex": "cdb296999f78d090a03ff1bf1a1e0bc1",++ "beacon": {++ "type": "beacon",++ "name": "Vector Mac",++ "port": 24820,++ "pairing": 3,++ "platform": "macos",++ "pair": "560a79d5d80bd38bb9cba7feab676f5a",++ "id": "-XmTqpe35G2Us-qQg4VJbw"++ },++ "messages": {++ "pair_start": {++ "type": "pair_start",++ "pair": "560a79d5d80bd38bb9cba7feab676f5a",++ "v": 3,++ "nonce": "pS-0yJrrPE2FLnLZaHFmFQ",++ "share": "FhI79KBQuNYQj9v7NGAwcMS7iJu7UZ2ocXYvPCRUGj0",++ "name": "Zo\u00eb\u2019s \ud835\udd39Phone",++ "id": "c1H0xSDyPidDhlGLBCY7RQ",++ "platform": "ios",++ "port": 0,++ "qr": 1++ },++ "pair_answer": {++ "type": "pair_answer",++ "pair": "560a79d5d80bd38bb9cba7feab676f5a",++ "ok": true,++ "share": "GP0Kt7BEla_d-XBF6APaynxuXtO1tYIiZioa20c-oQ8",++ "tag": "onrtrCsLNFJ7axhAPvkk6G9O5BUSeB3PKlkaFzmIduQlTYtPgRXhIePil7VlTeDe5bJmq_9NGIG7DmQXQMixiA",++ "name": "Vector Mac",++ "id": "-XmTqpe35G2Us-qQg4VJbw",++ "platform": "macos",++ "port": 24820++ },++ "pair_confirm": {++ "type": "pair_confirm",++ "pair": "560a79d5d80bd38bb9cba7feab676f5a",++ "tag": "s3xiE52r5_1f6dKL_JA2Rv1R7X5vC9tgvXn0ALIHU-P7j-eztOxY8Y5iJe-38HuUcY0AFBC_5mOakBtkQBxtcA"++ },++ "pair_done": {++ "type": "pair_done",++ "pair": "560a79d5d80bd38bb9cba7feab676f5a",++ "ok": true,++ "tag": "HXESQoKvH2m1e71bfXzprVMB04PH_1cduyEh33RqsP12iix-c9c0XBY6yhkPwUGvanKvaHHx5hJXA1VMC2MN7Q"++ }++ }++ },++ {++ "comment": "Desktop to desktop, typed, a code with leading zeros and a platform of the other family",++ "code": "000042",++ "qr_secret_hex": null,++ "prs_hex": "303030303432",++ "wall": 1790000000,++ "pair_id": "7485855e2ff3537624d6731e0b308f5d",++ "requester": {++ "name": "Vector Linux",++ "id_hex": "acbf7b53ac934af0f26eb25afef3e8c7",++ "platform": "linux",++ "port": 24820,++ "nonce_hex": "e833a976fa9b18ad5c7980cfaa55e7f7",++ "scalar_hex": "bdffd589e9ced02461a5ef4228f2ff2c82880d3d099803f75ad31542ff191b10"++ },++ "host": {++ "name": "Vector Mac",++ "id_hex": "a9499058bf9095dfccf322cd2eecdd63",++ "platform": "macos",++ "port": 24820,++ "scalar_hex": "d0c7b5bf565d63a9bfc559362408373daa9b54911cc4a6971255028963a6b6bd"++ },++ "sid_hex": "20373438353835356532666633353337363234643637333165306233303866356410e833a976fa9b18ad5c7980cfaa55e7f7",++ "ada_hex": "0972657175657374657210acbf7b53ac934af0f26eb25afef3e8c70c566563746f72204c696e7578056c696e75780260f4",++ "adb_hex": "04686f737410a9499058bf9095dfccf322cd2eecdd630a566563746f72204d6163056d61636f730260f4",++ "generator_string_hex": "084350616365323535063030303034326f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6265616d65722d706169722d76333220373438353835356532666633353337363234643637333165306233303866356410e833a976fa9b18ad5c7980cfaa55e7f7",++ "generator_hex": "fa378c5e5ee926a78be4658d8078c28d5cb09d97826188b58c4cb5f306120b37",++ "ya_hex": "c19aee9da1eb7c1e13fc65e94e9f1790fc94cde878c3c7cfc8a3b520521f352b",++ "yb_hex": "94ab022f3b8af4af14b3b8daf9fb7d7284fe8f73b0c69ff52c02704cdea5176b",++ "k_hex": "5787d0e9056ffa445c7090afc3a2d73c8156fe297b1f06adf254f29d001dc03c",++ "isk_hex": "d93f1bf808a9595fed05e3fda8bc817674b1106f57df7e097d06009ff17dbe9ede89c2983e39edab5feaaefa8870dd2e11fc6161f289b6e24d7d211c4ce1d9cd",++ "mac_key_hex": "7a661c4137e689dea5d61b2d69ae33689d8413cc75456fbaab867b385417e8832b3252c5bee83b254e7978810ee4ec2a3ce1e81470728a293c730dc0b9f307b5",++ "ta_hex": "e9dc788647dac88820bd6878c464ee9e0d542991e46d154a046a26b71437280bcbff1e3085621d31d6ee1f2b4588f9e681257b6499318811e1933d1da5b116d0",++ "tb_hex": "b6e6096fbc3a8d28175df2cb3c0d6089f2ef78d45f3d3715a3f53968d2f2855116fcae11c84321b4b30767ee5d0df51431c4f1a61cf2767dbaee0a83136eab79",++ "td_hex": "27e90f476470ce5598f3251791e2751dd9d847bdef452d3bff4898e4499162a17842091923facf3e4c61251c63d69575a527b957e3586fbe75f182a74d82d91a",++ "token": "esINH1XDelrSEJXsJtR21YTssYEyRvbtIqSSIOsWRTo",++ "key_id_hex": "caa0ab0e5217c66890086973797f5f84",++ "beacon": {++ "type": "beacon",++ "name": "Vector Mac",++ "port": 24820,++ "pairing": 3,++ "platform": "macos",++ "pair": "7485855e2ff3537624d6731e0b308f5d",++ "id": "qUmQWL-Qld_M8yLNLuzdYw"++ },++ "messages": {++ "pair_start": {++ "type": "pair_start",++ "pair": "7485855e2ff3537624d6731e0b308f5d",++ "v": 3,++ "nonce": "6DOpdvqbGK1ceYDPqlXn9w",++ "share": "wZrunaHrfB4T_GXpTp8XkPyUzeh4w8fPyKO1IFIfNSs",++ "name": "Vector Linux",++ "id": "rL97U6yTSvDybrJa_vPoxw",++ "platform": "linux",++ "port": 24820++ },++ "pair_answer": {++ "type": "pair_answer",++ "pair": "7485855e2ff3537624d6731e0b308f5d",++ "ok": true,++ "share": "lKsCLzuK9K8Us7ja-ft9coT-j3Owxp_1LAJwTN6lF2s",++ "tag": "tuYJb7w6jSgXXfLLPA1gifLveNRfPTcVo_U5aNLyhVEW_K4RyEMhtLMHZ-5dDfUUMcTxphzydn267gqDE26reQ",++ "name": "Vector Mac",++ "id": "qUmQWL-Qld_M8yLNLuzdYw",++ "platform": "macos",++ "port": 24820++ },++ "pair_confirm": {++ "type": "pair_confirm",++ "pair": "7485855e2ff3537624d6731e0b308f5d",++ "tag": "6dx4hkfayIggvWh4xGTung1UKZHkbRVKBGomtxQ3KAvL_x4whWIdMdbuHytFiPnmgSV7ZJkxiBHhkz0dpbEW0A"++ },++ "pair_done": {++ "type": "pair_done",++ "pair": "7485855e2ff3537624d6731e0b308f5d",++ "ok": true,++ "tag": "J-kPR2RwzlWY8yUXkeJ1HdnYR73vRS07_0iY5EmRYqF4QgkZI_rPPkxhJRxj1pV1pSe5V-NYb7518YKnTYLZGg"++ }++ }++ }++ ],++ "wrong_prs": {++ "$comment": "A QR's `qr` stripped from pair_start on the path. The host, seeing none, makes its answer from the 6-byte code; the requester, which used the 22-byte password, works out another Tb, so it must refuse the answer, send the abort once, and never send a tag of its own.",++ "code": "482913",++ "qr_secret_hex": "3666a6143242ff4d8e13976a5cf5dc4c",++ "pair_id": "f48bff217ad09abd9a9ea102fd35837b",++ "requester": {++ "name": "Vector iPhone",++ "id_hex": "a31775d1fa533aeb765a1cb27c8d3dd0",++ "platform": "ios",++ "port": 0,++ "nonce_hex": "e9b5efb759c3ff1fa75d5d419a9d3010",++ "scalar_hex": "5404d969974546686ebae1e98c6e3eb820d1ceebbd6bc2afa1549325697f8ce9"++ },++ "host": {++ "name": "Vector Mac",++ "id_hex": "e99388242ed8a48e1a2a52f413fedc4d",++ "platform": "macos",++ "port": 24820,++ "scalar_hex": "87fca97bb3ab7dc11b58737e34f1ab6612f101a921c686efc5c2797dfc383547"++ },++ "pair_start_sent": {++ "type": "pair_start",++ "pair": "f48bff217ad09abd9a9ea102fd35837b",++ "v": 3,++ "nonce": "6bXvt1nD_x-nXV1Bmp0wEA",++ "share": "12SR4JdY9lNANdwbTqWbdxUWP8kGtAZe1LtmmXPvKnM",++ "name": "Vector iPhone",++ "id": "oxd10fpTOut2WhyyfI090A",++ "platform": "ios",++ "port": 0,++ "qr": 1++ },++ "pair_start_received": {++ "type": "pair_start",++ "pair": "f48bff217ad09abd9a9ea102fd35837b",++ "v": 3,++ "nonce": "6bXvt1nD_x-nXV1Bmp0wEA",++ "share": "12SR4JdY9lNANdwbTqWbdxUWP8kGtAZe1LtmmXPvKnM",++ "name": "Vector iPhone",++ "id": "oxd10fpTOut2WhyyfI090A",++ "platform": "ios",++ "port": 0++ },++ "prs_used_by_host_hex": "343832393133",++ "prs_used_by_requester_hex": "3438323931333666a6143242ff4d8e13976a5cf5dc4c",++ "pair_answer": {++ "type": "pair_answer",++ "pair": "f48bff217ad09abd9a9ea102fd35837b",++ "ok": true,++ "share": "wJgT0kmLsiJ-vSn5E-gn7KkDnFY6YukdIs8EyFsUpns",++ "tag": "pnK6OEBUOrLxq6OX37qZixC90rDDSiUvzENE1nL2DW48qK2PbX4N-TNmj48adDvUvt-pCVtaRrHd8NUPkc7ObQ",++ "name": "Vector Mac",++ "id": "6ZOIJC7YpI4aKlL0E_7cTQ",++ "platform": "macos",++ "port": 24820++ },++ "answer_tb_hex": "a672ba3840543ab2f1aba397dfba998b10bdd2b0c34a252fcc4344d672f60d6e3ca8ad8f6d7e0df933668f8f1a743bd4bedfa9095b5a46b1ddf0d50f91cece6d",++ "expected_tb_hex": "03f59a2654737281a0b7f5e9f669680c5772ec58c415a35f0b96dd27ee801243af00a9b168cc9926528fe6b01921d5ed158b1b4587caba7e81af1af45f1ca03f",++ "requester_must": "refused",++ "pair_confirm_abort": {++ "type": "pair_confirm",++ "pair": "f48bff217ad09abd9a9ea102fd35837b",++ "tag": ""++ },++ "host_reply_to_abort": {++ "type": "pair_done",++ "pair": "f48bff217ad09abd9a9ea102fd35837b",++ "ok": false,++ "error": "refused"++ }++ },++ "tcp": {++ "$comment": "One exchange over TCP on port 24821, in order: the host sends its beacon as soon as the connection is accepted, then the four messages. Each is a 4-byte big-endian length, 1 to 1024, then the JSON a datagram would carry with \"beamy\":1 first. `message` is the object without `beamy`. The desktops write compact JSON with every character outside ASCII escaped as \\uXXXX (the requester's name here has some); a receiver must accept either spelling, because the tags bind the decoded name and id, never these bytes.",++ "exchange_comment": "A phone pairing by QR: port 0, qr 1, and a 22-byte password",++ "frames": [++ {++ "from": "host",++ "message": {++ "type": "beacon",++ "name": "Vector Mac",++ "port": 24820,++ "pairing": 3,++ "platform": "macos",++ "pair": "560a79d5d80bd38bb9cba7feab676f5a",++ "id": "-XmTqpe35G2Us-qQg4VJbw"++ },++ "bytes_hex": "000000a37b226265616d79223a312c2274797065223a22626561636f6e222c226e616d65223a22566563746f72204d6163222c22706f7274223a32343832302c2270616972696e67223a332c22706c6174666f726d223a226d61636f73222c2270616972223a223536306137396435643830626433386262396362613766656162363736663561222c226964223a222d586d547170653335473255732d71516734564a6277227d"++ },++ {++ "from": "requester",++ "message": {++ "type": "pair_start",++ "pair": "560a79d5d80bd38bb9cba7feab676f5a",++ "v": 3,++ "nonce": "pS-0yJrrPE2FLnLZaHFmFQ",++ "share": "FhI79KBQuNYQj9v7NGAwcMS7iJu7UZ2ocXYvPCRUGj0",++ "name": "Zo\u00eb\u2019s \ud835\udd39Phone",++ "id": "c1H0xSDyPidDhlGLBCY7RQ",++ "platform": "ios",++ "port": 0,++ "qr": 1++ },++ "bytes_hex": "000001107b226265616d79223a312c2274797065223a22706169725f7374617274222c2270616972223a223536306137396435643830626433386262396362613766656162363736663561222c2276223a332c226e6f6e6365223a2270532d30794a7272504532464c6e4c5a6148466d4651222c227368617265223a2246684937394b4251754e59516a3976374e474177634d5337694a7537555a326f6358597650435255476a30222c226e616d65223a225a6f5c75303065625c753230313973205c75643833355c756464333950686f6e65222c226964223a22633148307853447950696444686c474c424359375251222c22706c6174666f726d223a22696f73222c22706f7274223a302c227172223a317d"++ },++ {++ "from": "host",++ "message": {++ "type": "pair_answer",++ "pair": "560a79d5d80bd38bb9cba7feab676f5a",++ "ok": true,++ "share": "GP0Kt7BEla_d-XBF6APaynxuXtO1tYIiZioa20c-oQ8",++ "tag": "onrtrCsLNFJ7axhAPvkk6G9O5BUSeB3PKlkaFzmIduQlTYtPgRXhIePil7VlTeDe5bJmq_9NGIG7DmQXQMixiA",++ "name": "Vector Mac",++ "id": "-XmTqpe35G2Us-qQg4VJbw",++ "platform": "macos",++ "port": 24820++ },++ "bytes_hex": "0000013b7b226265616d79223a312c2274797065223a22706169725f616e73776572222c2270616972223a223536306137396435643830626433386262396362613766656162363736663561222c226f6b223a747275652c227368617265223a224750304b743742456c615f642d58424636415061796e787558744f31745949695a696f613230632d6f5138222c22746167223a226f6e72747243734c4e464a376178684150766b6b3647394f35425553654233504b6c6b61467a6d496475516c5459745067525868496550696c37566c5465446535624a6d715f394e47494737446d5158514d69786941222c226e616d65223a22566563746f72204d6163222c226964223a222d586d547170653335473255732d71516734564a6277222c22706c6174666f726d223a226d61636f73222c22706f7274223a32343832307d"++ },++ {++ "from": "requester",++ "message": {++ "type": "pair_confirm",++ "pair": "560a79d5d80bd38bb9cba7feab676f5a",++ "tag": "s3xiE52r5_1f6dKL_JA2Rv1R7X5vC9tgvXn0ALIHU-P7j-eztOxY8Y5iJe-38HuUcY0AFBC_5mOakBtkQBxtcA"++ },++ "bytes_hex": "000000aa7b226265616d79223a312c2274797065223a22706169725f636f6e6669726d222c2270616972223a223536306137396435643830626433386262396362613766656162363736663561222c22746167223a227333786945353272355f316636644b4c5f4a413252763152375835764339746776586e30414c4948552d50376a2d657a744f7859385935694a652d3338487555635930414642435f356d4f616b42746b514278746341227d"++ },++ {++ "from": "host",++ "message": {++ "type": "pair_done",++ "pair": "560a79d5d80bd38bb9cba7feab676f5a",++ "ok": true,++ "tag": "HXESQoKvH2m1e71bfXzprVMB04PH_1cduyEh33RqsP12iix-c9c0XBY6yhkPwUGvanKvaHHx5hJXA1VMC2MN7Q"++ },++ "bytes_hex": "000000b17b226265616d79223a312c2274797065223a22706169725f646f6e65222c2270616972223a223536306137396435643830626433386262396362613766656162363736663561222c226f6b223a747275652c22746167223a2248584553516f4b7648326d316537316266587a7072564d42303450485f3163647579456833335271735031326969782d633963305842593679686b5077554776616e4b766148487835684a584131564d43324d4e3751227d"++ }++ ]++ },++ "refusals": {++ "$comment": "pair_start messages whose id is not 16 bytes or is all zero. The host answers each with a refusal, drops its code, and stores nothing. Each case is offered to a fresh host. `answer_cases` are the same identities in an otherwise valid pair_answer to the requester whose `pair_start` is `requester_start`: it must refuse each before it sends a tag.",++ "code": "482913",++ "qr_secret_hex": "d0ad50d37c8a80130464b7b6db810cde",++ "pair_id": "a51e977cc732222ea863acfb997bbb65",++ "host": {++ "name": "Vector Mac",++ "id_hex": "12e943ce5db1d4ce5517ca8c5f4b9441",++ "platform": "macos",++ "port": 24820,++ "scalar_hex": "639cf3789074fcf2ada110845df67625d663b1773fc0339204cc68bfa56526f5"++ },++ "cases": [++ {++ "comment": "an id of 15 bytes",++ "pair_start": {++ "type": "pair_start",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "v": 3,++ "nonce": "Foy7tdc9AIfHP-kALt4WBA",++ "share": "exGh8KupW9xbtLwGcV5-HqiS_v4yeTedmSZUeqoMDww",++ "name": "Vector Mac 2",++ "id": "6isGOM0sd37xvObJNHXe",++ "platform": "macos",++ "port": 24820++ },++ "must_answer": {++ "type": "pair_answer",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "ok": false,++ "error": "refused"++ }++ },++ {++ "comment": "an id of 17 bytes",++ "pair_start": {++ "type": "pair_start",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "v": 3,++ "nonce": "Foy7tdc9AIfHP-kALt4WBA",++ "share": "exGh8KupW9xbtLwGcV5-HqiS_v4yeTedmSZUeqoMDww",++ "name": "Vector Mac 2",++ "id": "6isGOM0sd37xvObJNHXe9Ak",++ "platform": "macos",++ "port": 24820++ },++ "must_answer": {++ "type": "pair_answer",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "ok": false,++ "error": "refused"++ }++ },++ {++ "comment": "an id of sixteen zero bytes",++ "pair_start": {++ "type": "pair_start",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "v": 3,++ "nonce": "Foy7tdc9AIfHP-kALt4WBA",++ "share": "exGh8KupW9xbtLwGcV5-HqiS_v4yeTedmSZUeqoMDww",++ "name": "Vector Mac 2",++ "id": "AAAAAAAAAAAAAAAAAAAAAA",++ "platform": "macos",++ "port": 24820++ },++ "must_answer": {++ "type": "pair_answer",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "ok": false,++ "error": "refused"++ }++ },++ {++ "comment": "an empty id, as 1.4.3 sent",++ "pair_start": {++ "type": "pair_start",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "v": 3,++ "nonce": "Foy7tdc9AIfHP-kALt4WBA",++ "share": "exGh8KupW9xbtLwGcV5-HqiS_v4yeTedmSZUeqoMDww",++ "name": "Vector Mac 2",++ "id": "",++ "platform": "macos",++ "port": 24820++ },++ "must_answer": {++ "type": "pair_answer",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "ok": false,++ "error": "refused"++ }++ },++ {++ "comment": "an id of 32 bytes",++ "pair_start": {++ "type": "pair_start",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "v": 3,++ "nonce": "Foy7tdc9AIfHP-kALt4WBA",++ "share": "exGh8KupW9xbtLwGcV5-HqiS_v4yeTedmSZUeqoMDww",++ "name": "Vector Mac 2",++ "id": "Lt2oNXE5B9o3QY6gzSmPIEkuwr3ibAHmHVitsAGNkY4",++ "platform": "macos",++ "port": 24820++ },++ "must_answer": {++ "type": "pair_answer",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "ok": false,++ "error": "refused"++ }++ }++ ],++ "requester": {++ "name": "Vector Mac 2",++ "id_hex": "ea2b0638cd2c777ef1bce6c93475def4",++ "platform": "macos",++ "port": 24820,++ "nonce_hex": "168cbbb5d73d0087c73fe9002ede1604",++ "scalar_hex": "a65185c9519a1c46177b1c5d2233c2495997ea0dac8c90c5407a25e4a2d1a3d7"++ },++ "requester_start": {++ "type": "pair_start",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "v": 3,++ "nonce": "Foy7tdc9AIfHP-kALt4WBA",++ "share": "exGh8KupW9xbtLwGcV5-HqiS_v4yeTedmSZUeqoMDww",++ "name": "Vector Mac 2",++ "id": "6isGOM0sd37xvObJNHXe9A",++ "platform": "macos",++ "port": 24820++ },++ "answer_cases": [++ {++ "comment": "a host id of 15 bytes",++ "pair_answer": {++ "type": "pair_answer",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "ok": true,++ "share": "kQTdUhBZhzMTIFK7wnJoctuMB6QSc5GXlKg6gifPBU4",++ "tag": "5cEc6ZTCaAEAKdGgv7gb_U7dNqJv0G8l7TMJhDtGvw5kwXiqwvvVZ4OBMEAeuW858nckMWb7jLFxhbc01Od4NA",++ "name": "Vector Mac",++ "id": "6isGOM0sd37xvObJNHXe",++ "platform": "macos",++ "port": 24820++ },++ "requester_must": "refused"++ },++ {++ "comment": "a host id of 17 bytes",++ "pair_answer": {++ "type": "pair_answer",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "ok": true,++ "share": "kQTdUhBZhzMTIFK7wnJoctuMB6QSc5GXlKg6gifPBU4",++ "tag": "5cEc6ZTCaAEAKdGgv7gb_U7dNqJv0G8l7TMJhDtGvw5kwXiqwvvVZ4OBMEAeuW858nckMWb7jLFxhbc01Od4NA",++ "name": "Vector Mac",++ "id": "6isGOM0sd37xvObJNHXe9Ak",++ "platform": "macos",++ "port": 24820++ },++ "requester_must": "refused"++ },++ {++ "comment": "a host id of sixteen zero bytes",++ "pair_answer": {++ "type": "pair_answer",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "ok": true,++ "share": "kQTdUhBZhzMTIFK7wnJoctuMB6QSc5GXlKg6gifPBU4",++ "tag": "5cEc6ZTCaAEAKdGgv7gb_U7dNqJv0G8l7TMJhDtGvw5kwXiqwvvVZ4OBMEAeuW858nckMWb7jLFxhbc01Od4NA",++ "name": "Vector Mac",++ "id": "AAAAAAAAAAAAAAAAAAAAAA",++ "platform": "macos",++ "port": 24820++ },++ "requester_must": "refused"++ },++ {++ "comment": "an empty id, as 1.4.3 sent",++ "pair_answer": {++ "type": "pair_answer",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "ok": true,++ "share": "kQTdUhBZhzMTIFK7wnJoctuMB6QSc5GXlKg6gifPBU4",++ "tag": "5cEc6ZTCaAEAKdGgv7gb_U7dNqJv0G8l7TMJhDtGvw5kwXiqwvvVZ4OBMEAeuW858nckMWb7jLFxhbc01Od4NA",++ "name": "Vector Mac",++ "id": "",++ "platform": "macos",++ "port": 24820++ },++ "requester_must": "refused"++ },++ {++ "comment": "a host id of 32 bytes",++ "pair_answer": {++ "type": "pair_answer",++ "pair": "a51e977cc732222ea863acfb997bbb65",++ "ok": true,++ "share": "kQTdUhBZhzMTIFK7wnJoctuMB6QSc5GXlKg6gifPBU4",++ "tag": "5cEc6ZTCaAEAKdGgv7gb_U7dNqJv0G8l7TMJhDtGvw5kwXiqwvvVZ4OBMEAeuW858nckMWb7jLFxhbc01Od4NA",++ "name": "Vector Mac",++ "id": "Lt2oNXE5B9o3QY6gzSmPIEkuwr3ibAHmHVitsAGNkY4",++ "platform": "macos",++ "port": 24820++ },++ "requester_must": "refused"++ }++ ]++ }++ }++}diff --cc tools/phone_vectors.pyindex 0000000,0000000..4a42552new file mode 100644--- /dev/null+++ b/tools/phone_vectors.py@@@ -1,0 -1,0 +1,1191 @@@++"""Test vectors for phone clients of the v6 wire protocol, proved against the desktop's own++protocol.py and pairing.py rather than a description of them, so another implementation can be++checked byte for byte against the wire format.++++Every input (tokens, codes, key material, plaintexts) is fixed here, never random, so the file++this writes is a golden file: rerun it and the bytes do not move unless the wire format itself++changed.++++ python3 tools/phone_vectors.py++++Writes tools/phone_vectors.json beside this script.++"""++++from __future__ import annotations++++import hashlib++import hmac++import json++import struct++import sys++from pathlib import Path++++REPO = Path(__file__).resolve().parent.parent++sys.path.insert(0, str(REPO))++++from nacl.bindings import crypto_aead_chacha20poly1305_ietf_encrypt, crypto_scalarmult, crypto_scalarmult_base # noqa: E402++++from core import keytable # noqa: E402++from core import pairing # noqa: E402++from core import protocol # noqa: E402++++OLD_SECTIONS = ("protocol_version", "preamble", "derive_key", "frames", "pairing", "messages")++WALL = 1_790_000_000++I_TO_R = "initiator_to_responder"++R_TO_I = "responder_to_initiator"++++++def h(data: bytes) -> str:++ return data.hex()++++++def unhex(text: str) -> bytes:++ return bytes.fromhex(text)++++++def fixed_bytes(label: str, length: int = 32) -> bytes:++ """Stand-ins for the random values of an exchange, so the vectors never move."""++ return hashlib.sha256(label.encode("ascii")).digest()[:length]++++++def token_for(label: str) -> str:++ """A token as pairing makes one: the `b64` of 32 bytes."""++ return protocol.id_text(fixed_bytes(f"{label}-token"))++++++def scripted(*values: bytes):++ """An entropy source that hands out `values` in order, each checked for its length."""++ queue = list(values)++++ def entropy(length: int) -> bytes:++ value = queue.pop(0)++ assert len(value) == length, (len(value), length)++ return value++++ return entropy++++++def leb128(length: int) -> bytes:++ out = bytearray()++ while True:++ out.append((length & 0x7F) | (0x80 if length > 0x7F else 0))++ length >>= 7++ if not length:++ return bytes(out)++++++def lv(*parts: bytes) -> bytes:++ """The CPace draft's lv_cat, written here: each part behind its length as LEB128. A part of 128++ bytes or more needs two length bytes."""++ result = b"".join(leb128(len(part)) + part for part in parts)++ assert result == pairing._lv_cat(*parts)++ return result++++++def hkdf(ikm: bytes, salt: bytes, info: bytes) -> bytes:++ """RFC 5869 for one 32-byte block."""++ return hmac.new(hmac.new(salt, ikm, hashlib.sha256).digest(), info + b"\x01", hashlib.sha256).digest()++++++P = 2**255 - 19++++++def x25519_ladder(scalar: bytes, u: bytes) -> bytes:++ """RFC 7748's ladder in Python integers: bit 255 of the point ignored, the point reduced mod p,++ and a low-order point giving 32 zero bytes (z2 is 0, and pow(0, p - 2, p) is 0)."""++ k = bytearray(scalar)++ k[0] &= 248++ k[31] &= 127++ k[31] |= 64++ k = int.from_bytes(k, "little")++ x1 = (int.from_bytes(u, "little") & ((1 << 255) - 1)) % P++ x2, z2, x3, z3, swap = 1, 0, x1, 1, 0++ for t in range(254, -1, -1):++ bit = (k >> t) & 1++ swap ^= bit++ if swap:++ x2, x3, z2, z3 = x3, x2, z3, z2++ swap = bit++ a, b = (x2 + z2) % P, (x2 - z2) % P++ aa, bb = a * a % P, b * b % P++ e = (aa - bb) % P++ c, d = (x3 + z3) % P, (x3 - z3) % P++ da, cb = d * a % P, c * b % P++ x3, z3 = (da + cb) ** 2 % P, x1 * (da - cb) ** 2 % P++ x2, z2 = aa * bb % P, e * (aa + 121665 * e) % P++ if swap:++ x2, z2 = x3, z3++ return (x2 * pow(z2, P - 2, P) % P).to_bytes(32, "little")++++++# draft-irtf-cfrg-cpace-21, appendix B.1: the IETF's own numbers for CPACE-X25519-SHA512.++CPACE_DRAFT = {++ "prs_ascii": "Password",++ "ci_hex": "0b415f696e69746961746f720b425f726573706f6e646572",++ "sid_hex": "7e4b4791d6a8ef019b936c79fb7f2c57",++ "generator_hex": "d04bf6d41f6a289632a2e929fa29bebd51092512a7829fdde7d314b62f05a73f",++ "ada_ascii": "ADa",++ "ya_scalar_hex": "21b4f4bd9e64ed355c3eb676a28ebedaf6d8f17bdc365995b319097153044080",++ "ya_hex": "1d13c89278cdadd826f6d8d7f887701430f8380ddc17611cdd6dc989ce0c9f32",++ "adb_ascii": "ADb",++ "yb_scalar_hex": "848b0779ff415f0af4ea14df9dd1d3c29ac41d836c7808896c4eba19c51ac40a",++ "yb_hex": "248cccf6d5cdc3646f0ad593f9e6cef4e69d4945f8372e623512ecea32185623",++ "k_hex": "5b067effbdc0b2a0e1d907b21ebb25cfedb96a852179a847c37e43ee71322c6b",++ "isk_hex": (++ "6e19b875f7a561d6b3ca3dbb9ef42ac55de3e717881018204b8922b4d5e53bb2"++ "aa82c300bea7b65d2b671da71922ddf6472301b79bc270adfa8bf413285f2263"++ ),++}++++# RFC 9380, appendix J.4.2: u[0] and Q.x of each vector, the map's input and output before the++# cofactor is cleared. Both are integers printed big-endian, as the RFC prints them.++ELLIGATOR2 = [++ ("608d892b641f0328523802a6603427c26e55e6f27e71a91a478148d45b5093cd", "51125222da5e763d97f3c10fcc92ea6860b9ccbbd2eb1285728f566721c1e65b"),++ ("46f5b22494bfeaa7f232cc8d054be68561af50230234d7d1d63d1d9abeca8da5", "7d56d1e08cb0ccb92baf069c18c49bb5a0dcd927eff8dcf75ca921ef7f3e6eeb"),++ ("235fe40c443766ce7e18111c33862d66c3b33267efa50d50f9e8e5d252a40aaa", "3fbe66b9c9883d79e8407150e7c2a1c8680bee496c62fabe4619a72b3cabe90f"),++ ("001e92a544463bda9bd04ddbe3d6eed248f82de32f522669efc5ddce95f46f5b", "227e0bb89de700385d19ec40e857db6e6a3e634b1c32962f370d26f84ff19683"),++ ("1a68a1af9f663592291af987203393f707305c7bac9c8d63d6a729bdc553dc19", "3bcd651ee54d5f7b6013898aab251ee8ecc0688166fce6e9548d38472f6bd196"),++]++++# draft-irtf-cfrg-cpace-21, appendix B.1.10: shares on low-order points. With this scalar the++# first list gives the neutral element, so an exchange carrying one must be refused; the second++# gives the listed product, and only when bit 255 of the share is ignored as RFC 7748 requires.++LOW_ORDER_SCALAR = "af46e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449aff"++LOW_ORDER_REFUSED = [++ "0000000000000000000000000000000000000000000000000000000000000000",++ "0100000000000000000000000000000000000000000000000000000000000000",++ "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",++ "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800",++ "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157",++ "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",++ "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",++]++++++def check_published_vectors() -> None:++ """The IETF's and RFC 9380's numbers above, against pairing.py, before any of them is relied++ on: a phone checked against this file is then checked against the IETF's, not a typo."""++ draft = CPACE_DRAFT++ sid = bytes.fromhex(draft["sid_hex"])++ generator = pairing._generator(draft["prs_ascii"].encode("ascii"), bytes.fromhex(draft["ci_hex"]), sid)++ assert h(generator) == draft["generator_hex"]++ ya = pairing._x25519(bytes.fromhex(draft["ya_scalar_hex"]), generator)++ yb = pairing._x25519(bytes.fromhex(draft["yb_scalar_hex"]), generator)++ assert (h(ya), h(yb)) == (draft["ya_hex"], draft["yb_hex"])++ shared = pairing._x25519(bytes.fromhex(draft["ya_scalar_hex"]), yb)++ assert h(shared) == draft["k_hex"] == h(pairing._x25519(bytes.fromhex(draft["yb_scalar_hex"]), ya))++ isk = hashlib.sha512(++ pairing._lv_cat(b"CPace255_ISK", sid, shared)++ + pairing._lv_cat(ya, draft["ada_ascii"].encode("ascii"))++ + pairing._lv_cat(yb, draft["adb_ascii"].encode("ascii"))++ ).digest()++ assert h(isk) == draft["isk_hex"]++ for element, mapped in ELLIGATOR2:++ assert pairing._elligator2(int(element, 16)) == int(mapped, 16)++ assert x25519_ladder(bytes.fromhex(draft["ya_scalar_hex"]), generator) == ya++ assert x25519_ladder(bytes.fromhex(draft["ya_scalar_hex"]), yb) == shared++++++# ----------------------------------------------------------------------------------------------++# v6++++def build_constants() -> dict:++ return {++ "version": protocol.LINK_VERSION,++ "salt_ascii": protocol.LINK_SALT.decode("ascii"),++ "key_id_info_ascii": protocol.KEY_ID_INFO.decode("ascii"),++ "frame_info_label_ascii": protocol.KEY_INFO.decode("ascii"),++ "key_id_bytes": protocol.KEY_ID_SIZE,++ "preamble_bytes": protocol.LINK_PREAMBLE_SIZE,++ "short_reply_bytes": protocol.SHORT_REPLY_SIZE,++ "min_frame_bytes": protocol.MIN_FRAME_BYTES,++ "first_frame_max_bytes": protocol.HELLO_MAX_BYTES,++ }++++++def build_key_id() -> dict:++ cases = []++ for label in ("v6-key-id-1", "v6-key-id-2", "v6-key-id-3"):++ token = token_for(label)++ key = protocol.key_id(token)++ assert key == hkdf(token.encode("ascii"), b"beamer-link-v6", b"beamer-key-id")[:16]++ cases.append({"token": token, "key_id_hex": h(key)})++ canonical = cases[0]["token"]++ typed = ["hunter2", canonical[:-1] + ("B" if canonical[-1] != "B" else "C"), canonical + "=", "A" * 42]++ for token in typed:++ assert not protocol.is_paired_token(token)++ return {++ "$comment": "A token made by pairing is the b64 of 32 bytes in its one spelling. A typed token has no key id and never links.",++ "cases": cases,++ "typed_tokens": typed,++ }++++++def build_preamble() -> dict:++ token = token_for("v6-preamble")++ prefix, secret = fixed_bytes("v6-preamble-prefix", 8), fixed_bytes("v6-preamble-secret")++ session = protocol.LinkSession(token, protocol.ROLE_INITIATOR, prefix, secret)++ preamble = session.preamble()++ share = crypto_scalarmult_base(secret)++ assert preamble == b"BEAMY\x06" + prefix + protocol.key_id(token) + share and len(preamble) == 62++ assert share == x25519_ladder(secret, bytes([9]) + bytes(31))++ return {++ "token": token,++ "prefix_hex": h(prefix),++ "key_id_hex": h(protocol.key_id(token)),++ "secret_hex": h(secret),++ "share_hex": h(share),++ "preamble_hex": h(preamble),++ }++++++def build_short_reply() -> dict:++ prefix = fixed_bytes("v6-short-reply-prefix", 8)++ reply = protocol.short_reply(prefix)++ assert reply == b"BEAMY\x06" + prefix and len(reply) == 14++ return {"prefix_hex": h(prefix), "reply_hex": h(reply)}++++++def derive_case(comment: str, token: str, prefix_i: bytes, prefix_r: bytes, secret_i: bytes, secret_r: bytes) -> dict:++ key_id = protocol.key_id(token)++ share_i, share_r = crypto_scalarmult_base(secret_i), crypto_scalarmult_base(secret_r)++ assert share_i == x25519_ladder(secret_i, bytes([9]) + bytes(31)) and share_r == x25519_ladder(secret_r, bytes([9]) + bytes(31))++ shared = crypto_scalarmult(secret_i, share_r)++ assert shared == crypto_scalarmult(secret_r, share_i) == x25519_ladder(secret_i, share_r)++ ikm = token.encode("ascii") + shared++ assert ikm == protocol.link_ikm(token, shared) and len(ikm) == 75++ infos, keys = {}, {}++ for direction in (1, 2):++ info = b"beamer-frames" + b"\x06" + key_id + prefix_i + prefix_r + share_i + share_r + bytes([direction])++ assert info == protocol.link_info(key_id, prefix_i, prefix_r, share_i, share_r, direction) and len(info) == 111++ keys[direction] = hkdf(ikm, b"beamer-link-v6", info)++ assert keys[direction] == protocol.link_key(token, shared, key_id, prefix_i, prefix_r, share_i, share_r, direction)++ infos[direction] = info++ initiator = protocol.LinkSession(token, protocol.ROLE_INITIATOR, prefix_i, secret_i)++ responder = protocol.LinkSession(token, protocol.ROLE_RESPONDER, prefix_r, secret_r)++ responder.accept_preamble(initiator.preamble())++ initiator.accept_preamble(responder.preamble())++ assert (initiator._send_key, initiator._recv_key) == (keys[1], keys[2]) and (responder._send_key, responder._recv_key) == (keys[2], keys[1])++ return {++ "comment": comment,++ "token": token,++ "key_id_hex": h(key_id),++ "prefix_i_hex": h(prefix_i),++ "prefix_r_hex": h(prefix_r),++ "secret_i_hex": h(secret_i),++ "secret_r_hex": h(secret_r),++ "share_i_hex": h(share_i),++ "share_r_hex": h(share_r),++ "shared_hex": h(shared),++ "ikm_hex": h(ikm),++ "info_i_hex": h(infos[1]),++ "info_r_hex": h(infos[2]),++ "key_i_hex": h(keys[1]),++ "key_r_hex": h(keys[2]),++ }++++++def build_derive_key() -> dict:++ token = token_for("v6-derive")++ prefix_a, prefix_b = fixed_bytes("v6-derive-prefix-a", 8), fixed_bytes("v6-derive-prefix-b", 8)++ secret_a, secret_b = fixed_bytes("v6-derive-secret-a"), fixed_bytes("v6-derive-secret-b")++ return {++ "$comment": (++ "info_i and key_i are for direction 0x01, the frames the initiator seals; info_r and key_r for 0x02. "++ "The second case gives the same two machines' prefixes and secrets the opposite roles: the shared secret is "++ "the same and every key changes."++ ),++ "cases": [++ derive_case("A initiates, B responds", token, prefix_a, prefix_b, secret_a, secret_b),++ derive_case("the roles swapped: B initiates, A responds", token, prefix_b, prefix_a, secret_b, secret_a),++ ],++ }++++++def build_low_order() -> dict:++ secret = fixed_bytes("v6-low-order-secret")++ shares, seen = [], set()++ for canonical in LOW_ORDER_REFUSED:++ raw = bytes.fromhex(canonical)++ for comment, share in ((f"{canonical[:8]}..., bit 255 as listed", raw), (f"{canonical[:8]}..., bit 255 set", raw[:31] + bytes([raw[31] | 0x80]))):++ if share in seen:++ continue++ seen.add(share)++ result = x25519_ladder(secret, share)++ assert result == bytes(32)++ try:++ protocol._x25519_shared(secret, share)++ except protocol.PreambleRefused:++ pass++ else:++ raise AssertionError(f"low-order share {h(share)} was not refused")++ shares.append({"comment": comment, "share_hex": h(share), "result_hex": h(result)})++ p_low, p1_low = P.to_bytes(32, "little"), (P + 1).to_bytes(32, "little")++ assert h(p_low) in {s["share_hex"] for s in shares} and h(p1_low) in {s["share_hex"] for s in shares}++ return {++ "$comment": (++ "X25519 shares of low order, including the non-canonical spellings (u = p and p + 1, and each with bit 255 set, "++ "which X25519 ignores). Every one gives 32 zero bytes whatever the secret; a side that gets that result, or whose "++ "X25519 refuses the share, ends the handshake and sends nothing."++ ),++ "secret_hex": h(secret),++ "shares": shares,++ }++++++class ScriptedLink:++ """One link run through real LinkSessions, each frame also sealed a second time by hand and++ each opened by the other end before it is written down."""++++ def __init__(self, name: str, comment: str, token: str, initiator_id: bytes, responder_id: bytes):++ self.name, self.comment, self.token = name, comment, token++ self.ini_id, self.res_id = initiator_id, responder_id++ self.prefix_i, self.prefix_r = fixed_bytes(f"{name}-prefix-i", 8), fixed_bytes(f"{name}-prefix-r", 8)++ self.secret_i, self.secret_r = fixed_bytes(f"{name}-secret-i"), fixed_bytes(f"{name}-secret-r")++ self.ini = protocol.LinkSession(token, protocol.ROLE_INITIATOR, self.prefix_i, self.secret_i)++ self.res = protocol.LinkSession(token, protocol.ROLE_RESPONDER, self.prefix_r, self.secret_r)++ self.pre_i = self.ini.preamble()++ self.res.accept_preamble(self.pre_i)++ self.pre_r = self.res.preamble()++ self.ini.accept_preamble(self.pre_r)++ shared = crypto_scalarmult(self.secret_i, self.pre_r[30:])++ ikm = token.encode("ascii") + shared++ info = b"beamer-frames\x06" + protocol.key_id(token) + self.prefix_i + self.prefix_r + self.pre_i[30:] + self.pre_r[30:]++ self.keys = {I_TO_R: hkdf(ikm, b"beamer-link-v6", info + b"\x01"), R_TO_I: hkdf(ikm, b"beamer-link-v6", info + b"\x02")}++ self.counters = {I_TO_R: 0, R_TO_I: 0}++ self.frames = []++++ def send(self, direction: str, message: dict) -> dict:++ sender, receiver = (self.ini, self.res) if direction == I_TO_R else (self.res, self.ini)++ plain = protocol.dumps_message(message)++ frame = sender.seal(message)++ self.counters[direction] += 1++ counter = struct.pack(">I", self.counters[direction])++ prefix = self.prefix_i if direction == I_TO_R else self.prefix_r++ by_hand = crypto_aead_chacha20poly1305_ietf_encrypt(plain, None, prefix + counter, self.keys[direction])++ assert frame == struct.pack(">I", 4 + len(by_hand)) + counter + by_hand++ assert dict(receiver.open(frame[4:])) == message++ entry = {"direction": direction, "counter": self.counters[direction], "message": message, "plaintext_json": plain.decode("utf-8"), "frame_hex": h(frame)}++ self.frames.append(entry)++ return entry++++ def describe(self) -> dict:++ return {++ "name": self.name,++ "comment": self.comment,++ "token": self.token,++ "initiator": {"id_hex": h(self.ini_id), "prefix_hex": h(self.prefix_i), "secret_hex": h(self.secret_i)},++ "responder": {"id_hex": h(self.res_id), "prefix_hex": h(self.prefix_r), "secret_hex": h(self.secret_r)},++ "preamble_i_hex": h(self.pre_i),++ "preamble_r_hex": h(self.pre_r),++ "frames": self.frames,++ }++++++INITIATOR_ID = fixed_bytes("v6-initiator-id", 16)++RESPONDER_ID = fixed_bytes("v6-responder-id", 16)++THIRD_ID = fixed_bytes("v6-third-id", 16)++CAPS = ["clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings"]++INITIATOR_NAME = "Zoë’s \U0001d539eamer Mac"++# 48 code points and 177 bytes of UTF-8: the name's length and the whole of ADa both need two LEB128 bytes.++LONG_NAME = "Zoë’s " + "\U0001d539" * 42++++++def build_frames() -> dict:++ main = ScriptedLink(++ "main",++ "One pair, scripted end to end: the handshake frames, announcements, a take that lands at an edge, the clipboard and input, "++ "an acknowledgement, the responder sending the owner on, and the owner letting go.",++ token_for("v6-main"), INITIATOR_ID, RESPONDER_ID,++ )++ main.send(I_TO_R, protocol.hello_v6(INITIATOR_ID, INITIATOR_NAME, "macos", "1.5.0", CAPS, 24820, hw="02:00:5e:10:00:01"))++ main.send(R_TO_I, protocol.welcome_v6(RESPONDER_ID, "VECTOR-PC", "windows", "1.5.0", CAPS, True, hw="02:00:5e:10:00:02"))++ main.send(I_TO_R, protocol.paired_msg([THIRD_ID]))++ main.send(R_TO_I, protocol.paired_msg([THIRD_ID]))++ main.send(R_TO_I, protocol.arrangement_v6("left", WALL - 600, RESPONDER_ID))++ main.send(I_TO_R, protocol.focus_v6(1, RESPONDER_ID, edge="left", offset=0.42, resistance_px=120, reach=[THIRD_ID]))++ main.send(I_TO_R, {"type": protocol.MSG_CLIPBOARD, "data": {"text": "copied on the Mac"}})++ main.send(R_TO_I, protocol.accept_msg(1))++ main.send(I_TO_R, protocol.mousemove_msg(12, -7, seq=1))++ main.send(I_TO_R, protocol.key_msg(protocol.MSG_KEYDOWN, "a", us="a", seq=2))++ main.send(I_TO_R, protocol.key_msg(protocol.MSG_KEYUP, "a", us="a", seq=3))++ main.send(I_TO_R, protocol.text_msg("café \U0001f600", seq=4))++ main.send(I_TO_R, {"type": protocol.MSG_MOUSEDOWN, "data": {"button": "left", "seq": 5}})++ main.send(I_TO_R, {"type": protocol.MSG_MOUSEUP, "data": {"button": "left", "seq": 6}})++ main.send(I_TO_R, {"type": protocol.MSG_SCROLL, "data": {"dy": -14.5, "dx": 0, "mode": "pixel", "seq": 7}})++ main.send(I_TO_R, {"type": protocol.MSG_GESTURE, "data": {"name": "swipe_left", "seq": 8}})++ main.send(I_TO_R, {"type": "ping", "data": {}})++ main.send(R_TO_I, protocol.accepts_msg(True))++ main.send(R_TO_I, protocol.ack_v6(8, 1830))++ main.send(R_TO_I, protocol.switch_v6(1, THIRD_ID, edge="right", offset=0.5))++ main.send(I_TO_R, protocol.focus_v6(2, THIRD_ID))++++ second = ScriptedLink(++ "second_link_refuse",++ "Another machine's link to the same responder while the first owns it: its take is refused as owned.",++ token_for("v6-second"), THIRD_ID, RESPONDER_ID,++ )++ second.send(I_TO_R, protocol.hello_v6(THIRD_ID, "Vector Linux", "linux", "1.5.0", ["text"], 24820))++ second.send(R_TO_I, protocol.welcome_v6(RESPONDER_ID, "VECTOR-PC", "windows", "1.5.0", CAPS, True))++ second.send(I_TO_R, protocol.focus_v6(1, RESPONDER_ID, edge="right", offset=0.1, resistance_px=120, reach=[]))++ second.send(R_TO_I, protocol.refuse_msg(1, "owned"))++++ invalid = ScriptedLink(++ "invalid_hello",++ "A first frame that opens but is not a hello is answered with welcome carrying only version and error invalid_hello; the link then closes.",++ token_for("v6-invalid"), INITIATOR_ID, RESPONDER_ID,++ )++ invalid.send(I_TO_R, {"type": "ping", "data": {}})++ invalid.send(R_TO_I, protocol.invalid_hello_v6())++++ wrong = ScriptedLink(++ "wrong_id",++ "A well-formed hello whose id is not the one the responder holds for this pair is answered with welcome carrying only version and error wrong_id.",++ token_for("v6-wrong"), INITIATOR_ID, RESPONDER_ID,++ )++ wrong_id = fixed_bytes("v6-wrong-id", 16)++ wrong.send(I_TO_R, protocol.hello_v6(wrong_id, "Not the paired machine", "macos", "1.5.0", CAPS, 24820))++ wrong.send(R_TO_I, protocol.wrong_id_v6())++++ links = [main.describe(), second.describe(), invalid.describe(), wrong.describe()]++ links[3]["wrong_id_hello_id_hex"] = h(wrong_id)++ return {++ "$comment": (++ "Preambles and frames of scripted links, in order. `message` is the object sealed, `plaintext_json` its exact bytes as text "++ "(compact, UTF-8, keys in this order), `frame_hex` the whole frame as it crosses the wire: length, counter, ciphertext and tag. "++ "Each side counts its own frames from 1. A link's `initiator` and `responder` give the fixed prefix and ephemeral secret "++ "that made its keys."++ ),++ "links": links,++ }++++++def build_bad_frames() -> dict:++ link = ScriptedLink("bad_frames", "Fresh responders offered one bad frame each.", token_for("v6-bad"), INITIATOR_ID, RESPONDER_ID)++ good_message = protocol.hello_v6(INITIATOR_ID, "Vector Mac", "macos", "1.5.0", ["text"], 24820)++ good = link.send(I_TO_R, good_message)++ description = {key: value for key, value in link.describe().items() if key not in ("frames", "comment")}++++ flipped = bytearray(unhex(good["frame_hex"]))++ flipped[-1] ^= 1++++ twin = ScriptedLink("bad_frames", "", link.token, INITIATOR_ID, RESPONDER_ID)++ twin.send(I_TO_R, {"type": "ping", "data": {}})++ skipped = twin.send(I_TO_R, good_message)++ assert skipped["counter"] == 2++++ reflect = ScriptedLink("bad_frames", "", link.token, INITIATOR_ID, RESPONDER_ID)++ reflected = reflect.send(R_TO_I, {"type": "ping", "data": {}})++++ cases = [++ {"comment": "the last tag byte flipped", "receiver": "responder", "frame_hex": h(bytes(flipped)), "must": "close_without_reply"},++ {"comment": "a skipped counter: a valid hello sealed as counter 2, offered as the first frame", "receiver": "responder", "frame_hex": skipped["frame_hex"], "must": "close_without_reply"},++ {"comment": "sealed in the wrong direction: a frame the responder sealed, offered to the responder", "receiver": "responder", "frame_hex": reflected["frame_hex"], "must": "close_without_reply"},++ ]++ for case in cases:++ initiator, responder = sessions_from(description)++ try:++ responder.open(unhex(case["frame_hex"])[4:])++ except protocol.ProtocolError:++ pass++ else:++ raise AssertionError(case["comment"])++ return {++ "$comment": "Each case is offered to a responder that has accepted nothing yet; it must end the link without sending a byte. `good_frame_hex` is the untouched first frame the cases are made from.",++ "link": description,++ "good_message": good_message,++ "good_frame_hex": good["frame_hex"],++ "cases": cases,++ }++++++def sessions_from(link: dict):++ initiator = protocol.LinkSession(link["token"], protocol.ROLE_INITIATOR, unhex(link["initiator"]["prefix_hex"]), unhex(link["initiator"]["secret_hex"]))++ responder = protocol.LinkSession(link["token"], protocol.ROLE_RESPONDER, unhex(link["responder"]["prefix_hex"]), unhex(link["responder"]["secret_hex"]))++ responder.accept_preamble(initiator.preamble())++ initiator.accept_preamble(responder.preamble())++ return initiator, responder++++++def build_ids() -> dict:++ crafted = unhex("fbffbf") + bytes([0x11] * 13)++ ids = [fixed_bytes("v6-id-1", 16), fixed_bytes("v6-id-2", 16), crafted]++ cases = [{"id_hex": h(ident), "b64": protocol.id_text(ident)} for ident in ids]++ assert "-" in cases[2]["b64"] or "_" in cases[2]["b64"]++ spelling = cases[0]["b64"]++ flipped = spelling[:-1] + unused_bits_set(spelling[-1])++ standard = cases[2]["b64"].replace("-", "+").replace("_", "/")++ refused = [++ {"kind": "non_canonical", "comment": "padding added", "text": spelling + "==", "id_hex": cases[0]["id_hex"]},++ {"kind": "non_canonical", "comment": "the standard alphabet, + and / for - and _", "text": standard, "id_hex": cases[2]["id_hex"]},++ {"kind": "non_canonical", "comment": "the last character changed in its unused bits", "text": flipped, "id_hex": cases[0]["id_hex"]},++ {"kind": "all_zero", "comment": "sixteen zero bytes are never an id", "text": "A" * 22},++ {"kind": "wrong_length", "comment": "15 bytes", "text": protocol.id_text(ids[0][:15])},++ {"kind": "wrong_length", "comment": "17 bytes", "text": protocol.id_text(ids[0] + b"\x07")},++ {"kind": "whitespace", "comment": "a leading space", "text": " " + spelling},++ {"kind": "non_ascii", "comment": "a character outside ASCII", "text": spelling[:-1] + "é"},++ ]++ for item in refused:++ assert protocol.read_id(item["text"]) is None, item++ for case in cases:++ assert protocol.read_id(case["b64"]) == unhex(case["id_hex"])++ return {++ "$comment": "A machine id is 16 bytes in JSON as URL-safe base64 without padding, 22 characters, in its one spelling: decode, encode again, refuse the text if it differs.",++ "cases": cases,++ "refused": refused,++ }++++++URL_SAFE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"++++++def unused_bits_set(last: str) -> str:++ """The character of the same value in its top bits as the last of a 16-byte value's 22 characters,++ with one of its four unused low bits set: a lenient decoder reads the same bytes, `id_text` writes++ the other spelling."""++ index = URL_SAFE.index(last)++ assert index & 0xF == 0++ return URL_SAFE[index | 1]++++++def hello_fields(**change) -> dict:++ data = {++ "version": 6, "id": protocol.id_text(INITIATOR_ID), "name": "Vector Mac", "platform": "macos", "app": "1.5.0",++ "caps": ["clipboard", "text"], "port": 24820, "hw": "02:00:5e:10:00:01",++ }++ data.update(change)++ return data++++++def action_of(plain: bytes, reader: str) -> str:++ """What a desktop does with `plain` read as `reader` does: `end_link`, `ignore` (the message, the++ link goes on), `answer_invalid_hello` (a first frame that is not a valid hello), or `accepted`."""++ try:++ message = protocol.parse_message(plain)++ except protocol.NotAnObject:++ return "answer_invalid_hello" if reader == "hello" else "end_link"++ if reader == "hello":++ try:++ protocol.read_hello(message)++ except protocol.InvalidHello:++ return "answer_invalid_hello"++ return "accepted"++ if message.malformed:++ return "end_link" if reader in ("welcome", "ack") else "ignore"++ if reader in ("welcome", "ack"):++ try:++ {"welcome": protocol.read_welcome, "ack": protocol.read_ack}[reader](message)++ except protocol.ProtocolError:++ return "end_link"++ return "accepted"++ result = {++ "message": protocol.read_message,++ "input": protocol.read_input,++ "focus": lambda m: protocol.read_focus(m, bytes(range(1, 17))),++ "accept": protocol.read_accept,++ "refuse": protocol.read_refuse,++ "switch": protocol.read_switch,++ "arrangement": lambda m: protocol.read_arrangement_v6(m, now=WALL),++ }[reader](message)++ return "ignore" if result is None else "accepted"++++++def build_malformed() -> dict:++ def text(document) -> bytes:++ return json.dumps(document, separators=(",", ":")).encode("utf-8")++++ def hello(**change) -> bytes:++ return text({"type": "hello", "data": hello_fields(**change)})++++ def welcome(**change) -> bytes:++ data = {++ "version": 6, "id": protocol.id_text(RESPONDER_ID), "name": "VECTOR-PC", "platform": "windows", "app": "1.5.0",++ "caps": ["text"], "accepts": True,++ }++ data.update(change)++ return text({"type": "welcome", "data": data})++++ move = b'{"type":"mousemove","data":{"dx":%s,"dy":0,"seq":%s}}'++ # (comment, body, reader, action, whether a parser that refuses the text outright may end the link instead)++ cases = [++ ("an integer written 1.0 (dx)", move % (b"1.0", b"1"), "input", "ignore", False),++ ("an integer written 1e0 (seq)", move % (b"1", b"1e0"), "input", "ignore", False),++ ("a boolean for an integer (seq)", move % (b"1", b"true"), "input", "ignore", False),++ ("a boolean for an integer (dx)", move % (b"false", b"1"), "input", "ignore", False),++ ("NaN in a number", b'{"type":"scroll","data":{"dy":NaN,"dx":0,"mode":"line","seq":1}}', "input", "ignore", True),++ ("Infinity in a number", b'{"type":"scroll","data":{"dy":Infinity,"dx":0,"mode":"line","seq":1}}', "input", "ignore", True),++ ("a byte order mark before the object", b"\xef\xbb\xbf" + move % (b"1", b"1"), "input", "ignore", True),++ ("a lone surrogate in a string", b'{"type":"text","data":{"text":"\\ud800","seq":1}}', "input", "ignore", True),++ ("not an object: an array", b"[1,2]", "message", "end_link", False),++ ("not an object: a number", b"7", "message", "end_link", False),++ ("not UTF-8", b"\xff\xfe{}", "message", "end_link", False),++ ("no type", b'{"data":{}}', "message", "ignore", False),++ ("a type that is not a string", b'{"type":5,"data":{}}', "message", "ignore", False),++ ("data that is not an object", b'{"type":"ping","data":[]}', "message", "ignore", False),++ ("hello: hw in upper case", hello(hw="02:00:5E:10:00:01"), "hello", "answer_invalid_hello", False),++ ("hello: hw too short", hello(hw="02:00:5e"), "hello", "answer_invalid_hello", False),++ ("hello: app empty", hello(app=""), "hello", "answer_invalid_hello", False),++ ("hello: app over 32 characters", hello(app="x" * 33), "hello", "answer_invalid_hello", False),++ ("hello: app outside printable ASCII", hello(app="1.5.0é"), "hello", "answer_invalid_hello", False),++ ("hello: caps not a list", hello(caps="clipboard"), "hello", "answer_invalid_hello", False),++ ("hello: more than 16 caps", hello(caps=[f"cap{i}" for i in range(17)]), "hello", "answer_invalid_hello", False),++ ("hello: an empty cap", hello(caps=["text", ""]), "hello", "answer_invalid_hello", False),++ ("hello: a cap that is not a string", hello(caps=["text", 5]), "hello", "answer_invalid_hello", False),++ ("hello: platform with a space", hello(platform="Mac OS"), "hello", "answer_invalid_hello", False),++ ("hello: platform over 16 characters", hello(platform="a" * 17), "hello", "answer_invalid_hello", False),++ ("hello: name empty", hello(name=""), "hello", "answer_invalid_hello", False),++ ("hello: name of 49 code points", hello(name="n" * 49), "hello", "answer_invalid_hello", False),++ ("hello: id of sixteen zero bytes", hello(id="A" * 22), "hello", "answer_invalid_hello", False),++ ("hello: id of the wrong length", hello(id=protocol.id_text(INITIATOR_ID[:15])), "hello", "answer_invalid_hello", False),++ ("hello: version 5", hello(version=5), "hello", "answer_invalid_hello", False),++ ("hello: port above 65535", hello(port=65536), "hello", "answer_invalid_hello", False),++ ("hello: port as a string", hello(port="24820"), "hello", "answer_invalid_hello", False),++ ("hello: port written 1.0", hello(port=1.0), "hello", "answer_invalid_hello", False),++ ("welcome: accepts as a string", welcome(accepts="true"), "welcome", "end_link", False),++ ("welcome: accepts missing", text({"type": "welcome", "data": {k: v for k, v in json.loads(welcome())["data"].items() if k != "accepts"}}), "welcome", "end_link", False),++ ("welcome: an error that is not one of the two", text({"type": "welcome", "data": {"version": 6, "error": "go_away"}}), "welcome", "end_link", False),++ ("welcome: id of sixteen zero bytes", welcome(id="A" * 22), "welcome", "end_link", False),++ ("welcome: version 5", welcome(version=5), "welcome", "end_link", False),++ ("ack: seq written 1.0", b'{"type":"ack","data":{"seq":1.0,"held_us":0}}', "ack", "end_link", False),++ ("ack: held_us negative", b'{"type":"ack","data":{"seq":1,"held_us":-1}}', "ack", "end_link", False),++ ("ack: held_us above 2^31 - 1", b'{"type":"ack","data":{"seq":1,"held_us":2147483648}}', "ack", "end_link", False),++ ("ack: held_us missing", b'{"type":"ack","data":{"seq":1}}', "ack", "end_link", False),++ ("ack: locked false", b'{"type":"ack","data":{"seq":1,"held_us":0,"locked":false}}', "ack", "end_link", False),++ ("accept: route 0", b'{"type":"accept","data":{"route":0}}', "accept", "ignore", False),++ ("accept: route as a string", b'{"type":"accept","data":{"route":"1"}}', "accept", "ignore", False),++ ("refuse: no route", b'{"type":"refuse","data":{"why":"owned"}}', "refuse", "ignore", False),++ ("switch: next of sixteen zero bytes", text({"type": "switch", "data": {"route": 1, "next": "A" * 22}}), "switch", "ignore", False),++ ("switch: edge without offset", text({"type": "switch", "data": {"route": 1, "next": protocol.id_text(THIRD_ID), "edge": "left"}}), "switch", "ignore", False),++ ("switch: an edge that is not one", text({"type": "switch", "data": {"route": 1, "next": protocol.id_text(THIRD_ID), "edge": "middle", "offset": 0.5}}), "switch", "ignore", False),++ ]++ result = []++ for comment, plain, reader, action, parser_may_end in cases:++ assert action_of(plain, reader) == action, comment++ try:++ decoded = plain.decode("utf-8")++ except UnicodeDecodeError:++ decoded = None++ case = {"comment": comment, "hex": h(plain), "text": decoded, "reader": reader, "action": action}++ if parser_may_end:++ case["also_acceptable"] = "end_link"++ result.append(case)++++ repeated = b'{"type":"mousemove","data":{"dx":1,"dx":2,"dy":0,"seq":1}}'++ assert action_of(repeated, "input") == "ignore"++ good = hello()++ assert action_of(good, "hello") == "accepted"++ return {++ "$comment": (++ "Message bodies a receiver must not act on, and what a desktop does with each: `end_link` ends the link, `ignore` drops the message and the link goes on, "++ "`answer_invalid_hello` is a first frame answered with welcome carrying error invalid_hello (and the link closed). `reader` says which validator a desktop "++ "reads it with: a hello or welcome as the first frame each way, an ack, or any other message. `also_acceptable` is for a text a JSON parser may refuse outright "++ "(WIRE.md, Encodings): ending the link instead of ignoring it is allowed. `well_formed_hello` is accepted, so the refusals around it mean something."++ ),++ "well_formed_hello": {"hex": h(good), "text": good.decode("utf-8")},++ "cases": result,++ "implementation_defined": [++ {++ "comment": "a repeated key: a receiver may refuse the message or keep the last value (WIRE.md, Encodings); a desktop ignores it, and a correct sender never sends one",++ "hex": h(repeated), "text": repeated.decode("utf-8"), "reader": "input", "desktop_action": "ignore",++ }++ ],++ }++++++def build_qr() -> dict:++ good = []++ for host, port, code, label in (("192.168.0.7", 24821, "482913", "v6-qr-1"), ("192.168.1.20", 24821, "007045", "v6-qr-2")):++ secret = fixed_bytes(label, 16)++ qr = pairing.qr_text(host, port, code, secret)++ assert pairing.read_qr(qr) == {"host": host, "port": port, "code": code, "secret": secret} and len(qr.split("k=")[1]) == 22++ good.append({"text": qr, "host": host, "port": port, "code": code, "secret_hex": h(secret)})++ base = good[0]["text"]++ k = base.split("k=")[1]++ standard_k = protocol.id_text(unhex("fbffbf") + bytes(13))++ standard_k = standard_k.replace("-", "+").replace("_", "/")++ assert "+" in standard_k or "/" in standard_k++ bad = [++ ("the wrong scheme", base.replace("beamer://", "beamerx://")),++ ("a slash before the query", base.replace("pair?", "pair/?")),++ ("no k", base.rsplit("&k=", 1)[0]),++ ("an extra key", base + "&x=1"),++ ("the keys in another order", f"beamer://pair?port=24821&host=192.168.0.7&code=482913&k={k}"),++ ("an upper-case key", base.replace("host=", "Host=")),++ ("a repeated key", base + "&k=" + k),++ ("a host with a leading zero octet", base.replace("192.168.0.7", "192.168.0.07")),++ ("a host that is a name", base.replace("192.168.0.7", "beamer.example")),++ ("a host of five octets", base.replace("192.168.0.7", "192.168.0.7.5")),++ ("a host octet above 255", base.replace("192.168.0.7", "192.168.0.256")),++ ("port 0", base.replace("port=24821", "port=0")),++ ("port 65536", base.replace("port=24821", "port=65536")),++ ("a port with a leading zero", base.replace("port=24821", "port=024821")),++ ("a port with a sign", base.replace("port=24821", "port=+24821")),++ ("a port with a digit percent-encoded: the text is read as it is", base.replace("port=24821", "port=%32%34821")),++ ("a code of five digits", base.replace("code=482913", "code=48291")),++ ("a code with a letter", base.replace("code=482913", "code=48291a")),++ ("a code in full-width digits", base.replace("code=482913", "code=482913")),++ ("k of 21 characters", base.replace("k=" + k, "k=" + k[:-1])),++ ("k with padding", base + "=="),++ ("k in a non-canonical spelling: its last character changed in its unused bits", base[:-1] + unused_bits_set(k[-1])),++ ("k in the standard alphabet, + and / for - and _", base.replace("k=" + k, "k=" + standard_k)),++ ]++ for comment, text in bad:++ try:++ pairing.read_qr(text)++ except pairing.PairingError as exc:++ assert str(exc) == "bad_qr", comment++ else:++ raise AssertionError(comment)++ return {++ "$comment": "The text a pairing QR holds: four keys in order, lower case, each once, nothing else. `k` is the code's 16-byte QR secret as 22 characters of b64.",++ "good": good,++ "bad": [{"comment": comment, "text": text, "error": "bad_qr"} for comment, text in bad],++ }++++++KEY_ROWS = [++ ("Mac Control", "mac", "ctrl"), ("Mac right Control", "mac", "ctrl_r"), ("Mac Command", "mac", "cmd"),++ ("Mac right Command", "mac", "cmd_r"), ("Mac Option", "mac", "alt"), ("Mac right Option", "mac", "alt_r"),++ ("PC Control", "pc", "ctrl"), ("PC right Control", "pc", "ctrl_r"), ("PC Windows or Super", "pc", "cmd"),++ ("PC right Windows or Super", "pc", "cmd_r"), ("PC Alt", "pc", "alt"), ("PC right Alt or AltGr", "pc", "alt_r"),++]++++++def build_key_table() -> dict:++ platforms = {"mac": ("macos", "windows"), "pc": ("windows", "macos")}++ rows = []++ for label, sender, physical in KEY_ROWS:++ own, other = platforms[sender]++ rows.append({++ "key": label, "sender": sender, "physical": physical,++ "same_family": keytable.wire_name(physical, own, own, "semantic"),++ "across_semantic": keytable.wire_name(physical, own, other, "semantic"),++ "across_positional": keytable.wire_name(physical, own, other, "positional"),++ "across_mac_layout": (++ keytable.wire_name(physical, own, other, "mac_layout") if sender == "pc" else "—"++ ),++ })++ assert keytable.wire_name("ctrl", "freebsd", "macos", "semantic") == "cmd" and keytable.wire_name("ctrl", "freebsd", "windows", "semantic") == "ctrl"++ return {++ "$comment": (++ "WIRE.md section 7's table. `sender` is the family of the machine whose key was pressed (mac: macos and ios; pc: every other platform, an unknown one included); "++ "`physical` is the key on that machine's own keyboard; the columns are the name it travels as to a peer of the same family and across families under each saved style. "++ "`evdev` maps a Linux sender's key codes to physical names; a code not in it is a character key."++ ),++ "mac_platforms": sorted(keytable.MAC_PLATFORMS),++ "unknown_platform_is": "pc",++ "rows": rows,++ "names": sorted(keytable.SPEC_NAMES),++ "evdev": {str(code): name for code, name in sorted(keytable.EVDEV_NAMES.items())},++ }++++++def build_ack() -> dict:++ raw = [++ ("an ordinary acknowledgement", 5, 1_000_000, 1_012_400, 1_830),++ ("held longer than the round trip: the sample is clamped to 0", 6, 2_000_000, 2_000_900, 1_500),++ ("held_us asked above the limit is sent as 2^31 - 1", 7, 10_000_000, 13_000_000_000, 5_000_000_000),++ ("a negative held_us is sent as 0", 8, 500, 4_500, -5),++ ]++ cases = []++ for comment, seq, sent, arrived, asked in raw:++ message = protocol.ack_v6(seq, asked)++ on_wire = message["data"]["held_us"]++ assert on_wire == min(2**31 - 1, max(0, asked)) and protocol.read_ack(protocol.parse_message(protocol.dumps_message(message)))["held_us"] == on_wire++ cases.append({++ "comment": comment, "seq": seq, "sent_at_us": sent, "arrived_at_us": arrived,++ "held_us_asked": asked, "held_us_on_wire": on_wire, "sample_us": max(0, arrived - sent - on_wire), "message": message,++ })++ return {++ "$comment": "sample_us = max(0, (arrived_at_us - sent_at_us) - held_us): the round trip with the responder's holding time taken out, for an ack whose seq is higher than the last. `held_us_asked` is what a sender has, `held_us_on_wire` what it sends.",++ "cases": cases,++ }++++++def build_clipboard_images() -> dict:++ from core.tests import pngs++ limit = protocol.PNG_METADATA_MAX_BYTES++ stream = pngs.run(b"a", 1000)++ raw = [++ ("a 1 by 1 image", pngs.png(), True),++ ("an 8K screen's header, 7680 by 4320", pngs.png(7680, 4320), True),++ ("16384 by 2048, exactly 2^25 pixels", pngs.png(16384, 2048), True),++ ("bytes after IEND are ignored", pngs.png() + b"trailing", True),++ ("zTXt inflating to exactly 4 MiB", pngs.png(8, 8, pngs.ztxt(limit)), True),++ ("a side of 16385", pngs.png(16385, 1), False),++ ("6000 by 6000, past 2^25 pixels", pngs.png(6000, 6000), False),++ ("IHDR not the first chunk", protocol.PNG_SIGNATURE + pngs.chunk(b"tEXt", b"a\x00b") + pngs.png()[8:], False),++ ("no IEND", pngs.png()[:-12], False),++ ("a second IHDR", pngs.png(8, 8, pngs.ihdr(100000, 100000)), False),++ ("an APNG acTL", pngs.png(8, 8, pngs.chunk(b"acTL", bytes(8))), False),++ ("zTXt inflating to 4 MiB and one byte", pngs.png(8, 8, pngs.ztxt(limit + 1)), False),++ ("zTXt whose zlib stream is cut short", pngs.png(8, 8, pngs.chunk(b"zTXt", b"Comment\x00\x00" + stream[:-6])), False),++ ("iTXt with a compression flag of 2", pngs.png(8, 8, pngs.chunk(b"iTXt", b"Key\x00\x02\x00en\x00\x00text")), False),++ ]++ cases = []++ for comment, image, fits in raw:++ assert protocol.png_fits(image) is fits, comment++ cases.append({"comment": comment, "png_hex": h(image), "fits": fits})++ return {++ "$comment": "Clipboard images judged from their bytes before anything decodes them (WIRE.md section 3). `fits` false drops the image part of a clipboard message and keeps its text. Pixel data is not real past 1 by 1: nothing here decodes it.",++ "cases": cases,++ }++++++def build_v6() -> dict:++ return {++ "$comment": "Wire version 6 (WIRE.md). Hex is bytes in wire order. Generated from core/protocol.py and checked against HKDF, X25519 and ChaCha20-Poly1305 written apart from it.",++ "constants": build_constants(),++ "key_id": build_key_id(),++ "preamble": build_preamble(),++ "short_reply": build_short_reply(),++ "derive_key": build_derive_key(),++ "low_order": build_low_order(),++ "frames": build_frames(),++ "bad_frames": build_bad_frames(),++ "ids": build_ids(),++ "malformed": build_malformed(),++ "qr": build_qr(),++ "key_table": build_key_table(),++ "ack": build_ack(),++ "clipboard_images": build_clipboard_images(),++ }++++++# ----------------------------------------------------------------------------------------------++# pairing v3++++def party(role: bytes, who: dict) -> bytes:++ return lv(role, unhex(who["id_hex"]), who["name"].encode("utf-8"), who["platform"].encode("ascii"), who["port"].to_bytes(2, "big"))++++++def side(name: str, label: str, platform: str, port: int) -> dict:++ return {"name": name, "id_hex": h(fixed_bytes(f"{label}-id", 16)), "platform": platform, "port": port}++++++def make_host(label: str, host: dict, code: str, qr_secret, entropy_pair_id: bytes, scalar: bytes):++ stored = []++ machine = pairing.PairingHost(++ name=host["name"], identity=unhex(host["id_hex"]), version=3, platform=host["platform"], port=host["port"],++ entropy=scripted(entropy_pair_id, qr_secret if qr_secret is not None else bytes(16), scalar),++ peers=list, store=lambda entry, replaced: stored.append(entry), wall=lambda: WALL,++ )++ machine.begin()++ machine.code = code++ return machine, stored++++++def build_exchange_v3(comment: str, label: str, code: str, qr: bool, requester: dict, host: dict) -> dict:++ pair_id = fixed_bytes(f"{label}-pair-id", 16)++ qr_secret = fixed_bytes(f"{label}-qr-secret", 16) if qr else None++ nonce = fixed_bytes(f"{label}-nonce", pairing.NONCE_BYTES)++ requester_scalar, host_scalar = fixed_bytes(f"{label}-requester-scalar"), fixed_bytes(f"{label}-host-scalar")++ requester = {**requester, "nonce_hex": h(nonce), "scalar_hex": h(requester_scalar)}++ host = {**host, "scalar_hex": h(host_scalar)}++++ machine, stored = make_host(label, host, code, qr_secret, pair_id, host_scalar)++ beacon = machine.beacon(host["port"])++ assert beacon["pair"] == pair_id.hex() and beacon["id"] == pairing._b64(unhex(host["id_hex"])) and beacon["pairing"] == 3++ client = pairing.PairingClient(++ machine.pair_id, code, requester["name"], unhex(requester["id_hex"]), scripted(nonce, requester_scalar),++ version=3, platform=requester["platform"], port=requester["port"], qr_secret=qr_secret, wall=lambda: WALL,++ )++ start = client.start()++ answer = machine.handle(start, "10.1.2.3")++ confirm = client.accept(answer)++ done = machine.handle(confirm, "10.1.2.3")++ token = client.finish(done)++ assert len(stored) == 1 and stored[0]["token"] == token++ assert all(len(pairing.encode(message)) <= pairing.MAX_DATAGRAM_BYTES for message in (start, answer, confirm, done))++++ prs = code.encode("ascii") + (qr_secret or b"")++ assert len(prs) == (22 if qr else 6)++ sid = lv(pair_id.hex().encode("ascii"), nonce)++ padding = bytes(128 - 1 - len(pairing._prepend_len(prs)) - len(pairing._prepend_len(b"CPace255")))++ assert len(padding) == (95 if qr else 111)++ generator_string = lv(b"CPace255", prs, padding, b"beamer-pair-v3", sid)++ generator = pairing._elligator2(int.from_bytes(hashlib.sha512(generator_string).digest()[:32], "little") & ((1 << 255) - 1)).to_bytes(32, "little")++ assert generator == pairing._generator(prs, b"beamer-pair-v3", sid)++ ya, yb = x25519_ladder(requester_scalar, generator), x25519_ladder(host_scalar, generator)++ shared = x25519_ladder(requester_scalar, yb)++ assert shared == x25519_ladder(host_scalar, ya)++ ada, adb = party(b"requester", requester), party(b"host", host)++ isk = hashlib.sha512(lv(b"CPace255_ISK", sid, shared) + lv(ya, ada) + lv(yb, adb)).digest()++ mac_key = hashlib.sha512(b"CPaceMac" + sid + isk).digest()++ ta, tb, td = (hmac.new(mac_key, message, hashlib.sha512).digest() for message in (lv(ya, ada), lv(yb, adb), lv(b"beamer-pair-done")))++ expected_token = pairing._b64(hkdf(isk, sid, b"beamer-pair-token-v3"))++ assert token == expected_token++ assert (start["share"], answer["share"]) == (pairing._b64(ya), pairing._b64(yb))++ assert (confirm["tag"], answer["tag"], done["tag"]) == (pairing._b64(ta), pairing._b64(tb), pairing._b64(td))++++ return {++ "comment": comment,++ "code": code,++ "qr_secret_hex": h(qr_secret) if qr_secret else None,++ "prs_hex": h(prs),++ "wall": WALL,++ "pair_id": pair_id.hex(),++ "requester": requester,++ "host": host,++ "sid_hex": h(sid),++ "ada_hex": h(ada),++ "adb_hex": h(adb),++ "generator_string_hex": h(generator_string),++ "generator_hex": h(generator),++ "ya_hex": h(ya),++ "yb_hex": h(yb),++ "k_hex": h(shared),++ "isk_hex": h(isk),++ "mac_key_hex": h(mac_key),++ "ta_hex": h(ta),++ "tb_hex": h(tb),++ "td_hex": h(td),++ "token": token,++ "key_id_hex": h(protocol.key_id(token)),++ "beacon": beacon,++ "messages": {"pair_start": start, "pair_answer": answer, "pair_confirm": confirm, "pair_done": done},++ }++++++def build_wrong_prs() -> dict:++ label, code = "v3-wrong-prs", "482913"++ pair_id, qr_secret = fixed_bytes(f"{label}-pair-id", 16), fixed_bytes(f"{label}-qr-secret", 16)++ nonce = fixed_bytes(f"{label}-nonce", pairing.NONCE_BYTES)++ requester_scalar, host_scalar = fixed_bytes(f"{label}-requester-scalar"), fixed_bytes(f"{label}-host-scalar")++ requester = {**side("Vector iPhone", f"{label}-requester", "ios", 0), "nonce_hex": h(nonce), "scalar_hex": h(requester_scalar)}++ host = {**side("Vector Mac", f"{label}-host", "macos", 24820), "scalar_hex": h(host_scalar)}++ machine, _ = make_host(label, host, code, qr_secret, pair_id, host_scalar)++ client = pairing.PairingClient(++ machine.pair_id, code, requester["name"], unhex(requester["id_hex"]), scripted(nonce, requester_scalar),++ version=3, platform="ios", port=0, qr_secret=qr_secret,++ )++ sent = client.start()++ assert sent["qr"] == 1++ received = {key: value for key, value in sent.items() if key != "qr"}++ answer = machine.handle(received, "10.1.2.3")++ assert answer["ok"] is True++ try:++ client.accept(answer)++ except pairing.PairingError as exc:++ assert str(exc) == pairing.ERROR_REFUSED++ else:++ raise AssertionError("an answer made under another password was accepted")++ abort = client.abort()++ reply = machine.handle(abort, "10.1.2.3")++ assert reply == {"type": "pair_done", "pair": pair_id.hex(), "ok": False, "error": "refused"}++++ sid = lv(pair_id.hex().encode("ascii"), nonce)++ prs_requester = code.encode("ascii") + qr_secret++ generator = pairing._generator(prs_requester, b"beamer-pair-v3", sid)++ ya = x25519_ladder(requester_scalar, generator)++ assert pairing._b64(ya) == sent["share"]++ yb = unhex(h(pairing._unb64(answer["share"])))++ shared = x25519_ladder(requester_scalar, yb)++ ada = party(b"requester", requester)++ adb = party(b"host", {"name": answer["name"], "id_hex": h(pairing._unb64(answer["id"])), "platform": answer["platform"], "port": answer["port"]})++ isk = hashlib.sha512(lv(b"CPace255_ISK", sid, shared) + lv(ya, ada) + lv(yb, adb)).digest()++ expected_tb = hmac.new(hashlib.sha512(b"CPaceMac" + sid + isk).digest(), lv(yb, adb), hashlib.sha512).digest()++ answer_tb = pairing._unb64(answer["tag"])++ assert expected_tb != answer_tb++ return {++ "$comment": (++ "A QR's `qr` stripped from pair_start on the path. The host, seeing none, makes its answer from the 6-byte code; the requester, which "++ "used the 22-byte password, works out another Tb, so it must refuse the answer, send the abort once, and never send a tag of its own."++ ),++ "code": code,++ "qr_secret_hex": h(qr_secret),++ "pair_id": pair_id.hex(),++ "requester": requester,++ "host": host,++ "pair_start_sent": sent,++ "pair_start_received": received,++ "prs_used_by_host_hex": h(code.encode("ascii")),++ "prs_used_by_requester_hex": h(prs_requester),++ "pair_answer": answer,++ "answer_tb_hex": h(answer_tb),++ "expected_tb_hex": h(expected_tb),++ "requester_must": "refused",++ "pair_confirm_abort": abort,++ "host_reply_to_abort": reply,++ }++++++def build_refusals() -> dict:++ label, code = "v3-refusals", "482913"++ pair_id, qr_secret = fixed_bytes(f"{label}-pair-id", 16), fixed_bytes(f"{label}-qr-secret", 16)++ nonce = fixed_bytes(f"{label}-nonce", pairing.NONCE_BYTES)++ requester_scalar, host_scalar = fixed_bytes(f"{label}-requester-scalar"), fixed_bytes(f"{label}-host-scalar")++ host = {**side("Vector Mac", f"{label}-host", "macos", 24820), "scalar_hex": h(host_scalar)}++ requester_id = fixed_bytes(f"{label}-requester-id", 16)++ machine, _ = make_host(label, host, code, qr_secret, pair_id, host_scalar)++ client = pairing.PairingClient(++ machine.pair_id, code, "Vector Mac 2", requester_id, scripted(nonce, requester_scalar), version=3, platform="macos", port=24820,++ )++ good = client.start()++ answer = {"type": "pair_answer", "pair": pair_id.hex(), "ok": False, "error": "refused"}++ variants = [++ ("an id of 15 bytes", requester_id[:15]),++ ("an id of 17 bytes", requester_id + b"\x09"),++ ("an id of sixteen zero bytes", bytes(16)),++ ("an empty id, as 1.4.3 sent", b""),++ ("an id of 32 bytes", fixed_bytes(f"{label}-long-id", 32)),++ ]++ cases = []++ for comment, ident in variants:++ start = {**good, "id": pairing._b64(ident)}++ fresh, _ = make_host(label, host, code, qr_secret, pair_id, host_scalar)++ assert fresh.handle(start, "10.1.2.3") == answer and fresh.code is None, comment++ cases.append({"comment": comment, "pair_start": start, "must_answer": answer})++ served, _ = make_host(label, host, code, qr_secret, pair_id, host_scalar)++ honest = served.handle(good, "10.1.2.3")++ assert honest["ok"] is True++ answer_cases = []++ for comment, ident in variants:++ reply = {**honest, "id": pairing._b64(ident)}++ fresh = pairing.PairingClient(++ pair_id.hex(), code, "Vector Mac 2", requester_id, scripted(nonce, requester_scalar), version=3, platform="macos", port=24820,++ )++ assert fresh.start() == good++ try:++ fresh.accept(reply)++ except pairing.PairingError as exc:++ assert str(exc) == pairing.ERROR_REFUSED, comment++ else:++ raise AssertionError(comment)++ answer_cases.append({"comment": comment.replace("an id", "a host id", 1) if comment.startswith("an id") else comment, "pair_answer": reply, "requester_must": "refused"})++ return {++ "$comment": (++ "pair_start messages whose id is not 16 bytes or is all zero. The host answers each with a refusal, drops its code, and stores nothing. "++ "Each case is offered to a fresh host. `answer_cases` are the same identities in an otherwise valid pair_answer to the requester whose "++ "`pair_start` is `requester_start`: it must refuse each before it sends a tag."++ ),++ "code": code,++ "qr_secret_hex": h(qr_secret),++ "pair_id": pair_id.hex(),++ "host": host,++ "cases": cases,++ "requester": {"name": "Vector Mac 2", "id_hex": h(requester_id), "platform": "macos", "port": 24820, "nonce_hex": h(nonce), "scalar_hex": h(requester_scalar)},++ "requester_start": good,++ "answer_cases": answer_cases,++ }++++++class _Capture:++ def __init__(self):++ self.data = b""++++ def sendall(self, data: bytes) -> None:++ self.data += data++++++def build_tcp(exchange: dict) -> dict:++ order = (("host", "beacon"), ("requester", "pair_start"), ("host", "pair_answer"), ("requester", "pair_confirm"), ("host", "pair_done"))++ frames = []++ for who, name in order:++ message = exchange["beacon"] if name == "beacon" else exchange["messages"][name]++ sock = _Capture()++ pairing._send_frame(sock, message)++ (length,) = struct.unpack(">I", sock.data[:4])++ assert length == len(sock.data) - 4 and 0 < length <= 1024++ assert pairing.decode(sock.data[4:]) == {"beamy": 1, **message}++ frames.append({"from": who, "message": message, "bytes_hex": h(sock.data)})++ return {++ "$comment": (++ "One exchange over TCP on port 24821, in order: the host sends its beacon as soon as the connection is accepted, then the four messages. "++ "Each is a 4-byte big-endian length, 1 to 1024, then the JSON a datagram would carry with \"beamy\":1 first. `message` is the object "++ "without `beamy`. The desktops write compact JSON with every character outside ASCII escaped as \\uXXXX (the requester's name here has "++ "some); a receiver must accept either spelling, because the tags bind the decoded name and id, never these bytes."++ ),++ "exchange_comment": exchange["comment"],++ "frames": frames,++ }++++++def build_pairing_v3() -> dict:++ check_published_vectors()++ exchanges = [++ build_exchange_v3(++ "Desktop to desktop with the code typed; the requester's name is 48 code points outside ASCII and the BMP, 177 bytes, so its length in ADa takes two LEB128 bytes",++ "v3-pairing-1", "482913", False,++ side(LONG_NAME, "v3-pairing-1-requester", "macos", 24820), side("VECTOR-PC", "v3-pairing-1-host", "windows", 24820),++ ),++ build_exchange_v3(++ "A phone pairing by QR: port 0, qr 1, and a 22-byte password",++ "v3-pairing-2", "007045", True,++ side("Zoë’s \U0001d539Phone", "v3-pairing-2-requester", "ios", 0), side("Vector Mac", "v3-pairing-2-host", "macos", 24820),++ ),++ build_exchange_v3(++ "Desktop to desktop, typed, a code with leading zeros and a platform of the other family",++ "v3-pairing-3", "000042", False,++ side("Vector Linux", "v3-pairing-3-requester", "linux", 24820), side("Vector Mac", "v3-pairing-3-host", "macos", 24820),++ ),++ ]++ return {++ "$comment": (++ "Pairing version 3 (WIRE.md section 6). Hex is bytes in wire order. Every exchange shows every intermediate value and all four "++ "messages. The host of a typed exchange still draws a QR secret when it shows a code, which nothing uses, so its `qr_secret_hex` is null. "++ "`beacon` is the host's beacon while the code is up."++ ),++ "constants": {++ "pairing_version": pairing.PAIRING_V3,++ "pair_start_v": pairing.PAIRING_V3,++ "dsi_ascii": "CPace255",++ "channel_ascii": pairing.CHANNEL_V3.decode("ascii"),++ "token_info_ascii": pairing.TOKEN_INFO_V3.decode("ascii"),++ "done_label_ascii": pairing.DONE_LABEL.decode("ascii"),++ "role_requester_ascii": pairing.ROLE_REQUESTER.decode("ascii"),++ "role_host_ascii": pairing.ROLE_HOST.decode("ascii"),++ "id_bytes": pairing.ID_BYTES,++ "qr_secret_bytes": pairing.QR_SECRET_BYTES,++ "max_peers": pairing.MAX_PEERS,++ "nonce_bytes": pairing.NONCE_BYTES,++ "max_name_chars": pairing.MAX_NAME_CHARS,++ "tcp_port": pairing.PAIRING_PORT,++ "link_key_id_info_ascii": protocol.KEY_ID_INFO.decode("ascii"),++ },++ "exchanges": exchanges,++ "wrong_prs": build_wrong_prs(),++ "tcp": build_tcp(exchanges[1]),++ "refusals": build_refusals(),++ }++++++# ----------------------------------------------------------------------------------------------++++def build(old: dict) -> dict:++ """The whole file: the old sections as `old` has them, then the two new ones."""++ vectors = {++ "$comment": (++ "Generated by beamer/tools/phone_vectors.py. The protocol_version, preamble, derive_key, frames, pairing and messages sections "++ "(wire version 5 and pairing version 2) were written by 1.4.x's code and are carried over untouched; v6 and pairing_v3 are made from "++ "core/protocol.py and core/pairing.py. Every value is fixed, not random -- rerunning this script must reproduce this file byte for "++ "byte until the wire format changes."++ ),++ }++ for name in OLD_SECTIONS:++ vectors[name] = old[name]++ vectors["v6"] = build_v6()++ vectors["pairing_v3"] = build_pairing_v3()++ return vectors++++++def render(vectors: dict) -> str:++ return json.dumps(vectors, indent=2, sort_keys=False) + "\n"++++++def main() -> None:++ out_path = Path(__file__).resolve().parent / "phone_vectors.json"++ vectors = build(json.loads(out_path.read_text(encoding="utf-8")))++ out_path.write_text(render(vectors), encoding="utf-8")++ print(f"wrote {out_path}")++ # The sections beside the tests that replay them: this folder is not part of the public++ # repository, and the test suites and PAIRING.md there need them.++ tests = REPO / "core" / "tests"++ (tests / "pairing_vectors.json").write_text(render(vectors["pairing"]), encoding="utf-8")++ print(f"wrote {tests / 'pairing_vectors.json'}")++ (tests / "v6_vectors.json").write_text(render({"v6": vectors["v6"], "pairing_v3": vectors["pairing_v3"]}), encoding="utf-8")++ print(f"wrote {tests / 'v6_vectors.json'}")++++++if __name__ == "__main__":++ main()diff --cc tools/readme_shots_mac.pyindex 0000000,0000000..592804dnew file mode 100644--- /dev/null+++ b/tools/readme_shots_mac.py@@@ -1,0 -1,0 +1,70 @@@++"""The README's Mac screenshots and a layout check: the real settings window, built from a synthetic++config (documentation addresses, no house detail) and drawn page by page into a bitmap without++ever being put on screen. Starts nothing: no event tap, no link, no discovery."""++++import json++import logging++import os++import sys++import tempfile++import time++from pathlib import Path++++REPO = Path(sys.argv[1])++OUT = Path(sys.argv[2])++PAGES = sys.argv[3:] or ["overview", "design", "keyboard"]++sys.path.insert(0, str(REPO / "mac_app"))++++import AppKit # noqa: E402++from Foundation import NSDate, NSRunLoop # noqa: E402++++AppKit.NSApplication.sharedApplication()++++import kvm_bridge_app # noqa: E402++import settings_store # noqa: E402++from wake import WakingController as KVMController # noqa: E402++++kvm_bridge_app.VERSION = os.environ.get("SHOT_VERSION", kvm_bridge_app.VERSION)++kvm_bridge_app.accessibility_granted = lambda: True++kvm_bridge_app.input_monitoring_granted = lambda: True++++path = Path(tempfile.mkdtemp()) / "config.json"++raw = settings_store.config_to_raw(settings_store.editable_default_config())++raw.update(host="192.168.1.20", auth_token="synthetic", pc_name="Desktop PC",++ ignored_inputs=["button:back", "button:forward", "media:volume_up", "key:105"],++ appearance=os.environ.get("APPEARANCE", "dark"))++path.write_text(json.dumps(raw))++store = settings_store.SettingsStore(path)++logger = logging.getLogger("shots")++controller = KVMController(store.load(), logger=logger)++if os.environ.get("CONNECTED"):++ controller.sock = object()++ controller.connected_at = controller.last_ack_at = time.monotonic()++ controller.tap_ready.set()++ controller.event_tap = object()++window = kvm_bridge_app.ControlWindow.alloc().initWithController_settingsStore_logger_(controller, store, logger)++window.has_notch = True++controller.notch_range = (656.0, 856.0)++width, height = (int(v) for v in os.environ.get("SIZE", "900x640").split("x"))++# SWITCH_TO builds the window in APPEARANCE and switches it live, the way a choice or the Mac++# switching does, so a shot proves the repaint rather than a fresh build.++if os.environ.get("SWITCH_TO"):++ window._apply_appearance(os.environ["SWITCH_TO"])++window.window.setContentSize_((width, height))++OUT.mkdir(parents=True, exist_ok=True)++for key in PAGES:++ window._select_page(key)++ window.refresh()++ if key == "design" and window.previews is not None:++ loop = window.previews++ loop.started_at = time.monotonic() - float(os.environ.get("PREVIEW_AT", "1.6"))++ loop._tick()++ NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.3))++ view = window.window.contentView().superview() or window.window.contentView()++ view.layoutSubtreeIfNeeded()++ rep = view.bitmapImageRepForCachingDisplayInRect_(view.bounds())++ view.cacheDisplayInRect_toBitmapImageRep_(view.bounds(), rep)++ data = rep.representationUsingType_properties_(AppKit.NSBitmapImageFileTypePNG, {})++ suffix = os.environ.get("SUFFIX", "")++ data.writeToFile_atomically_(str(OUT / f"mac-{key}{suffix}.png"), True)++print(OUT)diff --cc tools/readme_shots_win.pyindex 0000000,0000000..81fe6e1new file mode 100644--- /dev/null+++ b/tools/readme_shots_win.py@@@ -1,0 -1,0 +1,85 @@@++"""The README's Windows screenshots: the real settings window, built offscreen from a synthetic++config (documentation addresses, no house detail) and grabbed page by page. Starts nothing: no++receiver, no hooks, no announcer.++++APPEARANCE=light|dark (default dark) is the palette the window is built in. SWITCH_TO=light|dark,++set as well, has the window built in APPEARANCE and then live-switched with _apply_appearance++before anything is shot -- proving the live switch renders the same as building in the target++appearance directly, not just the initial build."""++++import json++import os++import sys++import tempfile++import time++from pathlib import Path++++REPO = Path(sys.argv[1])++OUT = Path(sys.argv[2])++sys.path.insert(0, str(REPO / "win_app"))++++from PySide6.QtWidgets import QApplication # noqa: E402++++import theme # noqa: E402++++app = QApplication(sys.argv[:1])++theme.init_fonts()++appearance = os.environ.get("APPEARANCE", "dark").strip().lower()++app.setFont(theme.font(theme.TYPE["body"]))++++import kvm_bridge_win # noqa: E402++from core.receiver import ServerState # noqa: E402++++kvm_bridge_win.VERSION = os.environ.get("SHOT_VERSION", kvm_bridge_win.VERSION)++# Drawn as the installed app is, not as a run from source, which cannot start at sign-in.++kvm_bridge_win.autostart_win.installed_exe = lambda: Path("Beamer.exe")++kvm_bridge_win.autostart_win.is_enabled = lambda: True++folder = Path(tempfile.mkdtemp())++(folder / "config.json").write_text(json.dumps({++ "host": "192.168.1.20", "port": 24820, "auth_token": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8", "paired_with": "MacBook Pro",++ "mac_host": "192.168.1.10", "mac_return_edge": "left", "glow_colour": "signal",++ "ignored_inputs": ["button:back", "button:forward", "key:175", "key:174"],++ "appearance": appearance,++}))++window = kvm_bridge_win.WindowsApplication(folder / "settings.json")++window._set_status(ServerState.CONNECTED, "Connected to 192.168.1.10")++# This PC's own link to the Mac, as the Mac tool's CONNECTED fakes its socket: without it Overview++# says "not connected" under "Mac connected".++window.sender._sock = object()++window.resize(820, 700)++window.show()++# _set_status only takes effect on the next _refresh_window, whose status heading then cross-fades++# in: forced and settled here, before anything is timed, so that fade never lands mid-shot.++window._refresh_window()++started = time.monotonic()++while time.monotonic() - started < 0.25:++ app.processEvents()++ time.sleep(0.01)++++switch_to = os.environ.get("SWITCH_TO", "").strip().lower()++if switch_to:++ started = time.monotonic()++ while time.monotonic() - started < 0.1:++ app.processEvents()++ time.sleep(0.01)++ window._apply_appearance(switch_to)++ # Past the 200ms cross-fade (motion.DURATION), so the switch has fully settled.++ started = time.monotonic()++ while time.monotonic() - started < 0.5:++ app.processEvents()++ time.sleep(0.01)++++OUT.mkdir(parents=True, exist_ok=True)++# PAGES names pages, space-separated; the README's three by default.++for key in os.environ.get("PAGES", "overview design keyboard").split():++ settle = 0.3++ window._select_page(key)++ window.stack.setFocus()++ started = time.monotonic()++ while time.monotonic() - started < settle:++ app.processEvents()++ time.sleep(0.01)++ window._refresh_window()++ app.processEvents()++ window.grab().save(str(OUT / f"windows-{key}{os.environ.get('SUFFIX', '')}.png"))++print(OUT)diff --cc tools/render_colour_choices.pyindex 0000000,0000000..f48ee0bnew file mode 100644--- /dev/null+++ b/tools/render_colour_choices.py@@@ -1,0 -1,0 +1,300 @@@++"""Render native Design colour controls and every preview without showing a window.++++Run Mac and Qt separately: their modules intentionally share names.++"""++++import argparse++import json++import logging++import math++import os++from pathlib import Path++import sys++from unittest import mock++++ROOT = Path(__file__).resolve().parents[1]++sys.path.insert(0, str(ROOT))++NEW_COLOURS = {"aurora", "opal", "sea_glass", "arc", "magnesium", "ruby", "cobalt",++ "moss", "plum", "woad", "saffron", "citron", "laser", "electric", "fuchsia", "ultraviolet"}++++++def sample(renderer, style, colour):++ from core import effects++ image = renderer.preview(style, colour)++ scene_name = 'preview_switch_scene' if style.startswith('switch:') else 'preview_scene'++ original = getattr(effects, scene_name)++++ def without_effect(*args, **kwargs):++ return dict(original(*args, **kwargs), pens=[])++++ with mock.patch.object(effects, scene_name, without_effect):++ baseline = renderer.preview(style, colour)++ return image, renderer.changed_pixels(image, baseline)++++++def colour_rows(platform):++ sys.path.insert(0, str(ROOT / ("mac_app" if platform == "mac" else "win_app")))++ if platform == "mac":++ import pages++ import crossing++ return [(name, list(values)) for name, values in pages.colour_groups(crossing.GLOW_COLOURS)]++ import pages_win++ return [(name, list(values)) for name, values in pages_win.colour_groups()]++++++class MacRenderer:++ def __init__(self, scale=1):++ sys.path.insert(0, str(ROOT / "mac_app"))++ import AppKit++ import previews++ import theme++ from core import effects++ AppKit.NSApplication.sharedApplication()++ theme.init_fonts()++ self.A, self.previews, self.theme = AppKit, previews, theme++ self.scale = scale++ self.styles = ("glow", "beam") + effects.EFFECT_IDS + tuple('switch:' + value for value in effects.SWITCH_STYLES)++++ def set_dark(self, dark):++ self.theme.set_dark(dark)++++ def capture(self, view):++ A = self.A++ width, height = view.bounds().size++ rep = A.NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(++ None, math.ceil(width * self.scale), math.ceil(height * self.scale), 8, 4, True, False,++ A.NSDeviceRGBColorSpace, 0, 0)++ rep.setSize_((width, height))++ view.cacheDisplayInRect_toBitmapImageRep_(view.bounds(), rep)++ return rep++++ def preview(self, style, colour):++ from core import effects++ if style.startswith('switch:'):++ view = self.previews.switch_still(lambda: effects.switch_effect(style.split(':')[1], 'beam'),++ lambda: colour, logging.getLogger('colour-render'), height=84)++ else:++ view = self.previews.effect_still(style, lambda: colour, logging.getLogger("colour-render"), height=84)++ view.setFrame_(((0, 0), (180, 84)))++ return self.capture(view)++++ def changed_pixels(self, image, baseline):++ data, before, channels = bytes(image.bitmapData()), bytes(baseline.bitmapData()), image.samplesPerPixel()++ count = 0++ for y in range(image.pixelsHigh()):++ for x in range(image.pixelsWide()):++ at = y * image.bytesPerRow() + x * channels++ count += max(abs(data[at + c] - before[at + c]) for c in range(3)) > 3++ return count++++ def save(self, image, path):++ path.write_bytes(bytes(image.representationUsingType_properties_(self.A.NSBitmapImageFileTypePNG, {})))++++ def colour_page(self):++ from mac_app.tests.test_window_geometry import offscreen_control_window++ from mac_app.tests.design_offscreen import settle++ dark = self.theme.is_dark()++ control = offscreen_control_window()++ control.controller.cfg.appearance = "dark" if dark else "light"++ control._select_page("design")++ control.window.setFrame_display_(((100000, 100000), (1200, 1050)), False)++ settle(control.window)++ self.theme.set_dark(control.controller.cfg.appearance == "dark")++ self.theme.repaint(control.window.contentView())++ module = control.colour_module.view++ scroll = control.pages['design']++ clip, page = scroll.contentView(), scroll.documentView()++ rect = module.convertRect_toView_(module.bounds(), page)++ maximum = max(0, page.frame().size.height - clip.bounds().size.height)++ clip.scrollToPoint_((0, min(maximum, max(0, rect.origin.y - 12))))++ scroll.reflectScrolledClipView_(clip)++ settle(control.window)++ assert not control.window.isVisible()++ return self.capture(control.window.contentView())++++ def contact_sheet(self, rows, compact=False):++ A = self.A++ cell_w, cell_h, columns = 196, 108, 6++ styles = ("aperture",) if compact else self.styles++ per_colour = 28 + math.ceil(len(styles) / columns) * cell_h++ count = len(rows) if compact else sum(len(values) for _group, values in rows)++ view = A.NSView.alloc().initWithFrame_(((0, 0), (columns * cell_w, count * per_colour)))++ rep = self.capture(view)++ context = A.NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep)++ A.NSGraphicsContext.saveGraphicsState()++ A.NSGraphicsContext.setCurrentContext_(context)++ import Quartz++ cg = context.CGContext()++ Quartz.CGContextScaleCTM(cg, self.scale, self.scale)++ self.theme.colour("ground").setFill()++ A.NSRectFill(view.bounds())++ samples = []++ top = count * per_colour++ for group_index, (group, values) in enumerate(rows):++ for colour_index, (colour, title) in enumerate(values):++ x_offset = colour_index * cell_w if compact else 0++ if compact:++ top = count * per_colour - group_index * per_colour++ top -= 28++ text = A.NSString.stringWithString_(f"{group} / {title}" if compact else f"{group} / {title} ({colour})")++ text.drawAtPoint_withAttributes_((x_offset + 6, top + 5), {++ A.NSFontAttributeName: self.theme.font(11 if compact else 13), A.NSForegroundColorAttributeName: self.theme.colour("ink")})++ for index, style in enumerate(styles):++ column, row = index % columns, index // columns++ image, pixels = sample(self, style, colour)++ samples.append(dict(group=group, colour=colour, style=style, visible_pixels=pixels))++ native = A.NSImage.alloc().initWithSize_((180, 84))++ native.addRepresentation_(image)++ native.drawInRect_fromRect_operation_fraction_(((x_offset + column * cell_w + 8, top - (row + 1) * cell_h + 20), (180, 84)),++ ((0, 0), (180, 84)), A.NSCompositingOperationSourceOver, 1)++ A.NSString.stringWithString_(style).drawAtPoint_withAttributes_((x_offset + column * cell_w + 8, top - (row + 1) * cell_h + 4), {++ A.NSFontAttributeName: self.theme.font(10), A.NSForegroundColorAttributeName: self.theme.colour("ink_2")})++ top -= math.ceil(len(styles) / columns) * cell_h++ A.NSGraphicsContext.restoreGraphicsState()++ return rep, samples++++++class QtRenderer:++ def __init__(self, scale=1):++ os.environ["QT_QPA_PLATFORM"] = "offscreen"++ sys.path.insert(0, str(ROOT / "win_app"))++ from PySide6.QtWidgets import QApplication++ from PySide6.QtGui import QImage, QPainter, QColor++ from PySide6.QtCore import Qt++ import effect_previews++ import app_config++ import theme++ from core import effects++ self.app = QApplication.instance() or QApplication([])++ if self.app.platformName() != "offscreen":++ raise RuntimeError("Qt previews require the offscreen platform")++ theme.init_fonts()++ self.scale = scale++ self.QImage, self.QPainter, self.QColor, self.Qt = QImage, QPainter, QColor, Qt++ self.previews, self.config, self.theme = effect_previews, app_config, theme++ self.styles = ("glow", "beam") + effects.EFFECT_IDS + tuple('switch:' + value for value in effects.SWITCH_STYLES)++++ def set_dark(self, dark):++ self.theme.set_dark(dark)++++ def image(self, width, height):++ image = self.QImage(math.ceil(width * self.scale), math.ceil(height * self.scale), self.QImage.Format.Format_ARGB32_Premultiplied)++ image.setDevicePixelRatio(self.scale)++ image.fill(self.Qt.GlobalColor.transparent)++ return image++++ def capture(self, widget):++ from PySide6.QtCore import QPoint++ image = self.image(widget.width(), widget.height())++ painter = self.QPainter(image)++ widget.render(painter, QPoint(0, 0))++ painter.end()++ return image++++ def preview(self, style, colour):++ if style.startswith('switch:'):++ widget = self.previews.SwitchStill(style.split(':')[1], 'beam', self.config.palette_colours(colour))++ else:++ widget = self.previews.EffectStill(style, self.config.palette_colours(colour))++ widget.setFixedHeight(84)++ widget.resize(180, 84)++ image = self.image(180, 84)++ painter = self.QPainter(image)++ widget._paint_still(painter, widget.STILL_AT)++ painter.end()++ widget.deleteLater()++ return image++++ def changed_pixels(self, image, baseline):++ converted = image.convertToFormat(self.QImage.Format.Format_RGBA8888)++ data = bytes(converted.constBits())++ before = bytes(baseline.convertToFormat(self.QImage.Format.Format_RGBA8888).constBits())++ return sum(max(abs(data[index + c] - before[index + c]) for c in range(3)) > 3++ for index in range(0, len(data) - 3, 4))++++ def save(self, image, path):++ if not image.save(str(path)):++ raise RuntimeError(f"Could not save {path}")++++ def colour_page(self):++ from PySide6.QtWidgets import QWidget, QVBoxLayout++ import widgets++ host = QWidget()++ host.setStyleSheet(self.theme.stylesheet())++ layout = QVBoxLayout(host)++ layout.setContentsMargins(24, 24, 24, 24)++ layout.addWidget(widgets.label("Design / Colour", "heading"))++ choices = widgets.SwatchGroups([(group, [(value, title, self.config.palette_colours(value)) for value, title in values])++ for group, values in colour_rows("qt")], "colourful")++ layout.addWidget(choices.view)++ host.resize(1200, layout.sizeHint().height())++ layout.activate()++ return self.capture(host)++++ def contact_sheet(self, rows, compact=False):++ cell_w, cell_h, columns = 196, 108, 6++ styles = ("aperture",) if compact else self.styles++ per_colour = 28 + math.ceil(len(styles) / columns) * cell_h++ count = len(rows) if compact else sum(len(values) for _group, values in rows)++ image = self.image(columns * cell_w, count * per_colour)++ image.fill(self.QColor(self.theme.colour("ground")))++ painter = self.QPainter(image)++ painter.setPen(self.QColor(self.theme.colour("ink")))++ samples, top = [], 0++ for group_index, (group, values) in enumerate(rows):++ for colour_index, (colour, title) in enumerate(values):++ x_offset = colour_index * cell_w if compact else 0++ if compact:++ top = group_index * per_colour++ painter.setFont(self.theme.font(13))++ painter.setFont(self.theme.font(11 if compact else 13))++ painter.drawText(x_offset + 6, top + 20, f"{group} / {title}" if compact else f"{group} / {title} ({colour})")++ top += 28++ for index, style in enumerate(styles):++ column, row = index % columns, index // columns++ preview, pixels = sample(self, style, colour)++ samples.append(dict(group=group, colour=colour, style=style, visible_pixels=pixels))++ painter.drawImage(x_offset + column * cell_w + 8, top + row * cell_h, preview)++ painter.setFont(self.theme.font(10))++ painter.drawText(x_offset + column * cell_w + 8, top + row * cell_h + 100, style)++ top += math.ceil(len(styles) / columns) * cell_h++ painter.end()++ return image, samples++++++def main():++ parser = argparse.ArgumentParser(description=__doc__)++ parser.add_argument("--platform", choices=("mac", "qt"), required=True)++ parser.add_argument("--scale", type=int, choices=(1, 2), default=1)++ parser.add_argument("--output", type=Path, required=True)++ parser.add_argument("--contact-sheet", action="store_true")++ args = parser.parse_args()++ args.output.mkdir(parents=True, exist_ok=True)++ renderer = (MacRenderer if args.platform == "mac" else QtRenderer)(args.scale)++ rows, records = colour_rows(args.platform), []++ for dark in (False, True):++ mode = "dark" if dark else "light"++ renderer.set_dark(dark)++ path = args.output / f"{args.platform}-colours-1200pt-{args.scale}x-{mode}.png"++ renderer.save(renderer.colour_page(), path)++ print(path, flush=True)++ if args.contact_sheet:++ image, samples = renderer.contact_sheet(rows)++ path = args.output / f"{args.platform}-contact-{args.scale}x-{mode}.png"++ renderer.save(image, path)++ records.extend(dict(sample, mode=mode) for sample in samples)++ print(path, "samples", len(samples), "minimum visible pixels", min(s["visible_pixels"] for s in samples), flush=True)++ compact, _samples = renderer.contact_sheet(rows, compact=True)++ path = args.output / f"{args.platform}-palettes-{args.scale}x-{mode}.png"++ renderer.save(compact, path)++ print(path, flush=True)++ if records:++ path = args.output / f"{args.platform}-pixels-{args.scale}x.json"++ path.write_text(json.dumps(records, indent=2) + "\n")++ missing = [sample for sample in records if sample["visible_pixels"] == 0]++ if missing:++ raise RuntimeError(f"Native previews without visible coloured pixels: {missing}")++++++if __name__ == "__main__":++ main()diff --cc tools/runtime_probe.pyindex 0000000,0000000..e73ed50new file mode 100644--- /dev/null+++ b/tools/runtime_probe.py@@@ -1,0 -1,0 +1,51 @@@++"""build_dmg.sh runs this with the bundle's own python, which is signed with the hardened runtime, to++prove the app's code loads and its callbacks work without entitlements. No window, no permission++prompt, and nothing from the source tree on sys.path."""++import base64++import os++import sys++++import objc, AppKit, Foundation, Quartz, ApplicationServices, CoreFoundation as CF, rumps++++import bridge, clipboard_mac, config, crossing, gestures, key_codes, link_state, media_keys++import notch_beam, notch_island, pages, pointer_hide, previews, settings_store, theme, tokens++from core import pairing, protocol++import wake, widgets++++assert ".app/" in bridge.__file__, bridge.__file__++++# The link's X25519 and ChaCha20-Poly1305 and pairing's X25519 are all libsodium, reached through++# PyNaCl's own cffi extension: a link's handshake, a sealed frame and a whole pairing exchange prove++# that extension is in the bundle and loads under the hardened runtime.++probe_token = base64.urlsafe_b64encode(os.urandom(protocol.TOKEN_SIZE)).decode("ascii").rstrip("=")++one = protocol.LinkSession(probe_token, protocol.ROLE_INITIATOR)++two = protocol.LinkSession(probe_token, protocol.ROLE_RESPONDER)++two.accept_preamble(one.preamble())++one.accept_preamble(two.preamble())++assert two.open(one.seal({"type": "ping", "data": {}})[protocol.HEADER_SIZE:]) == {"type": "ping", "data": {}}++++pairing_host = pairing.PairingHost()++pairing_code = pairing_host.begin()++pairing_client = pairing.PairingClient(pairing_host.pair_id, pairing_code, "probe")++pairing_confirm = pairing_client.accept(pairing_host.handle(pairing_client.start()))++assert pairing_client.finish(pairing_host.handle(pairing_confirm)) == pairing_host.paired[0]++++++class Probe(Foundation.NSObject):++ def ping_(self, value):++ self.value = value++++++# A Python method called from Objective-C, and a C callback: both run through libffi closures, the++# thing the hardened runtime's executable-memory rules would break.++probe = Probe.new()++probe.performSelector_withObject_(b"ping:", 7)++assert probe.value == 7++++fired = []++timer = CF.CFRunLoopTimerCreate(None, CF.CFAbsoluteTimeGetCurrent(), 0, 0, 0, lambda t, i: fired.append(1), None)++CF.CFRunLoopAddTimer(CF.CFRunLoopGetCurrent(), timer, CF.kCFRunLoopDefaultMode)++CF.CFRunLoopRunInMode(CF.kCFRunLoopDefaultMode, 0.3, False)++assert fired++++print(f"Hardened runtime probe passed under {sys.executable}")diff --cc tools/wayland_observer.pyindex 0000000,0000000..d3e0c41new file mode 100644--- /dev/null+++ b/tools/wayland_observer.py@@@ -1,0 -1,0 +1,84 @@@++"""The app on the other end of tools/wayland_proof.py: a full-screen GTK 4 window, run with the++system's Python (it needs PyGObject), that writes every key, pointer move, button and scroll it is++given to a log as JSON lines, and copies or pastes the clipboard when the proof asks through a++commands file. What reaches it reached an app; what Beamer captured never does.++++ python3 tools/wayland_observer.py <log> <commands>"""++++import json++import os++import sys++import time++++import gi++++gi.require_version("Gtk", "4.0")++gi.require_version("Gdk", "4.0")++from gi.repository import Gdk, GLib, Gtk # noqa: E402++++LOG = open(sys.argv[1], "a", buffering=1)++COMMANDS = sys.argv[2]++# Commands written before this one started were for the one before it.++_read_to = [os.path.getsize(COMMANDS) if os.path.exists(COMMANDS) else 0]++++++def log(**fields) -> None:++ fields["t"] = time.monotonic()++ LOG.write(json.dumps(fields) + "\n")++++++def poll_commands(window) -> bool:++ try:++ with open(COMMANDS) as handle:++ handle.seek(_read_to[0])++ lines = handle.read()++ _read_to[0] = handle.tell()++ except OSError:++ return True++ clipboard = Gdk.Display.get_default().get_clipboard()++ for line in lines.splitlines():++ if line.startswith("copy:"):++ clipboard.set(line[5:])++ log(kind="copied", text=line[5:])++ elif line == "paste":++ def done(source, result):++ try:++ text = source.read_text_finish(result)++ except GLib.Error as error:++ text = None++ log(kind="paste-failed", error=str(error))++ log(kind="paste", text=text)++++ clipboard.read_text_async(None, done)++ elif line == "quit":++ window.get_application().quit()++ return True++++++def activate(app) -> None:++ window = Gtk.ApplicationWindow(application=app, title="Beamer proof observer")++ window.fullscreen()++ keys = Gtk.EventControllerKey()++ keys.connect("key-pressed", lambda c, keyval, code, state: log(++ kind="key", down=True, name=Gdk.keyval_name(keyval), code=code, state=int(state)) and False)++ keys.connect("key-released", lambda c, keyval, code, state: log(++ kind="key", down=False, name=Gdk.keyval_name(keyval), code=code, state=int(state)))++ window.add_controller(keys)++ motion = Gtk.EventControllerMotion()++ motion.connect("motion", lambda c, x, y: log(kind="motion", x=x, y=y))++ window.add_controller(motion)++ click = Gtk.GestureClick(button=0)++ click.connect("pressed", lambda g, n, x, y: log(kind="button", down=True, button=g.get_current_button(), x=x, y=y))++ click.connect("released", lambda g, n, x, y: log(kind="button", down=False, button=g.get_current_button(), x=x, y=y))++ window.add_controller(click)++ scroll = Gtk.EventControllerScroll(flags=Gtk.EventControllerScrollFlags.BOTH_AXES)++ scroll.connect("scroll", lambda c, dx, dy: log(kind="scroll", dx=dx, dy=dy) or True)++ window.add_controller(scroll)++ window.present()++ GLib.timeout_add(50, poll_commands, window)++ log(kind="ready", pid=os.getpid())++++++app = Gtk.Application(application_id="uk.co.kalkman.BeamerProofObserver")++app.connect("activate", activate)++app.run([])diff --cc tools/wayland_proof.pyindex 0000000,0000000..6bbdae3new file mode 100644--- /dev/null+++ b/tools/wayland_proof.py@@@ -1,0 -1,0 +1,566 @@@++"""The Wayland back ends against a real GNOME Shell and its portals: what the fakes in win_app/tests++cannot prove.++++Run by tools/wayland_proof.sh, which starts a headless GNOME Shell on its own D-Bus session. The++observer (tools/wayland_observer.py) is a full-screen app that logs what reaches it. This machine's++own mouse and keyboard are played through mutter's own remote desktop D-Bus (`Hand`), which a++headless shell lets any client use; the desktop's consent dialogs are answered with their own++keyboard shortcuts through it, as a person would. GNOME keeps a dialog that opens over a focused++window behind it, unfocused, so the observer is closed while a dialog is up and opened again++after.++++Each check prints PASS or FAIL, and NOTE for what is only reported; the exit status is the number++of failures. Proved here, through capture_portal: the barrier on a zone, a push held there and++crossing once the sender says so, keys, buttons, the wheel and motion arriving while input is away++and reaching no app, and every way home letting the pointer go where it should: the sender's++landing, a move back into the screen, a pause, a key at the edge, stop(), a killed process and a++stalled thread. Through inject_portal: the remembered permission, the pointer placed and moved,++buttons, keys and text off the layout, the wheel, everything let go, and a second start asking++nothing. Through clipboard_portal: another app pastes Beamer's text and image, and Beamer reads++another app's copy and not the echo of its own."""++++import hashlib++import json++import os++import signal++import subprocess++import sys++import threading++import time++from pathlib import Path++++ROOT = Path(__file__).resolve().parent.parent++sys.path[:0] = [str(ROOT / "win_app"), str(ROOT)]++++WORK = Path(os.environ["BEAMER_PROOF_DIR"])++OBSERVED = WORK / "observed.jsonl"++COMMANDS = WORK / "commands"++# evdev codes++ESC, A, S, ONE, LEFTSHIFT, LEFTCTRL, LEFTALT, C, I = 1, 30, 31, 2, 42, 29, 56, 46, 23++BTN_LEFT = 0x110++CAPTURE_ANSWER = [(LEFTALT, I), (LEFTALT, S)] # Allow Remote Input Capturing, Share++REMOTE_ANSWER = [(LEFTALT, I), (LEFTALT, C), (LEFTALT, S)] # Interaction, Clipboard, Share++++failures = []++++++def check(name, ok, detail=""):++ print(("PASS " if ok else "FAIL ") + name + ("" if ok else f": {detail}"), flush=True)++ if not ok:++ failures.append(name)++++++def note(text):++ print("NOTE " + text, flush=True)++++++def wait(condition, timeout=3.0):++ deadline = time.monotonic() + timeout++ while time.monotonic() < deadline:++ if condition():++ return True++ time.sleep(0.02)++ return bool(condition())++++++class Hand:++ """This machine's own keyboard and mouse: mutter's remote desktop session, relative motion."""++++ def __init__(self):++ from jeepney import DBusAddress, new_method_call++ from jeepney.io.blocking import open_dbus_connection++++ self._new = new_method_call++ self.conn = open_dbus_connection(bus="SESSION")++ manager = DBusAddress("/org/gnome/Mutter/RemoteDesktop", "org.gnome.Mutter.RemoteDesktop",++ "org.gnome.Mutter.RemoteDesktop")++ path = self.conn.send_and_get_reply(new_method_call(manager, "CreateSession")).body[0]++ self.session = DBusAddress(path, "org.gnome.Mutter.RemoteDesktop", "org.gnome.Mutter.RemoteDesktop.Session")++ self._call("Start")++ self._lock = threading.Lock()++++ def _call(self, method, signature=None, body=()):++ reply = self.conn.send_and_get_reply(self._new(self.session, method, signature, body))++ if reply.header.message_type.name == "error":++ raise RuntimeError(f"{method}: {reply.body}")++++ def key(self, code, down):++ with self._lock:++ self._call("NotifyKeyboardKeycode", "ub", (code, down))++++ def tap(self, *codes):++ for code in codes:++ self.key(code, True)++ for code in reversed(codes):++ self.key(code, False)++++ def move(self, dx, dy):++ with self._lock:++ self._call("NotifyPointerMotionRelative", "dd", (float(dx), float(dy)))++++ def to(self, x, y):++ """Into the top left corner, then out to (x, y), one axis at a time in small steps: mutter++ dropped one axis of a single large diagonal move (01-10-2026)."""++ for dx, dy in ((-4000, 0), (0, -4000)):++ self.move(dx, dy)++ for axis, distance in ((0, x), (1, y)):++ while distance > 0:++ step = min(100, distance)++ self.move(step if axis == 0 else 0, step if axis == 1 else 0)++ distance -= step++ time.sleep(0.1)++++ def button(self, code, down):++ with self._lock:++ self._call("NotifyPointerButton", "ib", (code, down))++++ def wheel(self, steps):++ with self._lock:++ self._call("NotifyPointerAxisDiscrete", "ui", (0, steps))++++ def answer_later(self, chords, delay=2.5, gap=0.8):++ def go():++ time.sleep(delay)++ for chord in chords:++ self.tap(*chord)++ time.sleep(gap)++++ thread = threading.Thread(target=go, daemon=True)++ thread.start()++ return thread++++++class Observer:++ """The full-screen app and what reached it, read from its log."""++++ def __init__(self):++ self._offset = 0++ self._process = None++++ def launch(self):++ self.mark()++ self._process = subprocess.Popen(++ [os.environ.get("OBSERVER_PYTHON", "/usr/bin/python3"), str(Path(__file__).with_name("wayland_observer.py")),++ str(OBSERVED), str(COMMANDS)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)++ ready = wait(lambda: self.seen("ready"), timeout=15)++ time.sleep(0.5)++ self.mark()++ return ready++++ def close(self):++ if self._process is None:++ return++ self.command("quit")++ try:++ self._process.wait(timeout=5)++ except subprocess.TimeoutExpired:++ self._process.kill()++ self._process.wait()++ self._process = None++ time.sleep(0.3)++++ def mark(self):++ self._offset = OBSERVED.stat().st_size if OBSERVED.exists() else 0++++ def seen(self, kind=None):++ if not OBSERVED.exists():++ return []++ with open(OBSERVED) as handle:++ handle.seek(self._offset)++ found = [json.loads(line) for line in handle if line.strip()]++ return [item for item in found if kind is None or item["kind"] == kind]++++ def keys(self):++ return [(item["name"], item["down"]) for item in self.seen("key")]++++ def last_motion(self):++ motions = self.seen("motion")++ return (round(motions[-1]["x"]), round(motions[-1]["y"])) if motions else None++++ def command(self, line):++ with open(COMMANDS, "a") as handle:++ handle.write(line + "\n")++++++class Sender:++ """What capture_portal's callbacks reach, with the sender's crossing as a threshold of pushed++ pixels, as the zone model's resistance is."""++++ def __init__(self, threshold=60):++ self.lock = threading.Lock()++ self.threshold = threshold++ self.away = False++ self.pushed = 0++ self.keys, self.mice, self.motions = [], [], []++ self.block_keys = 0.0++++ def on_key(self, name, down, vk, us):++ if self.block_keys:++ time.sleep(self.block_keys)++ with self.lock:++ self.keys.append((name, down))++ return True++++ def on_mouse(self, message, x, y, data):++ with self.lock:++ self.mice.append((message, data))++ return True++++ def on_motion(self, dx, dy):++ with self.lock:++ self.motions.append((dx, dy))++ if not self.away:++ self.pushed += dx++ if self.pushed >= self.threshold:++ self.away = True++++ def take(self):++ with self.lock:++ found = (self.keys, self.mice, self.motions)++ self.keys, self.mice, self.motions = [], [], []++ return found++++++def start_capture(hand, sender, observer):++ import capture_portal++ from core import return_edge++++ observer.close()++ hooks = capture_portal.Hooks(sender.on_key, sender.on_mouse, sender.on_motion)++ hooks.grab_while(lambda: sender.away)++ hooks.barriers_from(lambda: [return_edge.ReturnEdge("right")])++ homes = []++ hooks.on_home = lambda: homes.append(True) or setattr(sender, "away", False)++ failures_seen = []++ hooks.on_failure = failures_seen.append++ hand.answer_later(CAPTURE_ANSWER)++ hooks.start()++ ok = wait(lambda: hooks._session is not None and hooks._session.enabled, timeout=15)++ observer.launch()++ return hooks, ok, homes, failures_seen++++++def push_to_edge(hand, y=400, pushes=12, step=10):++ hand.to(1270, y)++ for _ in range(pushes):++ hand.move(step, 0)++ time.sleep(0.02)++++++def proof_capture(hand, observer):++ import capture_portal++ import desktop_portal++++ sender = Sender()++ hooks, ok, homes, seen_failures = start_capture(hand, sender, observer)++ check("the capture session starts once the desktop is answered and its barrier is accepted",++ ok and hooks._walls == {1: "right"}, f"enabled={ok} walls={getattr(hooks, '_walls', None)} failures={seen_failures}")++ if not ok:++ hooks.stop()++ return++++ observer.mark()++ push_to_edge(hand)++ crossed = wait(lambda: sender.away and hooks._away)++ check("a push into the barrier is held and crosses once the sender says so", crossed and hooks.holding,++ f"away={sender.away} pushed={sender.pushed} holding={hooks.holding}")++ check("the pointer is held on the last pixel of the edge", desktop_portal.position() == (1279, 400),++ str(desktop_portal.position()))++ sender.take()++++ hand.tap(A)++ hand.tap(LEFTSHIFT, A)++ hand.tap(LEFTCTRL)++ hand.button(BTN_LEFT, True)++ hand.button(BTN_LEFT, False)++ hand.wheel(1)++ hand.move(15, -7)++ time.sleep(0.4)++ keys, mice, motions = sender.take()++ check("keys while away are named as the layout types them", keys == [++ ("a", True), ("a", False), ("shift", True), ("A", True), ("A", False), ("shift", False), ("cmd", True), ("cmd", False)], str(keys))++ left_down, left_up = capture_portal._BUTTONS[1][:2]++ wheel = [m for m in mice if m[0] == capture_portal.WM_MOUSEWHEEL]++ check("buttons and the wheel while away arrive as the mouse messages",++ [m for m in mice if m[0] != capture_portal.WM_MOUSEWHEEL] == [(left_down, 0), (left_up, 0)]++ and wheel == [(capture_portal.WM_MOUSEWHEEL, capture_portal._wheel_data(-capture_portal.WHEEL_DELTA))], str(mice))++ check("motion while away arrives whole", (sum(m[0] for m in motions), sum(m[1] for m in motions)) == (15, -7), str(motions))++ check("nothing captured reached an app", observer.seen("key") == [] and observer.seen("button") == []++ and observer.seen("scroll") == [], str(observer.seen()[:6]))++++ desktop_portal.set_cursor_position(600, 400)++ sender.away = False++ released = wait(lambda: not hooks.holding)++ hand.move(1, 0)++ check("coming home lets the pointer go where the sender lands it", released and wait(lambda: observer.last_motion() == (601, 400)),++ f"released={released} last={observer.last_motion()}")++++ # A move back, a pause and a key, each at the edge without crossing.++ sender.threshold = 10 ** 6++ for name, act, expect in (++ ("a move back into the screen lets go where it ends", lambda: hand.move(-20, 0), (1258, 400)),++ ("a pause in the push lets go at the edge", lambda: time.sleep(capture_portal.IDLE_SECONDS + 0.3), (1278, 400)),++ ("a key at the edge lets go and reaches nobody", lambda: hand.tap(S), (1278, 400)),++ ):++ observer.mark()++ sender.take()++ push_to_edge(hand, pushes=3)++ held = wait(lambda: hooks.holding)++ act()++ let_go = wait(lambda: not hooks.holding)++ hand.move(-1, 0) # one pixel back in, where the app sees where it was let go++ landed = wait(lambda: observer.last_motion() == expect)++ keys = sender.take()[0]++ check(name, held and let_go and landed and keys == [] and observer.keys() == [],++ f"held={held} let_go={let_go} last={observer.last_motion()} keys={keys} app_keys={observer.keys()}")++++ # A drag into the barrier: whether GNOME captures with a button held.++ observer.mark()++ hand.to(1270, 300)++ hand.button(BTN_LEFT, True)++ for _ in range(4):++ hand.move(10, 0)++ time.sleep(0.02)++ dragged = wait(lambda: hooks.holding, timeout=0.5)++ hand.button(BTN_LEFT, False)++ wait(lambda: not hooks.holding, timeout=2)++ note(f"a drag into the barrier {'is' if dragged else 'is not'} captured by GNOME")++++ sender.threshold = 60++ sender.pushed = 0++ push_to_edge(hand)++ away = wait(lambda: sender.away and hooks._away)++ hooks.stop()++ observer.mark()++ hand.tap(A)++ check("stop() while input is away gives it back", away and wait(lambda: ("a", True) in observer.keys()),++ f"away={away} app_keys={observer.keys()}")++ sender.away = False++++ # The watchdog: a callback that hangs while the desktop holds input.++ import capture_portal as module++++ sender = Sender()++ hooks, ok, homes, seen_failures = start_capture(hand, sender, observer)++ push_to_edge(hand)++ away = ok and wait(lambda: sender.away and hooks._away)++ sender.block_keys = 30.0++ hand.tap(A) # the capture thread hangs in on_key++ observer.mark()++ time.sleep(module.STALL_SECONDS + 1.0)++ hand.tap(S)++ freed = wait(lambda: ("s", True) in observer.keys(), timeout=3)++ check("a capture thread stalled while input is away has its connection ended and input comes back",++ away and freed, f"away={away} app_keys={observer.keys()}")++ sender.block_keys = 0.0++++++def capture_child():++ """Capture until killed; says 'away' once input is away."""++ import capture_portal++ from core import return_edge++++ sender = Sender()++ hooks = capture_portal.Hooks(sender.on_key, sender.on_mouse, sender.on_motion)++ hooks.grab_while(lambda: sender.away)++ hooks.barriers_from(lambda: [return_edge.ReturnEdge("right")])++ hooks.start()++ enabled = wait(lambda: hooks._session is not None and hooks._session.enabled, timeout=15)++ print("enabled" if enabled else "not enabled", flush=True)++ away = enabled and wait(lambda: sender.away and hooks._away, timeout=15)++ print("away" if away else "not away", flush=True)++ time.sleep(60)++++++def proof_killed_process_lets_go(hand, observer):++ observer.close()++ child = subprocess.Popen([sys.executable, __file__, "capture-child"], stdout=subprocess.PIPE, text=True)++ try:++ hand.answer_later(CAPTURE_ANSWER)++ enabled = child.stdout.readline().strip() == "enabled"++ observer.launch()++ push_to_edge(hand)++ away = child.stdout.readline().strip() == "away"++ os.kill(child.pid, signal.SIGKILL)++ child.wait(timeout=5)++ observer.mark()++ time.sleep(0.5)++ hand.tap(A)++ check("a killed process holding input away gives it back", enabled and away and wait(lambda: ("a", True) in observer.keys()),++ f"enabled={enabled} away={away} app_keys={observer.keys()}")++ finally:++ if child.poll() is None:++ child.kill()++++++def proof_injection(hand, observer):++ import desktop_portal++ import inject_portal++ import portal++++ portal.TokenStore("remote-desktop").write("")++ observer.close()++ problems = []++ inject_portal.on_problem = problems.append++ hand.answer_later(REMOTE_ANSWER)++ remote = inject_portal.remote()++ remote.start()++ up = wait(lambda: remote.ready.is_set() and remote.layout is not None and remote._input_ready()++ and remote._with(inject_portal.CAP_POINTER_ABSOLUTE) is not None, timeout=15)++ check("remote control starts once the desktop is answered, with a keyboard, its layout and an absolute pointer",++ up and not problems, f"ready={remote.ready.is_set()} problems={problems}")++ if not up:++ return++ check("the desktop's permission is remembered", portal.TokenStore("remote-desktop").read() != "")++ observer.launch()++++ observer.mark()++ desktop_portal.set_cursor_position(100, 100)++ inject_portal.inject_mouse_move(10, 5)++ check("the pointer is placed and moved where Beamer says", wait(lambda: observer.last_motion() == (110, 105)),++ str(observer.last_motion()))++ inject_portal.inject_mouse_button("left", True)++ inject_portal.inject_mouse_button("left", False)++ buttons = lambda: [(b["button"], b["down"], round(b["x"]), round(b["y"])) for b in observer.seen("button")] # noqa: E731++ check("a button presses and lets go where the pointer is", wait(lambda: buttons() == [(1, True, 110, 105), (1, False, 110, 105)]),++ str(buttons()))++++ observer.mark()++ for name in ("a", "A", "!", "return"):++ inject_portal.inject_key(name, True)++ inject_portal.inject_key(name, False)++ inject_portal.inject_text("hi!")++ expect = [("a", True), ("a", False), ("Shift_L", True), ("A", True), ("A", False), ("Shift_L", False),++ ("Shift_L", True), ("exclam", True), ("exclam", False), ("Shift_L", False), ("Return", True), ("Return", False),++ ("h", True), ("h", False), ("i", True), ("i", False), ("Shift_L", True), ("exclam", True), ("Shift_L", False),++ ("1", False)] # let go after Shift, so the app names it by its unshifted keysym++ typed = wait(lambda: len(observer.keys()) >= len(expect), timeout=3)++ keys = [key for key in observer.keys()]++ check("keys and text type as the layout has them", typed and keys == expect, str(keys))++++ observer.mark()++ inject_portal.inject_key("é", True)++ inject_portal.inject_key("é", False)++ time.sleep(0.4)++ check("a character the layout has no key for is not typed", observer.keys() == [], str(observer.keys()))++++ observer.mark()++ inject_portal.inject_key("ctrl", True)++ inject_portal.inject_key("c", True)++ inject_portal.inject_key("c", False)++ inject_portal.inject_key("ctrl", False)++ chord = wait(lambda: len(observer.keys()) >= 4)++ ctrl_c = [item for item in observer.seen("key") if item["name"] == "c" and item["down"]]++ check("a chord reaches the app with its modifier held", chord and ctrl_c and ctrl_c[0]["state"] & 4,++ str(observer.seen("key")))++++ observer.mark()++ inject_portal.inject_scroll(1, 0, "line")++ check("the wheel scrolls away from the hand", wait(lambda: any(s["dy"] < 0 for s in observer.seen("scroll"))),++ str(observer.seen("scroll")))++++ observer.mark()++ inject_portal.inject_key("shift", True)++ inject_portal.inject_mouse_button("right", True)++ inject_portal.release_all()++ released = wait(lambda: ("Shift_L", False) in observer.keys() and any(++ b["button"] == 3 and not b["down"] for b in observer.seen("button")))++ check("release_all lets go of every key and button held for the peer", released,++ f"{observer.keys()} {observer.seen('button')}")++++ proof_clipboard(observer)++++ inject_portal.stop()++ inject_portal._remote = None++ started = time.monotonic()++ remote = inject_portal.remote()++ remote.start()++ restored = wait(lambda: remote.ready.is_set(), timeout=5)++ check("a second start asks nothing: the permission is restored", restored and time.monotonic() - started < 2.0,++ f"ready={restored} after {time.monotonic() - started:.2f} s")++ inject_portal.stop()++++++def png_bytes():++ from PySide6.QtCore import QBuffer, QIODevice++ from PySide6.QtGui import QColor, QImage++++ image = QImage(4, 3, QImage.Format.Format_RGB32)++ image.fill(QColor(20, 120, 220))++ buffer = QBuffer()++ buffer.open(QIODevice.OpenModeFlag.WriteOnly)++ image.save(buffer, "PNG")++ return bytes(buffer.data())++++++def proof_clipboard(observer):++ import clipboard_portal++++ observer.mark()++ check("Beamer's text is offered as the clipboard", clipboard_portal.set_contents("from beamer", None))++ # The compositor announces a new offer to an app a moment after it is made: a paste at once++ # can find the old one, so it is tried again, as a person would.++ found = []++ for _ in range(3):++ observer.mark()++ observer.command("paste")++ wait(lambda: observer.seen("paste"), timeout=4)++ found = [item.get("text") for item in observer.seen("paste")]++ if found == ["from beamer"]:++ break++ time.sleep(0.3)++ check("another app pastes Beamer's text", found == ["from beamer"], str(observer.seen()))++ check("Beamer's own copy is not read back as a change", clipboard_portal.changed_contents() == (None, None))++++ stamp = clipboard_portal.change_stamp()++ observer.command("copy:from the desktop")++ moved = wait(lambda: clipboard_portal.change_stamp() != stamp, timeout=4)++ contents = clipboard_portal.changed_contents()++ check("Beamer reads another app's copy once", moved and contents == ("from the desktop", None)++ and clipboard_portal.changed_contents() == (None, None), f"moved={moved} {contents}")++++ png = png_bytes()++ check("Beamer's image is offered as the clipboard", clipboard_portal.set_contents(None, png))++ pasted = subprocess.run(["wl-paste", "--no-newline", "--type", "image/png"], capture_output=True, timeout=10)++ check("another app pastes Beamer's image", pasted.stdout == png,++ f"{len(pasted.stdout)} bytes, sha {hashlib.sha256(pasted.stdout).hexdigest()[:12]}")++ copier = subprocess.Popen(["wl-copy", "--type", "image/png"], stdin=subprocess.PIPE)++ copier.communicate(png, timeout=10)++ wait(lambda: clipboard_portal.change_stamp() is not None, timeout=1)++ got = None++ deadline = time.monotonic() + 4++ while time.monotonic() < deadline and got is None:++ text, image = clipboard_portal.changed_contents()++ got = image++ time.sleep(0.1)++ check("Beamer reads another app's image", got == png, f"{None if got is None else len(got)} bytes")++++++def main():++ import logging++++ logging.basicConfig(level=logging.INFO, format="LOG %(name)s %(levelname)s %(message)s")++ hand = Hand()++ hand.tap(ESC) # out of the Overview the headless shell starts in++ # The portal and its GNOME back end start on first use, slowly: woken here, so the first dialog++ # opens as soon as it is asked for.++ subprocess.run(["gdbus", "call", "--session", "--dest", "org.freedesktop.portal.Desktop", "--object-path",++ "/org/freedesktop/portal/desktop", "--method", "org.freedesktop.portal.Settings.ReadAll", "[]"],++ capture_output=True, timeout=30)++ time.sleep(1.0)++ observer = Observer()++ try:++ proof_injection(hand, observer)++ proof_capture(hand, observer)++ proof_killed_process_lets_go(hand, observer)++ finally:++ observer.close()++++++if __name__ == "__main__":++ if len(sys.argv) > 1 and sys.argv[1] == "capture-child":++ capture_child()++ else:++ main()++ print(f"{len(failures)} failed" if failures else "all passed", flush=True)++ os._exit(min(len(failures), 100))diff --cc tools/wayland_proof.shindex 0000000,0000000..222084bnew file mode 100755--- /dev/null+++ b/tools/wayland_proof.sh@@@ -1,0 -1,0 +1,37 @@@++#!/usr/bin/env bash++# The Wayland back ends against a real GNOME Shell and its portals (tools/wayland_proof.py says what++# is proved). Starts a headless GNOME Shell on a D-Bus session of its own with one virtual monitor,++# so it never touches the desktop it is started from, then the proof, which opens the observer app.++# Needs GNOME Shell 45 or later, xdg-desktop-portal-gnome, libei, wl-clipboard, PyGObject with++# GTK 4 for the system python3, and win_app/requirements-linux.txt for PYTHON's.++# Exit status: 0 when every check passes.++set -euo pipefail++here="$(cd "$(dirname "$0")" && pwd)"++python="${PYTHON:-python3}"++if [ -z "${BEAMER_PROOF_DIR:-}" ]; then++ for tool in gnome-shell dbus-run-session wl-paste; do++ command -v "$tool" >/dev/null || { echo "$tool is not installed" >&2; exit 2; }++ done++ BEAMER_PROOF_DIR="$(mktemp -d)"++ export BEAMER_PROOF_DIR++ trap 'rm -rf "$BEAMER_PROOF_DIR"' EXIT++ dbus-run-session -- "$0" "$@"++ exit $?++fi++display="beamer-proof-$$"++export XDG_CURRENT_DESKTOP=GNOME XDG_SESSION_TYPE=wayland XDG_SESSION_DESKTOP=gnome WAYLAND_DISPLAY="$display"++unset DISPLAY++gnome-shell --headless --wayland --no-x11 --wayland-display "$display" --virtual-monitor 1280x800 \++ >"$BEAMER_PROOF_DIR/shell.log" 2>&1 &++shell=$!++trap 'kill "$shell" 2>/dev/null || true' EXIT++for _ in $(seq 100); do++ [ -S "$XDG_RUNTIME_DIR/$display" ] && break++ sleep 0.1++done++dbus-update-activation-environment WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE++touch "$BEAMER_PROOF_DIR/commands"++# Beamer's remembered permissions start empty: a fresh state directory.++export XDG_STATE_HOME="$BEAMER_PROOF_DIR/state"++sleep 2++"$python" "$here/wayland_proof.py"diff --cc tools/x11_proof.pyindex 0000000,0000000..ebd8722new file mode 100644--- /dev/null+++ b/tools/x11_proof.py@@@ -1,0 -1,0 +1,448 @@@++"""The X11 back ends against a real X server: what the fakes in win_app/tests cannot prove.++++Run by tools/x11_proof.sh, which starts Xvfb and sets DISPLAY; on a real desktop it can be run++directly (`python3 tools/x11_proof.py`), but it grabs the keyboard and mouse for a moment and++types into whatever has focus, so run it from a terminal with nothing else open.++++Each check prints PASS or FAIL; the exit status is the number of failures. Proved here:++injection through inject_x11 read back through capture_x11's listener (motion, every modifier,++letters, text off the layout, the wheel, every button), the listener dropping XTEST by default,++the grab (raw events still arrive, a second client's grab is refused, other clients see nothing,++and stop() and a killed process both let go), desktop_x11's geometry and warp, and the clipboard++owned for real: another app pastes what Beamer wrote, Beamer sees another app's copy, and not++the echo of its own."""++++import hashlib++import os++import signal++import subprocess++import sys++import threading++import time++from pathlib import Path++++ROOT = Path(__file__).resolve().parent.parent++sys.path[:0] = [str(ROOT / "win_app"), str(ROOT)]++++failures = []++++++def check(name, ok, detail=""):++ print(("PASS " if ok else "FAIL ") + name + ("" if ok else f": {detail}"), flush=True)++ if not ok:++ failures.append(name)++++++class Seen:++ def __init__(self):++ self.lock = threading.Lock()++ self.keys, self.mice, self.motions = [], [], []++ # What on_key answers: False hands a key from inside the grab back to this machine.++ self.key_answer = None++++ def on_key(self, name, down, vk, us):++ with self.lock:++ self.keys.append((name, down, vk, us))++ return self.key_answer++++ def on_mouse(self, message, x, y, data):++ with self.lock:++ self.mice.append((message, data))++++ def on_motion(self, dx, dy):++ with self.lock:++ self.motions.append((dx, dy))++++ def take(self, settle=0.3):++ time.sleep(settle)++ with self.lock:++ found = (self.keys, self.mice, self.motions)++ self.keys, self.mice, self.motions = [], [], []++ return found++++++def wait(condition, timeout=2.0):++ end = time.monotonic() + timeout++ while time.monotonic() < end:++ if condition():++ return True++ time.sleep(0.01)++ return condition()++++++def other_client_grab():++ """Whether a second client can grab the master keyboard now; it lets go at once if it can."""++ from Xlib import X, display++ from Xlib.ext import xinput++++ other = display.Display()++ try:++ opcode = other.display.get_extension_major("XInputExtension")++ keyboard = next(info.deviceid for info in other.xinput_query_device(xinput.AllMasterDevices).devices++ if info.use == xinput.MasterKeyboard)++ reply = xinput.XIGrabDevice(display=other.display, opcode=opcode, deviceid=keyboard, grab_window=other.screen().root,++ time=X.CurrentTime, cursor=X.NONE, grab_mode=xinput.GrabModeAsync,++ paired_device_mode=xinput.GrabModeAsync, owner_events=False, mask=0)++ if reply.status == 0:++ other.xinput_ungrab_device(keyboard, X.CurrentTime)++ other.sync()++ return reply.status == 0++ finally:++ other.close()++++++class Listener:++ """Another client listening for ordinary XI2 key presses on the root, as an app would: it sees++ them while nothing is grabbed, and nothing while Beamer holds the keyboard."""++++ def __init__(self):++ from Xlib import display++ from Xlib.ext import xinput++++ self.display = display.Display()++ self.opcode = self.display.display.get_extension_major("XInputExtension")++ xinput.XIQueryVersion(display=self.display.display, opcode=self.opcode, major_version=2, minor_version=2)++ self.display.screen().root.xinput_select_events([(xinput.AllMasterDevices, xinput.KeyPressMask)])++ self.display.sync()++++ def presses(self):++ time.sleep(0.3)++ count = 0++ while self.display.pending_events():++ event = self.display.next_event()++ if event.type == 35 and event.extension == self.opcode and event.evtype == 2:++ count += 1++ return count++++++def proof_injection_and_capture():++ import capture_x11++ import desktop_x11++ import inject_x11++++ seen = Seen()++ hooks = capture_x11.Hooks(seen.on_key, seen.on_mouse, seen.on_motion)++ away = [False]++ hooks.grab_while(lambda: away[0])++ hooks.start()++ try:++ seen.take()++ inject_x11.inject_mouse_move(5, 0)++ inject_x11.inject_key("a", True)++ inject_x11.inject_key("a", False)++ keys, mice, motions = seen.take()++ check("the listener drops this machine's own injection", not keys and not mice and not motions, (keys, mice, motions))++++ hooks.drop_injected = False++ inject_x11.inject_mouse_move(7, -3)++ keys, mice, motions = seen.take()++ check("relative motion read back as the mouse's counts", motions == [(7, -3)], motions)++ check("motion moves the pin", (capture_x11.WM_MOUSEMOVE, 0) in mice, mice)++++ inject_x11.move_to(400, 300)++ seen.take()++ check("an absolute move lands where it was sent", desktop_x11.cursor_position() == (400, 300), desktop_x11.cursor_position())++ desktop_x11.set_cursor_position(123, 45)++ _keys, _mice, motions = seen.take()++ check("a warp moves the pointer", desktop_x11.cursor_position() == (123, 45), desktop_x11.cursor_position())++ check("a warp makes no motion", motions == [], motions)++ monitors = desktop_x11.monitors()++ check("RandR reports the screen", len(monitors) == 1 and (monitors[0].width, monitors[0].height) == (1920, 1080), monitors)++++ expected = {"shift": "shift", "shift_r": "shift_r", "ctrl": "cmd", "ctrl_r": "cmd_r",++ "alt": "alt", "alt_r": "alt_r", "cmd": "ctrl", "cmd_r": "ctrl_r"}++ for pressed, named in expected.items():++ inject_x11.inject_key(pressed, True)++ inject_x11.inject_key(pressed, False)++ keys, _, _ = seen.take(0.15)++ check(f"modifier {pressed} reads back as {named}", [(k[0], k[1]) for k in keys] == [(named, True), (named, False)], keys)++++ inject_x11.inject_key("q", True, us="q")++ inject_x11.inject_key("q", False, us="q")++ keys, _, _ = seen.take()++ check("a letter reads back with its code and US place", keys == [("q", True, 16, "q"), ("q", False, 16, "q")], keys)++++ for message_dy, message_dx, expect in ((1, 0, ("wheel", 1.0, 0.0)), (-1, 0, ("wheel", -1.0, 0.0)),++ (0, 1, ("wheel", 0.0, 1.0)), (0, -1, ("wheel", 0.0, -1.0))):++ inject_x11.inject_scroll(message_dy, message_dx, "line")++ _, mice, _ = seen.take(0.15)++ events = [capture_x11.mouse_event(message, data) for message, data in mice]++ check(f"scroll {message_dy},{message_dx} reads back as {expect}", events == [expect], events)++ inject_x11.inject_scroll(30, 0, "pixel")++ inject_x11.inject_scroll(30, 0, "pixel")++ _, mice, _ = seen.take()++ check("pixel scroll carries its remainder into one click", [capture_x11.mouse_event(*m) for m in mice] == [("wheel", 1.0, 0.0)], mice)++++ for button in ("left", "middle", "right", "back", "forward"):++ inject_x11.inject_mouse_button(button, True)++ inject_x11.inject_mouse_button(button, False)++ _, mice, _ = seen.take(0.15)++ events = [capture_x11.mouse_event(message, data) for message, data in mice]++ check(f"button {button} reads back", events == [("button", button, True), ("button", button, False)], events)++++ # The grab.++ listener = Listener()++ inject_x11.inject_key("w", True)++ inject_x11.inject_key("w", False)++ check("another app sees keys while nothing is grabbed", listener.presses() == 1)++ seen.take()++ away[0] = True++ check("input away: the capture grabs", wait(lambda: hooks.grabbed))++ check("a second client's grab is refused", not other_client_grab())++ inject_x11.inject_key("shift", True)++ inject_x11.inject_key("A", True)++ inject_x11.inject_key("A", False)++ inject_x11.inject_key("shift", False)++ inject_x11.inject_text("é")++ inject_x11.inject_mouse_move(4, 4)++ keys, mice, motions = seen.take(0.5)++ check("while grabbed, keys arrive with the state at the moment of the key",++ [(k[0], k[1]) for k in keys] == [("shift", True), ("A", True), ("A", False), ("shift", False), ("é", True), ("é", False)], keys)++ check("while grabbed, raw motion still arrives", motions == [(4, 4)], motions)++ check("while grabbed, other apps see no keys", listener.presses() == 0)++ away[0] = False++ check("input home: the capture lets go", wait(lambda: not hooks.grabbed))++ check("after letting go, another client can grab", other_client_grab())++ inject_x11.inject_key("w", True)++ inject_x11.inject_key("w", False)++ check("after letting go, other apps see keys again", listener.presses() == 1)++++ proof_layout(hooks, seen, listener, away)++++ away[0] = True++ wait(lambda: hooks.grabbed)++ hooks.stop()++ check("stop() lets go", other_client_grab())++ inject_x11.release_all()++ finally:++ hooks.stop()++++++def fake(keycode, down=None):++ """A key through XTest directly, for keys the injector never names (the keypad, Num Lock)."""++ from Xlib import X, display++ from Xlib.ext import xtest++++ other = display.Display()++ try:++ for press in ((True, False) if down is None else (down,)):++ xtest.fake_input(other, X.KeyPress if press else X.KeyRelease, keycode)++ other.sync()++ finally:++ other.close()++++++def proof_layout(hooks, seen, listener, away):++ """Keys the layout decides, read back through XKB, and repeats and handed-back keys as another++ app sees them."""++ import inject_x11++ from Xlib import XK, display++++ names = lambda keys: [(key[0], key[1]) for key in keys] # noqa: E731++ away[0] = True++ wait(lambda: hooks.grabbed)++ seen.take()++++ fake(87)++ keys, _, _ = seen.take()++ check("the keypad with Num Lock off moves (end)", names(keys) == [("end", True), ("end", False)], keys)++ fake(77)++ fake(87)++ keys, _, _ = seen.take()++ check("the keypad with Num Lock on types (1)", [k for k in names(keys) if k[0] != "num_lock"] == [("1", True), ("1", False)], keys)++ fake(77)++ seen.take()++++ inject_x11.inject_key("caps_lock", True)++ inject_x11.inject_key("caps_lock", False)++ inject_x11.inject_key("a", True)++ inject_x11.inject_key("a", False)++ inject_x11.inject_key("caps_lock", True)++ inject_x11.inject_key("caps_lock", False)++ keys, _, _ = seen.take()++ letters = [k for k in names(keys) if len(k[0]) == 1]++ check("under Caps Lock a small letter is typed with Shift and reads back small", letters == [("a", True), ("a", False)], keys)++++ # A second group, built by remapping two keys: Xvfb takes per-key changes but not a new XKB++ # keymap. ISO_Next_Group locks the next group, as a layout switch does.++ other = display.Display()++ try:++ other.change_keyboard_mapping(38, [(ord("a"), ord("A"), XK.string_to_keysym("Cyrillic_ef"), XK.string_to_keysym("Cyrillic_EF"))])++ other.change_keyboard_mapping(250, [(XK.string_to_keysym("ISO_Next_Group"),) * 2])++ other.sync()++ finally:++ other.close()++ time.sleep(0.3)++ fake(250)++ inject_x11.inject_key("ф", True)++ inject_x11.inject_key("ф", False)++ inject_x11.inject_key("Ф", True)++ inject_x11.inject_key("Ф", False)++ keys, _, _ = seen.take()++ check("a second layout group is typed and read back", [k for k in names(keys) if len(k[0]) == 1] == [("ф", True), ("ф", False), ("Ф", True), ("Ф", False)], keys)++ fake(250)++ seen.take()++++ seen.key_answer = False++ listener.presses()++ inject_x11.inject_key("w", True)++ inject_x11.inject_key("w", False)++ check("a key handed back from inside the grab reaches another app", listener.presses() == 1)++ seen.key_answer = None++ check("and the grab is held again after it", hooks.grabbed and not other_client_grab())++ away[0] = False++ wait(lambda: not hooks.grabbed)++ seen.take()++++ listener.presses()++ inject_x11.inject_key("a", True)++ time.sleep(1.0)++ inject_x11.inject_key("a", True) # the peer's repeat++ inject_x11.inject_key("a", False)++ count = listener.presses()++ check("a held plain key is repeated by the server, the peer's repeat not pressed again", count > 3, count)++ inject_x11.inject_key("!", True)++ time.sleep(1.0)++ held_once = listener.presses()++ inject_x11.inject_key("!", True)++ inject_x11.inject_key("!", False)++ again = listener.presses()++ check("a key typed with Shift around it is not repeated by the server", held_once == 2, held_once) # Shift and 1++ check("and each of the peer's repeats types it again", again == 2, again)++ other = display.Display()++ try:++ repeats = other.get_keyboard_control().auto_repeats++ finally:++ other.close()++ check("its auto-repeat is back on after the release", bool(repeats[10 // 8] >> (10 % 8) & 1))++ seen.take()++++++def proof_killed_process_lets_go():++ child = subprocess.Popen([sys.executable, __file__, "grab-and-hang"], stdout=subprocess.PIPE, text=True)++ line = child.stdout.readline().strip()++ check("a child process holds the grab", line == "grabbed" and not other_client_grab(), line)++ os.kill(child.pid, signal.SIGKILL)++ child.wait()++ check("a killed process's grab goes with its socket", wait(other_client_grab))++++++def grab_and_hang():++ import capture_x11++++ hooks = capture_x11.Hooks(lambda *a: None, lambda *a: None, lambda *a: None)++ hooks.grab_while(lambda: True)++ hooks.start()++ wait(lambda: hooks.grabbed)++ print("grabbed", flush=True)++ time.sleep(60)++++++def quit_soon(app):++ """app.quit from any thread: a QTimer started off the GUI thread never fires."""++ from PySide6.QtCore import QMetaObject, Qt++++ QMetaObject.invokeMethod(app, "quit", Qt.ConnectionType.QueuedConnection)++++++def png_bytes():++ from PySide6.QtCore import QBuffer, QIODevice++ from PySide6.QtGui import QColor, QImage++++ image = QImage(3, 2, QImage.Format.Format_ARGB32)++ image.fill(QColor("teal"))++ buffer = QBuffer()++ buffer.open(QIODevice.OpenModeFlag.WriteOnly)++ image.save(buffer, "PNG")++ return bytes(buffer.data())++++++def proof_clipboard():++ """In a child with a real xcb Qt application, as Beamer runs."""++ done = subprocess.run([sys.executable, __file__, "clipboard-owner"], capture_output=True, text=True, timeout=60,++ env=dict(os.environ, QT_QPA_PLATFORM="xcb"))++ sys.stdout.write(done.stdout)++ if done.returncode != 0:++ check("the clipboard proof ran", False, done.stderr[-2000:])++ failures.extend(line[5:] for line in done.stdout.splitlines() if line.startswith("FAIL "))++++++def clipboard_owner():++ from PySide6.QtGui import QGuiApplication++++ import clipboard_x11++++ app = QGuiApplication([])++ png = png_bytes()++++ def other(*args, **kwargs):++ return subprocess.Popen([sys.executable, __file__, "clipboard-other", *args], stdout=subprocess.PIPE,++ stdin=subprocess.PIPE, text=True, **kwargs)++++ def run():++ # From a worker thread, as the receiver and the sender call it.++ try:++ check("Beamer writes text and an image", clipboard_x11.set_contents("from beamer", png))++ time.sleep(0.3)++ check("its own write is not a change", clipboard_x11.changed_contents() == (None, None))++ reader = other("read")++ text, digest = reader.stdout.readline().rstrip("\n").split("\t")++ reader.wait()++ check("another app pastes Beamer's text", text == "from beamer", text)++ check("another app pastes Beamer's image byte for byte", digest == hashlib.sha256(png).hexdigest(), digest)++ writer = other("write")++ ready = writer.stdout.readline().strip()++ time.sleep(0.5)++ got = clipboard_x11.changed_contents()++ writer.stdin.close()++ writer.wait()++ check("another app's copy is a change, read from its owner", ready == "set" and got == ("from another app", None), got)++ check("and read once", clipboard_x11.changed_contents() == (None, None))++ except Exception as exc:++ check("the clipboard proof finished", False, repr(exc))++ finally:++ quit_soon(app)++++ threading.Thread(target=run, daemon=True).start()++ app.exec()++ sys.exit(1 if failures else 0)++++++def clipboard_other(action):++ from PySide6.QtCore import QTimer++ from PySide6.QtGui import QGuiApplication++++ app = QGuiApplication([])++ clipboard = app.clipboard()++ if action == "read":++ def read():++ mime = clipboard.mimeData()++ data = bytes(mime.data("image/png")) if mime is not None and mime.hasFormat("image/png") else b""++ print(f"{clipboard.text()}\t{hashlib.sha256(data).hexdigest()}", flush=True)++ app.quit()++++ QTimer.singleShot(0, read)++ else:++ def write():++ clipboard.setText("from another app")++ print("set", flush=True)++++ # Owned until the owner has read it: an X selection dies with its owner.++ threading.Thread(target=lambda: (sys.stdin.read(), quit_soon(app)), daemon=True).start()++ QTimer.singleShot(0, write)++ app.exec()++++++if __name__ == "__main__":++ if len(sys.argv) > 1 and sys.argv[1] == "grab-and-hang":++ grab_and_hang()++ elif len(sys.argv) > 1 and sys.argv[1] == "clipboard-owner":++ clipboard_owner()++ elif len(sys.argv) > 1 and sys.argv[1] == "clipboard-other":++ clipboard_other(sys.argv[2])++ else:++ proof_injection_and_capture()++ proof_killed_process_lets_go()++ proof_clipboard()++ print(f"{len(failures)} failed" if failures else "all passed", flush=True)++ sys.exit(min(len(failures), 100))diff --cc tools/x11_proof.shindex 0000000,0000000..1916f99new file mode 100755--- /dev/null+++ b/tools/x11_proof.sh@@@ -1,0 -1,0 +1,21 @@@++#!/usr/bin/env bash++# The X11 back ends against a real X server (tools/x11_proof.py says what is proved). Starts Xvfb++# on a free display, so it runs headless and never touches the desktop it is started from.++# Needs Xvfb, Python 3 and win_app/requirements-linux.txt; PYTHON picks the interpreter.++# Exit status: 0 when every check passes.++set -euo pipefail++here="$(cd "$(dirname "$0")" && pwd)"++python="${PYTHON:-python3}"++command -v Xvfb >/dev/null || { echo "Xvfb is not installed (Fedora: xorg-x11-server-Xvfb, Debian/Ubuntu: xvfb)" >&2; exit 2; }++for number in $(seq 90 120); do++ [ -e "/tmp/.X11-unix/X$number" ] || [ -e "/tmp/.X$number-lock" ] || break++done++Xvfb ":$number" -screen 0 1920x1080x24 -nolisten tcp >/dev/null 2>&1 &++server=$!++trap 'kill "$server" 2>/dev/null || true' EXIT++for _ in $(seq 50); do++ [ -e "/tmp/.X11-unix/X$number" ] && break++ sleep 0.1++done++unset WAYLAND_DISPLAY++DISPLAY=":$number" XDG_SESSION_TYPE=x11 "$python" "$here/x11_proof.py"diff --cc uk.co.kalkman.beamer.jsonindex 0000000,0000000..205795bnew file mode 100644--- /dev/null+++ b/uk.co.kalkman.beamer.json@@@ -1,0 -1,0 +1,123 @@@++{++ "app-id": "uk.co.kalkman.beamer",++ "runtime": "org.kde.Platform",++ "runtime-version": "6.11",++ "sdk": "org.kde.Sdk",++ "base": "io.qt.PySide.BaseApp",++ "base-version": "6.11",++ "command": "beamer",++ "separate-locales": false,++ "finish-args": [++ "--socket=wayland",++ "--socket=fallback-x11",++ "--share=ipc",++ "--share=network",++ "--device=dri",++ "--nofilesystem=host:reset",++ "--no-talk-name=com.canonical.AppMenu.Registrar",++ "--no-talk-name=org.kde.KGlobalSettings",++ "--no-talk-name=org.kde.kconfig.notify",++ "--talk-name=org.kde.StatusNotifierWatcher",++ "--env=PYTHONPATH=/app/share/beamer/win_app:/app/share/beamer",++ "--env=PYTHONNOUSERSITE=1"++ ],++ "build-options": {++ "env": {++ "BASEAPP_REMOVE_WEBENGINE": "1",++ "BASEAPP_DISABLE_NUMPY": "1"++ }++ },++ "cleanup": ["/include", "/lib/pkgconfig", "/lib/*.a", "/lib/*.la"],++ "modules": [++ {++ "name": "libei-scanner-python",++ "buildsystem": "simple",++ "cleanup": ["*"],++ "build-commands": ["pip3 install --verbose --no-index --no-deps --no-build-isolation --prefix=/app MarkupSafe==3.0.3 Jinja2==3.1.6"],++ "sources": [++ {"type": "file", "url": "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", "sha256": "722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698"},++ {"type": "file", "url": "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", "sha256": "85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67"}++ ],++ "build-options": {"env": {"PIP_FIND_LINKS": "."}}++ },++ {++ "name": "libei",++ "buildsystem": "meson",++ "config-opts": ["-Dtests=disabled", "-Dliboeffis=disabled", "-Dlibeis=disabled", "-Ddocumentation=[]"],++ "sources": [{++ "type": "archive",++ "url": "https://gitlab.freedesktop.org/libinput/libei/-/archive/1.6.0/libei-1.6.0.tar.bz2",++ "sha256": "5ed6078fa63afd554cc04b1001675615da0ed8fe23b80492ab63403140b5a830"++ }]++ },++ {++ "name": "python3-pycparser",++ "buildsystem": "simple",++ "build-commands": ["pip3 install --verbose --exists-action=i --no-index --no-deps --no-build-isolation --prefix=/app pycparser==2.23"],++ "sources": [{"type": "file", "url": "https://files.pythonhosted.org/packages/a0/e3/59cd50310fc9b59512193629e1984c1f95e5c8ae6e5d8c69532ccc65a7fe/pycparser-2.23-py3-none-any.whl", "sha256": "e5c6e8d3fbad53479cab09ac03729e0a9faf2bee3db8208a550daf5af81a5934"}],++ "build-options": {"env": {"PIP_FIND_LINKS": "."}}++ },++ {++ "name": "python3-cffi",++ "buildsystem": "simple",++ "build-commands": ["pip3 install --verbose --exists-action=i --no-index --no-deps --no-build-isolation --prefix=/app cffi==2.0.0"],++ "sources": [{"type": "file", "url": "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", "sha256": "44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529"}],++ "build-options": {"env": {"PIP_FIND_LINKS": "."}}++ },++ {++ "name": "python3-pynacl",++ "buildsystem": "simple",++ "build-commands": ["pip3 install --verbose --exists-action=i --no-index --no-deps --no-build-isolation --prefix=/app PyNaCl==1.6.2"],++ "sources": [{"type": "file", "url": "https://files.pythonhosted.org/packages/d9/9a/4019b524b03a13438637b11538c82781a5eda427394380381af8f04f467a/pynacl-1.6.2.tar.gz", "sha256": "018494d6d696ae03c7e656e5e74cdfd8ea1326962cc401bcf018f1ed8436811c"}],++ "build-options": {"env": {"PIP_FIND_LINKS": "."}}++ },++ {++ "name": "python3-jeepney",++ "buildsystem": "simple",++ "build-commands": ["pip3 install --verbose --exists-action=i --no-index --no-deps --no-build-isolation --prefix=/app jeepney==0.9.0"],++ "sources": [{"type": "file", "url": "https://files.pythonhosted.org/packages/b2/a3/e137168c9c44d18eff0376253da9f1e9234d0239e0ee230d2fee6cea8e55/jeepney-0.9.0-py3-none-any.whl", "sha256": "97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683"}],++ "build-options": {"env": {"PIP_FIND_LINKS": "."}}++ },++ {++ "name": "python3-six",++ "buildsystem": "simple",++ "build-commands": ["pip3 install --verbose --exists-action=i --no-index --no-deps --no-build-isolation --prefix=/app six==1.17.0"],++ "sources": [{"type": "file", "url": "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", "sha256": "4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274"}],++ "build-options": {"env": {"PIP_FIND_LINKS": "."}}++ },++ {++ "name": "python3-xlib",++ "buildsystem": "simple",++ "build-commands": ["pip3 install --verbose --exists-action=i --no-index --no-deps --no-build-isolation --prefix=/app python-xlib==0.33"],++ "sources": [{"type": "file", "url": "https://files.pythonhosted.org/packages/fc/b8/ff33610932e0ee81ae7f1269c890f697d56ff74b9f5b2ee5d9b7fa2c5355/python_xlib-0.33-py2.py3-none-any.whl", "sha256": "c3534038d42e0df2f1392a1b30a15a4ff5fdc2b86cfa94f072bf11b10a164398"}],++ "build-options": {"env": {"PIP_FIND_LINKS": "."}}++ },++ {++ "name": "beamer",++ "buildsystem": "simple",++ "build-commands": [++ "install -d /app/share/beamer",++ "cp -r core win_app VERSION /app/share/beamer/",++ "install -Dm755 flatpak/beamer /app/bin/beamer",++ "install -Dm644 tools/flatpak_import_probe.py /app/share/beamer/tools/flatpak_import_probe.py",++ "install -Dm644 tools/wayland_proof.py /app/share/beamer/tools/wayland_proof.py",++ "install -Dm644 flatpak/uk.co.kalkman.beamer.desktop /app/share/applications/uk.co.kalkman.beamer.desktop",++ "sed -e \"s/@VERSION@/$(cat VERSION)/\" -e \"s/@TIMESTAMP@/$(date +%s)/\" flatpak/uk.co.kalkman.beamer.metainfo.xml > metainfo.xml",++ "install -Dm644 metainfo.xml /app/share/metainfo/uk.co.kalkman.beamer.metainfo.xml",++ "install -Dm644 Beamer.svg /app/share/icons/hicolor/scalable/apps/uk.co.kalkman.beamer.svg",++ "install -Dm644 LICENSE /app/share/licenses/uk.co.kalkman.beamer/LICENSE",++ "/app/cleanup-BaseApp.sh"++ ],++ "sources": [++ {"type": "dir", "path": "core", "dest": "core", "skip": ["tests", "__pycache__"]},++ {"type": "dir", "path": "win_app", "dest": "win_app", "skip": ["tests", "__pycache__", ".venv", "build", "dist", "Output"]},++ {"type": "dir", "path": "flatpak", "dest": "flatpak"},++ {"type": "file", "path": "tools/flatpak_import_probe.py", "dest": "tools"},++ {"type": "file", "path": "tools/wayland_proof.py", "dest": "tools"},++ {"type": "file", "path": "VERSION"},++ {"type": "file", "path": "LICENSE"},++ {"type": "file", "path": "Beamer.svg"}++ ]++ }++ ]++}diff --cc win_app/app_config.pyindex b508490,fccda56..a521301--- a/win_app/app_config.py+++ b/win_app/app_config.py@@@ -1,43 -1,23 +1,44 @@@-"""Configuration loading and saving for the Windows tray application."""+"""Configuration loading and saving for the Windows tray application.+The file is settings.json (WIRE.md section 1), migrated from 1.4.x's config.json on the first start+and never written back to it. `Config` is the flat view the window, the sender and the receiver have- always read: this PC's own settings, and `peers[0]` as the fields that used to be the Mac's++always read: this PC's own settings, and the first desktop peer as the fields that used to be the Mac's+(`mac_host`, `auth_token`, `send_to_mac` and the rest). Each peer's side and zones are written only by+`set_ways` and `apply_arrangement`, one peer at a time, never by a save of the flat view, so a view read+before another machine sent its side cannot put the old one back. The settings carry whatever else+the file holds through every save untouched."""++import base64+import binascii+import copy+import hashlibimport json+import loggingimport osimport tempfile-from dataclasses import dataclass, field+import threading+import time+from dataclasses import dataclass, field, fields, replacefrom pathlib import Path-import capture_win-import effects-import ignored-import protocol-import return_edge+from platform_parts import capture as capture_win+from core import effects+from core import ignored++from core import peerlist+from core import protocol+from core import receiver+from core import return_edge+from core import ways+from core.pairing import local_address_towardsimport tokens+LOGGER = logging.getLogger(__name__)+# Today's two styles and five colours, then every crossing effect and colour pack in effects.py.# Any colour goes with any style.GLOW_STYLES = ("glow", "beam") + effects.EFFECT_IDS--GLOW_COLOURS = ("signal", "colourful", "ocean", "sunset", "mono") + effects.PACK_IDS++GLOW_COLOURS = tuple(tokens.PALETTES) + effects.PACK_IDSEDGES = ("left", "right", "top", "bottom")CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")METHODS = ("edge", "part", "corner", "shortcut")@@@ -88,7 -62,7 +89,7 @@@ class Config# Mac configures the rest and tells this PC the return edge on every switch.edge_glow: bool = Trueglow_style: str = "glow"-- glow_colour: str = "signal"++ glow_colour: str = "colourful"# A switch by the shortcut or a menu, not a crossing, plays an arrival around the pointer.shortcut_arrival: bool = True# What that plays: "match" for whatever the crossing style plays, else see effects.SWITCH_STYLES.@@@ -308,7 -248,7 +309,7 @@@ def config_from_dict(raw: dict) -> Conftrigger_key = raw.get("trigger_key", "cmd_r")try:glow_style, glow_colour, switch_style = effects.offered(-- raw.get("glow_style", "glow"), raw.get("glow_colour", "signal"), raw.get("shortcut_arrival_style", "match"))++ raw.get("glow_style", "glow"), raw.get("glow_colour", "colourful"), raw.get("shortcut_arrival_style", "match"))config = Config(host=raw["host"],port=migrated_port(raw["port"]),@@@ -426,186 -352,8 +427,186 @@@ def config_to_dict(config: Config) -> d}-def save_config(path: Path, config: Config) -> None:- payload = config_to_dict(config)+# -- settings.json (WIRE.md sections 1 and 8) ---------------------------------------------------++SCHEMA = 6+MAX_PEERS = 32+# Flat fields that settings.json keeps somewhere else (a peer entry, the zones, or the top level's+# own `port` and `name`) or no longer keeps (the PC's own address, the Mac's resistance).+_ELSEWHERE = {+ "host", "port", "auth_token", "paired_with", "mac_host", "mac_hardware_address", "send_to_mac",+ "allow_mac_to_drive", "mac_return_edge", "arrangement_set_at", "crossing_methods", "crossing_corner",+ "crossing_edge_parts", "mac_resistance_px", "machine_id", "name",+}+# Every other field keeps its 1.4.x name and value at the top level.+KEPT_FIELDS = tuple(item.name for item in fields(Config) if item.name not in _ELSEWHERE)+KINDS = ("edge", "part", "corner")+++def _b64(data: bytes) -> str:+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")+++def _unb64(text, length: int):+ """The bytes of a `b64` text of that length, or None: it must encode back to the same text."""+ if not isinstance(text, str) or not text.isascii():+ return None+ try:+ raw = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))+ except (binascii.Error, ValueError):+ return None+ return raw if len(raw) == length and _b64(raw) == text else None+++def new_machine_id() -> str:+ while True:+ raw = os.urandom(16)+ if raw != bytes(16):+ return _b64(raw)+++def is_machine_id(text) -> bool:+ raw = _unb64(text, 16)+ return raw is not None and raw != bytes(16)+++def is_paired_token(token) -> bool:+ """A token pairing made: 43 characters of `b64`. Any other is one a user typed into 1.4.x."""+ return _unb64(token, 32) is not None+++def key_id(token: str) -> bytes:+ """The pair's key id (WIRE.md section 2), computed from a paired token when needed and never stored."""+ return protocol.hkdf_sha256(token.encode("utf-8"), b"beamer-link-v6", b"beamer-key-id")[:16]+++def token_sha256(token: str) -> str:+ return hashlib.sha256(token.encode("utf-8")).hexdigest()+++def _text(value) -> str:+ return value if isinstance(value, str) else ""+++def _flag(value, default: bool) -> bool:+ return value if isinstance(value, bool) else default+++def _legacy_port(raw: dict) -> int:+ try:+ return migrated_port(raw.get("port", protocol.DEFAULT_PORT))+ except (TypeError, ValueError):+ return protocol.DEFAULT_PORT+++def _corner_edge(corner: str, side: str) -> str:+ """The edge a corner zone crosses: the side, as 1.4.x built the PC's corner push with the return+ edge whichever edges the corner touches (WIRE.md section 8); the corner's own left or right edge+ until a side is chosen."""+ return side if side in return_edge.EDGES else corner.split("_")[1]+++def _peer_entry(raw: dict, token: str, port: int, own_id: str) -> dict:+ """A peer entry for a 1.4.x pairing, from a dict in 1.4.x's field names: a migrated config.json,+ or the flat fields of a Config that has just paired."""+ side = raw.get("mac_return_edge")+ side = side if side in EDGES else ""+ set_at = _stamp(raw.get("arrangement_set_at", 0))+ return {+ "id": "", "name": _text(raw.get("paired_with")), "platform": "macos", "token": token,+ "host": _text(raw.get("mac_host")), "port": port, "hw": _text(raw.get("mac_hardware_address")),+ "send": _flag(raw.get("send_to_mac"), True), "allow_drive": _flag(raw.get("allow_mac_to_drive"), True),+ "in_use": True,+ "side": side, "side_set_at": set_at, "side_by": own_id if set_at else "",+ "paired_with": [], "paired_at": 0, "linked": False, "from_1_4": True,+ }+++def _zone_fields(legacy: dict):+ methods = legacy.get("crossing_methods", ["edge", "shortcut"])+ methods = methods if isinstance(methods, list) else ["edge", "shortcut"]+ # The whole edge covers its thirds, so both on would be two zones over one stretch (WIRE.md section 8).+ methods = [m for m in methods if not (m == "part" and "edge" in methods)]+ corner = legacy.get("crossing_corner")+ parts = legacy.get("crossing_edge_parts")+ if not isinstance(parts, list) or not parts or not all(part in return_edge.PARTS for part in parts):+ parts = ["middle"]+ return methods, (corner if corner in CORNERS else "top_left"), parts+++def _zones_from_methods(peer_id: str, legacy: dict, side: str) -> list:+ methods, corner, parts = _zone_fields(legacy)+ rest = {"edge": {}, "part": {"parts": list(parts)}, "corner": {"corner": corner, "edge": _corner_edge(corner, side)}}+ return [{"peer": peer_id, "kind": kind, **rest[kind], **({} if kind in methods else {"off": True})} for kind in KINDS]+++def migrate(legacy, machine_id=None) -> dict:+ """The settings for a config.json in 1.4.x's shape (`None` when there is none) and a new id."""+ machine_id = machine_id or new_machine_id()+ settings = {+ "schema": SCHEMA, "machine_id": machine_id, "name": "", "port": protocol.DEFAULT_PORT, "shortcut": True,+ "peers": [], "zones": [], "migrated_token_sha256": "",+ }+ if not isinstance(legacy, dict):+ return settings+ settings.update({key: legacy[key] for key in KEPT_FIELDS if key in legacy})+ settings["port"] = _legacy_port(legacy)+ methods, _corner, _parts = _zone_fields(legacy)+ settings["shortcut"] = "shortcut" in methods+ token = _text(legacy.get("auth_token"))+ if token:+ settings["migrated_token_sha256"] = token_sha256(token)+ peer = _peer_entry(legacy, token, settings["port"], machine_id)+ settings["peers"].append(peer)+ settings["zones"] = _zones_from_methods("", legacy, peer["side"])+ return settings+++def remigrate(settings: dict, legacy: dict) -> bool:+ """A config.json whose token is not the one already migrated is a pairing made under 1.4.x after+ the upgrade: it replaces the `from_1_4` entry, or comes back if the user removed it. True when the+ settings changed."""+ token = _text(legacy.get("auth_token"))+ if not token or token_sha256(token) == settings["migrated_token_sha256"]:+ return False+ settings["migrated_token_sha256"] = token_sha256(token)+ peers, zones = settings["peers"], settings["zones"]- old = next((index for index, peer in enumerate(peers) if peer.get("from_1_4")), None)++ old = next((index for index, peer in enumerate(peers) if peer.get("from_1_4") and peer.get("port") != 0), None)+ if is_paired_token(token) and any(+ is_paired_token(peer.get("token")) and key_id(peer["token"]) == key_id(token)+ for index, peer in enumerate(peers) if index != old+ ):+ return True+ entry = _peer_entry(legacy, token, _legacy_port(legacy), settings["machine_id"])+ if old is not None:+ for zone in zones:+ if zone.get("peer") == peers[old].get("id"):+ zone["peer"] = ""+ peers[old] = entry+ elif len(peers) < MAX_PEERS:+ peers.append(entry)+ zones.extend(_zones_from_methods("", legacy, entry["side"]))+ return True+++def learn_peer_id(settings: dict, index: int, peer_id: str) -> None:+ """The first link with a migrated entry says who it is: fill the id in and point the zones that+ named the empty id at it."""+ peers = settings["peers"]+ if not is_machine_id(peer_id):+ raise ConfigError("a peer id must be a machine id")+ if peers[index].get("id"):+ raise ConfigError("that peer already has an id")+ if peer_id == settings["machine_id"] or any(peer.get("id") == peer_id for peer in peers):+ raise ConfigError("two machines cannot share an id")+ for zone in settings["zones"]:+ if zone.get("peer") == "":+ zone["peer"] = peer_id+ peers[index]["id"] = peer_id+++def _write_json(path: Path, payload: dict) -> None:+ """A new file beside the old, then a rename over it."""path.parent.mkdir(parents=True, exist_ok=True)temporary_path = Nonetry:@@@ -627,314 -375,3 +628,323 @@@finally: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)++ 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 peer and its++ """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 = settings["peers"][0] if settings["peers"] else None++ 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 peer's address, name and switches, never a side or a zone. A token that is not the first- peer's is a new pairing: it replaces that entry, and its zones point at the empty id until a link++ 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"]- if not peers or peers[0].get("token") != flat["auth_token"]:++ 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 = peers[0] if peers else {}++ 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 peers:++ if index is not None:+ for zone in settings["zones"]:- if zone.get("peer") == peers[0].get("id"):++ if zone.get("peer") == peer.get("id"):+ zone["peer"] = ""- peers[0] = entry++ peers[index] = entry+ else:- peers.insert(0, entry)- peer = peers[0]++ 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_json(path, settings)++ 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("hw") == address:++ 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:+ """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+ 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")+ 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):+ """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)+ if changed:+ _write_json(path, settings)+ return changed, noticesdiff --cc win_app/capture_portal.pyindex 2854945,0000000..3daec63mode 100644,000000..100644--- a/win_app/capture_portal.py+++ b/win_app/capture_portal.py@@@ -1,871 -1,0 +1,881 @@@+"""Keyboard and mouse capture on Wayland, through the InputCapture portal and libei: the twin of+capture_x11.py, with the same Hooks, Trigger and names, so the bridge and the sender drive it.++Wayland lets no app see input meant for another, so capture is the desktop's. Beamer puts pointer+barriers on the outside edges of this machine's zones (the edge, its thirds, or a corner's two+walls) and the compositor, when the pointer pushes through one, captures every keyboard and+pointer and sends their events to Beamer over libei until Beamer lets go (Release). Nothing else+can start a capture, so input leaves this machine only across an edge: the shortcut and the tray+bring it home but cannot send it away, and Beamer sees no key at all while input is here.++A push into a barrier is not yet a crossing. The barrier holds the pointer, as Windows holds it at+the edge of the desktop, and the movement that follows feeds the sender's own zone models, so the+resistance, the corners and the thirds behave as on the other machines. The pointer can slide+along the barrier while held; the desktop shows it still, so where it is lives in desktop_portal+and the pointer is let go there. Any movement back into the screen, a key, a button, or a pause+in the push lets go of it; the key or button that did is lost, since nothing can play it back+here. Once the zone gives, input is away until the sender brings it home, and the pointer is let+go where the sender lands it (it says so through desktop_portal before or just after it reports+input home, so the let-go waits a moment for it).++While input is away, a key the sender hands back (the stays-here list) is lost for the same+reason, and the full-screen hold and the drag guard have nothing to read (desktop_portal).++Every way home is the desktop's: Release, the session closing when its D-Bus connection does+(a stop, an error, the process dying), and a watchdog that ends that connection when the capture+thread stops answering while the desktop holds input for it.++InputCapture v2 (GNOME 51, Plasma 6.7) remembers the user's answer with a restore token, kept in+the state directory; v1 asks at every start."""++import logging+import math+import os+import select+import threading+import time+from typing import Callable, Dict, List, Optional, Tuple++from capture_win import ( # noqa: F401 (re-exported for the bridge, which reads them from here)+ BUTTON_TITLES,+ MODIFIER_NAMES,+ REDIRECT,+ RETURN,+ TOGGLE,+ WHEEL_DELTA,+ WM_MOUSEHWHEEL,+ WM_MOUSEWHEEL,+ Trigger,+ button_of,+ mouse_event,+ wheel_notches,+)+from capture_x11 import ( # noqa: F401 (the same evdev names and titles as X11)+ _BUTTONS,+ CHORD_MASK,+ KEYCODE_OFFSET,+ NOT_TRIGGER_VKS,+ UNRECORDABLE_TRIGGER_VKS,+ VK_TITLES,+ VK_TO_NAME,+ _wheel_data,+ character,+ hook_vk,+ input_title,+)+from core import keytable+from core import return_edge as crossing+import desktop_portal+import portal++LOGGER = logging.getLogger(__name__)++INTERFACE = "org.freedesktop.portal.InputCapture"+CAP_KEYBOARD, CAP_POINTER = 1, 2+TICK_SECONDS = 0.05+STALL_SECONDS = 2.0+# A push that stops for this long is a pointer resting at the edge, which is let go.+IDLE_SECONDS = 0.3+# How long a let-go waits for the sender to say where the pointer lands.+LANDING_SECONDS = 0.15+# How long the portal has to answer a request no user sees (zones, barriers).+REQUEST_SECONDS = 10.0+# After the desktop disables the session, the barriers are set again no sooner than this.+DISABLED_SECONDS = 1.0+# An Activated signal with no activation_id (the portal spec allows it): libei's sequences are not+# checked, and Release names none.+NO_ID = -1+# A push that met two barriers at once is put on the nearest within this many pixels of the pointer.+WALL_PX = 64+# While input is away with nothing captured, the sender is asked to bring it home this often.+HOME_AGAIN_SECONDS = 0.5+# ei events that arrive before the portal's Activated signal says which barrier, held until it does.+EARLY_MAX = 64+EARLY_SECONDS = 1.0+# libei's scroll is in the desktop's pixels; mutter and weston send 10 for one wheel click.+PIXELS_PER_NOTCH = 10.0+# evdev's button codes, as X numbers them for capture_x11's table.+EVDEV_BUTTONS = {0x110: 1, 0x111: 3, 0x112: 2, 0x113: 8, 0x114: 9}++# The core modifier bits a held key sets, for when the desktop does not say (libei sends a+# receiver its modifiers only if the compositor chooses to).+HELD_MODS = {42: 1, 54: 1, 29: 4, 97: 4, 56: 8, 125: 64, 126: 64}++# Wall outward directions.+_NORMAL = {"left": (-1, 0), "right": (1, 0), "top": (0, -1), "bottom": (0, 1)}++# The app's own sentences for what Wayland takes away; the bridge shows them as they are.+NO_PORTAL = ("This desktop does not let apps capture the keyboard and mouse (it has no InputCapture "+ "portal), so this machine cannot drive another one. It can still be driven if the "+ "desktop allows remote control.")+REFUSED = ("Beamer was not allowed to capture the keyboard and mouse, so this machine cannot drive "+ "another one. Turn sending off and on again to be asked again.")+ENDED = "The desktop stopped letting Beamer capture the keyboard and mouse: {detail}"+++class CaptureUnavailable(RuntimeError):+ """Capture cannot happen here; `sentence` says so in the app's words."""++ def __init__(self, sentence: str) -> None:+ super().__init__(sentence)+ self.sentence = sentence+++# -- barriers, pure -------------------------------------------------------+++def _outer(monitors: List[crossing.Rect], monitor: crossing.Rect, edge: str) -> List[Tuple[int, int]]:+ """The stretches of `monitor`'s `edge`, as [start, end) along it, that no other display lies+ beyond: a barrier must sit on the outside of the union of the zones."""+ if edge in ("left", "right"):+ line = monitor.x if edge == "left" else monitor.x + monitor.width+ start, end = monitor.y, monitor.y + monitor.height+ beyond = [(m.y, m.y + m.height) for m in monitors+ if (m.x + m.width == line if edge == "left" else m.x == line)]+ else:+ line = monitor.y if edge == "top" else monitor.y + monitor.height+ start, end = monitor.x, monitor.x + monitor.width+ beyond = [(m.x, m.x + m.width) for m in monitors+ if (m.y + m.height == line if edge == "top" else m.y == line)]+ stretches = [(start, end)]+ for low, high in beyond:+ cut = []+ for a, b in stretches:+ if high <= a or low >= b:+ cut.append((a, b))+ continue+ if a < low:+ cut.append((a, low))+ if high < b:+ cut.append((high, b))+ stretches = cut+ return stretches+++def _line(monitor: crossing.Rect, edge: str) -> int:+ return {"left": monitor.x, "right": monitor.x + monitor.width,+ "top": monitor.y, "bottom": monitor.y + monitor.height}[edge]+++def _segment(monitor: crossing.Rect, edge: str, a: int, b: int) -> Tuple[int, int, int, int]:+ line = _line(monitor, edge)+ if edge in ("left", "right"):+ return (line, a, line, b - 1)+ return (a, line, b - 1, line)+++def _clip(stretches, low: int, high: int) -> List[Tuple[int, int]]:+ return [(max(a, low), min(b, high)) for a, b in stretches if min(b, high) > max(a, low)]+++def _thirds(monitor: crossing.Rect, edge: str) -> List[Tuple[int, int]]:+ """Each third of `monitor` along `edge`, as [start, end), split where return_edge.part_of+ splits a fraction of the display."""+ start, length = (monitor.y, monitor.height) if edge in ("left", "right") else (monitor.x, monitor.width)+ cuts = [start + math.ceil(i * length / 3) for i in range(3)] + [start + length]+ return [(cuts[i], cuts[i + 1]) for i in range(3)]+++def barriers(models: list, monitors: List[crossing.Rect]) -> List[Tuple[str, Tuple[int, int, int, int]]]:+ """(wall, position) for every barrier the sender's zone models need on these displays, in the+ portal's coordinates, each once: a whole edge, the chosen thirds of it, or a corner's two walls+ of CORNER_PX + 1 pixels. A notch stretch (SpanEdge) is the Mac's and has none here."""+ found: List[Tuple[str, Tuple[int, int, int, int]]] = []++ def add(wall, position):+ if (wall, position) not in found:+ found.append((wall, position))++ for model in models:+ if isinstance(model, crossing.SpanEdge):+ continue+ for monitor in monitors:+ if isinstance(model, crossing.CornerPush):+ for wall in (model.vertical, model.horizontal):+ along_far = wall in ("left", "right")+ other = model.horizontal if wall in ("top", "bottom") else model.vertical+ if along_far: # a side wall runs along y, from the corner's top or bottom+ low = monitor.y if other == "top" else monitor.y + monitor.height - 1 - crossing.CORNER_PX+ else:+ low = monitor.x if other == "left" else monitor.x + monitor.width - 1 - crossing.CORNER_PX+ for a, b in _clip(_outer(monitors, monitor, wall), low, low + crossing.CORNER_PX + 1):+ add(wall, _segment(monitor, wall, a, b))+ continue+ stretches = _outer(monitors, monitor, model.edge)+ if isinstance(model, crossing.PartEdge):+ thirds = _thirds(monitor, model.edge)+ chosen = [thirds[crossing.PARTS.index(part)] for part in crossing.PARTS if part in model.parts]+ stretches = [piece for low, high in chosen for piece in _clip(stretches, low, high)]+ for a, b in stretches:+ add(model.edge, _segment(monitor, model.edge, a, b))+ return found+++def model_key(models: list) -> tuple:+ """What about the models places barriers, so they are set again only when it changes."""+ return tuple((type(m).__name__, m.edge, tuple(sorted(getattr(m, "parts", ()))), getattr(m, "corner", None))+ for m in models)+++class Press:+ """The pointer held at a barrier while input is still here: where it is, sliding along the+ wall, and whether the movement is still a push."""++ def __init__(self, wall: str, point: Tuple[int, int], displays: List[crossing.Rect], clock=time.monotonic) -> None:+ self.wall = wall+ self._displays = displays+ self.point = desktop_portal.clamp_to(displays, *point)+ self._clock = clock+ self._last_push = clock()+ self._exact = [float(self.point[0]), float(self.point[1])]++ def feed(self, dx: float, dy: float) -> bool:+ """True while the movement pushes outward or slides along the wall; False once it comes+ back into the screen, with `point` where it then is."""+ nx, ny = _NORMAL[self.wall]+ outward = dx * nx + dy * ny+ if outward < 0:+ self._move(dx, dy)+ return False+ # Only the part along the wall moves the pointer; the barrier holds the rest.+ self._move(dx * (1 - abs(nx)), dy * (1 - abs(ny)))+ if outward > 0:+ self._last_push = self._clock()+ return True++ def _move(self, dx: float, dy: float) -> None:+ self._exact[0] += dx+ self._exact[1] += dy+ self.point = desktop_portal.clamp_to(self._displays, *self._exact)+ # Travel past the display is not kept: the pointer cannot be there.+ for axis in (0, 1):+ if self.point[axis] != round(self._exact[axis]):+ self._exact[axis] = float(self.point[axis])++ def idle(self) -> bool:+ return self._clock() - self._last_push > IDLE_SECONDS+++# -- the session ----------------------------------------------------------+++class _Session:+ """The InputCapture session and its libei receiver, on the capture thread only."""++ def __init__(self, bus_factory, ei_factory, tokens, stopping) -> None:+ self.portal = portal.Portal(bus_factory(), stopping)+ self._ei_factory = ei_factory+ self._tokens = tokens+ self.handle = None+ self.ei = None+ self.zone_set = None+ self.enabled = False++ def check(self) -> None:+ preflight = getattr(self._ei_factory, "preflight", None)+ if preflight is not None:+ preflight()+ self.version = self.portal.version(INTERFACE)- if self.version < 1:- raise CaptureUnavailable(NO_PORTAL)++ def open(self) -> None:+ """Make and start the session; the user may be asked, for as long as they take."""++ LOGGER.info("Requesting InputCapture session (portal version %d)", self.version)+ try:+ if self.version >= 2:- results = portal.plain(self.portal.call(INTERFACE, "CreateSession2", "a{sv}",- ({"session_handle_token": ("s", self.portal.token())},)))++ try:++ results = portal.plain(self.portal.call(INTERFACE, "CreateSession2", "a{sv}",++ ({"session_handle_token": ("s", self.portal.token())},)))++ except portal.PortalError as exc:++ raise CaptureUnavailable(f"{NO_PORTAL} ({exc})") from exc+ self.handle = results[0]["session_handle"]+ options = {"capabilities": ("u", CAP_KEYBOARD | CAP_POINTER), "persist_mode": ("u", 2)}+ token = self._tokens.read()+ if token:+ options["restore_token"] = ("s", token)+ started = self.portal.request(INTERFACE, "Start", "osa{sv}", lambda handle_token: (+ self.handle, "", dict(options, handle_token=("s", handle_token))))+ if started.get("restore_token"):+ self._tokens.write(started["restore_token"])+ else:- results = self.portal.request(INTERFACE, "CreateSession", "sa{sv}", lambda handle_token: ("", {- "handle_token": ("s", handle_token),- "session_handle_token": ("s", self.portal.token()),- "capabilities": ("u", CAP_KEYBOARD | CAP_POINTER),- }))++ try:++ results = self.portal.request(INTERFACE, "CreateSession", "sa{sv}", lambda handle_token: ("", {++ "handle_token": ("s", handle_token),++ "session_handle_token": ("s", self.portal.token()),++ "capabilities": ("u", CAP_KEYBOARD | CAP_POINTER),++ }))++ except portal.PortalError as exc:++ raise CaptureUnavailable(f"{NO_PORTAL} ({exc})") from exc+ self.handle = results["session_handle"]+ except portal.Refused:+ self._tokens.write("")+ raise CaptureUnavailable(REFUSED) from None+ fd = self.portal.call(INTERFACE, "ConnectToEIS", "oa{sv}", (self.handle, {}))[0]+ try:+ self.ei = self._ei_factory(fd)+ except Exception:+ os.close(fd)+ raise++ def zones(self) -> List[crossing.Rect]:+ results = self.portal.request(INTERFACE, "GetZones", "oa{sv}", lambda token: (self.handle, {"handle_token": ("s", token)}),+ timeout=REQUEST_SECONDS)+ self.zone_set = results.get("zone_set")+ return [crossing.Rect(x, y, width, height) for width, height, x, y in results.get("zones", [])]++ def set_barriers(self, positions: List[Tuple[int, int, int, int]]) -> List[int]:+ """Barrier i + 1 for each position; the ids the desktop refused. Setting them suspends+ the session, so it is enabled again after, when there are any."""+ self.enabled = False+ listed = [{"barrier_id": ("u", index + 1), "position": ("(iiii)", tuple(position))}+ for index, position in enumerate(positions)]+ results = self.portal.request(INTERFACE, "SetPointerBarriers", "oa{sv}aa{sv}u", lambda token: (+ self.handle, {"handle_token": ("s", token)}, listed, self.zone_set or 0), timeout=REQUEST_SECONDS)+ if positions:+ self.enable()+ return list(results.get("failed_barriers", []))++ def enable(self) -> None:+ self.portal.call(INTERFACE, "Enable", "oa{sv}", (self.handle, {}))+ self.enabled = True+- def disable(self) -> None:- if self.enabled:- self.portal.call(INTERFACE, "Disable", "oa{sv}", (self.handle, {}))- self.enabled = False-+ def release(self, activation_id: int, point: Tuple[int, int]) -> None:+ options = {"cursor_position": ("(dd)", (float(point[0]), float(point[1])))}+ if activation_id != NO_ID:+ options["activation_id"] = ("u", int(activation_id))+ self.portal.call(INTERFACE, "Release", "oa{sv}", (self.handle, options))++ def close(self) -> None:+ try:+ if self.ei is not None:+ self.ei.close()+ finally:+ self.ei = None+ self.portal.close()+++class Hooks:+ """The capture thread and the session it owns, with capture_x11.Hooks' callbacks:+ `on_key(name, down, vk, us)`, `on_mouse(message, x, y, mouse_data)` and `on_motion(dx, dy)`,+ `vk` the evdev code. `grab_while(predicate)` says when input is away; `barriers_from(models)`+ gives the sender's zone models, empty while the edges are held. `on_home` is called on the+ capture thread when the desktop ends a capture while input is away (so it comes home), and+ `on_failure(exc)` when capture stops on its own after it started."""++ def __init__(self, on_key, on_mouse, on_motion, connect: Optional[Callable[[], object]] = None,+ ei: Optional[Callable[[int], object]] = None, tokens=None, clock=time.monotonic) -> None:+ self._on_key = on_key+ self._on_mouse = on_mouse+ self._on_motion = on_motion+ self._connect = connect or portal.JeepneyBus+ self._ei_factory = ei or _ei_receiver+ self._tokens = tokens or portal.TokenStore("input-capture")+ self._clock = clock+ self._thread: Optional[threading.Thread] = None+ self._ready = threading.Event()+ self._stopping = threading.Event()+ self._failure: Optional[BaseException] = None+ self._predicate: Optional[Callable[[], bool]] = None+ self._models: Callable[[], list] = lambda: []+ self.on_home: Optional[Callable[[], None]] = None+ self.on_failure: Optional[Callable[[BaseException], None]] = None+ self._session: Optional[_Session] = None+ self._beat = clock()+ self._reset()++ def _reset(self) -> None:+ self._activation: Optional[int] = None+ self._press: Optional[Press] = None+ self._away = False+ self._home_since: Optional[float] = None+ self._early: List[tuple] = []+ self._early_at = 0.0+ self._walls: Dict[int, str] = {}+ self._placed: List[Tuple[str, Tuple[int, int, int, int]]] = []+ self._sequences: Dict[object, int] = {} # libei device: the sequence it emulates under+ self._disabled_at: Optional[float] = None+ self._sent_home_at: Optional[float] = None+ self._key = None+ self._zones: List[crossing.Rect] = []+ self._keymap = None+ self._mods = (0, 0, 0, 0)- self._names_down: Dict[int, str] = {}++ self._names_down: Dict[Tuple[int, int], str] = {}+ self._carry = [0.0, 0.0]+ self._scroll_carry = [0.0, 0.0]+ self._frame: List[tuple] = []++ def grab_while(self, predicate: Callable[[], bool]) -> None:+ """Hold input for as long as `predicate` is true, once the desktop has captured it. Asked on+ the capture thread after every batch, so cheap and never blocking."""+ self._predicate = predicate++ def barriers_from(self, models: Callable[[], list]) -> None:+ self._models = models++ @property+ def grabbed(self) -> bool:+ return self._activation is not None++ @property+ def holding(self) -> bool:+ """Whether the desktop has captured input for Beamer now: only then can it go away."""+ return self._activation is not None++ def start(self) -> None:+ if self._thread is not None and self._thread.is_alive():+ if self._stopping.is_set():+ raise RuntimeError("The last capture thread has not stopped yet")+ return+ self._ready.clear()+ self._stopping.clear()+ self._failure = None+ self._thread = threading.Thread(target=self._run, name="Beamer-hooks", daemon=True)+ self._thread.start()+ if not self._ready.wait(timeout=5.0):+ raise RuntimeError("The input capture did not start within five seconds")+ if self._failure is not None:+ raise self._failure++ def stop(self) -> None:+ self._stopping.set()+ thread = self._thread+ if thread is None:+ return+ thread.join(timeout=2.0)+ if thread.is_alive():+ LOGGER.error("The capture thread did not stop within two seconds; ending its connection")+ self._abort()+ thread.join(timeout=1.0)+ if not thread.is_alive():+ self._thread = None++ def _abort(self) -> None:+ session = self._session+ if session is not None:+ abort = getattr(session.portal.bus, "abort", None)+ if abort is not None:+ abort()++ # -- the thread ----------------------------------------------------------++ def _run(self) -> None:+ session = None+ try:+ session = self._session = _Session(self._connect, self._ei_factory, self._tokens, self._stopping.is_set)+ session.check()+ self._beat = self._clock()+ threading.Thread(target=self._watch, name="Beamer-hooks-watch", daemon=True).start()+ self._ready.set()+ session.open()+ self._set_zones(session.zones())+ while not self._stopping.is_set():+ self._beat = self._clock()+ self._wait(session)+ self._beat = self._clock()+ for path, interface, member, body in session.portal.signals():+ if interface == INTERFACE and body and body[0] == session.handle:+ self._signal(member, body[1] if len(body) > 1 else {})+ elif interface == portal.SESSION and member == "Closed" and path == session.handle:+ raise CaptureUnavailable(ENDED.format(detail="the session was closed"))+ events = session.ei.events()+ for event in events:+ self._beat = self._clock()+ try:+ self._ei_event(event)+ except CaptureUnavailable:+ raise+ except Exception:+ LOGGER.exception("An input event could not be read; carrying on")+ self._tick()+ except Exception as exc:+ if not self._stopping.is_set():+ LOGGER.exception("Keyboard and mouse capture stopped")+ started = self._ready.is_set()+ self._failure = exc if not started else None+ self._ready.set()+ if started and not self._stopping.is_set() and self.on_failure is not None:+ try:+ self.on_failure(exc)+ except Exception:+ LOGGER.exception("Could not report that capture stopped")+ finally:+ self._end(session)+ self._stopping.set()++ def _end(self, session) -> None:+ """The way home on every exit: let go of a capture, then end the connection, which closes+ the session even if the Release could not be sent."""+ try:+ if session is not None and self._activation is not None:+ session.release(self._activation, desktop_portal.cursor_position())+ except Exception:+ LOGGER.exception("Could not let go of the captured input; closing the session lets go of it")+ finally:+ self._activation = None++ self._names_down.clear()+ desktop_portal.set_captured(False)+ if session is not None:+ try:+ session.close()+ except Exception:+ LOGGER.exception("The capture session did not close cleanly")+ self._session = None+ self._reset()++ def _wait(self, session) -> None:+ if session.portal.pending():+ return+ try:+ select.select([session.portal.fileno(), session.ei.fileno()], [], [], TICK_SECONDS)+ except (OSError, ValueError) as exc:+ raise CaptureUnavailable(ENDED.format(detail=exc)) from exc++ def _watch(self) -> None:+ """The safety net under a capture thread stuck while the desktop holds input for it:+ nothing else can let go, so its connection is ended and the portal closes the session."""+ while not self._stopping.wait(STALL_SECONDS / 8):+ if self._activation is not None and self._clock() - self._beat > STALL_SECONDS:+ LOGGER.error("The capture thread has not answered for %s s while the keyboard and mouse are captured; "+ "ending its connection to free them", STALL_SECONDS)+ self._abort()+ return++ # -- portal signals --------------------------------------------------------++ def _signal(self, member: str, options: dict) -> None:+ if member == "Activated":+ self._activated(options)+ elif member in ("Deactivated", "Disabled"):+ point = options.get("cursor_position")+ was_away = self._away+ self._activation = None+ self._press = None+ self._away = False+ self._frame = []+ desktop_portal.set_captured(False)+ if point is not None:+ desktop_portal.note_position(*point)+ if member == "Disabled":+ self._session.enabled = False+ self._key = None # set the barriers and enable again, after DISABLED_SECONDS+ self._disabled_at = self._clock()+ # Asked of the sender too: a tray switch may have sent input away a moment ago.+ if was_away or self._away_wanted():+ LOGGER.info("The desktop ended the capture while input was away; bringing it home")+ self._home()+ elif member == "ZonesChanged":+ self._set_zones(self._session.zones())++ def _activated(self, options: dict) -> None:+ activation = options.get("activation_id", NO_ID)+ point = options.get("cursor_position") or desktop_portal.cursor_position()+ barrier = options.get("barrier_id")+ # 0 is a push that met two barriers at once (a corner's two walls); the pointer says which.+ wall = self._walls.get(barrier) if barrier else self._wall_at(point)+ self._activation = activation+ self._frame = []+ desktop_portal.set_captured(True)+ if wall is None:+ LOGGER.info("Captured at a barrier Beamer does not know; letting go")+ self._let_go(desktop_portal.clamp_to(self._zones, *point))+ return+ self._press = Press(wall, point, self._zones, self._clock)+ desktop_portal.note_position(*self._press.point)+ early, self._early = self._early, []+ for event, sequence in early:+ if self._current(sequence):+ self._ei_event(event)++ def _wall_at(self, point) -> Optional[str]:+ """The wall of the placed barrier nearest the pointer, within WALL_PX: the desktop reports+ the pointer on the screen's side of a barrier, or past it by the push."""+ x, y = point+ best = None+ for index, (wall, (x1, y1, x2, y2)) in enumerate(self._placed):+ if index + 1 not in self._walls:+ continue+ distance = max(x1 - x, 0, x - x2) + max(y1 - y, 0, y - y2)+ if distance <= WALL_PX and (best is None or distance < best[0]):+ best = (distance, wall)+ return best[1] if best else None++ def _let_go_unannounced(self) -> None:+ """The desktop started sending input for a capture it never announced (no Activated):+ after EARLY_SECONDS it is let go under its libei sequence, which is its activation id."""+ if not self._early or self._clock() - self._early_at <= EARLY_SECONDS:+ return+ sequence = self._early[-1][1]+ self._early = []+ LOGGER.warning("The desktop captured input without saying so; letting go")+ self._activation = sequence+ self._let_go(desktop_portal.cursor_position())++ def _current(self, sequence: Optional[int]) -> bool:+ """Whether input emulated under `sequence` belongs to the capture now held: libei's start+ sequence is the portal's activation id."""+ return self._activation == NO_ID or sequence is None or sequence == self._activation++ def _home(self) -> None:+ if self.on_home is not None:+ self.on_home()++ def _let_go(self, point: Tuple[int, int]) -> None:+ """Release at `point`. Input counts as held until the Release has gone, and a Release that+ fails ends the session, whose closing lets go of input whatever else has failed."""+ activation = self._activation+ self._press = None+ self._away = False+ self._home_since = None+ self._frame = []+ desktop_portal.note_position(*point)+ try:+ if activation is not None and self._session is not None:+ self._session.release(activation, point)+ except Exception as exc:+ raise CaptureUnavailable(ENDED.format(detail=f"letting go failed: {exc}")) from exc+ finally:+ self._activation = None++ self._names_down.clear()+ desktop_portal.set_captured(False)+ # The sender may have landed the pointer while the Release was on its way.+ landed = desktop_portal.position()+ if landed is not None and landed != desktop_portal.clamp_to(self._zones, *point):+ desktop_portal.set_cursor_position(*landed)++ # -- the tick --------------------------------------------------------------++ def _away_wanted(self) -> bool:+ predicate = self._predicate+ if predicate is None:+ return False+ try:+ return bool(predicate())+ except Exception:+ LOGGER.exception("Could not tell whether input is away; bringing it home")+ return False++ def _tick(self) -> None:+ session = self._session+ if self._activation is None:+ # Input away with nothing captured (a switch that passed input_held() just before a+ # let-go): no key can reach the peer, so it comes home.+ if self._away_wanted():+ now = self._clock()+ if self._sent_home_at is None or now - self._sent_home_at >= HOME_AGAIN_SECONDS:+ if self._sent_home_at is None:+ LOGGER.info("Input went away with nothing captured; bringing it home")+ self._sent_home_at = now+ self._home()+ else:+ self._sent_home_at = None+ self._let_go_unannounced()+ if self._disabled_at is None or self._clock() - self._disabled_at >= DISABLED_SECONDS:+ self._place_barriers(session)+ return+ if self._press is not None:+ if self._away_wanted():+ self._press = None+ self._away = True+ elif self._press.idle() or not self._models():+ self._let_go(self._press.point)+ return+ if self._away_wanted():+ self._home_since = None+ return+ now = self._clock()+ if self._home_since is None:+ self._home_since = now+ return+ if now - self._home_since >= LANDING_SECONDS:+ self._let_go(desktop_portal.cursor_position())++ def _set_zones(self, zones: List[crossing.Rect]) -> None:+ self._zones = zones+ desktop_portal.set_zones(zones)+ self._key = None++ def _place_barriers(self, session) -> None:+ try:+ models = list(self._models())+ except Exception:+ LOGGER.exception("Could not read the zones; no barriers until the next change")+ models = []+ key = (model_key(models), tuple(self._zones))+ if key == self._key:+ if models and not session.enabled:+ session.enable()+ return+ self._key = key+ placed = self._placed = barriers(models, self._zones)+ failed = session.set_barriers([position for _wall, position in placed])+ self._walls = {index + 1: wall for index, (wall, _position) in enumerate(placed) if index + 1 not in failed}+ if failed:+ LOGGER.warning("The desktop refused %d of %d edge barriers", len(failed), len(placed))++ # -- ei events -------------------------------------------------------------++ def _ei_event(self, event: tuple) -> None:+ kind = event[0]+ if kind == "device_added":+ device = event[1]+ if hasattr(device, "keymap") and 4 in getattr(device, "caps", ()): # libei.CAP_KEYBOARD+ self._read_keymap(device)+ return+ if kind == "disconnect":+ raise CaptureUnavailable(ENDED.format(detail="its input connection closed"))++ if kind == "device_paused":++ device = event[1]++ for device_id, code in tuple(self._names_down):++ if device_id == id(device):++ self._key_event(code, False, device)++ return+ if kind == "modifiers":+ self._mods = tuple(event[2:6])+ return+ if kind == "start":+ self._sequences[event[1]] = event[2]+ return+ if kind == "stop":+ # What arrives between a let-go and the desktop ending the capture belongs to nobody.+ self._sequences.pop(event[1], None)+ if not self._sequences:+ self._early = []+ return+ if kind not in ("motion", "button", "key", "scroll", "scroll_discrete", "frame"):+ return+ sequence = self._sequences.get(event[1]) if len(event) > 1 else None+ if self._activation is None:+ # Ahead of the Activated signal that says which barrier.+ if sequence is not None and len(self._early) < EARLY_MAX:+ if not self._early:+ self._early_at = self._clock()+ self._early.append((event, sequence))+ return+ if not self._current(sequence):+ if sequence > self._activation and len(self._early) < EARLY_MAX:+ # The next capture's, ahead of its Activated signal.+ if not self._early:+ self._early_at = self._clock()+ self._early.append((event, sequence))+ return # else an earlier capture's+ if self._press is not None and self._away_wanted():+ # Sent away from another thread since the last look (the tray, a driven machine).+ self._press = None+ self._away = True+ if self._press is not None:+ self._pressing(event)+ return+ if kind == "frame":+ self._end_frame()+ else:+ self._frame.append(event)++ def _read_keymap(self, device) -> None:+ try:+ text = device.keymap()+ if text:+ import xkb_x11++ if self._keymap is not None:+ self._keymap.close()+ self._keymap = xkb_x11.Keymap.from_text(text)+ except Exception:+ LOGGER.exception("Could not read the captured keyboard's layout; keys with no fixed name are dropped")++ def _pressing(self, event: tuple) -> None:+ kind = event[0]+ if kind in ("key", "button"):+ if event[3]:+ LOGGER.info("A key or button at the edge lets go of the pointer; it does not reach an app")+ self._let_go(self._press.point)+ return+ if kind != "motion":+ return+ press = self._press+ if not press.feed(event[2], event[3]):+ self._let_go(press.point)+ return+ desktop_portal.note_position(*press.point)+ self._motion(event[2], event[3])+ if self._away_wanted():+ self._press = None+ self._away = True++ def _end_frame(self) -> None:+ events, self._frame = self._frame, []+ discrete = any(event[0] == "scroll_discrete" for event in events)+ for event in events:+ kind = event[0]+ if kind == "motion":+ self._motion(event[2], event[3])+ elif kind == "key":- self._key_event(event[2], event[3])++ self._key_event(event[2], event[3], event[1])+ elif kind == "button":+ self._button(event[2], event[3])+ elif kind == "scroll_discrete":+ self._wheel(event[2] / 120.0 * WHEEL_DELTA, event[3] / 120.0 * WHEEL_DELTA)+ elif kind == "scroll" and not discrete:+ self._wheel(event[2] / PIXELS_PER_NOTCH * WHEEL_DELTA, event[3] / PIXELS_PER_NOTCH * WHEEL_DELTA)++ def _motion(self, dx: float, dy: float) -> None:+ carry = self._carry+ carry[0] += dx+ carry[1] += dy+ whole_x, whole_y = int(carry[0]), int(carry[1])+ carry[0] -= whole_x+ carry[1] -= whole_y+ if whole_x or whole_y:+ self._on_motion(whole_x, whole_y)++ def _wheel(self, units_x: float, units_y: float) -> None:+ """libei scrolls positive down and right; Windows' wheel is positive up, its horizontal+ wheel positive right."""+ carry = self._scroll_carry+ carry[0] += units_x+ carry[1] -= units_y+ for index, message in ((1, WM_MOUSEWHEEL), (0, WM_MOUSEHWHEEL)):+ whole = int(carry[index])+ carry[index] -= whole+ if whole:+ self._on_mouse(message, 0, 0, _wheel_data(whole))++ def _button(self, code: int, down: bool) -> None:+ fixed = _BUTTONS.get(EVDEV_BUTTONS.get(code))+ if fixed is None:+ return+ press, release, data = fixed+ # An answer of False, the button kept here, cannot be played back on Wayland.+ self._on_mouse(press if down else release, 0, 0, data)+- def _key_event(self, code: int, down: bool) -> None:- name = self._names_down.get(code) if down else self._names_down.pop(code, None)++ def _key_event(self, code: int, down: bool, device) -> None:++ key = (id(device), code)++ name = self._names_down.get(key) if down else self._names_down.pop(key, None)+ if name is None:+ name = VK_TO_NAME.get(code)+ if name is None and self._keymap is not None:+ depressed, latched, locked, group = self._mods+ mods = self._keymap.core_mods(depressed | latched | locked)+ for held in self._names_down:- mods |= HELD_MODS.get(held, 0)++ held_code = held[1] if isinstance(held, tuple) else held++ mods |= HELD_MODS.get(held_code, 0)+ name = character(code + KEYCODE_OFFSET, mods, group, self._keymap)+ if name is None:+ return+ if down:- self._names_down[code] = name++ self._names_down[key] = name+ self._on_key(name, down, code, keytable.EVDEV_US.get(code))+++def _ei_receiver(fd: int):+ import libei++ return libei.Context(fd, sender=False)+++def _libei_present() -> None:+ import libei++ libei._load()+++# Checked before the session is asked for, so the desktop never asks for something Beamer cannot use.+_ei_receiver.preflight = _libei_presentdiff --cc win_app/capture_win.pyindex 87a543d,04d89c3..722f73d--- a/win_app/capture_win.py+++ b/win_app/capture_win.py@@@ -43,9 -43,8 +43,8 @@@ import ctypeimport loggingimport sysimport threading--import time-from typing import Callable, Dict, List, Optional, Set, Tuple+import unicodedata+from typing import Callable, Dict, List, Optional, Set, Tuple, Unionfrom input_injector import INJECTED_MARK, SCAN_TO_USdiff --cc win_app/diagram.pyindex 892521a,45c1907..7a19bc4--- a/win_app/diagram.py+++ b/win_app/diagram.py@@@ -4,7 -4,7 +4,7 @@@ strip in Resistance. Geometry is pages_from __future__ import annotationsfrom PySide6.QtCore import QPointF, QRectF, QSize, Qt--from PySide6.QtGui import QColor, QPainter, QPainterPath, QPen++from PySide6.QtGui import QColor, QFontMetrics, QPainter, QPainterPath, QPenfrom PySide6.QtWidgets import QSizePolicy, QWidgetimport motion@@@ -81,16 -48,12 +81,17 @@@ class ArrangementDiagram(QWidget)def __init__(self, parent: QWidget | None = None) -> None:super().__init__(parent)self.setAccessibleName("Arrangement")-- self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)++ policy = QSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)++ policy.setHeightForWidth(True)++ self.setSizePolicy(policy)self._state = None- self._angle = pages_win.SIDE_ANGLE["right"]- self._marks = _marks("right", (), (), "", False)+ self._machines: list = []+ # Where each machine's screen is drawn now, by key: [angle, start, end, shown], moving between states.+ self._places: dict = {}+ self._labels: dict = {}+ self._marks = _marks([], False)+ self._unplaced = ""self._cap_text = ""-- self.setFixedHeight(self._height())def sizeHint(self) -> QSize:return QSize(2 * round(SCREEN[0]) + round(GAP) + 2 * round(PAD), self._height())@@@ -98,86 -61,35 +99,91 @@@def minimumSizeHint(self) -> QSize:return QSize(2 * round(SCREEN[0]) + round(GAP), self._height())- def _height(self) -> int:- _pc, _mac, pair_h = pages_win.arrangement_rects(100.0, 0.0, self._angle, SCREEN, GAP)- return round(PAD + pair_h + PAD + CAP_ROW * self._marks[("cap",)])-- def set_state(self, edge, methods, parts, corner, key_name, style) -> None:- state = (edge, tuple(methods), tuple(parts), corner, key_name, style)+ def _drawing(self, width: float):+ keys = [key for key, place in self._places.items() if place[3] > 0.001]+ placed = [tuple(self._places[key][:3]) for key in keys]+ available = max(1.0, width - 2 * PAD)+ centre_pc = len(self._machines) > 1+ pc, rects, _height = pages_win.layout_rects(available, PAD, placed, SCREEN, GAP,+ centre_pc=centre_pc)+ bounds_left = min([pc[0], *(rect[0] for rect in rects)])+ bounds_right = max([pc[0] + pc[2], *(rect[0] + rect[2] for rect in rects)])- scale = max(1.0, available * 0.68 / max(1.0, bounds_right - bounds_left))++ scale = available * 0.9 / max(1.0, bounds_right - bounds_left)+ screen = (SCREEN[0] * scale, SCREEN[1] * scale)+ gap = GAP * scale+ pc, rects, height = pages_win.layout_rects(available, PAD, placed, screen, gap,+ centre_pc=centre_pc)++ metrics = QFontMetrics(theme.font(tokens.TYPE["small"], 600))++ needed = max((metrics.boundingRect(QRectF(0, 0, max(1, rect[2] - 8), 10000).toRect(),++ int(Qt.TextFlag.TextWrapAnywhere), name).height() + 4++ for rect, name in [(pc, "This PC"), *[(rect, self._labels.get(key, OTHER))++ for key, rect in zip(keys, rects)]]), default=screen[1])++ if needed > min([pc[3], *(rect[3] for rect in rects)]):++ screen = (screen[0], screen[1] * needed / max(1, min([pc[3], *(rect[3] for rect in rects)])))++ pc, rects, height = pages_win.layout_rects(available, PAD, placed, screen, gap,++ centre_pc=centre_pc)+ return (pc[0] + PAD, pc[1], pc[2], pc[3]), {key: (rect[0] + PAD, *rect[1:]) for key, rect in zip(keys, rects)}, height+- def _height(self) -> int:- _pc, _rects, height = self._drawing(float(self.width() or 2 * SCREEN[0] + GAP + 2 * PAD))++ def _height(self, width: int | None = None) -> int:++ _pc, _rects, height = self._drawing(float(width if width is not None else self.width() or 2 * SCREEN[0] + GAP + 2 * PAD))+ return round(PAD + height + PAD + (NOTE_ROW if self._unplaced else 0.0) + CAP_ROW * self._marks[("cap",)])+- def resizeEvent(self, event) -> None:- super().resizeEvent(event)- # A narrow page shrinks the drawing, and the widget's height follows it.- height = self._height()- if height != self.height():- self.setFixedHeight(height)++ def heightForWidth(self, width: int) -> int:++ return self._height(width)++ def set_machines(self, machines, key_name, style, shortcut) -> None:+ """Each machine a dict: `key`, `label` ("" for the placeholder of an unpaired PC), `side` (""+ when not placed), `methods`, `parts`, `corner` and `chosen`."""+ machines = [dict(machine, methods=list(machine["methods"]), parts=list(machine["parts"])) for machine in machines]+ state = (repr(machines), key_name, style, shortcut)if state == self._state:returnfirst = self._state is Noneself._state = state- shortcut = "shortcut" in methods+ self._machines = machines+ alone = len(machines) == 1+ self._labels = {machine["key"]: machine["label"] or OTHER for machine in machines}if shortcut:self._cap_text = pages_win.trigger_phrase(key_name, style)- self.setAccessibleDescription(pages_win.ways_summary(methods, edge, parts, corner, key_name, style))- targets = _marks(edge, methods, parts, corner, shortcut)+ self._unplaced = "" if alone else pages_win.unplaced_line(+ [machine["label"] for machine in machines if not machine.get("side")])+ self.setAccessibleDescription(pages_win.diagram_description(+ [dict(machine, label=self._labels[machine["key"]]) for machine in machines],+ key_name, style, shortcut))+ targets = _marks(machines, shortcut)+ slots = pages_win.side_slots([dict(machine, side=_drawn_side(machine, alone)) for machine in machines])+ ends = {}+ for machine, slot in zip(machines, slots):+ held = self._places.get(machine["key"])+ if slot is None:+ ends[machine["key"]] = list(held[:3]) + [0.0] if held else [0.0, 0.0, 1.0, 0.0]+ continue+ side, start, end = slot+ # A machine already drawn goes round to its new side; one just placed fades in there.+ drawn = held is not None and held[3] > 0.0 and not first+ angle = pages_win.turn_to(held[0], side) if drawn else pages_win.SIDE_ANGLE[side]+ ends[machine["key"]] = [angle, start, end, 1.0]+ for key, held in self._places.items():+ # A machine removed or no longer placed fades where it was.+ ends.setdefault(key, list(held[:3]) + [0.0])+ starts = {}+ for key, end in ends.items():+ held = self._places.get(key)+ starts[key] = list(held) if held is not None and held[3] > 0.0 else end[:3] + [0.0]start_marks = dict(self._marks)- start_angle = self._angle- end_angle = pages_win.turn_to(start_angle, edge)- if first:- end_angle = pages_win.SIDE_ANGLE[edge]def apply(t):- self._angle = start_angle + (end_angle - start_angle) * t- self._marks = {key: start_marks[key] + (targets[key] - start_marks[key]) * t for key in targets}- self.setFixedHeight(self._height())+ self._places = {key: [a + (b - a) * t for a, b in zip(starts[key], end)] for key, end in ends.items()}+ self._marks = {key: start_marks.get(key, 0.0) + (targets.get(key, 0.0) - start_marks.get(key, 0.0)) * t+ for key in set(targets) | set(start_marks)}- self.setFixedHeight(self._height())++ self.updateGeometry()self.update()def settle():- self._angle = end_angle % 360.0+ self._places = {key: [end[0] % 360.0, end[1], end[2], end[3]] for key, end in ends.items() if end[3] > 0.0+ or key in self._labels}+ self._marks = {key: level for key, level in targets.items()}- self.setFixedHeight(self._height())++ self.updateGeometry()self.update()if first:@@@ -189,62 -101,38 +195,56 @@@def paintEvent(self, _event) -> None:painter = QPainter(self)painter.setRenderHint(QPainter.RenderHint.Antialiasing)- pc, mac, pair_h = pages_win.arrangement_rects(self.width(), PAD, self._angle, SCREEN, GAP)+ pc, rects, height = self._drawing(float(self.width()))radius = tokens.RADIUS["field"]- self._screen(painter, QRectF(*mac), "Your Mac", "panel", "edge", "ink_3", radius)- self._screen(painter, QRectF(*pc), "This PC", "well", "edge", "ink_2", radius)- for key, level in self._marks.items():- if level <= 0.001:+ for key, rect in rects.items():+ painter.setOpacity(self._places[key][3])+ named = self._marks.get(("named", key), 0.0)+ self._screen(painter, QRectF(*rect), self._labels.get(key, OTHER), "panel", _blend("edge", "ink_3", named),+ _blend("ink_3", "ink", named), radius)+ painter.setOpacity(1.0)+ self._screen(painter, QRectF(*pc), "This PC", "well", _colour("edge"), _colour("ink_2"), radius)+ # The machines not shown first, so the chosen one's marks lie over theirs where they meet.+ for key, level in sorted(self._marks.items(), key=lambda item: self._marks.get(("lead", item[0][1]), 0.0)+ if len(item[0]) > 1 else 0.0):+ if level <= 0.001 or key[0] in ("cap", "lead", "named"):continue- kind = key[0]+ kind, lead = key[0], self._marks.get(("lead", key[1]), 0.0)if kind == "edge":- self._segment(painter, pc, key[1], 0.0, 1.0, level, "signal", LIT)+ self._segment(painter, pc, key[2], 0.0, 1.0, level, lead, LIT)elif kind == "track":- self._track(painter, pc, key[1], level)+ self._track(painter, pc, key[2], level)elif kind == "part":- start, end = pages_win.PART_SPANS[key[2]]- self._segment(painter, pc, key[1], start, end, level, "signal", LIT, gap=2.0)+ start, end = pages_win.PART_SPANS[key[3]]+ self._segment(painter, pc, key[2], start, end, level, lead, LIT, gap=2.0)elif kind == "corner":- self._corner(painter, pc, key[1], level)+ self._corner(painter, pc, key[2], level, lead)+ top = PAD + height + PAD+ if self._unplaced:+ painter.setPen(_colour("ink_3"))+ painter.setFont(theme.font(tokens.TYPE["note"]))+ line = QRectF(PAD, top, self.width() - 2 * PAD, NOTE_ROW)+ painter.drawText(line, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop,+ painter.fontMetrics().elidedText(self._unplaced, Qt.TextElideMode.ElideRight, int(line.width())))+ top += NOTE_ROWlevel = self._marks[("cap",)]if level > 0.001 and self._cap_text:- self._cap(painter, PAD + pair_h + PAD, level)+ self._cap(painter, top, level)painter.end()- def _screen(self, painter, rect: QRectF, name, fill, line, ink, radius) -> None:- painter.setPen(QPen(_colour(line), 1.0))+ def _screen(self, painter, rect: QRectF, name, fill, line: QColor, ink: QColor, radius) -> None:+ painter.setPen(QPen(line, 1.0))painter.setBrush(_colour(fill))painter.drawRoundedRect(rect.adjusted(0.5, 0.5, -0.5, -0.5), radius, radius)- painter.setPen(_colour(ink))+ painter.setPen(ink)painter.setFont(theme.font(tokens.TYPE["small"], 600))- painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, name)+ metrics = painter.fontMetrics()+ room = rect.adjusted(4, 2, -4, -2)- wrapped = Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWordWrap- needed = metrics.boundingRect(room.toRect(), wrapped, name)- if metrics.horizontalAdvance(name) > room.width() and needed.width() <= room.width() and needed.height() <= room.height():- # A screen sharing its side is half as wide: a two-word name goes onto two lines there.- painter.drawText(room, wrapped, name)- return- painter.drawText(rect, Qt.AlignmentFlag.AlignCenter,- metrics.elidedText(name, Qt.TextElideMode.ElideRight, int(rect.width()) - 8))++ wrapped = Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWrapAnywhere++ painter.drawText(room, wrapped, name)@staticmethod- def _segment(painter, rect, side, start, end, level, colour, width, gap=0.0) -> None:+ def _segment(painter, rect, side, start, end, level, lead, width, gap=0.0) -> None:# Grows from its middle as it comes in.middle = (start + end) / 2.0half = (end - start) / 2.0 * level@@@ -324,10 -208,9 +324,12 @@@ class PushStrip(QWidget)def __init__(self, parent: QWidget | None = None) -> None:super().__init__(parent)-- self.setFixedHeight(self.HEIGHT)-- self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)++ self.setMinimumHeight(self.HEIGHT)++ policy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)++ policy.setHeightForWidth(True)++ self.setSizePolicy(policy)self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)+ self._other = OTHERself._value = Noneself._shown = 0.0self._glow = 0.0@@@ -336,12 -219,6 +338,23 @@@def minimumSizeHint(self) -> QSize:return QSize(160, self.HEIGHT)++ def target_width(self, width=None):++ metrics = QFontMetrics(theme.font(tokens.TYPE["small"], 600))++ return min(max(self.MAC, metrics.horizontalAdvance(self._other) + 12),++ (self.width() if width is None else width) * .65)++++ def heightForWidth(self, width):++ metrics = QFontMetrics(theme.font(tokens.TYPE["small"], 600))++ room = QRectF(0, 0, max(1, self.target_width(width) - 8), 10000).toRect()++ return max(self.HEIGHT, metrics.boundingRect(room, int(Qt.TextFlag.TextWrapAnywhere), self._other).height() + 4)+++ def set_other_name(self, name: str) -> None:+ name = name or OTHER+ if name != self._other:+ self._other = name++ self.updateGeometry()+ self.update()+def set_edge(self, edge: str) -> None:mac_left = edge == "left"if mac_left != self._mac_left:@@@ -382,11 -259,11 +395,12 @@@painter.scale(-1, 1)band = QRectF(0.5, 0.5, self.width() - 1.0, self.height() - 1.0)radius = tokens.RADIUS["field"]-- edge_x = band.right() - self.MAC++ target_width = self.target_width()++ edge_x = band.right() - target_widthpainter.setPen(QPen(_colour("rule"), 1.0))painter.setBrush(_colour("well"))painter.drawRoundedRect(band, radius, radius)-- mac = QRectF(edge_x, band.top(), self.MAC, band.height())++ mac = QRectF(edge_x, band.top(), target_width, band.height())path = QPainterPath()path.addRoundedRect(mac, radius, radius)painter.setPen(Qt.PenStyle.NoPen)@@@ -404,15 -281,12 +418,14 @@@self._pointer(painter, tip)painter.setPen(_colour("ink_3"))painter.setFont(theme.font(tokens.TYPE["small"], 600))-- label = QRectF(edge_x, band.top(), self.MAC, band.height())++ label = QRectF(edge_x, band.top(), target_width, band.height()).adjusted(4, 2, -4, -2)if self._mac_left:# Text drawn in the flipped frame would read backwards.painter.resetTransform()label = QRectF(self.width() - label.right(), label.top(), label.width(), label.height())- painter.drawText(label, Qt.AlignmentFlag.AlignCenter, "Your Mac")+ painter.drawText(- label, Qt.AlignmentFlag.AlignCenter,- painter.fontMetrics().elidedText(self._other, Qt.TextElideMode.ElideRight, int(label.width()) - 4),++ label, Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWrapAnywhere, self._other,+ )painter.end()def _pointer(self, painter, tip: QPointF) -> None:diff --cc win_app/effect_overlay.pyindex 903b816,3baec68..3455b83--- a/win_app/effect_overlay.py+++ b/win_app/effect_overlay.py@@@ -15,9 -15,8 +15,16 @@@ from __future__ import annotationimport ctypesimport loggingimport math++import os+import sysimport time++# Qt splits antialiased fills into tiny span jobs and waits on each batch. On Windows the++# worker wake-ups cost more than these narrow strokes; serial fills produce identical pixels.++# Qt caches this process-wide switch on the first paint, before an overlay is ever created.++if sys.platform == "win32":++ os.environ["QT_NO_GUI_THREADPOOL"] = "1"++from PySide6.QtCore import QPointF, QRect, QRectF, Qt, QTimerfrom PySide6.QtGui import (QBrush,diff --cc win_app/effect_previews.pyindex 2944aa0,3fedddd..9728438--- a/win_app/effect_previews.py+++ b/win_app/effect_previews.py@@@ -6,8 -6,8 +6,9 @@@ from __future__ import annotationimport loggingimport time++import math--from PySide6.QtCore import QEvent, QObject, QRectF, Qt, QTimer++from PySide6.QtCore import QEvent, QObject, QRectF, QSize, Qt, QTimerfrom PySide6.QtGui import QColor, QImage, QPainter, QPainterPath, QPenfrom PySide6.QtWidgets import QSizePolicy, QWidget@@@ -27,7 -27,7 +28,7 @@@ _LAYERS = {STILL_HEIGHT = 56# A tile shows where the style plays rather than the whole scene too small to see: this many scene# points across, centred on the crossing at each place, the corner framed with room above the screens.--STILL_VIEW_W = 480.0++STILL_VIEW_W = 240.0STILL_CENTRE = {"edge": (effects.PREVIEW_SCREEN[0] + effects.PREVIEW_GAP / 2.0, effects.PREVIEW_SCREEN[1] * 0.45),"corner": (effects.PREVIEW_SCREEN[0] + effects.PREVIEW_GAP / 2.0, 40.0)}# A switch plays round a still pointer on one screen: its tile shows that part of the scene part-way@@@ -76,6 -76,6 +77,7 @@@ def paint_scene(painter: QPainter, recttop = rect.y() + (rect.height() - height * scale) / 2.0painter.save()painter.setRenderHint(QPainter.RenderHint.Antialiasing)++ local_transform = painter.transform()painter.setClipRect(QRectF(left, top, width * scale, height * scale))painter.translate(left, top)painter.scale(scale, scale)@@@ -84,7 -84,7 +86,10 @@@for x, y, w, h, os_name in scene["screens"]:painter.setPen(QPen(QColor(theme.colour("rule")), 1.0 / scale))painter.setBrush(QColor(theme.colour("well")))-- painter.drawRoundedRect(QRectF(x, y, w, h), radius, radius)++ screen = QRectF(x, y, w, h)++ if not labels:++ screen = screen.intersected(view).adjusted(1 / scale, 1 / scale, -1 / scale, -1 / scale)++ painter.drawRoundedRect(screen, radius, radius)if labels:painter.setPen(QColor(theme.colour("ink_3")))painter.setFont(theme.eyebrow_font())@@@ -119,7 -119,7 +124,7 @@@finally:layer_painter.end()painter.save()-- painter.resetTransform()++ painter.setTransform(local_transform)painter.translate(left, top)painter.drawImage(0, 0, layer)painter.restore()@@@ -159,13 -159,12 +164,23 @@@ class EffectStill(QWidget)self.palette = tuple(palette)self.place = "edge"self.pace = 1.0+ self.effect_size = "medium"self._image = Noneself.playing_since = None-- self.setFixedHeight(STILL_HEIGHT)-- self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)++ policy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)++ policy.setHeightForWidth(True)++ self.setSizePolicy(policy)self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)++ def hasHeightForWidth(self) -> bool:++ return True++++ def heightForWidth(self, width: int) -> int:++ return max(1, round(width / 2))++++ def sizeHint(self):++ return QSize(STILL_HEIGHT * 2, STILL_HEIGHT)++def set_palette(self, palette) -> None:if tuple(palette) != self.palette:self.palette = tuple(palette)@@@ -206,8 -199,8 +221,8 @@@painter.end()returnratio = self.devicePixelRatioF()-- size = self.size() * ratio-- if self._image is None or self._image.size() != size:++ size = QSize(math.ceil(self.width() * ratio), math.ceil(self.height() * ratio))++ if self._image is None or self._image.size() != size or self._image.devicePixelRatio() != ratio:self._image = QImage(size, QImage.Format.Format_ARGB32_Premultiplied)self._image.setDevicePixelRatio(ratio)self._image.fill(Qt.GlobalColor.transparent)@@@ -223,8 -216,8 +238,15 @@@painter.end()def _paint_still(self, painter: QPainter, t: float) -> None:++ if self.playing_since is None and self.effect_id == "beam" and self.place == "edge":++ t = 1.45scene = effects.preview_scene(effects.preview_effect(self.effect_id), t, self.place, self.palette,- system_reduced_motion(), theme.is_dark(), self.pace)+ system_reduced_motion(), theme.is_dark(), self.pace, self.effect_size)++ if self.playing_since is None and self.effect_id not in ("glow", "beam"):++ # A representative still includes the landing; hover keeps the real timed loop.++ arrival = effects.preview_scene(effects.preview_effect(self.effect_id), 2.35, self.place, self.palette,++ system_reduced_motion(), theme.is_dark(), self.pace, self.effect_size)++ scene["pens"] += arrival["pens"][1:]width = STILL_VIEW_Wview_h = min(effects.PREVIEW_SCREEN[1], width * self.height() / max(1, self.width()))centre = STILL_CENTRE[self.place]diff --cc win_app/inject_portal.pyindex 6448f9a,0000000..8c0729fmode 100644,000000..100644--- a/win_app/inject_portal.py+++ b/win_app/inject_portal.py@@@ -1,757 -1,0 +1,759 @@@+"""Keyboard and mouse injection on Wayland, through the RemoteDesktop portal and libei: the twin of+inject_x11.py, with the same functions, so the receiver drives it unchanged. The portal clipboard+rides on the same session (clipboard_portal), since GNOME offers its clipboard to a background app+only there.++One thread owns the session: its D-Bus connection, the libei sender and the clipboard's transfers.+The functions here hand it work and return; only a clipboard read waits for an answer. The session+starts when start() is called (the app does so when it can be driven or shares a clipboard) or at+the first event, and the desktop asks the user once: the answer is remembered with a restore+token (persist_mode 2), kept in the state directory, so later starts ask nothing.++Keys are pressed by evdev code on the keyboard the desktop gives, whose layout it hands over with+the device and whose locks and group it reports as they change. A character is typed as on X11+(inject_x11.plan_key: the layout's own key, Shift worked around it, the US place under a chord),+with two differences. The desktop's keymap cannot be changed, so a character the layout has no key+for is not typed (logged once). And a held key is repeated by the app it reaches, not the server,+so a key typed with Shift changed around it is let go at once and each of the peer's repeats types+it again.++The pointer is moved with libei's absolute pointer where the desktop offers one (GNOME does), at+a position Beamer keeps in desktop_portal, since no Wayland app can ask where the pointer is."""++import logging+import os+import queue+import select+import threading+import time+from typing import Callable, Dict, List, Optional, Set, Tuple++import desktop_portal+import portal+from capture_x11 import KEYCODE_OFFSET, LOCK_MASK, NUM_LOCK_MASK+from core.return_edge import Rect+from inject_x11 import (+ MAP,+ NO_REPEAT,+ PRESS,+ RELEASE,+ REPEAT,+ KeyState,+ Layout,+ plan_key,+ plan_text,+)++LOGGER = logging.getLogger(__name__)++INTERFACE = "org.freedesktop.portal.RemoteDesktop"+CLIPBOARD = "org.freedesktop.portal.Clipboard"+DEVICE_KEYBOARD, DEVICE_POINTER = 1, 2+TICK_SECONDS = 0.1+CALL_SECONDS = 2.0+# How long the portal has to answer a request no user sees.+REQUEST_SECONDS = 10.0+# After a session ends (not a refusal), the next one is opened no sooner than this.+RETRY_SECONDS = 5.0+# How long the desktop has, once connected, to offer the devices input waits for.+DEVICE_SECONDS = 2.0+# Input waiting for the session beyond this is dropped, not queued without end.+MAX_PENDING = 512+# How long an app pasting Beamer's clipboard has to take it.+WRITE_SECONDS = 5.0+# libei's capabilities (libei.py), here so this module imports without libei.+CAP_POINTER, CAP_POINTER_ABSOLUTE, CAP_KEYBOARD, CAP_SCROLL, CAP_BUTTON = 1, 2, 4, 16, 32++# evdev button codes.+BUTTONS = {"left": 0x110, "right": 0x111, "middle": 0x112, "back": 0x113, "forward": 0x114}+# A wheel click as libei counts it, and the pixels the PC reckons a click scrolls (inject_x11).+DISCRETE_PER_CLICK = 120+PIXELS_PER_CLICK = 40.0++NO_PORTAL = ("This desktop does not let apps control the keyboard and mouse (it has no RemoteDesktop "+ "portal with libei), so another machine cannot drive this one and the clipboard is not shared.")+REFUSED = ("Beamer was not allowed to control this machine, so another machine cannot drive it and the "+ "clipboard is not shared. Restart Beamer to be asked again.")+ENDED = "The desktop stopped letting Beamer control this machine: {detail}"+CLOSED = ("Remote control was stopped from the desktop, so another machine cannot drive this one and the "+ "clipboard is not shared until Beamer restarts.")+MISSING = "Beamer cannot control this machine: {detail}"++# Called with one of the sentences above when the session cannot start or ends; set by the app.+on_problem: Optional[Callable[[str], None]] = None+++class WaylandLayout(Layout):+ """inject_x11's Layout over the desktop's keymap, which cannot be changed: no spare keys."""++ def spare(self) -> List[int]:+ return []+++def wayland_steps(steps: list) -> List[Tuple[int, bool]]:+ """plan_key's or plan_text's steps as (evdev code, down). A key after NO_REPEAT is let go as soon+ as it is pressed; REPEAT, the X server's, means nothing here, and MAP cannot be planned with no+ spare keys."""+ out: List[Tuple[int, bool]] = []+ quick: Set[int] = set()+ for step in steps:+ kind, keycode = step[0], step[1]+ if kind == NO_REPEAT:+ quick.add(keycode)+ elif kind == PRESS:+ out.append((keycode - KEYCODE_OFFSET, True))+ if keycode in quick:+ out.append((keycode - KEYCODE_OFFSET, False))+ elif kind == RELEASE:+ out.append((keycode - KEYCODE_OFFSET, False))+ elif kind not in (REPEAT, MAP):+ LOGGER.warning("Unknown key step %r", step)+ return out+++def scroll_steps(dy: float, dx: float, mode: str, carry: List[float]) -> Tuple[str, float, float]:+ """One scroll message as libei's: ("discrete", x, y) in 120ths of a click for the wheel's lines,+ the fraction carried in `carry` ([y, x]); ("pixels", x, y) for a pixel scroll. The wire's y is+ positive away from the hand, libei's positive down."""+ if mode == "pixel":+ return "pixels", float(dx), -float(dy)+ carry[0] += float(dy) * DISCRETE_PER_CLICK+ carry[1] += float(dx) * DISCRETE_PER_CLICK+ whole_y, whole_x = int(carry[0]), int(carry[1])+ carry[0] -= whole_y+ carry[1] -= whole_x+ return "discrete", whole_x, -whole_y+++def _keymap_from_text(text: str):+ import xkb_x11++ return xkb_x11.Keymap.from_text(text)+++def _ei_sender(fd: int):+ import libei++ return libei.Context(fd, sender=True)+++def _libei_present() -> None:+ import libei++ libei._load()+++# Checked before the session is asked for, so the desktop never asks for something Beamer cannot use.+_ei_sender.preflight = _libei_present+++class Remote:+ """The RemoteDesktop session's thread. `submit(fn)` runs fn(self) there once the desktop's+ devices are up; `ask(fn)` runs it there at once and returns its answer.++ A refusal, or a desktop with no portal for it, stands until Beamer restarts, and no work is+ queued meanwhile. A session that ends any other way opens again at the next input, after+ RETRY_SECONDS, without asking: its restore token says the user already said yes."""++ def __init__(self, connect: Callable[[], object] = None, ei: Callable[[int], object] = None, tokens=None,+ keymap: Callable[[str], object] = None) -> None:+ self._connect = connect or portal.JeepneyBus+ self._ei_factory = ei or _ei_sender+ self._keymap = keymap or _keymap_from_text+ self._tokens = tokens or portal.TokenStore("remote-desktop")+ self._commands: "queue.Queue" = queue.Queue()+ self._wake_read, self._wake_write = os.pipe()+ os.set_blocking(self._wake_read, False)+ os.set_blocking(self._wake_write, False)+ self._thread: Optional[threading.Thread] = None+ self._stopping = threading.Event()+ self._lock = threading.Lock()+ self.ready = threading.Event()+ self.problem: Optional[str] = None+ self._terminal = False # refused or impossible: never asked again this run+ self._closed = False # stopped for good (Beamer quitting)+ self._retry_at = 0.0+ self._said_full = False+ self._generation = 0+ self.stamp = 0 # never reset, so a new session cannot repeat a stamp a caller holds+ self._reset()++ def _reset(self) -> None:+ self.portal = None+ self.ei = None+ self.handle = None+ self.clipboard_enabled = False+ self._devices: List[object] = [] # resumed, in the order they came+ self._added: List[object] = []+ self._sequence = 0+ self._eis_at: Optional[float] = None+ self._held: List[Callable] = [] # input waiting for the devices to resume+ self.layout: Optional[WaylandLayout] = None+ self.group = 0+ self.locks = 0+ self.state = KeyState()+ self.pressed: Set[int] = set()+ self.buttons: Dict[int, object] = {}+ self.scroll_carry = [0.0, 0.0]+ # The clipboard: what another app offers, what Beamer offers, and a count of other apps'+ # copies. `stamp` moves at every change, Beamer's own writes included (clipboard_portal).+ self.offered: List[str] = []+ self.ours = False+ self.changes = 0+ self.offer: Dict[str, bytes] = {}++ # -- from any thread ---------------------------------------------------------++ def _admits(self) -> bool:+ return not (self._closed or self._terminal)++ def start(self) -> None:+ with self._lock:+ if not self._admits():+ return+ if self._thread is not None and self._thread.is_alive():+ return+ if time.monotonic() < self._retry_at:+ return+ self._stopping.clear()+ self.ready.clear()+ self._thread = threading.Thread(target=self._run, name="Beamer-remote", daemon=True)+ self._thread.start()++ def stop(self) -> None:+ """For good: nothing after it opens the session again."""+ with self._lock:+ self._closed = True+ self._stopping.set()+ self._wake()+ thread = self._thread+ if thread is not None:+ thread.join(timeout=2.0)+ session = self.portal+ if thread.is_alive() and session is not None:+ abort = getattr(session.bus, "abort", None)+ if abort is not None:+ abort()++ def submit(self, work: Callable[["Remote"], None], release: bool = False) -> None:+ """`release` work (a key or button let go) is never dropped for a full queue: dropping it+ would leave the press held on this machine."""+ if not self._admits():+ return+ self.start()+ if self._commands.qsize() >= MAX_PENDING and not release:+ if not self._said_full:+ self._said_full = True+ LOGGER.warning("Remote control is not keeping up; input from the peer is dropped until it does")+ return+ self._said_full = False+ thread = self._thread+ if thread is None or not thread.is_alive():+ return # between sessions: input that late would play stale+ self._commands.put((work, None, None))+ self._wake()++ def ask(self, work: Callable[["Remote"], object], default=None, timeout: float = CALL_SECONDS,+ discard: Optional[Callable[[object], None]] = None):+ """Run `work` on the session's thread and return what it answers, or `default` when the+ session is not up or does not answer in time; an answer that comes after that is handed+ to `discard` (an fd is closed, say)."""+ if not self._admits():+ return default+ self.start()+ if not self.ready.wait(timeout):+ return default+ answer = _Answer(discard)+ self._commands.put((work, answer, None))+ self._wake()+ return answer.wait(timeout, default)++ def _wake(self) -> None:+ try:+ os.write(self._wake_write, b"x")+ except (BlockingIOError, OSError):+ pass++ # -- the thread --------------------------------------------------------------++ def _run(self) -> None:+ ended = False+ try:+ preflight = getattr(self._ei_factory, "preflight", None)+ try:+ if preflight is not None:+ preflight()+ bus = self._connect()+ except Exception as exc:+ # Missing libei or jeepney, or no session bus: no retry would find them.+ raise _Problem(MISSING.format(detail=exc), terminal=True) from exc+ self.portal = portal.Portal(bus, self._stopping.is_set)+ self._open()+ while not self._stopping.is_set():+ self._wait()+ for path, interface, member, body in self.portal.signals():+ self._signal(path, interface, member, body)+ for event in self.ei.events():+ self._ei_event(event)+ self._run_commands()+ except _Problem as problem:+ ended = not problem.terminal+ self._terminal = problem.terminal+ self._report(problem.sentence)+ except Exception as exc:+ if not self._stopping.is_set():+ LOGGER.exception("Remote control stopped")+ ended = True+ self._report(ENDED.format(detail=exc))+ finally:+ if ended:+ if self._tokens.read():+ self._retry_at = time.monotonic() + RETRY_SECONDS+ else:+ # Opened again it would ask again, prompted by the peer's input: it waits for a restart.+ self._terminal = True+ self._end()++ def _report(self, sentence: str) -> None:+ if sentence == self.problem:+ return # said already, and no session has opened since+ self.problem = sentence+ LOGGER.warning("%s", sentence)+ if on_problem is not None:+ try:+ on_problem(sentence)+ except Exception:+ LOGGER.exception("Could not report a remote control problem")++ def _open(self) -> None:+ portal_ = self.portal- if portal_.version(INTERFACE) < 2:++ version = portal_.version(INTERFACE)++ if version == 1:+ raise _Problem(NO_PORTAL, terminal=True)+ created = portal_.request(INTERFACE, "CreateSession", "a{sv}", lambda token: (+ {"handle_token": ("s", token), "session_handle_token": ("s", portal_.token())},), timeout=REQUEST_SECONDS)+ self.handle = created["session_handle"]- options = {"types": ("u", DEVICE_KEYBOARD | DEVICE_POINTER), "persist_mode": ("u", 2)}- token = self._tokens.read()- if token:- options["restore_token"] = ("s", token)++ options = {"types": ("u", DEVICE_KEYBOARD | DEVICE_POINTER)}++ if version >= 2:++ options["persist_mode"] = ("u", 2)++ token = self._tokens.read()++ if token:++ options["restore_token"] = ("s", token)+ portal_.request(INTERFACE, "SelectDevices", "oa{sv}", lambda handle_token: (+ self.handle, dict(options, handle_token=("s", handle_token))), timeout=REQUEST_SECONDS)- if portal_.version(CLIPBOARD) >= 1:- try:- portal_.call(CLIPBOARD, "RequestClipboard", "oa{sv}", (self.handle, {}))- except portal.PortalError:- LOGGER.info("The desktop offers no clipboard with remote control")++ try:++ portal_.call(CLIPBOARD, "RequestClipboard", "oa{sv}", (self.handle, {}))++ except portal.PortalError:++ LOGGER.info("The desktop offers no clipboard with remote control")+ try:+ started = portal_.request(INTERFACE, "Start", "osa{sv}", lambda handle_token: (+ self.handle, "", {"handle_token": ("s", handle_token)}))+ except portal.Refused:+ self._tokens.write("")+ raise _Problem(REFUSED, terminal=True) from None+ self._tokens.write(started.get("restore_token", ""))+ self.clipboard_enabled = bool(started.get("clipboard_enabled"))+ fd = portal_.call(INTERFACE, "ConnectToEIS", "oa{sv}", (self.handle, {}))[0]+ try:+ self.ei = self._ei_factory(fd)+ except Exception:+ os.close(fd)+ raise+ self._generation += 1+ self._eis_at = time.monotonic()+ self.problem = None+ self.ready.set()+ desktop_portal.set_mover(lambda x, y: self.submit(lambda remote: remote.place(x, y)))++ def _wait(self) -> None:+ if self.portal.pending() or (not self._commands.empty() and self._input_ready()):+ return+ try:+ ready, _, _ = select.select([self.portal.fileno(), self.ei.fileno(), self._wake_read], [], [], TICK_SECONDS)+ except (OSError, ValueError) as exc:+ raise _Problem(ENDED.format(detail=exc)) from exc+ if self._wake_read in ready:+ try:+ while os.read(self._wake_read, 256):+ pass+ except BlockingIOError:+ pass++ def _input_ready(self) -> bool:+ """Whether input can be played: a keyboard and a pointer are up, or the desktop has had+ DEVICE_SECONDS to offer them and what is up is all there will be."""+ if self._with(CAP_KEYBOARD) is not None and (self._with(CAP_POINTER_ABSOLUTE) or self._with(CAP_POINTER)):+ return True+ return self._eis_at is not None and time.monotonic() - self._eis_at >= DEVICE_SECONDS++ def _run_commands(self) -> None:+ while True:+ try:+ work, answer, _ = self._commands.get_nowait()+ except queue.Empty:+ break+ if answer is None:+ self._held.append(work)+ continue+ try:+ answer.give(True, work(self))+ except Exception:+ LOGGER.exception("Could not answer a clipboard request")+ answer.give(False, None)+ if not self._held or not self._input_ready():+ return+ held, self._held = self._held, []+ for work in held:+ try:+ work(self)+ except Exception:+ LOGGER.exception("Could not play an input from the peer")++ def _end(self) -> None:+ desktop_portal.set_mover(None)+ self.ready.clear()+ try:+ if self.ei is not None:+ self.release_held()+ except Exception:+ LOGGER.exception("Could not let go of what was held for the peer")+ try:+ if self.ei is not None:+ self.ei.close()+ finally:+ if self.portal is not None:+ self.portal.close()+ self._reset()+ # Work still queued answers nothing; the next start begins clean.+ while True:+ try:+ _work, answer, _ = self._commands.get_nowait()+ except queue.Empty:+ break+ if answer is not None:+ answer.give(False, None)++ # -- signals and devices -----------------------------------------------------++ def _signal(self, path, interface, member, body) -> None:+ if interface == portal.SESSION and member == "Closed" and path == self.handle:+ # The user stopped it from the desktop's indicator: it is not opened again behind them.+ raise _Problem(CLOSED, terminal=True)+ if interface != CLIPBOARD or not body or body[0] != self.handle:+ return+ if member == "SelectionOwnerChanged":+ options = body[1] if len(body) > 1 else {}+ self.ours = bool(options.get("session_is_owner"))+ if not self.ours:+ self.offered = list(options.get("mime_types", []))+ self.changes += 1+ self.stamp += 1+ elif member == "SelectionTransfer":+ try:+ self._transfer(body[1], body[2])+ except portal.PortalError:+ # One paste lost; the session and the clipboard carry on.+ LOGGER.exception("Could not hand the clipboard to the app pasting it")+ self._write_done(body[2], False)++ def _write_done(self, serial: int, ok: bool) -> None:+ try:+ self.portal.call(CLIPBOARD, "SelectionWriteDone", "oub", (self.handle, serial, ok))+ except portal.PortalError:+ LOGGER.exception("Could not tell the desktop a paste has finished")++ def _ei_event(self, event: tuple) -> None:+ kind = event[0]+ if kind == "device_added":+ self._add(event[1])+ elif kind == "device_removed":+ device = event[1]+ for listed in (self._devices, self._added):+ if device in listed:+ listed.remove(device)+ # Buttons it held went with it: the desktop lets go of a removed device's input.+ self.buttons = {code: held for code, held in self.buttons.items() if held is not device}+ elif kind == "device_resumed":+ device = event[1]+ if device not in self._devices:+ self._devices.append(device)+ self._sequence += 1+ self.ei.start(device, self._sequence)+ elif kind == "device_paused":+ if event[1] in self._devices:+ self._devices.remove(event[1])+ elif kind == "modifiers" and self.layout is not None:+ _device, _depressed, _latched, locked, group = event[1:6]+ self.group = group+ self.locks = self.layout.keymap.core_mods(locked) & (LOCK_MASK | NUM_LOCK_MASK)+ elif kind == "disconnect":+ raise _Problem(ENDED.format(detail="its input connection closed"))++ def _add(self, device) -> None:+ self._added.append(device)+ if device.has(CAP_POINTER_ABSOLUTE):+ regions = [Rect(x, y, width, height) for x, y, width, height, _scale in device.regions()]+ if regions:+ desktop_portal.set_regions(regions)+ if device.has(CAP_KEYBOARD) and self.layout is None:+ try:+ text = device.keymap()+ if text:+ self.layout = WaylandLayout(self._keymap(text))+ except Exception:+ LOGGER.exception("Could not read this desktop's keyboard layout; characters cannot be typed")++ def _with(self, cap: int):+ """The first resumed device with `cap`, or None."""+ return next((device for device in self._devices if device.has(cap)), None)++ # -- playing input, on the thread ---------------------------------------------++ def keys(self, presses: List[Tuple[int, bool]]) -> None:+ device = self._with(CAP_KEYBOARD)+ if device is None:+ return+ for code, down in presses:+ if down:+ self.pressed.add(code)+ elif code in self.pressed:+ self.pressed.discard(code)+ else:+ continue+ self.ei.key(device, code, down)+ self.ei.frame(device)++ def move_by(self, dx: float, dy: float) -> None:+ x, y = desktop_portal.cursor_position()+ if self._with(CAP_POINTER_ABSOLUTE) is not None:+ self.place(x + dx, y + dy)+ return+ device = self._with(CAP_POINTER)+ if device is not None:+ self.ei.motion(device, dx, dy)+ self.ei.frame(device)+ desktop_portal.note_position(x + dx, y + dy)++ def place(self, x: float, y: float) -> None:+ desktop_portal.note_position(x, y)+ point = desktop_portal.position()+ device = self._with(CAP_POINTER_ABSOLUTE)+ if device is not None:+ self.ei.absolute(device, float(point[0]), float(point[1]))+ self.ei.frame(device)++ def button(self, code: int, down: bool) -> None:+ if down:+ device = self._with(CAP_BUTTON)+ if device is None:+ return+ self.buttons[code] = device+ else:+ device = self.buttons.pop(code, None)+ if device is None:+ return+ self.ei.button(device, code, down)+ self.ei.frame(device)++ def scroll(self, dy: float, dx: float, mode: str) -> None:+ device = self._with(CAP_SCROLL)+ if device is None:+ return+ kind, x, y = scroll_steps(dy, dx, mode, self.scroll_carry)+ if kind == "pixels":+ self.ei.scroll(device, x, y)+ elif x or y:+ self.ei.scroll_discrete(device, int(x), int(y))+ else:+ return+ self.ei.frame(device)++ def release_held(self) -> None:+ self.keys([(code, False) for code in sorted(self.pressed)])+ for code in sorted(self.buttons):+ self.button(code, False)+ self.state = KeyState()+ self.scroll_carry = [0.0, 0.0]++ # -- the clipboard, on the thread ----------------------------------------------++ def set_selection(self, offer: Dict[str, bytes]) -> bool:+ if not self.clipboard_enabled:+ return False+ self.offer = dict(offer)+ self.portal.call(CLIPBOARD, "SetSelection", "oa{sv}", (self.handle, {"mime_types": ("as", list(offer))}))+ self.ours = True+ self.stamp += 1+ return True++ def open_selection(self, mime: str) -> Optional[int]:+ """An fd the owning app writes `mime`'s data into, for the caller to read and close."""+ if not self.clipboard_enabled:+ return None+ return self.portal.call(CLIPBOARD, "SelectionRead", "os", (self.handle, mime))[0]++ def _transfer(self, mime: str, serial: int) -> None:+ """Another app pastes what Beamer put on the clipboard: its data goes down an fd the portal+ gives, written on a helper thread so a slow reader never holds this one, within+ WRITE_SECONDS, and the portal is told it is done from here, by this session only."""+ data = self.offer.get(mime)+ if data is None:+ self._write_done(serial, False)+ return+ fd = self.portal.call(CLIPBOARD, "SelectionWrite", "ou", (self.handle, serial))[0]+ generation = self._generation+ stopping = self._stopping++ def write() -> None:+ ok = _write_all(fd, data, WRITE_SECONDS, stopping)++ def done(remote: "Remote") -> None:+ if remote._generation == generation and remote.portal is not None:+ remote._write_done(serial, ok)++ self._commands.put((done, _Answer(None), None))+ self._wake()++ threading.Thread(target=write, name="Beamer-clipboard-write", daemon=True).start()+++def _write_all(fd: int, data: bytes, seconds: float, stopping: threading.Event) -> bool:+ """Write `data` to `fd` and close it, giving up after `seconds` or when the session stops."""+ deadline = time.monotonic() + seconds+ try:+ os.set_blocking(fd, False)+ view = memoryview(data)+ while view:+ left = deadline - time.monotonic()+ if left <= 0 or stopping.is_set():+ LOGGER.warning("The app pasting the clipboard did not take it in time")+ return False+ _, ready, _ = select.select([], [fd], [], min(left, 0.2))+ if ready:+ view = view[os.write(fd, view):]+ return True+ except OSError:+ LOGGER.exception("Could not hand the clipboard to the app pasting it")+ return False+ finally:+ try:+ os.close(fd)+ except OSError:+ pass+++class _Answer:+ """One answer from the session's thread to a caller who waits a bounded time; an answer that+ comes after the caller gave up is handed to `discard`."""++ def __init__(self, discard: Optional[Callable[[object], None]]) -> None:+ self._discard = discard+ self._lock = threading.Lock()+ self._event = threading.Event()+ self._gave_up = False+ self._value = (False, None)++ def give(self, ok: bool, value) -> None:+ with self._lock:+ if not self._gave_up:+ self._value = (ok, value)+ self._event.set()+ return+ if ok and self._discard is not None and value is not None:+ try:+ self._discard(value)+ except Exception:+ LOGGER.exception("Could not discard a late answer")++ def wait(self, timeout: float, default):+ self._event.wait(timeout)+ with self._lock:+ if not self._event.is_set():+ self._gave_up = True+ return default+ ok, value = self._value+ return value if ok else default+++class _Problem(Exception):+ def __init__(self, sentence: str, terminal: bool = False) -> None:+ super().__init__(sentence)+ self.sentence = sentence+ self.terminal = terminal+++_remote: Optional[Remote] = None+_remote_lock = threading.Lock()+++def remote() -> Remote:+ global _remote+ with _remote_lock:+ if _remote is None:+ _remote = Remote()+ return _remote+++def start() -> None:+ """Open the session now, so the desktop asks while the user is at this machine."""+ remote().start()+++def stop() -> None:+ if _remote is not None:+ _remote.stop()+++def _warn_once(message: str, item: str, _said: Set[str] = set()) -> None:+ if item not in _said:+ _said.add(item)+ LOGGER.warning(message, item)+++def inject_key(name: str, down: bool, us: Optional[str] = None) -> None:+ def go(session: Remote) -> None:+ if session.layout is None and len(name) == 1:+ return # a named key needs no layout; a character does+ session.keys(wayland_steps(plan_key(name, down, us, session.state, session.layout, session.group, session.locks)))++ remote().submit(go, release=not down)+++def inject_text(text: str) -> None:+ def go(session: Remote) -> None:+ if session.layout is None:+ return+ session.keys(wayland_steps(plan_text(text, session.state, session.layout, session.group, session.locks)))++ remote().submit(go)+++def inject_mouse_move(dx: int, dy: int) -> None:+ remote().submit(lambda session: session.move_by(dx, dy))+++def move_to(x: int, y: int) -> None:+ remote().submit(lambda session: session.place(x, y))+++def inject_mouse_button(button: str, down: bool) -> None:+ code = BUTTONS.get(button)+ if code is None:+ _warn_once("Unknown mouse button ignored: %r", button)+ return+ remote().submit(lambda session: session.button(code, down), release=not down)+++def inject_scroll(dy, dx=0.0, mode: str = "line") -> None:+ remote().submit(lambda session: session.scroll(dy, dx, mode))+++def inject_gesture(name: str, swipe=None) -> None:+ """As on X11: a Linux machine does not offer `gestures`."""+ _warn_once("Gestures are not yet on Linux; %r dropped", name)+++def release_all() -> None:+ """Let go of every key and button held for the peer."""+ if _remote is not None:+ _remote.submit(lambda session: session.release_held(), release=True)diff --cc win_app/input_injector.pyindex 3032548,22c124d..3809dda--- a/win_app/input_injector.py+++ b/win_app/input_injector.py@@@ -374,6 -375,6 +374,7 @@@ def plan_key_inputs_mods_down: Set[str] = set()_char_vk_down: Dict[str, int] = {}++_named_down: Dict[str, Tuple[int, int, int]] = {}# One lock over the held-key bookkeeping and the send it describes: a session# thread injecting while a reconnect's release_all snapshots and clears would# otherwise press a key that nothing then remembers to release.@@@ -392,7 -393,7 +393,17 @@@ def _locked(function)@_lockeddef inject_key(name: str, down: bool, us: Optional[str] = None) -> None:LOGGER.debug("key %s %s (mods held: %s)", name, "down" if down else "up", sorted(_mods_down))-- plan = plan_key_inputs(name, down, _mods_down, _char_vk_down, _vk_key_scan, _map_virtual_key, us, _key_at)++ lowered = name.lower()++ held = _named_down.get(lowered) if lowered in VK_MAP and lowered not in MODIFIER_KEYS else None++ if held is not None:++ vk, scan, flags = held++ plan = [(vk, scan, flags if down else flags | KEYEVENTF_KEYUP)]++ if not down:++ _named_down.pop(lowered, None)++ else:++ plan = plan_key_inputs(name, down, _mods_down, _char_vk_down, _vk_key_scan, _map_virtual_key, us, _key_at)++ if down and plan and lowered in VK_MAP and lowered not in MODIFIER_KEYS:++ _named_down[lowered] = plan[0]if not plan:return_send_input(*(_keybd_input(vk, scan, flags) for vk, scan, flags in plan))@@@ -558,6 -539,6 +569,11 @@@ def release_all() -> Noneinput_injector_mac.release_all: the receiver calls it when the peer'sinput goes home or its link dies, so a modifier held through a switchdoes not stay down on this PC."""++ for name in sorted(_named_down):++ try:++ inject_key(name, down=False)++ except Exception:++ LOGGER.exception("Could not release %r", name)for name in sorted(_mods_down):try:inject_key(name, down=False)@@@ -575,6 -556,6 +591,7 @@@LOGGER.exception("Could not release the %s mouse button", button)_mods_down.clear()_char_vk_down.clear()++ _named_down.clear()_buttons_down.clear()diff --cc win_app/kvm_bridge_win.pyindex c7157b8,eccd33c..b1e83cf--- a/win_app/kvm_bridge_win.py+++ b/win_app/kvm_bridge_win.py@@@ -23,12 -21,12 +23,13 @@@ from PySide6.QtWidgets importQHBoxLayout,QLabel,QLineEdit,++ QLayout,QMenu,QMessageBox,QPushButton,QScrollArea,-- QSlider,QStackedWidget,++ QStyle,QSystemTrayIcon,QVBoxLayout,QWidget,@@@ -56,30 -52,23 +57,32 @@@ from diagram import ArrangementDiagramfrom edge_glow import EdgeGlow, PreviewLoopfrom effect_overlay import EffectOverlay, logical_pointfrom effect_previews import EffectStill, SwitchStill, TileHover-import firewall_win-import ignored+from core import ignoredimport motion-import pairing-from pairing import PAIRING_PORT, Announcer, local_address_towards+from core import pairing+from core import keytable+from core import peerlist- from core.pairing import PAIRING_PORT, PairingService, local_address_towards++from core.pairing import PairingService, local_address_towards+import machines_winimport pages_win-import protocol-import receiver-from receiver import ReceiverServer, ServerState-import return_edge-import sender-from sender import MacSender+import hardware_win+import peers_view+import platform_parts+import qr_code+from core import protocol+from core import receiver+from core.receiver import LinkResponder, ServerState+from core import return_edge+from core import settings_sync+from core import ways+from sender import OWN_PLATFORM, LinkSenderimport themeimport tokens-import updates+from core import updatesimport widgets++QPushButton = widgets.ActionButton++LOGGER = logging.getLogger(__name__)# The repo-root VERSION file is the one place the version is set; build.spec bundles it.@@@ -213,6 -185,6 +216,36 @@@ def status_icon(state: ServerState, sizreturn pixmap++def page_column_width(free: float) -> float:++ """One centred section column, with a 24 DIP margin on either side."""++ return min(880, max(1, free - 48))++++++class ColumnFit(QObject):++ """Keeps a page's column at page_column_width() of the free width, on every resize of its scroll++ area. The free width is the scroll area less a scrollbar's width whether or not one shows: the++ viewport's own width would move with the column, since a column's wrapped text sets whether the++ page needs a scrollbar, so the column would chase its own tail."""++++ def __init__(self, scroll: QScrollArea, column: QWidget) -> None:++ super().__init__(scroll)++ self.scroll = scroll++ self.column = column++ self.timer = QTimer(self)++ self.timer.setSingleShot(True)++ self.timer.timeout.connect(self.fit)++ scroll.installEventFilter(self)++++ def fit(self) -> None:++ self.column.setFixedWidth(round(page_column_width(self.scroll.width() - 16)))++++ def eventFilter(self, watched, event) -> bool:++ if event.type() in (QEvent.Type.Resize, QEvent.Type.Show):++ # QScrollArea must finish resizing its document before its width constraints change.++ self.timer.start(0)++ return False++++class StatusBridge(QObject):"""Marshals receiver-thread status callbacks onto the GUI thread."""@@@ -245,8 -211,8 +278,16 @@@class WindowsApplication(QWidget):++ def resizeEvent(self, event):++ super().resizeEvent(event)++ if hasattr(self, "sidebar"):++ self.sidebar.set_window_width(self.width())++ if hasattr(self, "footer_note"):++ self.footer_note.setVisible(self.width() >= 640)++def __init__(self, config_path: Path) -> None:super().__init__()++ widgets.install_text_localisation()self.config_path = config_pathself._status_lock = threading.RLock()self._status = ServerState.STOPPED@@@ -341,48 -271,20 +382,50 @@@arrival_callback=lambda edge, x, y: self.bridge.arrived.emit("switch" if edge is None else "edge", edge or "", float(x), float(y)),+ desktop=platform_parts.desktop,+ clipboard=platform_parts.clipboard,)+ self.sender.driven = lambda: self.server.drivenself.sender.send_peer_home = self.server.send_home- # Pause crossing and the full-screen hold are about this screen: the Mac's pointer does+ # Same on all machines, over either link: applied on the GUI thread, and announced with+ # this PC's own arrangement the moment a link comes up.+ self.sender.settings_callback = lambda peer, data: self.bridge.settings.emit(protocol.id_text(peer), data)+ self.sender.arrangement_callback = lambda peer, read: self.bridge.arrangement.emit(+ protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back"),+ protocol.id_text(read["way_back_by"]) if read.get("way_back_by") else None+ )+ self.sender.link_callback = lambda peer, up: self.bridge.peers_changed.emit()+ self.sender.paired_callback = self._store_paired+ self.sender.hw_learned = self._learn_peer_hardware+ self.sender.announce = self._announce+ self.scope_labels: dict = {}+ self.own_notes: list = []+ self._same_seen = None+ self._design_states = {}++ self._followed_version = None++ self._design_path = []+ # Pause crossing and the full-screen hold are about this screen: a peer's pointer does# not go home through a held edge either.self.server.edges_held = lambda: self.sender.edges_held- self.server.return_model = self._return_modelself.sender.on_alert = self.bridge.alert.emit- self.sender.on_mac_learned = self.bridge.mac_learned.emitself.bridge.alert.connect(self._on_alert)- self.bridge.mac_learned.connect(self._on_mac_learned)- self.hooks = capture_win.Hooks(self._on_hook_key, self.sender.on_mouse, self.sender.on_motion)+ self.hooks = capture_win.Hooks(self._on_hook_key, self._on_hook_mouse, self.sender.on_motion)+ # X11 cannot swallow one event, only grab the devices; the capture thread holds the grab+ # for as long as input is away.+ grab_while = getattr(self.hooks, "grab_while", None)+ if grab_while is not None:+ grab_while(lambda: self.sender.redirecting)+ self.hooks.on_failure = self._capture_stopped+ # Wayland: only the desktop captures input, at barriers on this machine's zones, and it+ # may end a capture itself, which brings input home.+ if hasattr(self.hooks, "barriers_from"):+ self.hooks.barriers_from(self.sender.zone_models)+ self.hooks.on_home = lambda: self.sender.set_redirecting(False)+ self.sender.input_held = lambda: self.hooks.holding+ if hasattr(platform_parts.injector, "on_problem"):+ platform_parts.injector.on_problem = lambda sentence: self.bridge.alert.emit("Beamer", sentence)self._trigger = capture_win.Trigger()- self._sending_detail = "Not connected to the Mac"+ self._sending_detail = "Not connected"self.update_checker = updates.Checker(VERSION, lambda: self._config is None or self._config.check_updates, self.bridge.update.emit, logger=LOGGER)@@@ -421,8 -304,8 +464,8 @@@theme.set_dark(theme.wants_dark(appearance, theme.system_dark()))self.setWindowTitle("Beamer")-- self.resize(820, 720)-- self.setMinimumSize(*tokens.MIN_WINDOW["windows"])++ self.resize(900, 640)++ self.setMinimumSize(320, 300)self.setWindowIcon(QIcon(str(ICON_PATH)))self.preview_loop = PreviewLoop(self)self.tile_hover = TileHover(self.preview_loop, self)@@@ -463,6 -346,6 +506,7 @@@foot_tip=HOME_PAGE,)self.sidebar.setFixedWidth(theme.SIDEBAR_WIDTH)++ self.sidebar.set_window_width(self.width())row_layout.addWidget(self.sidebar)row_layout.addWidget(widgets.rule())@@@ -505,23 -388,11 +549,28 @@@scroll.setFrameShape(QFrame.Shape.NoFrame)# Nothing scrolls sideways, at any width.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)++ scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)++ scroll.verticalScrollBar().setFixedWidth(16)page = QWidget()page.setProperty("vernier", "plain")- layout = QVBoxLayout(page)- layout.setContentsMargins(28, 24, 28, 24)- layout.setSpacing(16)+ page_layout = QVBoxLayout(page)+ page_layout.setContentsMargins(0, 0, 0, 0)+ page_layout.setSpacing(0)++ page_layout.setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint)+ centred = QHBoxLayout()+ centred.setContentsMargins(0, 0, 0, 0)+ centred.addStretch(1)+ content = QWidget()++ content.setObjectName("page_column")+ content.setProperty("vernier", "plain")- content.setMaximumWidth(tokens.PAGE_CONTENT_WIDTH)++ # Its width is set by ColumnFit on every resize; the stretches either side only centre it.++ ColumnFit(scroll, content)+ centred.addWidget(content)+ centred.addStretch(1)+ page_layout.addLayout(centred)+ layout = QVBoxLayout(content)- layout.setContentsMargins(28, 24, 28, 24)- layout.setSpacing(16)++ layout.setContentsMargins(0, 24, 0, 24)++ layout.setSpacing(20)heading = widgets.label(title.upper(), "heading")heading.setFont(theme.font(theme.HEADING, 700))layout.addWidget(heading)@@@ -647,10 -512,10 +696,10 @@@return moduledef _input_module(self) -> QWidget:- """The Mac's two everyday buttons: send input across without the shortcut or an edge, and- hold the edges for a while."""+ """The everyday buttons: send input across without the shortcut or an edge, and hold the+ edges for a while."""module = widgets.Module("Keyboard and mouse")- self.redirect_button = QPushButton("Send input across")- self.redirect_button = QPushButton("Send input to your Mac")++ self.redirect_button = widgets.ActionButton("Send input across")self.redirect_button.setProperty("vernier", "primary")self.redirect_button.setCursor(Qt.CursorShape.PointingHandCursor)self.redirect_button.clicked.connect(self.toggle_redirect)@@@ -670,36 -532,8 +719,36 @@@# Hidden while only the shortcut is chosen: there is no edge to pause.self.pause_row = self._row(self.pause_button, self.crossing_state)module.body.addWidget(self.pause_row)+ self.hold_switch = widgets.Switch("Hold this PC's edges while an app on it is full screen")+ self.hold_switch.setFont(theme.font(theme.TYPE["body"]))+ self.hold_switch.setChecked(self._config.hold_full_screen if self._config else False)+ self.hold_switch.toggled.connect(self._set_hold_full_screen)+ module.body.addWidget(self.hold_switch)+ own_note = self._own_note()+ module.body.addWidget(own_note)+ hold_note = widgets.label(- "Off, your pointer can leave a full-screen game or video, and another machine's pointer can come "- "home through this PC's edge. Useful if your keyboard has no key for the shortcut.", "note", wrap=True)++ "This screen decides, including when another machine drives it. On, a full-screen app here holds pointer crossings; shortcuts and jump keys still work. Off, another machine's pointer can go home or onward through the configured ways.", "note", wrap=True)+ module.body.addWidget(hold_note)++ self.hold_switch.setToolTip("This screen's setting applies to every pointer on it.")+ self.wayland_crossing_note = widgets.label(+ "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.", "note", wrap=True)+ module.body.addWidget(self.wayland_crossing_note)+ for widget in (self.hold_switch, own_note, hold_note):+ widget.setVisible(not platform_parts.WAYLAND)+ self.wayland_crossing_note.setVisible(platform_parts.WAYLAND)return module+ def _redirect_text(self) -> str:+ """Names the machine the button sends input to, which is the one the shortcut would pick."""+ target = self.sender.shortcut_target()+ if target is not None and target in self._labels_by_id:+ return f"Send input to {self._labels_by_id[target]}"- sendable = [entry for entry in self._peer_entries++ sendable = [entry for entry in peerlist.desktops(self._peer_entries)+ if entry.get("in_use", True) is True and entry.get("send")]+ # The entry migrated from 1.4.x has no id to pick it by until its first link.+ return f"Send input to {self._shown(peerlist.labels(self._peer_entries)[sendable[0]['token']])}" if len(sendable) == 1 else "Send input across"+def toggle_redirect(self) -> None:self.sender.toggle()@@@ -708,17 -542,14 +757,17 @@@self._refresh_window()def _crossing_state_args(self) -> tuple:- entries = self._peer_entries- config = self._config- methods = set(config.crossing_methods) if config is not None else set()++ entries = peerlist.desktops(self._peer_entries)return (- config is not None, bool(config and config.mac_host), bool(config and config.send_to_mac),- self.sender.connected, bool(methods & {"edge", "part", "corner"}),- self.sender.crossing_paused, self.sender.full_screen_app,+ bool(entries), any(entry.get("host") for entry in entries), self._any_send(),+ bool(self.sender.peers_up()), bool(self._ways_in()),+ self.sender.crossing_paused, self.sender.full_screen_app, self._machines_name(),)+ def _machines_name(self) -> str:- entries = self._peer_entries++ entries = peerlist.desktops(self._peer_entries)+ return self._shown(peerlist.labels(entries)[entries[0]["token"]]) if len(entries) == 1 else "your machines"+def _crossing_state_sentence(self) -> str:return pages_win.crossing_state_sentence(*self._crossing_state_args())@@@ -739,287 -570,32 +788,361 @@@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- old = False- on = self._config.same_on_both- 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)- self.same_switch.setEnabled(self._paired and not old)- who = settings_sync.who([self._shown(label) for label in peerlist.labels(self._peer_entries).values()])++ 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 _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)- unavailable = []- for entry in self._peer_entries:- peer_text = entry.get("id", "")- peer = protocol.read_id(peer_text)- if peer is None:- continue++ 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")- supported = peer_text in self._design_states- item = QStandardItem(name if supported else f"{name} — Needs beta.6 or later")- item.setData(peer_text, Qt.ItemDataRole.UserRole)- if not supported:++ 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)- unavailable.append(name)++ 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)- peer = next((item for item in self._peer_entries if item.get("id") == self._config.design_follow_peer), None)++ 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:- name = self._shown(peer.get('name') or 'that machine')+ if self._config.same_on_both:- self.design_follow_note.setText(f"Following {name}, paused while Same on all machines is on.")++ 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:- self.design_follow_note.setText(f"Following {name}. Change a Design setting to stop following.")- elif unavailable:- self.design_follow_note.setText("A paired machine is unavailable until it has beta.6 or later.")++ note = ""+ else:- self.design_follow_note.setText("None: this PC keeps its own Design.")++ 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._persist()++ 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()++ self._apply_followed_design(force=True)+- def _apply_followed_design(self) -> None:++ 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, config.design_set_at,- config.design_by,++ current, state, peer, peer, config.same_on_both, stamp,++ author, own_id=config.machine_id, force=force,+ )+ if taken is None:+ return- settings_sync.apply_pc(config, taken["values"])- config.design_set_at = taken["set_at"]- config.design_by = taken["by"]++ 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 self._persist() and taken["changed"]:++ 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 caps++ 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("side") in return_edge.EDGES and entry.get("side_set_at") and author is not None:++ 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 "settings" in self._peer_caps().get(peer, ()):++ 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()++ 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:++ 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 state is not None:- self._apply_followed_design()- self._refresh_design_follow()+ 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")@@@ -1070,9 -676,9 +1193,23 @@@@staticmethoddef _row(*items) -> QWidget:"""Widgets and layouts that show and hide as one row of a module."""++ if len(items) >= 2 and isinstance(items[0], QLabel) and items[0].property("vernier") == "key":++ controls = [item for item in items[1:]++ if isinstance(item, QLayout) or isinstance(item, QWidget) and not isinstance(item, QLabel)]++ if len(controls) == 1:++ control = controls[0]++ if isinstance(control, QLayout):++ holder = QWidget()++ control.setContentsMargins(0, 0, 0, 0)++ holder.setLayout(control)++ holder.setMaximumWidth(360)++ control = holder++ notes = [item for item in items[1:] if isinstance(item, QLabel)]++ return widgets.FormRow(items[0], control, notes)row = QWidget()row.setProperty("vernier", "plain")column = QVBoxLayout(row)++ column.setSizeConstraint(QLayout.SizeConstraint.SetMinimumSize)column.setContentsMargins(0, 0, 0, 0)column.setSpacing(8)for item in items:@@@ -1080,415 -686,159 +1217,433 @@@return rowdef _ways_module(self, current: Config) -> QWidget:-- module = widgets.Module("Ways in")++ module = widgets.Module("Ways from this screen")++ self.ways_module = module+ # Which machine everything below shows and edits; only there with more than one paired.+ holder = QWidget()+ holder.setProperty("vernier", "plain")+ self._machine_slot = QVBoxLayout(holder)+ self._machine_slot.setContentsMargins(0, 0, 0, 0)+ self.machine_choice = widgets.Choice((), 1, "")+ self._machine_slot.addWidget(self.machine_choice.view)+ self.machine_row = self._row(widgets.label("Machine", "key"), holder)+ # A wider step under the choice than between the rows it governs, so it reads as their heading.+ self.machine_row.layout().setContentsMargins(0, 0, 0, 8)+ self.machine_row.setVisible(False)+ module.body.addWidget(self.machine_row)self.ways_summary = widgets.label("", "note", wrap=True)module.body.addWidget(self.ways_summary)self.arrangement_diagram = ArrangementDiagram()-- module.body.addWidget(self.arrangement_diagram)++ # The diagram beside the ways it draws, once the column holds both; stacked below that.++ ways_list = QWidget()++ ways_list.setProperty("vernier", "plain")++ ways_column = QVBoxLayout(ways_list)++ ways_column.setContentsMargins(0, 0, 0, 0)++ ways_column.setSpacing(8)++ self.ways_pair = widgets.SideBySide(self.arrangement_diagram, ways_list)++ module.body.addWidget(self.ways_pair)self.way_boxes: dict = {}for value, text, detail in pages_win.WAY_ROWS:box = QCheckBox(text)box.toggled.connect(lambda on, v=value: self._ways_changed(v, on))self.way_boxes[value] = boxif not detail:-- module.body.addWidget(box)++ ways_column.addWidget(box)continuebox.setAccessibleDescription(detail)-- line = QHBoxLayout()-- line.setSpacing(8)-- line.addWidget(box)-- line.addWidget(widgets.label(detail, "small"))-- line.addStretch(1)-- module.body.addLayout(line)-- self.edge_choice = widgets.Choice(- EDGE_CHOICES, columns=4, current=current.mac_return_edge, on_change=self._set_arrangement- )- self.edge_choice.set_names("Where your Mac is")- self.edge_unlearned = widgets.label(pages_win.NOT_LEARNED_EDGE, "note", wrap=True)- self.edge_unlearned.setVisible(not current.mac_return_edge)++ ways_column.addWidget(box)++ ways_column.addWidget(widgets.label(detail, "small", wrap=True))++ ways_column.addStretch(1)+ # A way refused because it would share a stretch of this screen with another machine's.+ self.clash_note = widgets.label("", "note-amber", wrap=True)+ self.clash_note.setVisible(False)+ module.body.addWidget(self.clash_note)+ # What stops a way working, under the ways it is about: a side another machine's edge holds,+ # a machine that may drive this PC and is not paired with the chosen one, and the chosen one+ # saying none of its own ways leads back here.+ self.blocked_note = widgets.label("", "note-amber", wrap=True)+ self.missing_note = widgets.label("", "note", wrap=True)+ self.no_way_back_note = widgets.label("", "note", wrap=True)+ for note in (self.blocked_note, self.missing_note, self.no_way_back_note):+ note.setVisible(False)+ module.body.addWidget(note)++ self.edge_choice = widgets.Choice(EDGE_CHOICES, columns=4, current="", on_change=self._set_arrangement)+ self.edge_heading = widgets.label("", "key")+ self.edge_note = widgets.label("", "note", wrap=True)+ self.edge_unlearned = widgets.label(pages_win.not_learned_edge(), "note", wrap=True)self.crossing_rows = {- "edge": self._row(- widgets.label("Where your Mac is", "key"),- widgets.label(- "One border, walked both ways, so changing it here moves it on your Mac too.",- "note",- wrap=True,- ),- self.edge_choice.view,- self.edge_unlearned,- ),+ "edge": self._row(self.edge_heading, self.edge_note, self.edge_choice.view, self.edge_unlearned),}-- chips = QHBoxLayout()- chips.setSpacing(4)- self.part_buttons: dict = {}+ # A group within Ways, never a panel of its own: a panel inside a panel reads as a second page.+ self.share_module = QWidget()+ self.share_module.body = QVBoxLayout(self.share_module)+ self.share_module.body.setContentsMargins(0, 0, 0, 0)+ self.share_module.body.setSpacing(8)+ self.share_module.eyebrow = widgets.Eyebrow("Share the edge")+ self.share_module.body.addWidget(self.share_module.eyebrow)+ self.share_sentence = widgets.label("", "note", wrap=True)+ self.share_module.body.addWidget(self.share_sentence)+ share_tiles = QHBoxLayout()+ share_tiles.setSpacing(4)+ self.share_tiles = {}for part in return_edge.PARTS:- tile = QPushButton()- button = QPushButton()- button.setProperty("vernier", "choice")- button.setCheckable(True)- button.setMinimumHeight(widgets.MIN_TARGET)- button.setCursor(Qt.CursorShape.PointingHandCursor)- button.setChecked(part in current.crossing_edge_parts)++ tile = widgets.ElidingButton()+ tile.setProperty("vernier", "choice")+ tile.setCheckable(True)+ tile.setMinimumHeight(48)+ tile.clicked.connect(lambda _on=False, part=part: self._share_part(part))+ share_tiles.addWidget(tile, 1)+ self.share_tiles[part] = tile+ self.share_module.body.addLayout(share_tiles)+ self.share_button = QPushButton("Share the edge")+ self.share_button.setProperty("vernier", "primary")+ self.share_button.clicked.connect(self._share_side)+ self.share_module.body.addWidget(self.share_button)+ self.share_module.setVisible(False)+- chips = QHBoxLayout()- chips.setSpacing(4)- self.part_buttons: dict = {}- for part in return_edge.PARTS:- button = QPushButton()- button.setProperty("vernier", "choice")- button.setCheckable(True)- button.setMinimumHeight(widgets.MIN_TARGET)- button.setCursor(Qt.CursorShape.PointingHandCursor)++ self.parts_choice = widgets.Choice([(part, name) for part, name in++ zip(return_edge.PARTS, ("Top", "Middle", "Bottom"))], 3, "", exclusive=False)++ self.part_buttons = self.parts_choice._buttons++ for part, button in self.part_buttons.items():button.clicked.connect(lambda on, p=part: self._set_part(p, on))-- chips.addWidget(button, 1)-- self.part_buttons[part] = buttonself.parts_note = widgets.label("", "note", wrap=True)-- self.crossing_rows["parts"] = self._row(widgets.label("Parts", "key"), chips, self.parts_note)++ self.crossing_rows["parts"] = self._row(widgets.label("Parts", "key"), self.parts_choice.view, self.parts_note)- self.corner_choice = widgets.Choice(- CORNER_CHOICES, columns=2, current=current.crossing_corner, on_change=self._set_corner- )+ self.corner_choice = widgets.Choice(CORNER_CHOICES, columns=2, current="", on_change=self._set_corner)self.corner_choice.set_names("Corner")self.crossing_rows["corner"] = self._row(widgets.label("Corner", "key"), self.corner_choice.view)-- self.dragging_switch = widgets.Switch("Don't cross while dragging")++ self.dragging_switch = widgets.Switch("Don't cross while dragging with this PC's pointer")++ self.dragging_switch.setToolTip("Applies when this physical pointer pushes through this screen's ways; visiting pointers are not protected by this switch.")self.dragging_switch.setFont(theme.font(theme.TYPE["body"]))self.dragging_switch.setChecked(current.block_while_dragging)self.dragging_switch.toggled.connect(self._set_block_while_dragging)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 straight here")++ self.jump_heading = widgets.Eyebrow("Jump to this machine")+ module.body.addWidget(self.jump_heading)- jump_row = QHBoxLayout()++ 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 = QPushButton("Clear")++ 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)++ 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 ""- return {"machine_id": own, "peers": self._peer_entries, "zones": self._zone_entries}++ 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)+ 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"])+ 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()+ return True++ def _ways_changed(self, way: str, on: bool) -> None:+ if self._config is None:+ return+ if way == "shortcut":+ # The shortcut is this PC's own, whichever machine the page shows.+ self._config.crossing_methods = pages_win.toggle_way(self._config.crossing_methods, way, on)+ self._persist()+ self.sender.update_config(self._config)+ self._reflect_ways()+ self._reflect_look()+ return+ held = ways.ways(self._crossing_settings(), self._chosen_machine())["methods"]+ self._write_ways(methods=[kind for kind in pages_win.toggle_way(held, way, on) if kind != "shortcut"])++ def _set_part(self, part: str, on: bool) -> None:+ held = ways.ways(self._crossing_settings(), self._chosen_machine())["parts"]+ self._write_ways(parts=pages_win.toggle_part(held, part, on))def _reflect_ways(self) -> None:- """The ways' boxes, the parts' chips and which rows show, from the config: a row a chosen- way does not use is hidden, not dimmed, and comes back the moment one does."""+ """The machine choice, the ways' boxes, the parts' chips and which rows show, for the chosen+ machine: a row a chosen way does not use is hidden, not dimmed, and comes back the moment one+ does."""config = self._config or default_config()+ settings = self._crossing_settings()+ machines = self._crossing_machines()+ chosen = self._chosen_machine()+ several = len(machines) > 1+ self._rebuild_machine_choice(machines if several else [])+ self.machine_choice.set_value(chosen)+ motion.set_shown(self.machine_row, several)+ name = dict(machines).get(chosen) if several else None+ name = name or "the other machine"++ self.ways_module.eyebrow.setText(f"Ways from this screen to {name}")+ held = ways.ways(settings, chosen)+ shortcut = "shortcut" in config.crossing_methods+ methods = held["methods"] + (["shortcut"] if shortcut else [])for value, box in self.way_boxes.items():- if box.isChecked() != (value in config.crossing_methods):+ if box.isChecked() != (value in methods):box.blockSignals(True)- box.setChecked(value in config.crossing_methods)+ box.setChecked(value in methods)box.blockSignals(False)- edge = config.mac_return_edge or "right"+ side = held["side"]+ self.edge_choice.set_value(side)+ self.edge_choice.set_names(f"Where {name} is")+ self.edge_heading.setText(f"Where {name} is")- self.edge_note.setText(f"One border, walked both ways, so changing it here moves it on {name} too.")++ self.edge_note.setText(f"Changing a side updates {name}'s side too; it can turn overlapping ways off, with a notice.")+ self.edge_unlearned.setText(pages_win.not_learned_edge(name))+ self.corner_choice.set_value(held["corner"])++ self.corner_choice.view.setToolTip(f"This corner leads to {name} on its configured side.")+ edge = side or "right"names = pages_win.part_names(edge)for part, button in self.part_buttons.items():button.setText(names[part])- button.setChecked(part in config.crossing_edge_parts)+ button.setChecked(part in held["parts"])++ self.parts_choice.view.refresh_metrics()self.parts_note.setText(- f"Crosses only along {pages_win.parts_phrase(edge, config.crossing_edge_parts)}; the rest of "+ f"Crosses only along {pages_win.parts_phrase(edge, held['parts'])}; the rest of ""it is a wall. Choose any, but at least one.")- shown = pages_win.crossing_rows(config.crossing_methods)+ # Resistance and the drag guard are this PC's own, there while any machine has a zone.+ own = {"dragging", "resistance"} & pages_win.crossing_rows(self._ways_in() | set(methods))+ shown = (pages_win.crossing_rows(methods) - {"dragging", "resistance"}) | ownfor key, row in self.crossing_rows.items():- motion.set_shown(row, key in shown)+ # Wayland shows no button held before the pointer meets the edge (wayland_crossing_note).+ motion.set_shown(row, key in shown and not (key == "dragging" and platform_parts.WAYLAND))motion.set_shown(self.resistance_module, "resistance" in shown)-- motion.set_shown(self.shortcut_module, "shortcut" in shown)++ motion.set_shown(self.shortcut_module, "shortcut" in shown or bool(getattr(self, "_trigger_conflict", "")))key_name = TRIGGER_KEYS.get(config.trigger_key, config.trigger_key)- summary = pages_win.ways_summary(config.crossing_methods, config.mac_return_edge, config.crossing_edge_parts,- config.crossing_corner, key_name, config.trigger_style)+ summary = pages_win.ways_summary(methods, side, held["parts"], held["corner"], key_name, config.trigger_style,+ name, several)if summary != self.ways_summary.text():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+ 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.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}")- self.jump_note.setText(f"sends input to {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._config.mac_return_edge = pc_edge- self._config.arrangement_set_at = int(time.time())+ self._write_ways(side=pc_edge)++ def _set_hold_full_screen(self, enabled: bool) -> None:+ if self._config is None:+ return+ 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:@@@ -1594,9 -907,9 +1749,9 @@@def _update_resistance_hint(self, value: int) -> None:text = (-- "Switches the moment the pointer touches the edge."++ "Switches the moment this PC's pointer touches the edge. Each screen supplies its own zones."if value == 0-- else "How far to push past the edge before it gives."++ else "Follows this PC's mouse on every screen; each screen supplies its own zones.")if text != self.resistance_hint.text():self.resistance_hint.setText(text)@@@ -1697,6 -1010,6 +1852,7 @@@row = QFrame()row.setProperty("vernier", "entry")row_layout = QHBoxLayout(row)++ row_layout.setSizeConstraint(QLayout.SizeConstraint.SetMinimumSize)row_layout.setContentsMargins(12, 2, 4, 2)name = widgets.label(capture_win.input_title(entry), "readout")row_layout.addWidget(name, 1)@@@ -1809,10 -1116,10 +1965,15 @@@)self.trigger_note.setVisible(True)return-- self.trigger_note.setVisible(False)-- self.trigger_recorder.set_title(TRIGGER_KEYS[name])if self._config is None:return++ try:++ ways.check_trigger_key({"peers": self.book.peers()}, name)++ except ValueError as exc:++ self._show_trigger_conflict(str(exc))++ return++ self._show_trigger_conflict("")++ self.trigger_recorder.set_title(TRIGGER_KEYS[name])self._config.trigger_key = nameself._persist()self._configure_trigger(self._config)@@@ -1821,6 -1128,6 +1982,11 @@@# The shortcut always stays with Beamer, so it cannot also be on the stays-here list.self._set_ignored([entry for entry in self._config.ignored_inputs if entry != ignored.key(value)])++ def _show_trigger_conflict(self, note) -> None:++ self._trigger_conflict = note++ self.trigger_note.setText(note)++ self.trigger_note.setVisible(bool(note))++def _set_trigger_style(self, value: str) -> None:if self._config is None:return@@@ -1833,7 -1140,7 +1999,7 @@@def _update_style_hint(self, style: str) -> None:text = (- "Input is on another machine for as long as the key is held."- "Input is on the Mac for as long as the key is held."++ "Input is on another machine for as long as the key is held. If you jump while holding the shortcut, releasing it brings input home."if style == "hold"else "Tap twice to switch; tap twice again to come back.")@@@ -1854,15 -1161,7 +2020,17 @@@layout.addWidget(self._on_screen_module(current))self.look_module = self._edge_look_module(current)layout.addWidget(self.look_module)++ layout.addWidget(self.colour_module)+ layout.addWidget(self._appearance_module(current))+ follow = widgets.Module("Match design with")+ self.design_follow_choice = QComboBox()++ self.design_follow_choice.setMaximumWidth(320)+ self.design_follow_choice.currentIndexChanged.connect(self._design_follow_chosen)- follow.body.addWidget(self.design_follow_choice)++ follow.body.addWidget(self._row(widgets.label("Machine", "key"), self.design_follow_choice))+ self.design_follow_note = widgets.label("None: this PC keeps its own Design.", "note", wrap=True)+ follow.body.addWidget(self.design_follow_note)+ layout.addWidget(follow)+ self._refresh_design_follow()- layout.addWidget(self._appearance_module(current))self._reflect_look()def _appearance_module(self, current: Config) -> QWidget:@@@ -1874,8 -1172,8 +2042,13 @@@(("system", "System"), ("light", "Light"), ("dark", "Dark")), 3, current.appearance,on_change=self._appearance_chosen,)++ self.appearance_choice.set_width(252)module.body.addWidget(self._row(widgets.label("This window", "key"), self.appearance_choice.view))-- module.body.addWidget(widgets.label("System follows Windows' light or dark setting.", "note", wrap=True))++ if sys.platform.startswith("linux"):++ appearance_note = "System follows your Linux desktop's light or dark setting."++ else:++ appearance_note = "System follows Windows' light or dark setting."++ module.body.addWidget(widgets.label(appearance_note, "note", wrap=True))return moduledef _appearance_chosen(self, choice: str) -> None:@@@ -1893,11 -1191,10 +2066,10 @@@self.glow_toggle.setChecked(current.edge_glow)self.glow_toggle.toggled.connect(self._apply_look)module.body.addWidget(self.glow_toggle)+ module.body.addWidget(self._own_note())module.body.addWidget(widgets.label(- "Lights this PC as you push toward another machine. Switched off, crossing still works. "- "Each machine sets how its own edge looks.",- "Lights this PC as you push toward your Mac. Switched off, crossing still works. "- "Your Mac sets how its own edge and notch look.",++ "Turns crossing and landing animations on or off on this screen. Saved style choices stay in place.","note",wrap=True,)@@@ -1910,37 -1207,38 +2082,41 @@@self.landing_row = self._row(self.landing_toggle,widgets.label(-- "When the shortcut or a menu brings input to this PC, an animation plays around the "-- "pointer. Choose it under Style for: Shortcut and menu.",++ "For shortcut, menu and jump arrivals; requires Animate crossings on this screen.","note",wrap=True,),)self.landing_row.layout().setSpacing(12)module.body.addWidget(self.landing_row)++ self.landing_toggle.setToolTip("Jump arrivals use this screen's landing animation too.")return moduledef _edge_look_module(self, current: Config) -> QWidget:-- module = widgets.Module("Style and colour")- edge = current.mac_return_edge or "right"++ module = widgets.Module("Style")++ module.body.addWidget(self._follow_banner())colours = app_config.palette_colours(current.glow_colour)++ self.style_preview_hint = widgets.label("Hover to preview", "preview-hint")++ module.body.addWidget(self.style_preview_hint)# Which animation the tiles below choose. Not saved: it only says which one is being worked on.self.design_mode_choice = widgets.Choice((("crossing", "Crossing"), ("switch", "Shortcut and menu")), 2, "crossing", on_change=self._preview_method)self.design_mode_choice.set_names("Style for")++ self.design_mode_choice.set_width(240)self.style_for_row = self._row(widgets.label("Style for", "key"), self.design_mode_choice.view)-- module.body.addWidget(self.style_for_row)# Where every tile below plays its style: never switched off by the style, and what differs# there is said beneath it. The edge or a corner; a PC has no notch to show.self.effect_method_choice = widgets.Choice((("edge", "Edge"), ("corner", "Corner")), 2, "edge", on_change=self._place_picked)self.effect_method_choice.set_names("Show at")++ self.effect_method_choice.set_width(176)self._place_chosen = Falseself.place_note = widgets.label("", "small", wrap=True)self.preview_at_row = self._row(widgets.label("Show at", "key"), self.effect_method_choice.view, self.place_note)++ module.body.addWidget(self.style_for_row)module.body.addWidget(self.preview_at_row)-- module.body.addSpacing(6)self.effect_stills = {}groups = []for title, items in pages_win.style_groups():@@@ -1959,7 -1257,7 +2135,9 @@@tiles.append((choice, name, detail, picture))switch_groups.append((title, tiles))self.switch_style_choice = widgets.TileGroups(switch_groups, current.shortcut_arrival_style, on_change=self._apply_look)++ self.switch_style_choice.view.setToolTip("For shortcut, menu and jump arrivals. Same as crossing uses this screen's crossing style.")module.body.addWidget(self.switch_style_choice.view)++ module.body.addSpacing(6)# Each tile plays its preview while the pointer is over it.for choices, pictures in ((self.glow_style_choice, self.effect_stills),(self.switch_style_choice, self.switch_stills)):@@@ -1975,34 -1273,26 +2153,24 @@@# Every style and every switch plays at this length, so it follows the tiles either way.self.length_choice = widgets.Choice(effects.LENGTHS, 3, current.effect_length, on_change=self._apply_look)self.length_choice.set_names("Length")- module.body.addWidget(self._row(- widgets.label("Length", "key"), self.length_choice.view,- widgets.label("How long each animation takes to play through once the pointer crosses, and to land.",- "small", wrap=True),- ))- module.body.addSpacing(10)- colour_head = QHBoxLayout()- colour_head.setSpacing(8)- colour_head.addWidget(widgets.label("Colour", "key"))++ self.length_choice.set_width(240)+ self.size_choice = widgets.Choice(effects.SIZES, 3, current.effect_size, on_change=self._apply_look)+ self.size_choice.set_names("Size")- controls = QHBoxLayout()- controls.setSpacing(12)++ self.size_choice.set_width(240)+ for title, choice in (("Length", self.length_choice), ("Size", self.size_choice)):- field = QVBoxLayout()- field.setSpacing(5)- field.addWidget(widgets.label(title, "key"))- field.addWidget(choice.view)- controls.addLayout(field, 1)- module.body.addLayout(controls)++ module.body.addWidget(self._row(widgets.label(title, "key"), choice.view))+ module.body.addWidget(widgets.label(- "Length sets how long each animation plays. Size sets the edge band's depth.", "small", wrap=True))- module.body.addSpacing(10)- colour_head = QHBoxLayout()- colour_head.setSpacing(8)- colour_head.addWidget(widgets.label("Colour", "key"))++ "Length changes effect playback time, not crossing resistance or key timing. Size changes depth for styles that support it; it does not change resistance.", "small", wrap=True))++ self.colour_module = widgets.Module("Colour")self.colour_note = widgets.label("For the crossing and the shortcut alike", "small")-- colour_head.addWidget(self.colour_note)-- colour_head.addStretch(1)-- module.body.addLayout(colour_head)++ self.colour_module.body.addWidget(self.colour_note)self.glow_colour_choice = widgets.SwatchGroups([(title, [(value, name, app_config.palette_colours(value)) for value, name in items])for title, items in pages_win.colour_groups()],current.glow_colour,on_change=self._apply_look,)-- module.body.addWidget(self.glow_colour_choice.view)++ self.colour_module.body.addWidget(self.glow_colour_choice.view)self._look = Nonereturn module@@@ -2035,6 -1324,6 +2203,7 @@@# With the animations off, what they look like cannot apply, so it is hidden, not faded.motion.set_shown(self.landing_row, on)motion.set_shown(self.look_module, on)++ motion.set_shown(self.colour_module, on)# Style for exists only while a switch plays anything; otherwise the module is Crossing.motion.set_shown(self.style_for_row, landing)self.colour_note.setVisible(landing)@@@ -2134,358 -1416,112 +2303,360 @@@def _persist(self) -> bool:if self._config is None:return False+ # A change to a shared setting while Same on all machines is on is stamped here, where+ # every page's changes are saved, and sent once saved.+ fields = self._same_fields()+ shared = self._same_seen is not None and fields != self._same_seen and self._config.same_on_both+ self._same_seen = fields+ design_fields = self._design_fields()+ design_changed = self._design_seen is not None and design_fields != self._design_seen+ self._design_seen = design_fields+ if design_changed:- self._config.design_follow_peer = ""+ self._config.design_set_at = settings_sync.next_stamp(+ max(self._config.design_set_at, self._config.same_set_at), time.time())+ self._config.design_by = self._config.machine_id+ if shared:+ self._config.same_set_at = settings_sync.next_stamp(+ max(self._config.same_set_at, self._config.design_set_at), time.time())+ self._config.same_by = self._config.machine_idtry:- save_config(self.config_path, self._config)- # A change on the Crossing page reaches the Mac's pointer while it is here, not at its- # next crossing: the way home is built from these settings when it arrives.- self.server.rearm_return()+ with app_config.SETTINGS_LOCK:+ # What links wrote since this was loaded (an address, a hardware address, a name)+ # is not this window's to overwrite with what it last read.+ learned = app_config.learned_fields(self.config_path)+ # A fold or a new pairing made another entry the first: the flat view follows it+ # whole, or this save would put the old one back.+ names = app_config.LEARNED if learned["auth_token"] != self._config.auth_token else app_config.LINK_WRITTEN+ for name in names:+ setattr(self._config, name, learned[name])+ save_config(self.config_path, self._config)+ # A change on the Crossing page reaches a peer's pointer while it is here, not at its+ # next crossing: its way on is built from these settings when it arrives.+ self.server.peers_changed()+ self.sender.refresh()+ if shared or design_changed:+ self._send_same()+ self._refresh_design_follow()return Trueexcept (ConfigError, OSError):LOGGER.exception("Setting could not be saved")return False- # -- Pairing --------------------------------------------------------------------------+ # -- Machines and pairing ---------------------------------------------------------------- def _pairing_block(self, layout, current: Config) -> None:- module = widgets.Module("Your Mac")- self.mac_module = module- self.paired_heading = widgets.label("", "tile-name", wrap=True)- module.body.addWidget(self.paired_heading)- self.pair_intro = widgets.label(- "Press Pair a Mac, then on your Mac choose this PC and type the six-digit code shown here. "- "You only do this once.",- "note",- wrap=True,+ def _read_kept(self) -> tuple:+ """This PC's port and Hide addresses as settings.json keeps them, which hold with no machine paired."""+ try:+ settings = app_config.load_settings(self.config_path)+ except (ConfigError, OSError):+ return default_config().port, False+ return settings["port"], bool(settings.get("hide_addresses"))++ def _hide_addresses(self) -> bool:+ return self._config.hide_addresses if self._config is not None else self._kept_hide++ def _make_pairing(self) -> Optional[PairingService]:+ try:+ settings = app_config.load_settings(self.config_path)+ except (ConfigError, OSError):+ LOGGER.exception("Pairing is unavailable: the settings could not be read")+ return None+ identity = protocol.read_id(settings["machine_id"])+ if identity is None:+ return None+ name = settings.get("name") or pairing.machine_name()+ return PairingService(+ name, identity, OWN_PLATFORM, self._announced_port, self.book.peers, self._store_peer,+ on_paired=self.bridge.paired.emit, logger=LOGGER,)- module.body.addWidget(self.pair_intro)- # The last pairing's outcome; takes no room while there is none.- self.pair_note = widgets.label("", "note", wrap=True)- self.pair_note.setVisible(False)- module.body.addWidget(self.pair_note)- self.pair_button = QPushButton()- self.pair_button.setProperty("vernier", "primary")- self.pair_button.setCursor(Qt.CursorShape.PointingHandCursor)- self.pair_button.clicked.connect(self._toggle_pairing)- module.body.addWidget(self.pair_button, 0, Qt.AlignmentFlag.AlignLeft)- layout.addWidget(module)- self.code_module = widgets.Module("Pairing code")- code_row = QHBoxLayout()- code_row.setSpacing(18)- self.code_label = widgets.label(IDLE_CODE, "code-idle")- self.code_label.setFont(theme.mono_font(theme.PAIRING_CODE))- # Reachable by Tab and read out digit by digit, so a screen reader user can type it.- self.code_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByKeyboard- | Qt.TextInteractionFlag.TextSelectableByMouse)- self.code_label.setFocusPolicy(Qt.FocusPolicy.StrongFocus)- self.code_label.setAccessibleName("Pairing code")- # The digits have no descenders, so the line box can be trimmed to the ink.- self.code_label.setFixedHeight(round(theme.PAIRING_CODE))- code_row.addWidget(self.code_label, 1, Qt.AlignmentFlag.AlignVCenter)- self.count_label = widgets.label("1:00", "count-idle")- self.count_label.setFont(theme.mono_font(theme.COUNT))- self.count_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)- self.count_label.setAccessibleName("Time left")- code_row.addWidget(self.count_label, 0, Qt.AlignmentFlag.AlignVCenter)- self.code_module.body.addLayout(code_row)- self.drain = widgets.Drain()- self.code_module.body.addWidget(self.drain)- self.code_module.body.addWidget(widgets.label(PAIR_HINT, "note", wrap=True))- # Pairing by address, for a network whose broadcasts never reach the Mac.- self.address_note = widgets.label("", "note", wrap=True)- self.address_note.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)- self.code_module.body.addWidget(self.address_note)- self.code_module.setVisible(False)- layout.addWidget(self.code_module)- self._show_paired(current.paired_with)-- def _show_paired(self, name: str) -> None:- self.paired_heading.setText(f"Paired with {name}" if name else "Not paired yet")- self.pair_intro.setVisible(not name)- if self.announcer.code is None:- self.pair_button.setText("Pair a different Mac" if name else "Pair a Mac")- self._place_pairing(bool(name))-- def _place_pairing(self, paired: bool) -> None:- """First of Overview's modules until a Mac is paired, then just above At sign-in. The page's- title and purpose sit in the same layout, above the modules."""- layout = getattr(self, "overview_layout", None)- if layout is None or not hasattr(self, "code_module"):- return- for widget in (self.mac_module, self.code_module):- layout.removeWidget(widget)- at = layout.indexOf(self.sign_in_module if paired else self.link_module)- layout.insertWidget(at, self.mac_module)- layout.insertWidget(at + 1, self.code_module)-- def _toggle_pairing(self) -> None:- if self.announcer.code is not None:- self.announcer.cancel_pairing()- return- if self.announcer.error:- self._say_pairing(f"Pairing is not available: {self.announcer.error}", "note-fault")- return- self._say_pairing("", "note")- self.announcer.begin_pairing()+ def _store_peer(self, entry: dict, replaced) -> None:+ """PairingService's write, on a socket thread with the service's lock held: the new peer takes+ the place of the entry it replaces (WIRE.md section 6, item 5). It must never wait on the GUI+ thread, and nothing here may call the service."""+ with app_config.SETTINGS_LOCK:+ settings = app_config.load_settings(self.config_path)+ if replaced is not None:+ # `replaced` was read before this lock: it may have changed or gone since+ # (WIRE.md section 6, item 4).+ held = next((peer for peer in settings["peers"] if peer.get("token") == replaced.get("token")), None)+ if held is None or held.get("id") != replaced.get("id") or held.get("linked") != replaced.get("linked"):+ raise ConfigError("the machine being replaced changed while pairing")+ peerlist.add_peer(settings, entry, replaced)+ app_config.write_settings(self.config_path, settings)++ def _peer_items(self, peers: list) -> list:+ """(entry, label, state, where) for every paired machine, from what the links know of it now."""+ labels = peerlist.labels(peers)+ hide = self._hide_addresses()+ driver, here, live = self.server.owner, self.sender.owner, self.server.links()+ items = []+ self._labels_by_id = {}+ for entry in peers:+ peer = protocol.read_id(entry.get("id"))+ token = entry["token"]+ labels[token] = self._shown(labels[token])+ if peer is not None:+ self._labels_by_id[peer] = labels[token]+ state = peers_view.describe(+ entry, labels[token],+ up=peer is not None and (self.sender.links.up(peer) or peer in live),+ driving=peer is not None and peer == driver,+ input_there=peer is not None and peer == here,+ kind=self.sender.links.kind(token), status=self.sender.links.status(token),+ waking=peer is not None and self.sender.is_waking(peer),+ )+ state = replace(state, detail=self._shown(state.detail))- where = f"{peers_view.platform_name(entry)} · {peers_view.address_line(entry, hide)}"++ where = peers_view.platform_name(entry)++ if entry.get("port") != 0:++ where += f" · {peers_view.address_line(entry, hide)}"+ items.append((entry, labels[token], state, where))+ return items++ def _refresh_peers(self) -> None:+ try:+ peers, zones = self.book.peers(), self.book.zones()+ except (ConfigError, OSError):+ LOGGER.exception("The peers could not be read")+ peers, zones = [], []+ self._peer_entries, self._zone_entries = peers, zones- if self._config is not None and self._config.design_follow_peer not in {p.get("id") for p in peers}:++ if self._config is not None and self._config.design_follow_peer not in {p.get("id") for p in peerlist.desktops(peers)}:+ if self._config.design_follow_peer:+ self._config.design_follow_peer = ""+ self._persist()+ self._refresh_design_follow()+ self.machines.set_peers(self._peer_items(peers))+ if hasattr(self, "arrangement_diagram"):+ self._reflect_other_name()+ # A machine paired, removed or renamed, or a side or zone a link wrote: the Crossing page follows.+ seen = repr((peers, zones, self._hide_addresses()))+ if seen != self._crossing_seen:+ self._crossing_seen = seen+ self._reflect_ways()++ def _reflect_other_name(self) -> None:+ name = self._machines_name() if len(self._peer_entries) == 1 else ""+ self.resistance_strip.set_other_name(name)++ def _refresh_peer_states(self) -> None:+ """The rows' states again from the peers last read: the links move faster than the file does."""+ self.machines.set_peers(self._peer_items(self._peer_entries))++ def _any_send(self) -> bool:+ return any(entry.get("in_use", True) is True and entry.get("send") and protocol.linkable(entry)- for entry in self._peer_entries)++ for entry in peerlist.desktops(self._peer_entries))++ def _label_of(self, peer: Optional[bytes]) -> str:+ return self._labels_by_id.get(peer, "another machine") if peer is not None else ""++ def _edit_peer(self, token: str, **fields) -> bool:+ try:+ with app_config.SETTINGS_LOCK:+ settings = app_config.load_settings(self.config_path)+ entry = next((item for item in settings["peers"] if item.get("token") == token), None)+ if entry is None:+ return False+ entry.update(fields)+ app_config.write_settings(self.config_path, settings)+ except (ConfigError, OSError):+ LOGGER.exception("A machine's setting could not be saved")+ return False+ return True++ def _set_peer_send(self, token: str, enabled: bool) -> None:+ """This PC's input may go to that machine or not. Takes effect at once: the hooks that watch this+ PC's own keyboard are in only while some machine can be sent to."""+ # Home before the save: the links read `send` from the settings themselves, and one that read+ # it first would end with input still on its machine. Home after a failed save is harmless.+ if not enabled and self._input_is_on(token):+ self.sender.set_redirecting(False)+ if self._edit_peer(token, send=bool(enabled)):+ self._after_peers_edit()++ def _input_is_on(self, token: str) -> bool:+ """Whether this PC's input is on the machine paired under `token`."""+ on = self.sender.owner+ return on is not None and any(+ protocol.read_id(entry.get("id")) == on for entry in self._peer_entries if entry.get("token") == token+ )++ def _set_peer_allow(self, token: str, enabled: bool) -> None:+ """That machine may drive this PC or not. The listener stays up either way, since arrangements and+ settings still travel on its link; off ends its ownership and tells it (section 4)."""+ if self._edit_peer(token, allow_drive=bool(enabled)):+ self._after_peers_edit()++ def _set_peer_in_use(self, token: str, enabled: bool) -> None:+ """Takes input home before closing this machine's links when it leaves use."""+ if not enabled and self._input_is_on(token):+ self.sender.set_redirecting(False)+ if self._edit_peer(token, in_use=bool(enabled)):+ self._after_peers_edit()++ def _set_every_peer(self, field: str, enabled: bool) -> None:+ """The tray's two ticks: one direction for every paired machine at once."""+ if field == "send" and not enabled and self.sender.owner is not None:+ # Home first, as _set_peer_send does: before the save the links read `send` from.+ self.sender.set_redirecting(False)+ try:+ with app_config.SETTINGS_LOCK:+ settings = app_config.load_settings(self.config_path)- for entry in settings["peers"]:++ for entry in peerlist.desktops(settings["peers"]) if field == "send" else settings["peers"]:+ entry[field] = bool(enabled)+ app_config.write_settings(self.config_path, settings)+ except (ConfigError, OSError):+ LOGGER.exception("The machines' settings could not be saved")+ return+ self._after_peers_edit()++ def _refresh_tray_directions(self) -> None:+ """The tray's ticks name who they cover and show whether every machine has the direction on."""- entries = self._peer_entries- labels = peerlist.labels(entries)- who = self._shown(labels[entries[0]["token"]]) if len(entries) == 1 else "machines"+ for action, field, text in (- (self.drive_action, "allow_drive", f"{who} drives this PC" if len(entries) == 1 else "Machines drive this PC"),- (self.send_action, "send", f"This PC drives {who}"),++ (self.drive_action, "allow_drive", "Machines drive this PC"),++ (self.send_action, "send", "This PC drives machines"),+ ):++ entries = peerlist.desktops(self._peer_entries) if field == "send" else self._peer_entries++ if len(entries) == 1:++ who = self._shown(peerlist.labels(entries)[entries[0]["token"]])++ text = f"{who} drives this PC" if field == "allow_drive" else f"This PC drives {who}"+ action.setEnabled(bool(entries))+ if action.text() != text:+ action.setText(text)+ on = bool(entries) and all(entry.get(field) for entry in entries)+ if action.isChecked() != on:+ action.setChecked(on)++ def _refresh_tray_machines(self) -> None:+ """With more than one machine to send to, the tray has "Send input to" for each, and the toggle+ is only there to bring input back; with one, the toggle names it, as it always did."""+ labels = peerlist.labels(self._peer_entries)+ sendable = [(entry["id"], f"Send input to {self._shown(labels[entry['token']])}") for entry in self._peer_entries+ if entry.get("in_use", True) is True and entry.get("send") and entry.get("port")+ and protocol.read_id(entry.get("id")) is not None]+ items = sendable if len(sendable) > 1 else []+ if items != [(ident, action.text()) for ident, action in self.machine_actions.items()]:+ for action in self.machine_actions.values():+ self.tray_menu.removeAction(action)+ action.deleteLater()+ self.machine_actions = {}+ for ident, text in items:+ action = QAction(text, self.tray_menu)+ action.triggered.connect(lambda _checked=False, peer=protocol.read_id(ident): self.sender.go(peer))+ self.tray_menu.insertAction(self.pause_action, action)+ self.machine_actions[ident] = action+ on = self.sender.owner+ for ident, action in self.machine_actions.items():+ action.setEnabled(protocol.read_id(ident) != on)+ self.redirect_action.setVisible(not self.machine_actions or self.sender.redirecting)++ def _after_peers_edit(self) -> None:+ """Whatever changed the peers list: the flat view and the links follow, and the machines are listed again."""+ if self._config is not None and not self._paired:+ try:+ config = load_config(self.config_path)+ except (ConfigError, OSError):+ config = None+ if config is not None:+ self._paired = True+ self._host = config.host+ self._apply_config(config)+ self._configure_trigger(config)+ self._reflect_config(config)+ elif self._config is not None:+ self._pull_peer_fields()+ self.sender.refresh()+ self.server.peers_changed()+ self._send_paired()+ self._refresh_peers()+ self._sync_sending()++ def _sync_sending(self) -> None:+ """The links and the hooks that feed them run while some machine can be sent to, whatever changed the list."""+ if self._config is None:+ return+ if self._any_send():+ self._start_sending(self._config)+ else:+ self.sender.set_redirecting(False)+ self._stop_sending()++ def _remove_peer(self, token: str) -> None:+ try:+ with app_config.SETTINGS_LOCK:+ settings = app_config.load_settings(self.config_path)+ before = ways.way_back_state(settings)+ removed = peerlist.remove_peer(settings, token)+ if removed is None:+ return+ if settings.get("design_follow_peer") == removed.get("id"):+ settings["design_follow_peer"] = ""+ after = ways.way_back_state(settings)+ app_config.write_settings(self.config_path, settings)+ remaining = bool(settings["peers"])+ except (ConfigError, OSError):+ LOGGER.exception("A machine could not be removed")+ self._on_alert("Beamer", "Beamer could not save the removal. Try again in a moment.")+ return+ LOGGER.info("Removed %s from the paired machines", removed.get("name") or "a machine")+ if remaining:+ self._after_peers_edit()+ for peer, state in after.items():+ if before.get(peer) != state:+ self._tell(peer)+ return+ self.sender.set_redirecting(False)+ self._stop_sending()+ self._paired = False+ try:+ self._config = load_config(self.config_path, unpaired_ok=True)+ except (ConfigError, OSError):+ self._config = None+ self._same_seen = self._same_fields() if self._config is not None else None+ self._design_seen = self._design_fields() if self._config is not None else None+ self.sender.update_config(self._config)+ if self._config is not None:+ self._reflect_config(self._config)+ self.server.peers_changed()+ self.sender.refresh()+ self.same_switch.setEnabled(False)+ self._refresh_peers()++ def _toggle_pairing_sheet(self) -> None:+ self._pairing_open = not self._pairing_open+ if not self._pairing_open and self.pairing is not None:+ self.pairing.cancel_pairing()+ self.sheet.setVisible(self._pairing_open)+ self.machines.set_pairing_open(self._pairing_open)+ self._refresh_pairing()++ def _show_code(self) -> None:+ if self.pairing is None:+ self.sheet.say_host("Pairing is not available: this PC's settings could not be read.", "note-fault")+ return+ if self.pairing.error:+ self.sheet.say_host(f"Pairing is not available: {self.pairing.error}", "note-fault")+ return+ self.sheet.say_host("", "note")+ try:+ self.pairing.begin_pairing()+ except pairing.PairingError as exc:+ text = peerlist.host_outcome_text("full", None) if str(exc) == pairing.ERROR_FULL else f"Pairing is not available: {exc}"+ self.sheet.say_host(text, "note-fault")+ return+ self._code_address = self._pairing_address()self._refresh_pairing()- def _pairing_addresses(self) -> list:- """The one address worth typing on the Mac: this PC's on the network that reaches the Mac- it last knew, else on the default route. Every adapter's address, virtual switches and- the hotspot included, only when neither can be found."""- mac = self._config.mac_host if self._config is not None else ""- # Connecting a UDP socket only picks the interface; nothing is sent to either address.- for target in (mac, "192.0.2.1"):- if not target:- continue+ def _cancel_code(self) -> None:+ if self.pairing is not None:+ self.pairing.cancel_pairing()+ self._refresh_pairing()++ def _pairing_address(self) -> str:+ """The one address worth typing on another machine: this PC's on the network that reaches the+ machine it last knew, else on the default route (WIRE.md section 6)."""+ for peer in self._peer_entries:try:- address = local_address_towards(target)+ address = local_address_towards(peer.get("host") or "192.0.2.1")except OSError:continueif address and not address.startswith(("127.", "0.")):@@@ -2590,31 -1626,47 +2761,22 @@@))layout.addWidget(privacy)module = widgets.Module("This PC")-- fields = QGridLayout()-- fields.setHorizontalSpacing(10)-- fields.setVerticalSpacing(10)-- fields.setColumnStretch(1, 1)---- def field(row, caption, entry, span=2):++ def field(caption, entry):# The caption is the field's buddy and its accessible name, so a screen reader and# Alt+letter both reach the field by what it is called.key = widgets.label(caption, "key")key.setBuddy(entry)entry.setAccessibleName(caption)-- fields.addWidget(key, row, 0)-- fields.addWidget(entry, row, 1, 1, span)++ module.body.addWidget(widgets.FormRow(key, entry))- # The address the Mac connects to. Pairing fills it in; a hand set-up copies it from here.- self.host_entry = QLineEdit(self._host)- field(0, "This PC's address", self.host_entry)+ # Read-only: the address that faces the machines this PC knows, which is what another machine+ # types to pair by address.+ self.host_readout = widgets.label(self._shown(self._host) or "Not known yet", "readout", wrap=True)+ self.host_readout.setAccessibleName("This PC's address")- key = widgets.label("This PC's address", "key")- key.setBuddy(self.host_readout)- fields.addWidget(key, 0, 0)- fields.addWidget(self.host_readout, 0, 1, 1, 2)++ field("This PC's address", self.host_readout)self.port_entry = QLineEdit(str(current.port))-- field(1, "Port", self.port_entry)- self.token_entry = QLineEdit(current.auth_token)- self.token_entry.setEchoMode(QLineEdit.EchoMode.Password)- self.token_entry.setMinimumWidth(80)- field(2, "Shared token", self.token_entry, span=1)- self.show_token = QPushButton("Show")- self.show_token.setProperty("vernier", "small")- self.show_token.setCheckable(True)- self.show_token.setMinimumHeight(widgets.MIN_TARGET)- self.show_token.setCursor(Qt.CursorShape.PointingHandCursor)- self.show_token.setToolTip("Show the shared token in this window")- self.show_token.setAccessibleName("Show the shared token")- self.show_token.toggled.connect(self._update_token_visibility)- fields.addWidget(self.show_token, 2, 2)-- module.body.addLayout(fields)- mac_row = QHBoxLayout()- mac_row.setSpacing(6)- mac_row.addWidget(widgets.label("Your Mac's IP address:", "note"))- self.mac_host_readout = widgets.label(self._shown(current.mac_host) or "Not learned yet", "readout", wrap=True)- self.mac_host_readout.setAccessibleName("Your Mac's IP address")- mac_row.addWidget(self.mac_host_readout, 1)- module.body.addLayout(mac_row)- self._show_host_entry()++ self.port_entry.setMaximumWidth(240)++ field("This PC's listening port", self.port_entry)self.save_message = widgets.label("", "note", wrap=True)self.save_message.setVisible(False)module.body.addWidget(self.save_message)@@@ -2698,8 -1750,8 +2860,14 @@@# -- Firewall, on Connection --------------------------------------------------------------def _firewall_module(self, layout) -> None:-- module = widgets.Module("Windows Firewall")-- self.firewall_note = widgets.label("Checking Windows Firewall…", "note", wrap=True)++ if sys.platform.startswith("linux"):++ title = "Linux firewall"++ checking = "Beamer's firewall check is not yet on Linux."++ else:++ title = "Windows Firewall"++ checking = "Checking Windows Firewall…"++ module = widgets.Module(title)++ self.firewall_note = widgets.label(checking, "note", wrap=True)module.body.addWidget(self.firewall_note)self.firewall_button = QPushButton("Checking…")self.firewall_button.setCursor(Qt.CursorShape.PointingHandCursor)@@@ -2811,7 -1864,7 +2979,7 @@@def _apply_theme(self) -> None:app = QApplication.instance()if app is not None:-- app.setStyleSheet(theme.stylesheet())++ theme.apply_stylesheet(app)self._apply_title_bar()def _apply_title_bar(self) -> None:@@@ -3045,18 -2066,12 +3213,17 @@@"""Every key, on the hook thread. The trigger is swallowed as itswitches; everything else goes to the Mac only while the Mac hasinput, and a key on the ignored list not even then."""+ if isinstance(name, capture_win.TextInput):+ return self.sender.on_text(name.text, vk)+ if isinstance(name, capture_win.DeadKey):+ return self.sender.on_dead_key(vk)+ if self.sender.handle_jump_key(name, down, vk):+ return True++ if not self.sender.shortcut_armed:++ self._trigger.configure(self._trigger.key, self._trigger.style, self._trigger.window_ms)++ return self.sender.on_key(name, down, vk, us)action = self._trigger.feed(name, down, time.monotonic())if action is not None:-- if not self.sender.shortcut_armed:-- # The key is still the trigger's, so it never reaches an app,-- # but with the shortcut switched off it moves nothing.-- return Trueif action == capture_win.TOGGLE:self.sender.toggle()else:diff --cc win_app/libei.pyindex 4867638,0000000..69ccd7amode 100644,000000..100644--- a/win_app/libei.py+++ b/win_app/libei.py@@@ -1,368 -1,0 +1,367 @@@+"""Beamer's own small ctypes layer over libei, the input emulation library the Wayland portals hand+input over: a receiver for InputCapture (this machine's own keys and pointer while they are away)+and a sender for RemoteDesktop (a peer's input played here). Only the calls Beamer makes are bound;+Peter Hutterer's snegg is the reference for the shapes, not a dependency (its API is not stable and+it has no release).++`Context.events()` turns libei's events into plain tuples, so the capture and injection modules+read them without ctypes and their tests feed tuples of their own:++ ("connect",) ("disconnect",)+ ("seat",) a seat, already bound to every capability it has+ ("device_added", device) ("device_removed", device)+ ("device_resumed", device) ("device_paused", device)+ ("start", device, sequence) ("stop", device)+ ("frame", device, time_us)+ ("motion", device, dx, dy)+ ("absolute", device, x, y)+ ("button", device, code, down) an evdev button code (BTN_LEFT is 0x110)+ ("scroll", device, dx, dy) in logical pixels+ ("scroll_discrete", device, dx, dy) in 120ths of a notch, as libei counts them+ ("scroll_stop", device)+ ("key", device, code, down) an evdev key code+ ("modifiers", device, depressed, latched, locked, group)++A device is a `Device`, which holds its own reference and says its name, capabilities, regions and+keymap; a removed one lets go of its reference at the next events(), once its removal has been+read. A seat is bound here, while its event still holds it, so no seat pointer leaves this module.+libei is reached only when a Context is made, so this module imports anywhere."""++import ctypes+import ctypes.util+import logging+import os+from typing import List, Optional, Tuple++LOGGER = logging.getLogger(__name__)++CAP_POINTER = 1 << 0+CAP_POINTER_ABSOLUTE = 1 << 1+CAP_KEYBOARD = 1 << 2+CAP_TOUCH = 1 << 3+CAP_SCROLL = 1 << 4+CAP_BUTTON = 1 << 5- CAP_TEXT = 1 << 6+CAPS = (CAP_POINTER, CAP_POINTER_ABSOLUTE, CAP_KEYBOARD, CAP_TOUCH, CAP_SCROLL, CAP_BUTTON)++KEYMAP_XKB = 1++EV_CONNECT = 1+EV_DISCONNECT = 2+EV_SEAT_ADDED = 3+EV_SEAT_REMOVED = 4+EV_DEVICE_ADDED = 5+EV_DEVICE_REMOVED = 6+EV_DEVICE_PAUSED = 7+EV_DEVICE_RESUMED = 8+EV_KEYBOARD_MODIFIERS = 9+EV_FRAME = 100+EV_START_EMULATING = 200+EV_STOP_EMULATING = 201+EV_POINTER_MOTION = 300+EV_POINTER_MOTION_ABSOLUTE = 400+EV_BUTTON = 500+EV_SCROLL_DELTA = 600+EV_SCROLL_STOP = 601+EV_SCROLL_CANCEL = 602+EV_SCROLL_DISCRETE = 603+EV_KEYBOARD_KEY = 700++_lib = None+++def _load():+ global _lib+ if _lib is not None:+ return _lib+ path = ctypes.util.find_library("ei") or "libei.so.1"+ try:+ lib = ctypes.CDLL(path)+ except OSError as exc:+ raise RuntimeError("libei is not installed; Beamer needs it to capture and play input on Wayland") from exc+ p, u32, i32, dbl, b = ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int32, ctypes.c_double, ctypes.c_bool+ signatures = {+ "ei_new_sender": (p, [p]),+ "ei_new_receiver": (p, [p]),+ "ei_unref": (p, [p]),+ "ei_configure_name": (None, [p, ctypes.c_char_p]),+ "ei_setup_backend_fd": (ctypes.c_int, [p, ctypes.c_int]),+ "ei_get_fd": (ctypes.c_int, [p]),+ "ei_dispatch": (None, [p]),+ "ei_get_event": (p, [p]),+ "ei_now": (ctypes.c_uint64, [p]),+ "ei_disconnect": (None, [p]),+ "ei_event_unref": (p, [p]),+ "ei_event_get_type": (ctypes.c_int, [p]),+ "ei_event_get_device": (p, [p]),+ "ei_event_get_seat": (p, [p]),+ "ei_event_get_time": (ctypes.c_uint64, [p]),+ "ei_seat_ref": (p, [p]),+ "ei_seat_unref": (p, [p]),+ "ei_seat_has_capability": (b, [p, ctypes.c_int]),+ "ei_device_ref": (p, [p]),+ "ei_device_unref": (p, [p]),+ "ei_device_get_name": (ctypes.c_char_p, [p]),+ "ei_device_has_capability": (b, [p, ctypes.c_int]),+ "ei_device_get_region": (p, [p, ctypes.c_size_t]),+ "ei_device_keyboard_get_keymap": (p, [p]),+ "ei_device_start_emulating": (None, [p, u32]),+ "ei_device_stop_emulating": (None, [p]),+ "ei_device_frame": (None, [p, ctypes.c_uint64]),+ "ei_device_pointer_motion": (None, [p, dbl, dbl]),+ "ei_device_pointer_motion_absolute": (None, [p, dbl, dbl]),+ "ei_device_button_button": (None, [p, u32, b]),+ "ei_device_scroll_delta": (None, [p, dbl, dbl]),+ "ei_device_scroll_discrete": (None, [p, i32, i32]),+ "ei_device_scroll_stop": (None, [p, b, b]),+ "ei_device_keyboard_key": (None, [p, u32, b]),+ "ei_region_get_x": (u32, [p]),+ "ei_region_get_y": (u32, [p]),+ "ei_region_get_width": (u32, [p]),+ "ei_region_get_height": (u32, [p]),+ "ei_region_get_physical_scale": (dbl, [p]),+ "ei_keymap_get_size": (ctypes.c_size_t, [p]),+ "ei_keymap_get_type": (ctypes.c_int, [p]),+ "ei_keymap_get_fd": (ctypes.c_int, [p]),+ "ei_event_emulating_get_sequence": (u32, [p]),+ "ei_event_keyboard_get_xkb_mods_depressed": (u32, [p]),+ "ei_event_keyboard_get_xkb_mods_latched": (u32, [p]),+ "ei_event_keyboard_get_xkb_mods_locked": (u32, [p]),+ "ei_event_keyboard_get_xkb_group": (u32, [p]),+ "ei_event_pointer_get_dx": (dbl, [p]),+ "ei_event_pointer_get_dy": (dbl, [p]),+ "ei_event_pointer_get_absolute_x": (dbl, [p]),+ "ei_event_pointer_get_absolute_y": (dbl, [p]),+ "ei_event_button_get_button": (u32, [p]),+ "ei_event_button_get_is_press": (b, [p]),+ "ei_event_scroll_get_dx": (dbl, [p]),+ "ei_event_scroll_get_dy": (dbl, [p]),+ "ei_event_scroll_get_discrete_dx": (i32, [p]),+ "ei_event_scroll_get_discrete_dy": (i32, [p]),+ "ei_event_keyboard_get_key": (u32, [p]),+ "ei_event_keyboard_get_key_is_press": (b, [p]),+ }+ for name, (restype, argtypes) in signatures.items():+ function = getattr(lib, name)+ function.restype = restype+ function.argtypes = argtypes+ # Variadic, ended by a zero: its arguments are given types at the call, never in argtypes.+ lib.ei_seat_bind_capabilities.restype = None+ _lib = lib+ return lib+++class Device:+ """A libei device, holding a reference of its own until close()."""++ def __init__(self, lib, pointer: int) -> None:+ self._lib = lib+ self.pointer = lib.ei_device_ref(pointer)+ raw = lib.ei_device_get_name(self.pointer)+ self.name = raw.decode("utf-8", "replace") if raw else ""+ self.caps = {cap for cap in CAPS if lib.ei_device_has_capability(self.pointer, cap)}++ def has(self, cap: int) -> bool:+ return cap in self.caps++ def regions(self) -> List[Tuple[int, int, int, int, float]]:+ """(x, y, width, height, scale) for each region of a virtual device, in the compositor's+ logical pixels: where an absolute position lands."""+ found = []+ index = 0+ while True:+ region = self._lib.ei_device_get_region(self.pointer, index)+ if not region:+ return found+ found.append((self._lib.ei_region_get_x(region), self._lib.ei_region_get_y(region),+ self._lib.ei_region_get_width(region), self._lib.ei_region_get_height(region),+ self._lib.ei_region_get_physical_scale(region)))+ index += 1++ def keymap(self) -> Optional[str]:+ """The XKB keymap the compositor gave this keyboard, as text, or None. The fd is libei's and+ stays open; it is read with pread so its offset is never moved."""+ keymap = self._lib.ei_device_keyboard_get_keymap(self.pointer)+ if not keymap or self._lib.ei_keymap_get_type(keymap) != KEYMAP_XKB:+ return None+ size = self._lib.ei_keymap_get_size(keymap)+ fd = self._lib.ei_keymap_get_fd(keymap)+ if fd < 0 or size <= 0:+ return None+ data = os.pread(fd, size, 0)+ return data.rstrip(b"\0").decode("utf-8", "replace")++ def close(self) -> None:+ if self.pointer:+ self._lib.ei_device_unref(self.pointer)+ self.pointer = None+++class Context:+ """One libei connection over an fd a portal's ConnectToEIS gave. `sender` False for capture.+ Not thread-safe: one thread dispatches and sends."""++ def __init__(self, fd: int, sender: bool, name: str = "Beamer") -> None:+ lib = self._lib = _load()+ self.sender = sender+ self._ei = lib.ei_new_sender(None) if sender else lib.ei_new_receiver(None)+ if not self._ei:+ raise RuntimeError("libei could not make a context")+ lib.ei_configure_name(self._ei, name.encode())+ result = lib.ei_setup_backend_fd(self._ei, fd)+ if result != 0:+ lib.ei_unref(self._ei)+ self._ei = None+ raise OSError(-result, f"libei refused the portal's connection: {os.strerror(-result)}")+ self._devices = {}+ self._removed = []++ def fileno(self) -> int:+ return self._lib.ei_get_fd(self._ei)++ def now(self) -> int:+ return self._lib.ei_now(self._ei)++ def _bind(self, seat: int) -> None:+ """Ask the seat for every capability it has: a receiver gets whatever the compositor+ captures, a sender every device it may emulate."""+ lib = self._lib+ caps = [ctypes.c_int(cap) for cap in CAPS if lib.ei_seat_has_capability(seat, cap)]+ lib.ei_seat_bind_capabilities(ctypes.c_void_p(seat), *caps, ctypes.c_void_p(None))++ def _device(self, pointer: int) -> Device:+ device = self._devices.get(pointer)+ if device is None:+ device = self._devices[pointer] = Device(self._lib, pointer)+ return device++ def events(self) -> list:+ """Dispatch what the fd holds and return every event as a tuple (see the module's)."""+ lib = self._lib+ for device in self._removed:+ device.close()+ self._removed = []+ lib.ei_dispatch(self._ei)+ found = []+ while True:+ event = lib.ei_get_event(self._ei)+ if not event:+ return found+ try:+ item = self._read(event)+ finally:+ lib.ei_event_unref(event)+ if item is not None:+ found.append(item)++ def _read(self, event) -> Optional[tuple]:+ lib = self._lib+ kind = lib.ei_event_get_type(event)+ if kind == EV_CONNECT:+ return ("connect",)+ if kind == EV_DISCONNECT:+ return ("disconnect",)+ if kind == EV_SEAT_ADDED:+ self._bind(lib.ei_event_get_seat(event))+ return ("seat",)+ if kind == EV_SEAT_REMOVED:+ return None+ pointer = lib.ei_event_get_device(event)+ if not pointer:+ return None+ device = self._device(pointer)+ if kind == EV_DEVICE_ADDED:+ return ("device_added", device)+ if kind == EV_DEVICE_REMOVED:+ self._removed.append(self._devices.pop(pointer, device))+ return ("device_removed", device)+ if kind == EV_DEVICE_RESUMED:+ return ("device_resumed", device)+ if kind == EV_DEVICE_PAUSED:+ return ("device_paused", device)+ if kind == EV_START_EMULATING:+ return ("start", device, lib.ei_event_emulating_get_sequence(event))+ if kind == EV_STOP_EMULATING:+ return ("stop", device)+ if kind == EV_FRAME:+ return ("frame", device, lib.ei_event_get_time(event))+ if kind == EV_POINTER_MOTION:+ return ("motion", device, lib.ei_event_pointer_get_dx(event), lib.ei_event_pointer_get_dy(event))+ if kind == EV_POINTER_MOTION_ABSOLUTE:+ return ("absolute", device, lib.ei_event_pointer_get_absolute_x(event), lib.ei_event_pointer_get_absolute_y(event))+ if kind == EV_BUTTON:+ return ("button", device, lib.ei_event_button_get_button(event), bool(lib.ei_event_button_get_is_press(event)))+ if kind == EV_SCROLL_DELTA:+ return ("scroll", device, lib.ei_event_scroll_get_dx(event), lib.ei_event_scroll_get_dy(event))+ if kind == EV_SCROLL_DISCRETE:+ return ("scroll_discrete", device, lib.ei_event_scroll_get_discrete_dx(event), lib.ei_event_scroll_get_discrete_dy(event))+ if kind in (EV_SCROLL_STOP, EV_SCROLL_CANCEL):+ return ("scroll_stop", device)+ if kind == EV_KEYBOARD_KEY:+ return ("key", device, lib.ei_event_keyboard_get_key(event), bool(lib.ei_event_keyboard_get_key_is_press(event)))+ if kind == EV_KEYBOARD_MODIFIERS:+ return ("modifiers", device, lib.ei_event_keyboard_get_xkb_mods_depressed(event),+ lib.ei_event_keyboard_get_xkb_mods_latched(event), lib.ei_event_keyboard_get_xkb_mods_locked(event),+ lib.ei_event_keyboard_get_xkb_group(event))+ return None++ # Sending. A device the desktop removed has let go of its reference; sending on it does nothing.++ def start(self, device: Device, sequence: int) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_start_emulating(device.pointer, sequence)++ def stop(self, device: Device) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_stop_emulating(device.pointer)++ def frame(self, device: Device) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_frame(device.pointer, self.now())++ def motion(self, device: Device, dx: float, dy: float) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_pointer_motion(device.pointer, dx, dy)++ def absolute(self, device: Device, x: float, y: float) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_pointer_motion_absolute(device.pointer, x, y)++ def button(self, device: Device, code: int, down: bool) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_button_button(device.pointer, code, down)++ def scroll(self, device: Device, dx: float, dy: float) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_scroll_delta(device.pointer, dx, dy)++ def scroll_discrete(self, device: Device, dx: int, dy: int) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_scroll_discrete(device.pointer, dx, dy)++ def scroll_stop(self, device: Device) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_scroll_stop(device.pointer, True, True)++ def key(self, device: Device, code: int, down: bool) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_keyboard_key(device.pointer, code, down)++ def close(self) -> None:+ if self._ei:+ for device in list(self._devices.values()) + self._removed:+ device.close()+ self._devices.clear()+ self._removed = []+ self._lib.ei_disconnect(self._ei)+ self._lib.ei_unref(self._ei)+ self._ei = Nonediff --cc win_app/machines_win.pyindex 0c38686,0000000..023dac5mode 100644,000000..100644--- a/win_app/machines_win.py+++ b/win_app/machines_win.py@@@ -1,449 -1,0 +1,723 @@@+"""Overview's two pieces for paired machines: the list with each one's state and switches, and the+pairing sheet. Plain widgets that hold no settings and make no calls of their own: the window feeds+them and gives each the one function it calls back."""++from __future__ import annotations++from typing import Callable, Optional+- from PySide6.QtCore import QRectF, QRegularExpression, QSize, Qt- from PySide6.QtGui import QColor, QPainter, QRegularExpressionValidator++from PySide6.QtCore import QPointF, QRectF, QRegularExpression, QSize, Qt++from PySide6.QtGui import QColor, QFontMetricsF, QPainter, QPen, QRegularExpressionValidator+from PySide6.QtWidgets import (+ QButtonGroup,++ QBoxLayout,+ QHBoxLayout,++ QLabel,+ QLineEdit,++ QLayout,+ QPushButton,+ QSizePolicy,+ QVBoxLayout,+ QWidget,+)++import peers_view+import theme+import widgets- from core import pairing, peerlist++from core import feature_flags, pairing, peerlist++KEEP_NOTE = "It stays paired on that machine until you remove this one there too."+EMPTY = "No machines paired yet."+OLDER = "Older Beamer"+CODE_DIGITS = 6+QR_SCALE = 5++CODE_CELL_GAP = 6++CODE_GROUP_GAP = 12++CODE_CELL_PAD_X = 4++CODE_CELL_PAD_Y = 6+++def _plain() -> QWidget:+ item = QWidget()+ item.setProperty("vernier", "plain")+ return item+++def _button(text: str, role: str = "") -> QPushButton:+ button = QPushButton(text)++ button.setMinimumHeight(widgets.MIN_TARGET)+ if role:+ button.setProperty("vernier", role)+ button.setCursor(Qt.CursorShape.PointingHandCursor)+ return button++++class _PairCodeCells:++ """The six digits, each centred by its measured ink bounds inside its own cell."""++++ def _cell_rectangles(self) -> list[QRectF]:++ metrics = QFontMetricsF(self.font())++ width = max(34.0, metrics.horizontalAdvance("0") + CODE_CELL_PAD_X * 2)++ height = min(max(40.0, metrics.height() + CODE_CELL_PAD_Y * 2), float(self.height()))++ advances = [width + CODE_CELL_GAP] * 6++ advances[2] += CODE_GROUP_GAP++ group_width = sum(advances) - CODE_CELL_GAP++ x = (self.width() - group_width) / 2++ y = (self.height() - height) / 2++ cells = []++ for index in range(6):++ cells.append(QRectF(x, y, width, height))++ x += advances[index]++ return cells++++ def digit_cells(self) -> list[QRectF]:++ return [cell.adjusted(1, 1, -1, -1) for cell in self._cell_rectangles()]++++ def _paint_digits(self, painter: QPainter, text: str, selected: tuple[int, int] = (0, 0), focused: bool = False) -> None:++ metrics = QFontMetricsF(self.font())++ digits = "".join(character for character in text if character.isdigit())[:6]++ cells = self._cell_rectangles()++ inner = self.digit_cells()++ start, length = selected++ for index, (cell, ink_box) in enumerate(zip(cells, inner)):++ painter.setBrush(QColor(theme.colour("ground")))++ painter.setPen(QPen(QColor(theme.colour("signal" if focused and index == min(5, len(digits)) else "edge")), 1))++ painter.drawRoundedRect(cell, 4, 4)++ if start <= index < start + length:++ painter.fillRect(ink_box, QColor(theme.colour("signal_dim")))++ if index >= len(digits):++ continue++ character = digits[index]++ bounds = metrics.tightBoundingRect(character)++ centre = ink_box.center()++ baseline = QPointF(centre.x() - bounds.center().x(), centre.y() - bounds.center().y())++ painter.setPen(QColor(theme.colour("ink")))++ painter.drawText(baseline, character)++ if focused and length == 0:++ index = min(5, max(0, self.cursorPosition()))++ cell = cells[index]++ cursor_x = cell.left() + (cell.width() + metrics.horizontalAdvance("0")) / 2++ if index < len(digits):++ cursor_x = cell.center().x() - metrics.horizontalAdvance(digits[index]) / 2++ painter.setPen(QPen(QColor(theme.colour("signal")), 1))++ painter.drawLine(QPointF(cursor_x, cell.top() + 8), QPointF(cursor_x, cell.bottom() - 8))++++++class PairCodeEdit(QLineEdit, _PairCodeCells):++ """A QLineEdit with the usual paste, selection and deletion behaviour, painted as six cells."""++++ def __init__(self, parent: Optional[QWidget] = None) -> None:++ super().__init__(parent)++ self.setProperty("vernier", "pair-code")++ self.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)++ self.setTextMargins(0, 0, 0, 0)++ self._mouse_anchor = 0++ self._mouse_selecting = False++ self._double_clicked = False++++ def paintEvent(self, event) -> None:++ super().paintEvent(event)++ painter = QPainter(self)++ self._paint_digits(painter, self.text(), (self.selectionStart(), len(self.selectedText())), self.hasFocus())++++ def mousePressEvent(self, event) -> None:++ if event.button() != Qt.MouseButton.LeftButton:++ super().mousePressEvent(event)++ return++ old_cursor = self.cursorPosition()++ if self.hasSelectedText():++ start = self.selectionStart()++ end = start + len(self.selectedText())++ anchor = end if old_cursor == start else start++ else:++ anchor = old_cursor++ super().mousePressEvent(event)++ target = self._cursor_at(event.position().x())++ if event.modifiers() & Qt.KeyboardModifier.ShiftModifier:++ self._mouse_anchor = anchor++ self._select_to(target)++ else:++ self._mouse_anchor = target++ self.setCursorPosition(target)++ self._mouse_selecting = True++++ def mouseMoveEvent(self, event) -> None:++ super().mouseMoveEvent(event)++ if self._mouse_selecting and event.buttons() & Qt.MouseButton.LeftButton:++ self._select_to(self._cursor_at(event.position().x()))++++ def mouseReleaseEvent(self, event) -> None:++ super().mouseReleaseEvent(event)++ if event.button() == Qt.MouseButton.LeftButton:++ if self._double_clicked:++ self._double_clicked = False++ else:++ self._select_to(self._cursor_at(event.position().x()))++ self._mouse_selecting = False++++ def mouseDoubleClickEvent(self, event) -> None:++ super().mouseDoubleClickEvent(event)++ if event.button() == Qt.MouseButton.LeftButton:++ slot = next((index for index, cell in enumerate(self._cell_rectangles())++ if cell.left() <= event.position().x() <= cell.right()), CODE_DIGITS - 1)++ self._mouse_anchor = slot++ self.setSelection(slot, 1)++ self._double_clicked = True++++ def _cursor_at(self, x: float) -> int:++ for index, cell in enumerate(self._cell_rectangles()):++ if cell.left() <= x <= cell.right():++ return index + (x >= cell.center().x())++ if x < cell.left():++ return index++ return CODE_DIGITS++++ def _select_to(self, position: int) -> None:++ if position == self._mouse_anchor:++ self.setCursorPosition(position)++ else:++ self.setSelection(self._mouse_anchor, position - self._mouse_anchor)++++++class PairCodeLabel(QLabel, _PairCodeCells):++ """Read-only pairing digits in the same six-cell layout as the entry control."""++++ def __init__(self, parent: Optional[QWidget] = None) -> None:++ super().__init__(parent)++ self.setAccessibleName("Pairing code")++ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)++ self._mouse_anchor = 0++ self._cursor_position = 0++ self._mouse_selecting = False++ self._double_clicked = False++++ def sizeHint(self) -> QSize:++ metrics = QFontMetricsF(self.font())++ height = max(40.0, metrics.height() + CODE_CELL_PAD_Y * 2) + 2++ return QSize(6 * 42 + 5 * CODE_CELL_GAP + CODE_GROUP_GAP, round(height))++++ def paintEvent(self, _event) -> None:++ painter = QPainter(self)++ painter.setRenderHint(QPainter.RenderHint.Antialiasing)++ painter.setRenderHint(QPainter.RenderHint.TextAntialiasing)++ selected = (0, 0)++ if self.hasSelectedText():++ start = self.selectionStart()++ end = start + len(self.selectedText())++ positions = (0, 1, 2, 4, 5, 6)++ indexes = [index for index, position in enumerate(positions) if start <= position < end]++ if indexes:++ selected = (indexes[0], len(indexes))++ self._paint_digits(painter, self.text(), selected)++++ def mousePressEvent(self, event) -> None:++ if event.button() != Qt.MouseButton.LeftButton:++ super().mousePressEvent(event)++ return++ if self.hasSelectedText():++ start = self.selectionStart()++ end = start + len(self.selectedText())++ anchor = end if self._cursor_position == start else start++ else:++ anchor = self._cursor_position++ super().mousePressEvent(event)++ target = self._text_position_at(event.position().x())++ self._mouse_anchor = (anchor if event.modifiers() & Qt.KeyboardModifier.ShiftModifier++ else target)++ self._cursor_position = target++ self._select_to(target)++ self._mouse_selecting = True++++ def mouseMoveEvent(self, event) -> None:++ super().mouseMoveEvent(event)++ if self._mouse_selecting and event.buttons() & Qt.MouseButton.LeftButton:++ self._select_to(self._text_position_at(event.position().x()))++++ def mouseReleaseEvent(self, event) -> None:++ super().mouseReleaseEvent(event)++ if event.button() == Qt.MouseButton.LeftButton:++ if self._double_clicked:++ self._double_clicked = False++ else:++ target = self._text_position_at(event.position().x())++ self._cursor_position = target++ self._select_to(target)++ self._mouse_selecting = False++++ def mouseDoubleClickEvent(self, event) -> None:++ super().mouseDoubleClickEvent(event)++ if event.button() != Qt.MouseButton.LeftButton:++ return++ slot = min(5, self._slot_at(event.position().x()))++ positions = (0, 1, 2, 4, 5, 6)++ self._cursor_position = positions[slot] + 1++ self._mouse_anchor = positions[slot]++ self.setSelection(self._mouse_anchor, 1)++ self._double_clicked = True++++ def _slot_at(self, x: float) -> int:++ for index, cell in enumerate(self._cell_rectangles()):++ if x <= cell.center().x():++ return index++ return CODE_DIGITS++++ def _text_position_at(self, x: float) -> int:++ digit_positions = (0, 1, 2, 4, 5, 6)++ for index, cell in enumerate(self._cell_rectangles()):++ if cell.left() <= x <= cell.right():++ return digit_positions[index] + (x >= cell.center().x())++ if x < cell.left():++ return digit_positions[index]++ return len(self.text())++++ def _select_to(self, target: int) -> None:++ if target == self._mouse_anchor:++ self.setSelection(self._mouse_anchor, 0)++ else:++ self.setSelection(self._mouse_anchor, target - self._mouse_anchor)+++++class PeerRow(QWidget):+ """One paired machine: its name and state, use switch, direction disclosure and Remove."""++ def __init__(self, token: str, on_send: Callable, on_allow: Callable, on_in_use: Callable, on_remove: Callable) -> None:+ super().__init__()+ self.setProperty("vernier", "plain")+ self.token = token++ self._phone = False+ self._on_remove = on_remove+ column = QVBoxLayout(self)+ column.setContentsMargins(0, 0, 0, 8)+ column.setSpacing(6)+ self.divider = widgets.rule(False)+ column.addWidget(self.divider)+ column.addSpacing(4)- head = QHBoxLayout()++ head = QBoxLayout(QBoxLayout.Direction.TopToBottom)++ self.head = head+ head.setSpacing(10)+ self.led = widgets.Led()- head.addWidget(self.led, 0, Qt.AlignmentFlag.AlignVCenter)++ name_line = QWidget()++ name_line.setProperty("vernier", "plain")++ name_layout = QHBoxLayout(name_line)++ name_layout.setContentsMargins(0, 0, 0, 0)++ name_layout.setSpacing(10)++ name_layout.addWidget(self.led, 0, Qt.AlignmentFlag.AlignVCenter)+ self.name = widgets.label("", "tile-name", wrap=True)- head.addWidget(self.name, 1)++ name_layout.addWidget(self.name, 1)++ head.addWidget(name_line, 1)+ self.word = widgets.label("", "readout")- head.addWidget(self.word, 0, Qt.AlignmentFlag.AlignRight)++ head.addWidget(self.word)+ column.addLayout(head)+ self.where = widgets.label("", "note-quiet", wrap=True)+ column.addWidget(self.where)+ self.detail = widgets.label("", "note", wrap=True)+ column.addWidget(self.detail)+ self.in_use = widgets.Switch("In use")+ self.in_use.toggled.connect(lambda on: on_in_use(self.token, on))++ self.in_use.setToolTip("Off on this PC: no input or settings link to this machine. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect.")+ self.send = widgets.Switch("This PC drives it")++ self.send.setToolTip("Input moves only when this PC enables this switch and the other machine enables It drives this PC.")+ self.allow = widgets.Switch("It drives this PC")++ self.allow.setToolTip("Input moves only when the other machine enables This machine drives it and this PC enables this switch.")+ for switch in (self.send, self.allow):+ switch.setFont(theme.font(theme.TYPE["body"]))+ self.send.toggled.connect(lambda on: on_send(self.token, on))+ self.allow.toggled.connect(lambda on: on_allow(self.token, on))+ self.remove_button = _button("Remove", "small")+ self.remove_button.setMinimumHeight(widgets.MIN_TARGET)+ self.remove_button.clicked.connect(lambda: self._ask(True))- controls = QHBoxLayout()++ controls = QBoxLayout(QBoxLayout.Direction.TopToBottom)+ controls.setSpacing(16)+ directions = QVBoxLayout()++ directions.setContentsMargins(0, 0, 0, 0)++ directions.setSizeConstraint(QLayout.SizeConstraint.SetMinimumSize)+ directions.setSpacing(2)+ directions.addWidget(self.send)+ directions.addWidget(self.allow)+ self.direction_group = QWidget()+ self.direction_group.setLayout(directions)+ self.direction_group.setVisible(False)+ self.directions = _button("Directions", "small")+ self.directions.setCheckable(True)+ self.directions.toggled.connect(self.direction_group.setVisible)+ self.directions.toggled.connect(lambda on: self.directions.setText("Hide directions" if on else "Directions"))+ for switch in (self.send, self.allow):+ switch.setMaximumWidth(300)- controls.addWidget(self.in_use)+ controls.addStretch(1)++ controls.addWidget(self.in_use)+ controls.addWidget(self.directions)+ controls.addWidget(self.remove_button, 0, Qt.AlignmentFlag.AlignBottom)+ self.controls = controls+ column.addLayout(controls)+ column.addWidget(self.direction_group)+ self.confirm = _plain()+ sure = QVBoxLayout(self.confirm)++ sure.setSizeConstraint(QLayout.SizeConstraint.SetMinimumSize)+ sure.setContentsMargins(0, 0, 0, 0)+ sure.setSpacing(8)+ self.confirm_text = widgets.label("", "note", wrap=True)+ sure.addWidget(self.confirm_text)+ buttons = QHBoxLayout()+ buttons.setSpacing(8)+ self.really = _button("Remove", "small")+ self.really.setMinimumHeight(widgets.MIN_TARGET)+ self.really.clicked.connect(lambda: self._on_remove(self.token))+ self.keep = _button("Keep", "small")+ self.keep.setMinimumHeight(widgets.MIN_TARGET)+ self.keep.clicked.connect(lambda: self._ask(False))+ buttons.addWidget(self.really)+ buttons.addWidget(self.keep)+ buttons.addStretch(1)+ sure.addLayout(buttons)+ self.confirm.setVisible(False)+ column.addWidget(self.confirm)+++ def resizeEvent(self, event):++ super().resizeEvent(event)++ wide = self.width() >= 400++ direction = QBoxLayout.Direction.LeftToRight if wide else QBoxLayout.Direction.TopToBottom++ self.head.setDirection(direction)++ self.head.setAlignment(self.word, Qt.AlignmentFlag.AlignRight if wide else Qt.AlignmentFlag.AlignLeft)++ self.controls.setDirection(direction)++ for control in (self.in_use, self.directions, self.remove_button):++ self.controls.setAlignment(control, Qt.AlignmentFlag.AlignRight if wide else Qt.AlignmentFlag.AlignLeft)+++ def _ask(self, asking: bool) -> None:+ self.confirm.setVisible(asking)+ self.remove_button.setVisible(not asking)+ self.in_use.setVisible(not asking)- self.directions.setVisible(not asking)- self.direction_group.setVisible(not asking and self.directions.isChecked())++ self.directions.setVisible(not asking and not self._phone)++ self.direction_group.setVisible(not asking and not self._phone and self.directions.isChecked())++ def refresh(self, entry: dict, label: str, state, where: str) -> None:++ self._phone = entry.get("port") == 0++ asking = self.confirm.isVisibleTo(self)++ self.directions.setVisible(not self._phone and not asking)++ self.direction_group.setVisible(not self._phone and not asking and self.directions.isChecked())+ self.led.set_tone(state.tone)+ for item, text in ((self.name, label), (self.word, state.word), (self.where, where), (self.detail, state.detail),+ (self.confirm_text, f"Remove {label}? {KEEP_NOTE}")):+ if item.text() != text:+ item.setText(text)+ for switch, value in ((self.in_use, entry.get("in_use", True) is True),+ (self.send, bool(entry.get("send"))), (self.allow, bool(entry.get("allow_drive")))):+ if switch.isChecked() != value:+ switch.blockSignals(True)+ switch.setChecked(value)+ switch.blockSignals(False)+ self.word.setAccessibleName(f"{label}: {state.word}")+ self.remove_button.setAccessibleName(f"Remove {label}")++ self.in_use.setToolTip(f"Off on this PC: no input or settings link to {label}. Pairing, directions, ways and jump key are kept. Turn it back on here to reconnect.")++ if self._phone:++ self.in_use.setToolTip(f"Off on this PC: {label} cannot connect or drive it. Turn it back on here to reconnect.")++ self.send.setToolTip(f"Input moves only when this PC enables this switch and {label} enables It drives this PC.")++ self.allow.setToolTip(f"Input moves only when {label} enables This PC drives it and this PC enables this switch.")+++class MachinesModule(widgets.Module):+ """The paired machines, one row each, and the button that opens the pairing sheet."""++ def __init__(self, on_send: Callable, on_allow: Callable, on_in_use: Callable, on_remove: Callable, on_pair: Callable) -> None:+ super().__init__("Machines")+ self._callbacks = (on_send, on_allow, on_in_use, on_remove)+ self.rows: dict = {}+ self.rows_layout = QVBoxLayout()+ self.rows_layout.setContentsMargins(0, 0, 0, 0)+ self.rows_layout.setSpacing(0)- self.body.addLayout(self.rows_layout)- self.empty = widgets.label(EMPTY, "note", wrap=True)- self.body.addWidget(self.empty)+ self.pair_button = _button("Pair a machine", "primary")+ self.pair_button.clicked.connect(on_pair)+ self.body.addWidget(self.pair_button, 0, Qt.AlignmentFlag.AlignLeft)++ self.body.addLayout(self.rows_layout)++ self.empty = widgets.label(EMPTY, "note", wrap=True)++ self.body.addWidget(self.empty)++ def set_peers(self, items: list) -> None:+ """`items`: (entry, label, state, where) for each paired machine, in the order to show them."""+ tokens = [entry["token"] for entry, *_ in items]+ for token in [held for held in self.rows if held not in tokens]:+ row = self.rows.pop(token)+ self.rows_layout.removeWidget(row)+ row.hide()+ row.deleteLater()+ for index, (entry, label, state, where) in enumerate(items):+ row = self.rows.get(entry["token"])+ if row is None:+ row = self.rows[entry["token"]] = PeerRow(entry["token"], *self._callbacks)+ self.rows_layout.insertWidget(index, row)+ elif self.rows_layout.indexOf(row) != index:+ self.rows_layout.removeWidget(row)+ self.rows_layout.insertWidget(index, row)+ row.refresh(entry, label, state, where)+ row.divider.setVisible(index > 0)+ self.empty.setVisible(not items)++ def set_pairing_open(self, opened: bool) -> None:+ text = "Cancel" if opened else "Pair a machine"+ if self.pair_button.text() != text:+ self.pair_button.setText(text)+ widgets.set_role(self.pair_button, "" if opened else "primary")+++class QrView(QWidget):+ """The pairing QR: dark modules on a light ground whatever the theme, since a phone reads+ contrast, not colour."""++ def __init__(self) -> None:+ super().__init__()+ self._rows: list = []+ self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)+ self.setAccessibleName("QR code for the pairing code")++ def set_rows(self, rows: list) -> None:+ if rows != self._rows:+ self._rows = rows+ side = len(rows) * QR_SCALE+ self.setFixedSize(side, side)+ self.update()++ def sizeHint(self) -> QSize:+ side = len(self._rows) * QR_SCALE+ return QSize(side, side)++ def paintEvent(self, _event) -> None:+ painter = QPainter(self)+ painter.fillRect(self.rect(), QColor("#ffffff"))+ painter.setPen(Qt.PenStyle.NoPen)+ painter.setBrush(QColor("#000000"))+ for y, row in enumerate(self._rows):+ for x, dark in enumerate(row):+ if dark:+ painter.drawRect(QRectF(x * QR_SCALE, y * QR_SCALE, QR_SCALE, QR_SCALE))+++class PairingSheet(widgets.Module):+ """Both halves of pairing: showing a code on this PC, and entering one from another machine."""++ def __init__(self, on_show: Callable, on_cancel: Callable, on_pair: Callable, on_pick: Callable) -> None:+ super().__init__("Pair a machine")+ self._on_pair = on_pair+ self._on_pick = on_pick+ self._machines: list = []+ self._listed: tuple = ()+ self._working = False+ self.body.addWidget(widgets.label("Show a code on this PC", "tile-name"))+ self.show_button = _button("Show a code", "primary")+ self.show_button.clicked.connect(on_show)+ self.cancel_button = _button("Cancel", "small")+ self.cancel_button.setMinimumHeight(widgets.MIN_TARGET)+ self.cancel_button.clicked.connect(on_cancel)+ self.cancel_button.setVisible(False)+ buttons = QHBoxLayout()+ buttons.setSpacing(8)+ buttons.addWidget(self.show_button)+ buttons.addWidget(self.cancel_button)+ buttons.addStretch(1)+ self.body.addLayout(buttons)+ self.host_note = widgets.label("", "note", wrap=True)+ self.host_note.setVisible(False)+ self.body.addWidget(self.host_note)+ self.code_box = _plain()+ box = QVBoxLayout(self.code_box)+ box.setContentsMargins(0, 0, 0, 0)+ box.setSpacing(10)+ row = QHBoxLayout()+ row.setSpacing(18)- self.code_label = widgets.label("", "code")++ self.code_label = PairCodeLabel()+ self.code_label.setFont(theme.mono_font(theme.PAIRING_CODE))+ self.code_label.setAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter)+ self.code_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByKeyboard+ | Qt.TextInteractionFlag.TextSelectableByMouse)+ self.code_label.setFocusPolicy(Qt.FocusPolicy.StrongFocus)- self.code_label.setFixedHeight(round(theme.PAIRING_CODE))++ self.code_label.setFixedHeight(self.code_label.sizeHint().height())+ row.addWidget(self.code_label, 1, Qt.AlignmentFlag.AlignVCenter)+ self.count_label = widgets.label("", "count")+ self.count_label.setFont(theme.mono_font(theme.TYPE["body"]))+ self.count_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)+ self.count_label.setAccessibleName("Time left")- row.addWidget(self.count_label, 0, Qt.AlignmentFlag.AlignVCenter)+ box.addLayout(row)++ count_row = QHBoxLayout()++ count_row.addStretch(1)++ count_row.addWidget(self.count_label, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)++ box.addLayout(count_row)+ self.drain = widgets.Drain()+ box.addWidget(self.drain)+ self.address_note = widgets.label("", "note", wrap=True)+ self.address_note.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)+ box.addWidget(self.address_note)+ self.qr = QrView()+ self.qr.setVisible(False)+ box.addWidget(self.qr, 0, Qt.AlignmentFlag.AlignLeft)+ self.qr_caption = widgets.label("", "note-quiet", wrap=True)+ box.addWidget(self.qr_caption)+ self.code_box.setVisible(False)+ self.body.addWidget(self.code_box)++ self.body.addWidget(widgets.rule(False))+ self.body.addWidget(widgets.label("Enter a code from another machine", "tile-name"))+ self.body.addWidget(widgets.label("On this network", "note-quiet"))+ self.heard_layout = QVBoxLayout()+ self.heard_layout.setContentsMargins(0, 0, 0, 0)+ self.heard_layout.setSpacing(6)+ self.body.addLayout(self.heard_layout)+ self.none_heard = widgets.label("No other machine is showing a code yet.", "note", wrap=True)+ self.body.addWidget(self.none_heard)+ self.group = QButtonGroup(self)+ self.group.setExclusive(True)+ self.address = QLineEdit()+ self.address.setAccessibleName("Address of the other machine")+ self.address.setPlaceholderText("Address")+ self.address.textEdited.connect(self._typed_address)+ self.body.addWidget(self.address)+ self.body.addWidget(widgets.label("Not listed? Type its address.", "note-quiet"))- self.code = QLineEdit()++ self.code = PairCodeEdit()+ self.code.setAccessibleName("Code")- self.code.setPlaceholderText("Code")+ self.code.setValidator(QRegularExpressionValidator(QRegularExpression(r"[0-9 ]{0,12}"), self.code))- self.code.setFont(theme.mono_font(theme.TYPE["body"]))++ self.code.setFont(theme.mono_font(20))++ self.code.setFixedHeight(self.code.fontMetrics().height() + CODE_CELL_PAD_Y * 2 + 4)+ self.code.textEdited.connect(self._typed_code)+ self.code.returnPressed.connect(self._pair)+ self.body.addWidget(self.code)+ self.pair_button = _button("Pair", "primary")+ self.pair_button.clicked.connect(self._pair)+ self.body.addWidget(self.pair_button, 0, Qt.AlignmentFlag.AlignLeft)+ self.pair_note = widgets.label("", "note", wrap=True)+ self.pair_note.setVisible(False)+ self.body.addWidget(self.pair_note)+ self._refresh_pair_button()++ # The host half.++ def show_code(self, code: str, seconds: int, address: str, qr_rows: Optional[list], qr_note: str) -> None:+ shown = f"{code[:3]} {code[3:]}"+ if self.code_label.text() != shown:+ self.code_label.setText(shown)+ self.code_label.setAccessibleName(f"Pairing code {' '.join(code)}")+ self.count_label.setText(f"Expires in {seconds} s")+ self.drain.set_remaining(seconds)+ if self.address_note.text() != address:+ self.address_note.setText(address)+ self.address_note.setVisible(bool(address))++ if not feature_flags.PAIRING_QR_VISIBLE:++ qr_rows, qr_note = None, ""+ self.qr.setVisible(qr_rows is not None)+ if qr_rows is not None:+ self.qr.set_rows(qr_rows)+ caption = "The same code as a QR, for a phone to scan." if qr_rows is not None else qr_note+ if self.qr_caption.text() != caption:+ self.qr_caption.setText(caption)+ self.qr_caption.setVisible(bool(caption))+ self.cancel_button.setVisible(True)+ self.show_button.setVisible(False)+ self.code_box.setVisible(True)++ def hide_code(self) -> None:+ self.cancel_button.setVisible(False)+ self.show_button.setVisible(True)+ self.drain.set_remaining(0)+ self.code_label.setAccessibleName("Pairing code")+ self.code_box.setVisible(False)++ @property+ def code_showing(self) -> bool:+ return self.cancel_button.isVisibleTo(self)++ def say_host(self, text: str, tone: str) -> None:+ if self.host_note.text() != text:+ self.host_note.setText(text)+ self.host_note.setVisible(bool(text))+ widgets.set_role(self.host_note, tone)++ # The requester half.++ def set_machines(self, machines: list, shown: Callable[[str], str] = lambda text: text) -> None:+ """What discovery hears: dicts with name, address, platform and pairing, and `pair_id` while a+ code is up. Only a machine showing a code is worth choosing, but one that speaks the old exchange+ is listed too, as Older Beamer, so it is not mistaken for missing. A machine heard on two+ interfaces is two rows of one name, so where names are shared each row says its address, as+ `shown` (the window's Hide addresses) lets it."""+ listed = [item for item in machines if item.get("pair_id") or item.get("pairing") != pairing.PAIRING_V3]+ wheres = [shown(item["address"]) if shared else "" for item, shared in zip(listed, peerlist.sharing_a_name(listed))]+ key = tuple((item["address"], item["name"], item.get("platform"), item.get("pairing"), item.get("pair_id"), where)+ for item, where in zip(listed, wheres))+ if key == self._listed:+ return+ self._listed = key+ chosen = self.chosen_machine()+ self._machines = listed+ for button in list(self.group.buttons()):+ self.group.removeButton(button)+ self.heard_layout.removeWidget(button)+ button.hide()+ button.deleteLater()+ for item, where in zip(listed, wheres):+ version = item.get("pairing") == pairing.PAIRING_V3+ parts = (item["name"], peers_view.platform_name(item), where, "showing a code" if version else OLDER)+ text = " · ".join(part for part in parts if part)- button = _button(text, "choice")++ button = widgets.ElidingButton(text)++ button.setProperty("vernier", "choice")++ button.setCursor(Qt.CursorShape.PointingHandCursor)++ button.set_elision_suffix(" · " + " · ".join(part for part in parts[1:] if part))+ button.setCheckable(True)+ button.setMinimumHeight(widgets.MIN_TARGET)+ # A list of machines reads down its left edge; the theme centres a choice.+ button.setStyleSheet("text-align: left; padding-left: 12px;")+ button.setProperty("address", item["address"])+ button.clicked.connect(lambda _checked=False, address=item["address"]: self._pick(address))+ self.group.addButton(button)+ self.heard_layout.addWidget(button)+ if chosen is not None and chosen["address"] == item["address"]:+ button.setChecked(True)+ if chosen is not None and not any(b.isChecked() for b in self.group.buttons()):+ self._on_pick(None)+ self.none_heard.setVisible(not listed)+ self._refresh_pair_button()++ def chosen_machine(self) -> Optional[dict]:+ for button in self.group.buttons():+ if button.isChecked():+ return next((item for item in self._machines if item["address"] == button.property("address")), None)+ return None++ def _pick(self, address: str) -> None:+ self.address.clear()+ self._on_pick(next((item for item in self._machines if item["address"] == address), None))+ self._refresh_pair_button()++ def _typed_address(self, _text: str) -> None:+ checked = self.group.checkedButton()+ if checked is not None:+ self.group.setExclusive(False)+ checked.setChecked(False)+ self.group.setExclusive(True)+ self._on_pick(None)+ self._refresh_pair_button()++ def _typed_code(self, text: str) -> None:+ digits = "".join(char for char in text if char.isdigit())[:CODE_DIGITS]+ if digits != text:+ self.code.setText(digits)+ self._refresh_pair_button()++ def _refresh_pair_button(self) -> None:+ chosen = self.chosen_machine()+ usable = (chosen is not None and chosen.get("pairing") == pairing.PAIRING_V3) or bool(self.address.text().strip())+ self.pair_button.setEnabled(usable and len(self.code.text()) == CODE_DIGITS and not self._working)++ def _pair(self) -> None:+ if self.pair_button.isEnabled():+ self._on_pair(self.chosen_machine(), self.address.text().strip(), self.code.text())++ def say_pair(self, text: str, tone: str) -> None:+ if self.pair_note.text() != text:+ self.pair_note.setText(text)+ self.pair_note.setVisible(bool(text))+ widgets.set_role(self.pair_note, tone)++ def busy(self, working: bool) -> None:+ self._working = working+ self.pair_button.setText("Pairing…" if working else "Pair")+ self._refresh_pair_button()++ def clear_code(self) -> None:+ self.code.clear()+ self._refresh_pair_button()diff --cc win_app/pages_win.pyindex 3c26724,6e9398c..45c6116--- a/win_app/pages_win.py+++ b/win_app/pages_win.py@@@ -7,39 -7,35 +7,37 @@@ from __future__ import annotationimport re-import effects+from core import effects+from core import peerlist++from core.ways import part_names, parts_phrase, toggle_part# (key, name, what the page is for), in sidebar order, which is setup order; Ctrl+1 is the first.PAGES = (("overview", "Overview",- "Where input is right now, and the controls you reach for every day. Pair with your Mac here "- "first."),+ "The machines paired with this PC, where input is right now, and the controls you reach for "+ "every day. Pair a machine here first."),("crossing", "Crossing",- "Choose how the pointer or a key moves input to your Mac, and how hard the edge pushes back "- "first."),+ "Choose how the pointer or a key moves input to another machine, and how hard the edge "+ "pushes back first."),("keyboard", "Keyboard",- "How this PC's Ctrl and Windows keys arrive on your Mac, the keys and buttons that stay here, "- "and how fast your Mac's pointer moves here."),+ "How this PC's Ctrl and Windows keys arrive on another machine, the keys and buttons that stay "+ "here, and how fast another machine's pointer moves here."),("design", "Design",- "How crossing looks on this PC: the light as you push toward your Mac, and where the pointer "- "lands."),+ "How crossing looks on this PC: the light as you push toward another machine, and where the "+ "pointer lands."),("connection", "Connection",- "Whether Windows Firewall lets your other machines in, this PC's address, port and shared token, "- "and each paired machine's IP address, which pairing learns."),- "Whether Windows Firewall lets your Mac in, this PC's address, port and shared token, and your "- "Mac's IP address, which pairing learns."),++ "This PC's network access, address and listening port; hide addresses in this window and tray."),)KEYS = tuple(page[0] for page in PAGES)-# Under the purpose on the pages whose settings are this PC's alone, so nobody looks for the Mac's-# on the PC: each app sets only its own machine.+# Under the purpose on the pages whose settings are this PC's alone, so nobody looks for another+# machine's on the PC: each app sets only its own machine.SCOPE = {- "crossing": "For this PC only; every other machine keeps its own. Only which side a machine is on is shared, "- "with that machine. This PC's resistance is also what its pointer meets at another machine's edge "- "on the way back.",- "design": "For this PC's screen only; every other machine keeps its own.",- "keyboard": "For this PC's keyboard only; every other machine keeps its own.",- "crossing": "For this PC only; your Mac keeps its own. Only which side your Mac is on is shared. This PC's "- "resistance is also what its pointer meets at your Mac's edge on the way back.",- "design": "For this PC's screen only; your Mac keeps its own.",- "keyboard": "For this PC's keyboard only; your Mac keeps its own.",++ "crossing": "Ways below lead to the selected machine. Its side is shared with that machine. Resistance, drag protection and Shortcut apply to this PC's input for every destination.",++ "design": "Used on this screen. Shared animation settings may follow another machine; Animate and window appearance stay on this PC.",++ "keyboard": "Modifier keys and Stays here belong to this PC's input. Pointer speed and scrolling belong to this screen when another machine drives it. Every machine keeps its own.",}+# With Same on all machines on, under each row of the shared pages that stays this PC's own.+OWN_ROW = "This PC only."# The window's footer; the first sentence goes on Connection, whose changes wait for its button.FOOTER_APPLY = "Changes apply as you make them."FOOTER_TRAY = "Closing this window keeps Beamer running in the tray."@@@ -70,9 -66,8 +68,9 @@@ CLASSIC = "LightTODAY_STYLES = (("glow", "Glow", "A band of light that deepens the harder you push."),("beam", "Beam", "A thin line with a comet of light running along it."),+ ("aperture", "Aperture", "A fine lens of light opens under pressure and closes softly behind the arriving pointer."),)--TODAY_COLOURS = (("signal", "Signal"), ("colourful", "Colourful"), ("ocean", "Ocean"), ("sunset", "Sunset"), ("mono", "Mono"))++TODAY_COLOURS = (("signal", "Signal"), ("colourful", "Colourful"), ("ocean", "Ocean"), ("sunset", "Sunset"), ("mono", "Mono"), ("aurora", "Aurora"))def effects_load_error():@@@ -103,12 -96,12 +101,8 @@@ def style_groups() -> tupledef colour_groups() -> tuple:"""(group title, ((colour id, name), ...)) in the page's order, grouped as the styles are."""-- groups = [(CLASSIC, TODAY_COLOURS)]-- if effects_load_error() is not None:-- return tuple(groups)-- for _module, title, _effects, pack_ids in effects.DIRECTIONS:-- groups.append((title, tuple((pack_id, effects.pack(pack_id)[0]) for pack_id in pack_ids)))-- return tuple(groups)++ return tuple((title, tuple(choices)) for title, choices in++ effects.colour_groups(TODAY_COLOURS, effects_load_error() is None))def is_effect(style: str) -> bool:@@@ -137,30 -130,20 +131,14 @@@ def place_note(style: str, place: str,--def part_names(edge):-- """The names of return_edge.PARTS along `edge`, as the page shows them: top to bottom on a side-- edge, left to right along the top or bottom."""-- if edge in ("left", "right"):-- return {"start": "Top", "middle": "Middle", "end": "Bottom"}-- return {"start": "Left", "middle": "Middle", "end": "Right"}------def parts_phrase(edge, parts):-- """The chosen thirds in a sentence: "the top and middle of the right edge"."""-- names = part_names(edge)-- chosen = [names[part].lower() for part in ("start", "middle", "end") 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 share_sentence(holders, side, name):+ """Name the machines already using the side the chosen machine wants."""+ names = holders[0] if len(holders) == 1 else ", ".join(holders[:-1]) + " and " + holders[-1]+ verb = "crosses" if len(holders) == 1 else "cross"+ # The sentence says what picking a third means: it goes to `name`.+ keep = f"stay with {holders[0]}" if len(holders) == 1 else "stay where they are"+ return (f"{names} already {verb} from the {side} edge of this PC. The thirds you pick go to {name}; "+ f"the rest {keep}.")# The Crossing page's ways in, in the page's order. Edge and Part of the edge are two readings of@@@ -179,48 -162,41 +157,39 @@@ def toggle_way(methods, way, on) -> lisreturn [method for method in WAYS if method in chosen]--def toggle_part(parts, part, on) -> list:-- """`parts` with `part` turned on or off, in return_edge.PARTS order. Turning off the last one-- is refused: Part of the edge with no part would be a wall."""-- chosen = set(parts) | {part} if on else set(parts) - {part}-- if not chosen:-- chosen = set(parts)-- return [candidate for candidate in ("start", "middle", "end") if candidate in chosen]--+def not_learned_edge(name: str = "the other machine") -> str:+ """Under Where it is, while this PC holds no side for the machine named."""+ return f"Not learned yet: choose a side here or on {name}."-NOT_LEARNED_EDGE = "Not learned yet: your Mac tells this PC when it first connects, or choose a side."+def crossing_machines(peers: list) -> list:+ """(id, label) for every paired machine a zone can lead to, in the list's order: never a phone,+ which is never dialled (WIRE.md section 5). The entry migrated from 1.4.x has the id ""."""+ labels = peerlist.labels(peers)+ return [(entry.get("id") or "", labels[entry["token"]]) for entry in peers+ if entry.get("in_use", True) is True and entry.get("port") != 0]-def crossing_state_sentence(paired, mac_heard, sending, connected, armed, paused, full_screen_app) -> str:+def crossing_state_sentence(paired, heard, sending, connected, armed, paused, full_screen_app, name="the other machine") -> str:"""The Crossing page's line under Pause: why nothing can cross, first match wins, and only then- whether crossing is on, held or paused."""+ whether crossing is on, held or paused. `name` is the machine it is about."""if not paired:- return "Not paired yet, so no edge or shortcut moves input until you pair with your Mac above."- if not mac_heard:- return "Waiting to hear from your Mac. This PC cannot push into it until your Mac has connected once."+ return "Not paired yet, so no edge or shortcut moves input until you pair a machine above."+ if not heard:+ return f"Waiting to hear from {name}. This PC cannot push into it until it has connected once."if not sending:- return "This PC drives your Mac is off, so edges and the shortcut do nothing."+ return f"This PC does not drive {name}, so edges and the shortcut do nothing."if not connected:return (- "Not connected to your Mac, so edges and the shortcut do nothing yet. "- "Check that Windows drives this Mac is on, on your Mac."+ f"Not connected to {name}, so edges and the shortcut do nothing yet. "+ "Check that it is switched on and lets this PC drive it.")if not armed:return "Only the shortcut is switched on; there is nothing to pause."if paused:-- return "Paused. The edge, part of the edge and corner do nothing until you resume; the shortcut still works."++ return "Pauses pointer crossing through this screen, including another machine's pointer. Shortcuts and jump keys still work. Resets when Beamer restarts."if full_screen_app is not None:- return (- f"Off while {full_screen_app} is full screen, so the pointer stays put at "- "the edges; the shortcut still works."- )+ return "Held: an app is full screen."return "On. Pause it to lean on an edge without switching."@@@ -272,7 -252,7 +241,7 @@@ WAY_ROWS =("edge", "Edge", "One whole side"),("part", "Part of the edge", "Only the thirds you pick"),("corner", "Corner", "Push diagonally into a corner"),-- ("shortcut", "Shortcut", ""),++ ("shortcut", "Shortcut", "Press a key to switch input"),)CORNER_NAMES = {"top_left": "top-left", "top_right": "top-right", "bottom_left": "bottom-left", "bottom_right": "bottom-right"}@@@ -282,25 -262,11 +251,25 @@@ def trigger_phrase(key_name: str, stylereturn f"{key_name}, {'held' if style == 'hold' else 'twice'}"- SHORTCUT_SEVERAL = "The shortcut takes input to the machine it was last on."-def ways_summary(methods, edge, parts, corner, key_name, style) -> str:- """The Ways in module's first line: every way input leaves for the Mac, in one sentence."""- if not edge:- return "Nothing moves input to your Mac until it has connected once and told this PC which side it is on."++SHORTCUT_SEVERAL = "The shortcut switches home or to the last available machine; if it is unavailable, another available machine can take input."+++def _joined(items) -> str:+ return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]+++def ways_summary(methods, edge, parts, corner, key_name, style, name="the other machine", several=False) -> str:+ """The Ways in module's first line: every way input leaves for the machine `name`, in one+ sentence. With `several` machines paired the shortcut is not this one's, so it gets a sentence of+ its own."""methods = set(methods)+ if not edge:+ # A PC's edge, thirds and corner all cross the side it holds; only the shortcut needs none.+ if "shortcut" in methods and not several:+ press = f"hold {key_name}" if style == "hold" else f"press {key_name} twice"+ return (f"Input moves to {name} when you {press}. Its edges and corner wait until this PC knows "+ f"which side {name} is on.")+ return f"Nothing moves input to {name} until this PC knows which side it is on."ways = []if "edge" in methods:ways.append(f"push through the whole {edge} edge")diff --cc win_app/sender.pyindex e2b37b1,db95afd..003f049--- a/win_app/sender.py+++ b/win_app/sender.py@@@ -159,74 -177,63 +159,75 @@@ class LinkSenderself._config = Noneself._config_lock = threading.RLock()- self._socket_lock = threading.RLock()- self._sequence_lock = threading.RLock()- self._sock: Optional[socket.socket] = None- self._session: Optional[protocol.SecureSession] = None- self._outbound: "queue.Queue[dict]" = queue.Queue(maxsize=OUTBOUND_QUEUE_SIZE)- self._stop_event = threading.Event()- self._threads = []-- self._status = "Not connected to the Mac"- # Keys whose down-stroke went to the Mac and whose release has not: a- # dict, not a set, only so the hook thread's pop() stays one operation.- self._keys_down: dict = {}+ # One lock for the owner, the zone models and every decision they feed. Held for the+ # owner's call and the queueing of what it answers, never across a socket or the clipboard.+ self._lock = threading.RLock()+ self._owner: Optional[owner_module.Owner] = None+ self._own_id: Optional[bytes] = None+ self._peers: dict = {} # peer id: the entry as the settings hold it+ self._entries: list = [] # every entry, in the order the UI shows them+ self._zone_list: list = []+ self._models: list = [] # [(peer id, model)], this PC's zones in use++ self._edge_cursor_error_logged = Falseself._ignore_gate = ignored.Gate()- self._last_sent_seq = 0- self._last_ack_seq = -1- self._last_ack_at = 0.0- self._connected_at = 0.0- self._last_send_at = 0.0-- self.redirecting = False- # Where the pointer was pinned while the Mac has input, and where it- # last was while this PC has it. Two names for two states: conflating- # them made a push against the edge measure its delta from the pin.+ # The name a key went down under, by virtual key, so its release matches even when Shift or+ # the style changes while it is held.+ self._keys_down: dict = {}+ self._accepts: dict = {} # peer id: whether it lets this PC drive it+ self._sent_names: dict = {} # (peer, physical key): the name its press went out under+ self._buttons_held = set()self._pin_point = None- self._last_point = None- self._edge = None- # Two ways the pointer leaves, either or both armed: the whole edge- # that leads to the Mac, and the corner sitting at one end of it. The- # corner is tried first, because its box is inside the edge's strip.- self._edge_model: Optional[return_edge.ReturnEdge] = None- self._corner_model: Optional[return_edge.CornerPush] = Noneself._monitors = Noneself._monitors_at = 0.0- # Set by the app while the Mac is driving this PC: the outbound edge- # stays disarmed for as long as it is, so input that arrived over the- # other link cannot push itself straight back out.- self._receiving = False- # The receiver's way of sending the Mac's input home, handed in by the- # app that owns both halves.- self.send_peer_home = None- # Both hold the edges and leave the shortcut working, as on the Mac: Pause crossing,- # which a restart forgets, and the name of a full-screen app in front, set by the app.+ self._clipboard_stamp = None+ # The machine this PC's input last landed on, as an id text, for the shortcut's choice.+ self._last_on: Optional[str] = None+ self._jump_modifiers = set()+ self._jump_swallowed = set()+ self._jump_pressed = set()+ self.jump_recording = False+ self._reported_redirecting = False+ self._followed_at = 0.0+ self._overflowed = False+ self._armed_for = frozenset()+ self._clip_wait: dict = {} # peer: actions held back while its clipboard is read+ self._clip_lock = threading.Lock()+ self._clip_jobs = collections.deque()+ self._clip_busy = False+ self._statuses: dict = {}+ self._waking = set()+ self._wake_lock = threading.Lock()+ self._outbound: "queue.Queue[tuple]" = queue.Queue(maxsize=SEND_QUEUE_SIZE)+ self._stop_event = threading.Event()+ self._threads = []++ # Pause crossing, which a restart forgets, and the name of a full-screen app in front, set+ # by the app: both hold the edges and leave the shortcut working, as on the Mac.self.crossing_paused = False- self.full_screen_app = None- # The buttons of this PC's own mouse that are down, so a push with one held is a drag.- self._buttons_held = set()- # (title, message) for a notification, and the Mac's hardware address when the ARP table- # names a new one; both called off the GUI thread.+ self._full_screen_app = None+ # (title, message) for a notification, called off the GUI thread, and the hardware address+ # of a peer that did not say its own, read from the ARP table while its entry is fresh.self.on_alert = None- self.on_mac_learned = None- self._wake_sender = wake_sender- self._mac_lookup = mac_lookup- self._waking = False- self._wake_lock = threading.Lock()- self._unacked_sent_at = collections.deque()- self._round_trips = collections.deque(maxlen=ROUND_TRIP_SAMPLES)- self._round_trip_at = 0.0+ # What discovery hears, dicts with `name` and `address`, for following a peer whose address+ # changed (section 6); the pairing window supplies it.+ self.machines: Callable[[], list] = lambda: []+ self.hw_learned: Optional[Callable[[bytes, str], None]] = None+ # Whether this machine's input can be taken now. Always, except where only the desktop can+ # capture it (Wayland), which it does at an edge barrier: there the shortcut and the tray+ # cannot send input away, only an edge push can.+ self.input_held: Callable[[], bool] = lambda: True+ # The responder's: whether a peer's input is on this PC, and sending it home.+ self.driven: Callable[[], bool] = lambda: False+ self.send_peer_home: Callable[[], bool] = lambda: False+ # The messages to send a peer once its link is up, and what to do with each kind that+ # arrives: set by the app, called on a link's thread.+ self.announce: Callable[[bytes], list] = lambda peer: []+ self.arrangement_callback: Optional[Callable] = None+ self.settings_callback: Optional[Callable] = None+ self.paired_callback: Optional[Callable] = None+ self.link_callback: Optional[Callable[[bytes, bool], None]] = None++ self.links = links(self) if links is not None else _default_links(self)# -- state the GUI reads ------------------------------------------------@@@ -336,201 -312,125 +337,205 @@@def update_config(self, config) -> None:with self._config_lock:- previous = self._configself._config = configself._ignore_gate.configure(getattr(config, "ignored_inputs", None) or ())- edge = getattr(config, "mac_return_edge", "") or None- self._edge = edge if edge in return_edge.EDGES else None- self._rearm_edge()- if previous is not None and self._address(previous) != self._address(config):- self._drop_connection()-- @staticmethod- def _address(config):- return (getattr(config, "mac_host", "") or "", int(getattr(config, "port", 0) or 0))-- def _ready_config(self):- with self._config_lock:- config = self._config- if config is None or not getattr(config, "send_to_mac", True):- return None- host, port = self._address(config)- if not host or not port or not config.auth_token:- return None- if self._is_local(host):- return None- return config-- # -- the hooks' two decisions --------------------------------------------- def _link_live(self) -> bool:- """Whether input may still be taken from this PC. Deliberately cheap- and lock-light: it is read on the hook thread for every keystroke and- every mouse move, and a hook that cannot answer promptly is a hook- Windows removes -- with the user's keyboard inside it."""- if self._sock is None:+ own = protocol.read_id(getattr(config, "machine_id", "")) if config is not None else None+ with self._lock:+ if own is not None and own != self._own_id:+ self._own_id = own+ self._owner = owner_module.Owner(own, self._clock, self._resistance())+ elif self._owner is not None:+ self._owner.resistance_px = self._resistance()+ self.refresh()++ def refresh(self) -> None:+ """Reads the peers and zones as the app holds them now, brings the links in step and+ rebuilds the zones: after any change to either, and when a link has learnt a peer's id."""+ try:+ entries = self._book.peers()+ zones = list(self._zones() or [])+ except Exception:+ LOGGER.exception("The peers could not be read")+ return+ peers = {}+ for entry in entries:+ peer = protocol.read_id(entry.get("id"))+ if peer is not None:+ peers[peer] = entry+ with self._lock:+ self._entries, self._peers, self._zone_list = entries, peers, zones+ self._arm_locked()+ self.links.sync(entries)++ # -- the hooks' decisions -----------------------------------------------++ def _live(self) -> bool:+ """Whether input may still be taken from this PC. Deliberately cheap and lock-light: it is+ read on the hook thread for every keystroke and every mouse move, and a hook that cannot+ answer promptly is a hook Windows removes -- with the user's keyboard inside it."""+ peer = self.owner+ return peer is None or self.links.live(peer)++ def _lost(self) -> None:+ peer = self.owner+ if peer is None:+ return+ LOGGER.error("the link to %s went quiet; input returns to this PC", self._name(peer))+ self.links.close(peer)+ self._forget_held(peer)+ self._feed(lambda o: o.link_down(peer))++ def handle_jump_key(self, name: str, down: bool, vk: Optional[int] = None) -> bool:+ """Handles a recorded local chord before trigger detection or ordinary key routing. Keys are+ known by virtual key where there is one: the name carries Shift, so a Shift let go before the+ key would make its release a different name."""+ modifiers = {"alt", "alt_r", "cmd", "cmd_r", "ctrl", "ctrl_r", "shift", "shift_r"}+ if name in modifiers:+ if down:+ self._jump_modifiers.add(name)+ else:+ self._jump_modifiers.discard(name)return False- last = max(self._last_ack_at, self._connected_at)- return (self._clock() - last) <= ACK_TIMEOUT_SECONDS-- def on_key(self, name: str, down: bool, vk: Optional[int] = None, us: Optional[str] = None) -> bool:- # Held keys are known by their virtual key where there is one: the name is the character- # with Shift applied, so Shift let go before A made A's release arrive as "a" and miss.held = vk if vk is not None else name- if not self.redirecting:- # A key that went down on the Mac and is still held after input- # came home: the Mac was sent its release when input left, and- # Windows never saw it go down, so it must see neither its- # autorepeats nor its release. The entry goes on the release.- if held not in self._keys_down:- return False- if not down:- self._keys_down.pop(held, None)+ if not down:+ self._jump_pressed.discard(held)+ if held in self._jump_swallowed:+ self._jump_swallowed.discard(held)+ return True+ return False+ # A key already down when its modifiers arrive repeats; it is not a press of the chord.+ repeat = held in self._jump_pressed+ self._jump_pressed.add(held)+ if held in self._jump_swallowed:return True- if not self._link_live():- self._force_local("the link to the Mac went quiet")+ if repeat or self.jump_recording:+ return False+ chord = ways.jump_chord(self._jump_modifiers, name)+ target = protocol.read_id(ways.jump_peer(self._entries, chord)) if chord else None+ if target is None:+ return False+ self._jump_swallowed.add(held)+ if self.owner == target:+ self.set_redirecting(False)+ else:+ self.go(target)+ return True++ def on_dead_key(self, vk: Optional[int] = None) -> bool:+ """Swallow a dead key only while its live peer owns this PC's input."""+ owner = self._owner+ if owner is None or not owner.away:+ return False+ if not self._live():+ self._lost()+ return False+ if vk is not None and self._ignore_gate.keeps(ignored.key(vk), True):return False- if vk is not None and self._ignore_gate.keeps(ignored.key(vk), down):+ return True++ def on_key(self, name: str, down: bool, vk: Optional[int] = None, us: Optional[str] = None) -> bool:+ """One key, from the hook thread: True when it is not for this PC. Held keys are known by+ their virtual key where there is one: the name is the character with Shift applied, so+ Shift let go before A made A's release arrive as "a" and miss."""+ owner = self._owner+ if owner is None:return False+ held = vk if vk is not None else nameif down:- # The name it went down under is kept, so its release matches even if Shift or the- # modifier style changes while it is held.data = self._keys_down.get(held) or self._key_data(name, us)self._keys_down[held] = data- self._enqueue({"type": protocol.MSG_KEYDOWN, "data": data})else:data = self._keys_down.pop(held, None) or self._key_data(name, us)- # Marked, so a release still queued when input comes home is sent- # rather than dropped by the gate: the Mac has the key-down.- self._enqueue({"type": protocol.MSG_KEYUP, "data": data, _RELEASE_MARK: True})- return True+ if owner.away:+ if not self._live():+ self._lost()+ elif vk is not None and self._ignore_gate.keeps(ignored.key(vk), down):+ return False++ elif vk is not None and not down:++ self._ignore_gate.keeps(ignored.key(vk), False)+ return self._input({"type": protocol.MSG_KEYDOWN if down else protocol.MSG_KEYUP, "data": dict(data)})++ def on_text(self, text: str, vk: Optional[int] = None) -> bool:+ """Sends a composed key sequence as text when this PC's input is away."""+ owner = self._owner+ if owner is None:+ return False+ if owner.away:+ if not self._live():+ self._lost()+ return False+ elif vk is not None and self._ignore_gate.keeps(ignored.key(vk), True):+ return False+ actions = []+ with self._lock:+ owner = self._owner+ if owner is None:+ return False+ message = protocol.text_msg(text)+ message["_bracket_modifiers"] = True+ actions = owner.input(message)+ self._queue(actions)+ self._report(actions)+ return not any(action is owner_module.LOCAL for action in actions)- def _key_data(self, name: str, us: Optional[str]) -> dict:- """A key message's data. `us` is the key's place on a US keyboard, which the Mac types on- when its layout cannot type the character: a PC on Russian sends C as "с"."""- data = {"key": self._wire_name(name)}+ @staticmethod+ def _key_data(name: str, us: Optional[str]) -> dict:+ """A key message's data, with the physical key's name. `us` is the key's place on a US+ keyboard, which the receiver types on when its layout cannot type the character: a PC on+ Russian sends C as "с"."""+ data = {"key": PHYSICAL.get(name, name)}if us is not None:data["us"] = usreturn data- def _wire_name(self, name: str) -> str:- """The capture names Ctrl "cmd" and the Windows key "ctrl", the Semantic style;- Positional swaps them back, so each key arrives as the Mac key in its place."""- if self._setting("modifier_style", "semantic") == "positional":- return POSITIONAL_SWAP.get(name, name)- return name-- def on_mouse(self, message: int, x: int, y: int, mouse_data: int) -> bool:- """Buttons and the wheel, and swallowing a move -- never the distance- it covered, which comes from on_motion. Returns True when the event- belongs to the Mac and Windows must not see it."""- import capture_win-- button = capture_win.button_of(message, mouse_data)- if button is not None:- name, down = button- if down:- self._buttons_held.add(name)- else:- self._buttons_held.discard(name)+ def on_button(self, name: str, down: bool) -> bool:+ """A mouse button, from the hook thread: True when it is not for this PC."""+ if down:+ self._buttons_held.add(name)+ else:+ self._buttons_held.discard(name)+ owner = self._owner+ if owner is None:+ return False+ if owner.away:+ if not self._live():+ self._lost()+ elif self._ignore_gate.keeps(ignored.button(name), down):+ return False++ elif not down:++ self._ignore_gate.keeps(ignored.button(name), False)+ return self._input({"type": protocol.MSG_MOUSEDOWN if down else protocol.MSG_MOUSEUP, "data": {"button": name}})++ def on_wheel(self, dy: float, dx: float) -> bool:+ """The wheel, in notches, positive away from the hand: True when it is not for this PC."""if not self.redirecting:return False- if not self._link_live():- self._force_local("the link to the Mac went quiet")+ if not self._live():+ self._lost()return False- if message == capture_win.WM_MOUSEMOVE:- # Swallowed, and the pointer put back where it was: a hook that- # returns 1 stops the message, but the cursor has already been- # moved by the time it runs.- self._warp_to_pin()- return True- return self._send_mouse(capture_win, message, mouse_data)+ return self._input(protocol.scroll_msg(dy, dx, "line"))++ def on_pointer_move(self) -> bool:+ """A move the hook saw, never the distance it covered, which comes from on_motion. While+ input is elsewhere the pointer is put back where it was, because a hook that returns True+ stops the message but the cursor has already been moved by the time it runs. True when the+ move is not for this PC."""+ if not self.redirecting:+ return False+ if not self._live():+ self._lost()+ return False+ self._warp_to_pin()+ return Truedef on_motion(self, dx: int, dy: int) -> None:- """One raw mouse movement, in the mouse's own counts. Consumes- nothing: raw input cannot block an event, so the hook above is what- keeps the movement off this PC."""+ """One raw mouse movement, in the mouse's own counts. Consumes nothing: raw input cannot+ block an event, so the hook above is what keeps the movement off this PC."""if self.redirecting:- if not self._link_live():- self._force_local("the link to the Mac went quiet")+ if not self._live():+ self._lost()return- self._enqueue({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": int(dx), "dy": int(dy)}})+ self._input({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": int(dx), "dy": int(dy)}})returnself._press_edge(int(dx), int(dy))@@@ -566,12 -481,14 +571,19 @@@try:desktop = self._desktop_module()monitors = self._cached_monitors()-- pointer = desktop.cursor_position()- outcome = model = None- for candidate in (self._corner_model, self._edge_model):- if candidate is None:- continue++ try:++ pointer = desktop.cursor_position()++ except Exception:++ if not self._edge_cursor_error_logged:++ LOGGER.warning("Could not read the cursor position; skipping this edge event", exc_info=True)++ self._edge_cursor_error_logged = True++ return++ self._edge_cursor_error_logged = False+ outcome = model = target = None+ for peer, candidate in list(self._models):result = candidate.feed(monitors, pointer, float(dx), float(dy))if result.action != return_edge.PASS:- outcome, model = result, candidate+ outcome, model, target = result, candidate, peerbreakif outcome is None:return@@@ -855,330 -808,186 +867,333 @@@finally:self._outbound.task_done()- def _process_outbound(self, message) -> None:- message_type = message.get("type")- if message_type not in _GATE_EXEMPT_TYPES and not self.redirecting and not message.get(_RELEASE_MARK):+ def _deliver(self, action) -> None:+ """Sends in the order the owner gave them, except that reading the clipboard (which can be+ slow) never holds up another peer's messages: what follows a clipboard read for the same+ peer waits for it, and everything else goes on. The clipboard's reads and writes go one at a+ time, in the order decided, on a thread of their own, so a read never overtakes a write+ decided before it."""+ if isinstance(action, owner_module.SetClipboard):+ self._on_clipboard(lambda message=action.message: self._set_clipboard(message))return- if message_type == _LOCAL_CLIPBOARD_SENTINEL_TYPE:- self._send_local_clipboard()+ peer = action.peer+ if isinstance(action, owner_module.Drop):+ # A hand-over given up before its answer: closing the link ends any ownership a late+ # accept began there, and it reconnects (WIRE.md section 5).+ self._forget_held(peer)+ self.links.close(peer, owner_module.DROPPED)return- if message_type in CONTROL_MESSAGE_TYPES:- self._send_raw(message)+ with self._clip_lock:+ waiting = self._clip_wait.get(peer)+ if waiting is not None:+ waiting.append(action)+ return+ if isinstance(action, owner_module.SendClipboard):+ waiting = self._clip_wait[peer] = collections.deque()+ try:+ self._on_clipboard_locked(lambda peer=peer: self._clipboard_then_rest(peer, waiting))+ except RuntimeError:+ # No thread at shutdown: nothing must wait behind a read that never starts.+ del self._clip_wait[peer]+ raise+ return+ self._send(peer, action.message)++ def _clipboard_then_rest(self, peer: bytes, waiting) -> None:+ """The clipboard for `peer`, then what `waiting` held behind it, in order. `waiting` belongs to+ the link it was made on: once that link is lost (`_forget_held`) none of it is sent, as the+ machine that reconnects will be taken afresh. A clipboard asked for again takes its turn+ among the clipboard's other work, behind any write decided before it."""+ try:+ self._send_clipboard(peer, waiting)+ except Exception:+ LOGGER.exception("The clipboard could not be sent")+ while True:+ with self._clip_lock:+ if self._clip_wait.get(peer) is not waiting:+ return+ if not waiting:+ del self._clip_wait[peer]+ return+ action = waiting.popleft()+ if isinstance(action, owner_module.SendClipboard):+ self._on_clipboard_locked(lambda peer=peer: self._clipboard_then_rest(peer, waiting))+ return+ try:+ self._send(peer, action.message)+ except Exception:+ LOGGER.exception("A message held behind the clipboard could not be sent")++ def _on_clipboard(self, job) -> None:+ with self._clip_lock:+ self._on_clipboard_locked(job)++ def _on_clipboard_locked(self, job) -> None:+ """Under `_clip_lock`: `job` done after every clipboard job before it, on the one thread+ that does them, started when there is none."""+ self._clip_jobs.append(job)+ if self._clip_busy:return- with self._sequence_lock:- self._last_sent_seq += 1- seq = self._last_sent_seq- data = dict(message.get("data", {}))- data["seq"] = seq- if self._send_raw({"type": message_type, "data": data}):- with self._sequence_lock:- self._unacked_sent_at.append((seq, self._last_send_at))-- def send_arrangement(self, mac_edge: str, set_at: int) -> bool:- """Tell the Mac where the machines are, when the change was made here."""- return self._send_raw(protocol.arrangement_msg(mac_edge, set_at))-- def _send_local_clipboard(self) -> None:try:- text, image = self._clipboard_module().changed_contents()+ threading.Thread(target=self._clipboard_worker, name="Beamer-links-clipboard", daemon=True).start()+ except RuntimeError:+ self._clip_jobs.pop()+ raise+ self._clip_busy = True++ def _clipboard_worker(self) -> None:+ while True:+ with self._clip_lock:+ if not self._clip_jobs:+ self._clip_busy = False+ return+ job = self._clip_jobs.popleft()+ try:+ job()+ except Exception:+ LOGGER.exception("Clipboard work failed")++ def _forget_held(self, peer: bytes) -> None:+ """`peer`'s link is lost: what waited for its clipboard is for a link that is gone."""+ with self._clip_lock:+ self._clip_wait.pop(peer, None)++ for held in tuple(self._sent_names):++ if held[0] == peer:++ self._sent_names.pop(held, None)++ def _send(self, peer: bytes, message: dict) -> None:+ kind = message["type"]+ if kind == protocol.MSG_FOCUS:+ data = message["data"]+ message = protocol.focus_v6(+ data["route"], data["target"], data.get("edge"), data.get("offset"),+ data.get("resistance_px"), data.get("reach"), bool(data.get("stay")),+ )+ elif kind in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP):+ preserve = message.pop("_preserve_key_name", False)+ message = self._key_message(peer, message, preserve=preserve)+ if message is None:+ return+ if kind in INPUT_TYPES:+ if not self.links.send_input(peer, message):+ LOGGER.warning("input could not be sent to %s", self._name(peer))+ self._send_failed(peer)+ else:+ self.links.post(peer, message)++ def _key_message(self, peer: bytes, message: dict, preserve: bool = False) -> Optional[dict]:+ """The key as `peer` is sent it: named by the key table for the peer's platform and the+ user's style, and dropped when the peer does not take media keys."""+ data = message["data"]+ physical = data["key"]+ entry = self._peers.get(peer) or {}+ if physical in MEDIA_KEYS and "media_keys" not in self.links.caps(peer):+ return None+ held = (peer, physical)+ if message["type"] == protocol.MSG_KEYUP and held in self._sent_names and preserve:+ name = self._sent_names[held]+ elif message["type"] == protocol.MSG_KEYUP and held in self._sent_names:+ # The release leaves under the name its press went under, whatever the style says now.+ name = self._sent_names.pop(held)+ elif message["type"] == protocol.MSG_KEYDOWN and held in self._sent_names:+ # So does each auto-repeat of it.+ name = self._sent_names[held]+ else:+ style = self._setting("modifier_style", "semantic")+ try:+ name = keytable.wire_name(physical, OWN_PLATFORM, entry.get("platform") or "", style)+ except ValueError:+ name = physical+ if message["type"] == protocol.MSG_KEYDOWN:+ self._sent_names[held] = name+ return {"type": message["type"], "data": dict(data, key=name)}++ def _send_failed(self, peer: bytes) -> None:+ self.links.close(peer)+ self._forget_held(peer)+ self._feed(lambda o: o.link_down(peer))++ def _feed(self, call) -> None:+ with self._lock:+ actions = call(self._owner)+ self._queue(actions)+ self._report(actions)++ # -- the clipboard ------------------------------------------------------++ def _note_clipboard(self) -> None:+ """Under the lock, before anything that may send the clipboard: whether it changed by this+ PC's own hand since this PC last sent or set it, which the owner needs to know (section 5)."""+ stamp = getattr(self._clipboard_module(), "change_stamp", lambda: None)()+ if stamp is not None and stamp != self._clipboard_stamp:+ self._clipboard_stamp = stamp+ self._owner.clipboard_changed()++ def _send_clipboard(self, peer: bytes, waiting) -> None:+ try:+ text, image = self._clipboard_module().get_contents()except Exception:- LOGGER.exception("Failed to read the local clipboard for the Mac")+ LOGGER.exception("Failed to read the local clipboard for %s", self._name(peer))return- if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:- LOGGER.warning("Local clipboard text too large; skipping the text")+ with self._clip_lock:+ if self._clip_wait.get(peer) is not waiting:+ return+ caps = self.links.caps(peer)+ if text and ("clipboard" not in caps or len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES):text = None- if image is not None and len(image) > protocol.CLIPBOARD_IMAGE_MAX_BYTES:- LOGGER.warning("Local clipboard image over the cap; skipping the image")+ if image is not None and ("clipboard_image" not in caps or not protocol.png_fits(image)):image = Noneif not text and image is None:return- self._send_raw(protocol.clipboard_msg(text or None, image))+ self.links.post(peer, protocol.clipboard_msg(text or None, image))- def _send_raw(self, message) -> bool:- with self._socket_lock:- sock, session = self._sock, self._session- if sock is None:- return False- try:- protocol.send_msg(sock, session, message)- self._last_send_at = self._clock()- return True- except (OSError, protocol.ProtocolError) as exc:- self._connection_failed(f"Sending to the Mac failed: {exc}", expected_socket=sock)- return False-- def _reader_worker(self) -> None:- active_socket = None- decoder = None- while not self._stop_event.is_set():- with self._socket_lock:- sock, session = self._sock, self._session- if sock is None:- active_socket = None- self._stop_event.wait(0.1)- continue- if sock is not active_socket:- active_socket = sock- decoder = FrameDecoder(session)- try:- chunk = sock.recv(4096)- except socket.timeout:- continue- except OSError as exc:- self._connection_failed(f"Receiving from the Mac failed: {exc}", expected_socket=sock)- active_socket = None- continue- if not chunk:- self._connection_failed("The Mac closed the connection", expected_socket=sock)- active_socket = None- continue- try:- for message in decoder.feed(chunk):- self._handle_inbound(message)- except protocol.AuthenticationError:- self._connection_failed(AUTH_FAILED_STATUS, expected_socket=sock)- active_socket = None- except protocol.ProtocolError as exc:- self._connection_failed(f"Invalid stream from the Mac: {exc}", expected_socket=sock)- active_socket = None- except Exception as exc:- # The same outcome as a malformed frame: this connection goes,- # the thread stays, and the next connection gets a reader.- LOGGER.exception("inbound handling failed")- self._connection_failed(f"Inbound message from the Mac failed: {exc}", expected_socket=sock)- active_socket = None-- def _handle_inbound(self, message) -> None:- message_type = message.get("type")- if not isinstance(message_type, str) or not message_type:- raise protocol.ProtocolError(f"malformed inbound message: {message!r}")- with self._sequence_lock:- self._last_ack_at = self._clock()- if message_type == protocol.MSG_ACK:- self._record_ack(message)+ def _set_clipboard(self, message: dict) -> None:+ read = protocol.read_clipboard(message)+ if read is None or (read["text"] is None and read["image"] is None):return- if message_type == protocol.MSG_CLIPBOARD:- self._apply_inbound_clipboard(message.get("data", {}))+ try:+ self._clipboard_module().set_contents(read["text"], read["image"])+ except Exception:+ LOGGER.exception("Failed to set the local clipboard")return- if message_type == protocol.MSG_SWITCH:- self._handle_switch(message.get("data", {}))+ self._clipboard_stamp = getattr(self._clipboard_module(), "change_stamp", lambda: None)()++ # -- what the owner reports ---------------------------------------------++ def _moved(self, moved: owner_module.Moved) -> None:+ if moved.to is not None:+ self._last_on = protocol.id_text(moved.to)+ if self._pin_point is None:+ self._pin_point = self._desktop_module().cursor_position()+ LOGGER.info("input is on %s%s", self._name(moved.to), _at_edge(moved.edge))+ self._report_redirecting(True)return- if message_type == protocol.MSG_ARRANGEMENT:- read = protocol.read_arrangement(message.get("data"))- if read is not None and self._arrangement_callback is not None:- try:- self._arrangement_callback(*read)- except Exception:- LOGGER.exception("Arrangement callback failed")+ self._pin_point = None+ self._ignore_gate.reset()+ # A fresh set of models, not a reset one: a model disarms itself at breakthrough so a burst+ # of deltas still in flight cannot cross twice, and nothing else re-arms it.+ with self._lock:+ self._arm_locked()+ LOGGER.info("input returned to this PC (%s)%s", moved.why, _at_edge(moved.edge))+ self._report_redirecting(False)+ if moved.edge in return_edge.EDGES and isinstance(moved.offset, (int, float)):+ self._land(moved.edge, moved.offset)+ elif moved.why in ("asked", "switch"):+ self._report_arrival(None)+ else:+ other = ""+ if isinstance(moved.other, bytes) and moved.other != self._own_id:+ other = peerlist.label_for(self._entries, peer_id=protocol.id_text(moved.other))+ reason = peerlist.refusal_text(moved.why, self._name(moved.left), other)+ if reason is None:+ reason = HOME_REASONS.get(moved.why, "{name} returned the input").format(name=self._name(moved.left))+ self._alert(reason)++ def _land(self, edge: str, offset: float) -> None:+ """The peer pushed the pointer back through its zone: land it on the edge of this PC it comes+ back to."""+ try:+ desktop = self._desktop_module()+ x, y = return_edge.arrival_position(self._cached_monitors(), edge, offset)+ desktop.set_cursor_position(x, y)+ except Exception:+ LOGGER.exception("Could not place the pointer at the %s edge on arrival", edge)return+ self._report_arrival(edge, x, y)- def _record_ack(self, message) -> None:- data = message.get("data")- if not isinstance(data, dict):- raise protocol.ProtocolError("ACK data must be a JSON object")- seq = data.get("seq")- if isinstance(seq, bool) or not isinstance(seq, int) or seq < 0:- raise protocol.ProtocolError("ACK seq must be a non-negative integer")- with self._sequence_lock:- if seq < self._last_ack_seq:- raise protocol.ProtocolError("ACK seq moved backwards")- if seq > self._last_sent_seq:- raise protocol.ProtocolError("ACK seq is ahead of the sender")- advanced = seq > self._last_ack_seq- self._last_ack_seq = seq- if advanced:- self._measure_round_trip(seq, self._clock())-- def _measure_round_trip(self, seq, now) -> None:- """Under _sequence_lock. From the send of the event the ACK names, as on the Mac: the- receiver acknowledges the highest seq it has handled on a timer, so an older one would- only measure that timer."""- sent_at = None- while self._unacked_sent_at and self._unacked_sent_at[0][0] <= seq:- sent_seq, at = self._unacked_sent_at.popleft()- if sent_seq == seq:- sent_at = at- if sent_at is not None:- self._round_trips.append(now - sent_at)- self._round_trip_at = now-- def _apply_inbound_clipboard(self, data) -> None:- if not isinstance(data, dict):- return- text = data.get("text")- if not isinstance(text, str) or not text:- text = None- elif len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:- LOGGER.warning("Ignoring oversized inbound clipboard text from the Mac")- text = None- image = protocol.clipboard_image(data)- if text is None and image is None:+ def _report_arrival(self, edge, x=None, y=None) -> None:+ if self._arrival_callback is None:returntry:- self._clipboard_module().set_contents(text, image)+ if x is None:+ x, y = self._desktop_module().cursor_position()+ self._arrival_callback(edge, x, y)except Exception:- LOGGER.exception("Failed to set the local clipboard from the Mac")+ LOGGER.exception("Arrival callback failed")- def _watchdog_worker(self) -> None:- while not self._stop_event.wait(0.1):- self._watchdog_tick()+ def _report_redirecting(self, value: bool) -> None:+ if value == self._reported_redirecting:+ return+ self._reported_redirecting = value+ if self._redirect_callback is not None:+ self._call(self._redirect_callback, value)- def _watchdog_tick(self) -> bool:- if not self.connected:+ def _unreachable(self, action: owner_module.Unreachable) -> None:+ name = self._name(action.peer)+ if action.why == "unreachable" and not self.links.up(action.peer):+ if not self.wake(action.peer):+ self._alert(f"Cannot switch — {self._status_of(action.peer)}")+ return+ if action.why == "unreachable" and self._accepts.get(action.peer) is False:+ self._alert("Cannot switch — " + HOME_REASONS["not_allowed"].format(name=name))+ return+ other = ""+ if isinstance(action.other, bytes) and action.other != self._own_id:+ other = peerlist.label_for(self._entries, peer_id=protocol.id_text(action.other))+ reason = peerlist.refusal_text(action.why, name, other)+ if reason is None:+ reason = f"Cannot switch — {name} could not be reached"+ self._alert(reason)++ def _learn_hardware(self, peer: bytes) -> None:+ """A peer's hardware address, read from the ARP table while the entry is fresh, for the wake-up+ a later switch may need. Only when the peer did not say its own in its `welcome`."""+ entry = self._peers.get(peer) or {}- if entry.get("hw") or not entry.get("host"):++ if entry.get("port") == 0 or entry.get("hw") or not entry.get("host"):+ return+ try:+ address = self._mac_lookup(entry["host"])+ except Exception:+ LOGGER.exception("hardware address lookup failed")+ return+ if address and self.hw_learned is not None:+ LOGGER.info("learned the hardware address of %s from the ARP table", self._name(peer))+ self._call(self.hw_learned, peer, address)++ # -- waking -------------------------------------------------------------++ def wake(self, peer: Optional[bytes] = None) -> bool:+ """Sends a peer a wake-on-LAN packet and waits up to a minute for its link. Nothing is+ queued: the person switches again once it is up. False when there is no address to wake,+ the peer answered and refused (it is awake; waking it would hide why), or a wake is+ already in flight."""+ peer = peer or self.shortcut_target()+ entry = self._peers.get(peer) if peer is not None else None+ address = (entry or {}).get("hw") or ""- if not address or self.links.up(peer) or self.links.refused(peer):++ if (entry or {}).get("port") == 0 or not address or self.links.up(peer) or self.links.refused(peer):return False- now = self._clock()- with self._sequence_lock:- last_heartbeat = max(self._last_ack_at, self._connected_at)- if now - last_heartbeat > ACK_TIMEOUT_SECONDS:- self._connection_failed("The Mac stopped responding")- return True- if now - self._last_send_at >= PING_INTERVAL_SECONDS:- self._send_raw(protocol.ping_msg())- return False+ with self._wake_lock:+ if peer in self._waking:+ return True+ self._waking.add(peer)+ threading.Thread(target=self._wake_worker, args=(peer, address, entry), name="Beamer-wake", daemon=True).start()+ return True++ def _wake_worker(self, peer, address, entry) -> None:+ name = self._name(peer)+ started = self._clock()+ try:+ try:+ self._wake_sender(address, entry.get("host") or None)+ except (OSError, ValueError) as exc:+ LOGGER.warning("wake-on-LAN packet not sent: %s", exc)+ self._alert("Could not send the wake-up packet")+ return+ LOGGER.info("sent wake-on-LAN to %s", name)+ self._alert(WAKING_STATUS.format(name=name))+ while not self._stop_event.wait(WAKE_POLL_SECONDS):+ if self.links.up(peer):+ LOGGER.info("%s woke and connected", name)+ self._alert(f"{name} is awake — switch again to send input")+ return+ if self._clock() - started >= wol.WAKE_WINDOW_SECONDS:+ break+ if not self._stop_event.is_set():+ LOGGER.warning("%s did not answer within %.0fs of the wake-on-LAN packet", name, wol.WAKE_WINDOW_SECONDS)+ self._alert(NOT_WOKEN_STATUS.format(name=name))+ finally:+ with self._wake_lock:+ self._waking.discard(peer)# -- plumbing -----------------------------------------------------------@@@ -1299,183 -1143,11 +1314,183 @@@except 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")++ 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 protocol.linkable(entry) and not self._is_local(entry.get("host") or "")++ 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/portal_fakes.pyindex c45947f,0000000..0dc8407mode 100644,000000..100644--- a/win_app/tests/portal_fakes.py+++ b/win_app/tests/portal_fakes.py@@@ -1,185 -1,0 +1,188 @@@+"""Fakes for the Wayland back ends' seams: a session bus with a scripted desktop portal on it, and a+libei context the test feeds events into. Neither needs D-Bus, libei or Qt, so the portal modules'+tests run on every machine."""++import os+import threading+import time++import portal+++def variant(value):+ """A value as jeepney hands over each entry of an a{sv}: (signature, value)."""+ return ("v", value)+++def vardict(values: dict) -> dict:+ return {key: variant(value) for key, value in values.items()}+++class FakeBus:+ """The portal as a script: `answers[method]` is (code, results) for a method answered by a+ Response, or a callable taking the body and returning one; `returns[method]` is the body a+ plain call returns. Every call is recorded in `calls` as (interface, method, body)."""++ REQUESTS = {"CreateSession", "SelectDevices", "Start", "GetZones", "SetPointerBarriers"}++ def __init__(self, versions=None) -> None:+ self.unique_name = ":1.42"+ self.versions = versions or {}++ self.failures = {}+ self.answers = {}+ self.returns = {}+ self.calls = []+ self.closed = False+ self.aborted = False+ self._signals = []+ self._lock = threading.Lock()+ self._read, self._write = os.pipe()++ def call(self, path, interface, method, signature, body):+ if self.closed:+ raise portal.PortalError("the connection is closed")+ with self._lock:+ self.calls.append((interface, method, body))++ if method in self.failures:++ raise self.failures[method]+ if interface == portal.PROPERTIES and method == "Get":+ version = self.versions.get(body[0])+ if version is None:+ raise portal.PortalError("No such interface")+ return (("u", version),)+ if method in self.REQUESTS:+ options = next(item for item in body if isinstance(item, dict))+ token = options["handle_token"][1]+ request = f"/org/freedesktop/portal/desktop/request/1_42/{token}"+ answer = self.answers.get(method, (0, {}))+ if callable(answer):+ answer = answer(body)+ if answer is not None:+ code, results = answer+ self.emit(request, portal.REQUEST, "Response", (code, vardict(results)))+ return (request,)+ returned = self.returns.get(method, ())+ return returned(body) if callable(returned) else returned++ def emit(self, path, interface, member, body) -> None:+ with self._lock:+ self._signals.append(("signal", path, interface, member, body))+ os.write(self._write, b"x")++ def receive(self, timeout):+ with self._lock:+ found, self._signals = self._signals, []+ if not found and timeout > 0:+ time.sleep(min(timeout, 0.01))+ return found++ def made(self, method):+ with self._lock:+ return [body for _interface, name, body in self.calls if name == method]++ def fileno(self):+ return self._read++ def abort(self):+ self.aborted = True+ self.closed = True++ def close(self):+ self.closed = True+++class FakeDevice:+ def __init__(self, name, caps, regions=(), keymap=None) -> None:+ self.name = name+ self.caps = set(caps)+ self._regions = list(regions)+ self._keymap = keymap++ def has(self, cap):+ return cap in self.caps++ def regions(self):+ return list(self._regions)++ def keymap(self):+ return self._keymap++ def __repr__(self):+ return f"FakeDevice({self.name})"+++class FakeEi:+ """A libei context: `feed(*events)` queues events for the next events(); what is sent is in+ `sent`, as (call, device name, *args)."""++ def __init__(self, fd=None) -> None:+ self.fd = fd+ self._events = []+ self._lock = threading.Lock()+ self.sent = []+ self.bound = []+ self.closed = False+ self._read, self._write = os.pipe()++ def feed(self, *events) -> None:+ with self._lock:+ self._events.extend(events)+ os.write(self._write, b"x")++ def events(self):+ with self._lock:+ found, self._events = self._events, []+ return found++ def fileno(self):+ return self._read++ def bind(self, seat):+ self.bound.append(seat)++ def _record(self, call, device, *args):+ with self._lock:+ self.sent.append((call, device.name) + args)++ def start(self, device, sequence):+ self._record("start", device, sequence)++ def stop(self, device):+ self._record("stop", device)++ def frame(self, device):+ self._record("frame", device)++ def motion(self, device, dx, dy):+ self._record("motion", device, dx, dy)++ def absolute(self, device, x, y):+ self._record("absolute", device, x, y)++ def button(self, device, code, down):+ self._record("button", device, code, down)++ def scroll(self, device, dx, dy):+ self._record("scroll", device, dx, dy)++ def scroll_discrete(self, device, dx, dy):+ self._record("scroll_discrete", device, dx, dy)++ def key(self, device, code, down):+ self._record("key", device, code, down)++ def sends(self, call=None):+ with self._lock:+ return [item for item in self.sent if call is None or item[0] == call]++ def close(self):+ self.closed = True+++def wait_for(condition, timeout=3.0, what="the condition"):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if condition():+ return+ time.sleep(0.01)+ raise AssertionError(f"timed out waiting for {what}")diff --cc win_app/tests/render_settings_layout.pyindex 0000000,0000000..1f745e9new file mode 100644--- /dev/null+++ b/win_app/tests/render_settings_layout.py@@@ -1,0 -1,0 +1,317 @@@++"""Render the synthetic Qt settings pages offscreen across the layout matrix.++++Run with the worktree's Qt Python. The matrix mode starts a fresh process for every++width and scale because Qt reads scale settings before QApplication is constructed.++"""++++from __future__ import annotations++++import json++import os++import subprocess++import sys++import unittest++from concurrent.futures import ThreadPoolExecutor++from pathlib import Path++++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")++ROOT = Path(__file__).resolve().parents[2]++TESTS = Path(__file__).resolve().parent++sys.path.insert(0, str(ROOT))++sys.path.insert(0, str(ROOT / "win_app"))++sys.path.insert(0, str(TESTS))++++from PySide6.QtCore import QCoreApplication, QEvent, QPoint, Qt++from PySide6.QtGui import QColor, QImage, QPainter, QFont++from PySide6.QtWidgets import QApplication, QFrame, QWidget++++import pages_win++import theme++from test_settings_layout_acceptance import SyntheticWindow, write_synthetic_settings++++++WIDTHS = (320, 640, 900, 1440, 1920)++SCALES = ("1.0", "1.25", "1.5", "2.0")++HEIGHT = 900++OUT = Path(os.environ.get("BEAMER_RENDER_OUT", ROOT / "renders"))++++++def capture_document(page):++ raster = page.grab().toImage()++ canvas = QImage(raster.size(), QImage.Format.Format_ARGB32_Premultiplied)++ canvas.setDevicePixelRatio(raster.devicePixelRatio())++ canvas.fill(QColor(theme.colour("ground")))++ painter = QPainter(canvas)++ painter.drawImage(0, 0, raster)++ painter.end()++ return canvas++++++def settle(app):++ for _ in range(8):++ QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)++ QCoreApplication.sendPostedEvents(None, QEvent.Type.LayoutRequest)++ app.processEvents()++++++def rect_in(widget, origin):++ point = widget.mapTo(origin, QPoint())++ return [point.x(), point.y(), widget.width(), widget.height()]++++++def descendants(widget):++ return [widget, *widget.findChildren(QWidget)]++++++def widget_record(widget, origin):++ return {++ "class": type(widget).__name__,++ "name": widget.objectName(),++ "text": widget.text() if hasattr(widget, "text") else None,++ "rect": rect_in(widget, origin),++ "minimum": [widget.minimumWidth(), widget.minimumHeight()],++ "maximum": [widget.maximumWidth(), widget.maximumHeight()],++ "visible": widget.isVisible(),++ "dpr": widget.devicePixelRatioF(),++ }++++++def measurements(window, key, width, scale):++ scroll = window.stack.currentWidget()++ page = scroll.widget()++ column = page.findChild(QWidget, "page_column")++ modules = [child for child in page.findChildren(QFrame)++ if child.property("vernier") == "module" and child.isVisible()]++ visible = [child for child in descendants(column) if child.isVisible()]++ overflowing = []++ for child in visible:++ rect = child.rect()++ point = child.mapTo(column, QPoint())++ if point.x() < 0 or point.x() + rect.width() > column.width() + 1:++ overflowing.append(widget_record(child, column))++ row_groups = {}++ for attr in ("glow_style_choice", "switch_style_choice"):++ group = getattr(window, attr, None)++ if group is None:++ continue++ row_groups[attr] = {++ family: [widget_record(tile, group.view) for tile in choices._tiles.values()]++ for family, choices in group.groups.items()++ }++ swatches = getattr(window, "glow_colour_choice", None)++ return {++ "page": key,++ "requested_width_dip": width,++ "requested_height_dip": HEIGHT,++ "actual_window_dip": [window.width(), window.height()],++ "actual_client_dip": [window.contentsRect().width(), window.contentsRect().height()],++ "scale": float(scale),++ "window_dpr": window.devicePixelRatioF(),++ "raster_size": [window.grab().width(), window.grab().height()],++ "application_font": {++ "family": QApplication.instance().font().family(),++ "point_size": QApplication.instance().font().pointSizeF(),++ "pixel_size": QApplication.instance().font().pixelSize(),++ "weight": int(QApplication.instance().font().weight()),++ },++ "sidebar": widget_record(window.sidebar, window),++ "page_column": widget_record(column, page),++ "viewport": [scroll.viewport().width(), scroll.viewport().height()],++ "document": [page.width(), page.height()],++ "sections": [widget_record(module, page) for module in modules],++ "overflowing_children": overflowing,++ "style_families": row_groups,++ "swatches": ({value: widget_record(sw, swatches.view)++ for value, sw in swatches._swatches.items()} if swatches else {}),++ "selected_sidebar": [name for name, button in window.sidebar._buttons.items()++ if button.isChecked()],++ "focused_sidebar": [name for name, button in window.sidebar._buttons.items()++ if button.hasFocus()],++ }++++++def make_contact_sheet(images, destination, title, columns=4, tile_width=260, tile_height=190):++ label_height, padding = 25, 12++ rows = (len(images) + columns - 1) // columns++ sheet = QImage(columns * (tile_width + padding) + padding,++ rows * (tile_height + label_height + padding) + padding + 30,++ QImage.Format.Format_ARGB32_Premultiplied)++ sheet.fill(0xFF202124)++ painter = QPainter(sheet)++ painter.setPen(Qt.GlobalColor.white)++ painter.setFont(QFont("Hanken Grotesk", 11))++ painter.drawText(padding, 18, title)++ for index, (label, path) in enumerate(images):++ image = QImage(str(path))++ if image.isNull():++ painter.end()++ raise RuntimeError(f"could not read render {path}")++ col, row = index % columns, index // columns++ x = padding + col * (tile_width + padding)++ y = 30 + padding + row * (tile_height + label_height + padding)++ scaled = image.scaled(tile_width, tile_height, Qt.AspectRatioMode.KeepAspectRatio,++ Qt.TransformationMode.SmoothTransformation)++ painter.drawText(x, y + label_height - 6, label)++ painter.drawImage(x, y + label_height, scaled)++ painter.end()++ if not sheet.save(str(destination)):++ raise RuntimeError(f"could not save contact sheet {destination}")++++++def run_case(width, scale):++ cell = OUT / f"width-{width}-scale-{scale}"++ cell.mkdir(parents=True, exist_ok=True)++ app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ app.setFont(theme.font(theme.TYPE["body"]))++ font = app.font()++ if not font.family().lower().startswith("hanken"):++ raise RuntimeError(f"real application font not active: {font.family()!r}")++++ import tempfile++ from core.tests import responder_harness++++ scratch = OUT / "test-working"++ scratch.mkdir(parents=True, exist_ok=True)++ synthetic_dir = tempfile.TemporaryDirectory(prefix="beamer-layout-render-", dir=scratch)++ config_dir = Path(synthetic_dir.name)++ window = SyntheticWindow(write_synthetic_settings(config_dir))++ window.full_screen_timer.stop()++ window.refresh_timer.stop()++ window.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, True)++ window.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)++ window.resize(width, HEIGHT)++ window.show()++ settle(app)++ actual_dpr = window.devicePixelRatioF()++ if abs(actual_dpr - float(scale)) > 0.01:++ window.server.stop()++ window.close()++ synthetic_dir.cleanup()++ raise RuntimeError(f"requested Qt scale {scale}, window reports DPR {actual_dpr}")++ all_measures, sheet_images = [], []++ try:++ for key, _name, _purpose in pages_win.PAGES:++ window._select_page(key)++ settle(app)++ scroll = window.stack.currentWidget()++ page = scroll.widget()++ page_images = []++ for position in ("top", "middle", "bottom"):++ bar = scroll.verticalScrollBar()++ if position == "top":++ bar.setValue(bar.minimum())++ elif position == "middle":++ bar.setValue((bar.minimum() + bar.maximum()) // 2)++ else:++ bar.setValue(bar.maximum())++ settle(app)++ path = cell / f"{key}-{position}.png"++ image = window.grab().toImage()++ if image.isNull() or not image.save(str(path)):++ raise RuntimeError(f"QWidget.grab() failed for {path}")++ page_images.append((position, path))++ sheet_images.append((f"{key} {position}", path))++ full_path = cell / f"{key}-full-document.png"++ full_image = capture_document(page)++ if full_image.isNull() or not full_image.save(str(full_path)):++ raise RuntimeError(f"full document grab failed for {full_path}")++ sheet_images.append((f"{key} full", full_path))++ all_measures.append(measurements(window, key, width, scale))++ print(f"rendered {key}: window={window.width()}x{window.height()} DIP, "++ f"dpr={window.devicePixelRatioF()}, font={font.family()}", flush=True)++ (cell / "measurements.json").write_text(json.dumps(all_measures, indent=2) + "\n")++ make_contact_sheet(sheet_images, cell / "contact-sheet.png",++ f"Qt settings · {width} DIP · {scale}x · Hanken Grotesk")++ finally:++ window.server.stop()++ window.close()++ window.deleteLater()++ app.processEvents()++ synthetic_dir.cleanup()++++++def run_matrix():++ cells = [(width, scale) for width in WIDTHS for scale in SCALES]++++ def render_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 = OUT / f"width-{width}-scale-{scale}.log"++ OUT.mkdir(parents=True, exist_ok=True)++ with log_path.open("w", encoding="utf-8") as log:++ result = subprocess.run(++ [sys.executable, str(Path(__file__).resolve()), "--case", str(width), scale],++ env=env, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, text=True,++ )++ return cell, result.returncode, log_path++++ with ThreadPoolExecutor(max_workers=2) as workers:++ results = list(workers.map(render_cell, cells))++ failures = [item for item in results if item[1]]++ print(f"render matrix: cells={len(results)} passed={len(results) - len(failures)} "++ f"failed={len(failures)} contact-sheets={len(results)} path={OUT}")++ if failures:++ print("failed cells: " + ", ".join(++ f"{cell[0]}@{cell[1]}x" for cell, _status, _log in failures), file=sys.stderr)++ raise SystemExit(1)++++++def comparison_sheets(qt_root):++ mac_root = ROOT.parent / "laymac" / "renders"++ app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ app.setFont(theme.font(theme.TYPE["body"]))++ for width in WIDTHS:++ images = []++ for key, name, _purpose in pages_win.PAGES:++ mac = mac_root / f"{key}-{width}-2x-top.png"++ qt = qt_root / f"width-{width}-scale-2.0" / f"{key}-top.png"++ if not mac.exists() or not qt.exists():++ raise RuntimeError(f"missing comparison render: {mac} or {qt}")++ images.extend(((f"Mac · {name}", mac), (f"Qt · {name}", qt)))++ make_contact_sheet(images, OUT / f"mac-against-qt-{width}-2x.png",++ f"Mac / Qt · {width} logical units · 2x", columns=2,++ tile_width=640, tile_height=600)++ print(f"comparison sheets: widths={len(WIDTHS)} pages={len(pages_win.PAGES)} path={OUT}")++++++def run_test_suite(selectors=()):++ app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ app.setFont(theme.font(theme.TYPE["body"]))++ if not app.font().family().lower().startswith("hanken"):++ raise RuntimeError(f"suite did not start with Hanken Grotesk: {app.font().family()!r}")++ print(f"test suite application font={app.font().family()} point={app.font().pointSizeF()} "++ f"pixel={app.font().pixelSize()}", flush=True)++ if selectors:++ suite = unittest.TestSuite(++ unittest.defaultTestLoader.loadTestsFromName(selector) for selector in selectors++ )++ else:++ suite = unittest.defaultTestLoader.discover(str(TESTS), pattern="test*.py")++ class QtTestResult(unittest.TextTestResult):++ def stopTest(self, test):++ # processEvents alone retains deleteLater windows and their refresh timers.++ QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)++ super().stopTest(test)++++ result = unittest.TextTestRunner(verbosity=2, resultclass=QtTestResult).run(suite)++ raise SystemExit(0 if result.wasSuccessful() else 1)++++++if __name__ == "__main__":++ if len(sys.argv) == 2 and sys.argv[1] == "--matrix":++ run_matrix()++ elif len(sys.argv) == 3 and sys.argv[1] == "--compare":++ comparison_sheets(Path(sys.argv[2]))++ elif len(sys.argv) >= 2 and sys.argv[1] == "--test-suite":++ run_test_suite(sys.argv[2:])++ elif len(sys.argv) == 4 and sys.argv[1] == "--case":++ run_case(int(sys.argv[2]), sys.argv[3])++ else:++ print("usage: render_settings_layout.py --matrix | --case WIDTH SCALE", file=sys.stderr)++ raise SystemExit(2)diff --cc win_app/tests/test_app_config.pyindex 61bfd98,69a51ec..d6e575c--- a/win_app/tests/test_app_config.py+++ b/win_app/tests/test_app_config.py@@@ -45,7 -41,7 +45,9 @@@ class EdgeGlowConfigTests(unittest.Testdef test_style_and_colour_default_to_the_original_look_and_round_trip(self):config = config_from_dict(dict(BASE))-- self.assertEqual((config.glow_style, config.glow_colour), ("glow", "signal"))++ self.assertEqual((config.glow_style, config.glow_colour), ("glow", "colourful"))++ existing = config_from_dict({**BASE, "glow_colour": "signal"})++ self.assertEqual(existing.glow_colour, "signal")config = config_from_dict({**BASE, "glow_style": "beam", "glow_colour": "sunset"})saved = config_to_dict(config)self.assertEqual((saved["glow_style"], saved["glow_colour"]), ("beam", "sunset"))@@@ -56,8 -52,8 +58,19 @@@self.assertEqual(app_config.GLOW_COLOURS, tuple(tokens.PALETTES) + effects.PACK_IDS)++ def test_all_original_saved_colours_keep_their_id_and_stops(self):++ from pathlib import Path++ import json++ fixture = Path(__file__).resolve().parents[2] / 'core/tests/colour_packs_rc3.json'++ for value, stops in json.loads(fixture.read_text()).items():++ with self.subTest(value=value):++ saved = config_to_dict(config_from_dict({**BASE, 'glow_colour': value}))++ loaded = config_from_dict(saved)++ self.assertEqual(loaded.glow_colour, value)++ self.assertEqual(app_config.palette_colours(loaded.glow_colour), tuple(stops))++def test_every_crossing_effect_and_pack_is_accepted_and_round_trips(self):- import effects+ from core import effectsfor style in effects.EFFECT_IDS:with self.subTest(style=style):diff --cc win_app/tests/test_appearance_contrast.pyindex 0000000,0000000..810373cnew file mode 100644--- /dev/null+++ b/win_app/tests/test_appearance_contrast.py@@@ -1,0 -1,0 +1,241 @@@++"""Every settings page, rendered offscreen in Light and in Dark, read back as pixels: each piece of++text against what is behind it, the module cards against the palette, and both after the++appearance changes with the window already built and another page open. The Mac twin of this++check caught 1.5.0-rc.5 leaving the hidden pages' cards dark after Light was chosen on Design.++++BEAMER_RENDERS=<folder> also writes each page at 900 DIP in both appearances."""++++from __future__ import annotations++++import os++import sys++import tempfile++import unittest++from collections import Counter++from pathlib import Path++from unittest import mock++++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"))++sys.path.insert(0, str(Path(__file__).resolve().parent))++++from PySide6.QtCore import QCoreApplication, QEvent, QPoint, Qt # noqa: E402++from PySide6.QtGui import QColor, QPalette # noqa: E402++from PySide6.QtWidgets import QAbstractButton, QApplication, QLabel, QWidget # noqa: E402++++import motion # noqa: E402++import pages_win # noqa: E402++import theme # noqa: E402++import tokens # noqa: E402++from test_settings_layout_acceptance import SyntheticWindow, write_synthetic_settings # noqa: E402++++WIDTH = 900++KEYS = tuple(key for key, _name, _purpose in pages_win.PAGES)++++++def _luminance(rgb):++ def channel(value):++ return value / 12.92 if value <= 0.03928 else ((value + 0.055) / 1.055) ** 2.4++ red, green, blue = (channel(value) for value in rgb)++ return 0.2126 * red + 0.7152 * green + 0.0722 * blue++++++def contrast(first, second):++ lighter, darker = sorted((_luminance(first), _luminance(second)), reverse=True)++ return (lighter + 0.05) / (darker + 0.05)++++++def _rgb(colour: QColor):++ return colour.redF(), colour.greenF(), colour.blueF()++++++class AppearanceContrast(unittest.TestCase):++ maxDiff = None++++ @classmethod++ def setUpClass(cls):++ cls.app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ cls.app.setFont(theme.font(theme.TYPE["body"]))++ cls.folder = tempfile.TemporaryDirectory(prefix="beamer-contrast-")++ cls.window = SyntheticWindow(write_synthetic_settings(Path(cls.folder.name)))++ cls.window.full_screen_timer.stop()++ cls.window.refresh_timer.stop()++ cls.window.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, True)++ cls.window.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)++ cls.window.resize(WIDTH, 900)++ cls.window.show()++ cls.renders = os.environ.get("BEAMER_RENDERS")++ # The cross-fade's ghost of the old palette would sit over the grab; measured is the++ # settled window, as with reduced motion.++ cls.still = mock.patch.object(motion, "reduced", return_value=True)++ cls.still.start()++++ @classmethod++ def tearDownClass(cls):++ cls.still.stop()++ cls.window.server.stop()++ cls.window.close()++ cls.window.deleteLater()++ QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)++ cls.app.processEvents()++ theme.set_dark(True)++ cls.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 choose(self, choice):++ self.window.appearance_choice.set_value(choice)++ self.window._apply_appearance(choice)++ self.settle()++++ def show_page(self, key):++ """The page at 900 DIP, the window tall enough that the whole page is in view."""++ window = self.window++ window._select_page(key)++ window.resize(WIDTH, 900)++ self.settle()++ scroll = window.stack.currentWidget()++ document = scroll.widget()++ chrome = window.height() - scroll.viewport().height()++ window.resize(WIDTH, document.sizeHint().height() + chrome + 2)++ self.settle()++ return window.grab().toImage()++++ @staticmethod++ def ground(image, rect, ratio):++ counts = Counter()++ steps_x, steps_y = 24, 8++ for i in range(steps_x):++ for j in range(steps_y):++ x = int((rect.x() + rect.width() * (i + 0.5) / steps_x) * ratio)++ y = int((rect.y() + rect.height() * (j + 0.5) / steps_y) * ratio)++ x = min(max(x, 0), image.width() - 1)++ y = min(max(y, 0), image.height() - 1)++ counts[image.pixelColor(x, y).rgb()] += 1++ return QColor.fromRgb(counts.most_common(1)[0][0])++++ @staticmethod++ def strongest(image, rect, ratio, behind):++ best, best_value = behind, 1.0++ for y in range(int(rect.y() * ratio), int((rect.y() + rect.height()) * ratio)):++ for x in range(int(rect.x() * ratio), int((rect.x() + rect.width()) * ratio)):++ colour = image.pixelColor(min(x, image.width() - 1), min(y, image.height() - 1))++ value = contrast(_rgb(colour), _rgb(behind))++ if value > best_value:++ best, best_value = colour, value++ return best++++ def texts(self):++ for widget in self.window.findChildren(QWidget):++ if isinstance(widget, QLabel):++ text, role = widget.text(), QPalette.ColorRole.WindowText++ if widget.textFormat() == Qt.TextFormat.RichText or "<" in text:++ continue++ elif isinstance(widget, QAbstractButton):++ text, role = widget.text(), QPalette.ColorRole.ButtonText++ else:++ continue++ if not text.strip() or not widget.isVisibleTo(self.window) or not widget.isEnabled():++ continue++ if widget.width() < 2 or widget.height() < 2:++ continue++ yield widget, text, role++++ def check_text(self, image, label):++ failures, checked = [], 0++ ratio = image.devicePixelRatio()++ for widget, text, role in self.texts():++ origin = widget.mapTo(self.window, QPoint())++ rect = widget.rect().translated(origin)++ if rect.bottom() > self.window.height() or rect.right() > self.window.width():++ continue++ behind = self.ground(image, rect, ratio)++ ink = widget.palette().color(role)++ if isinstance(widget, QAbstractButton) and widget.isChecked():++ # A :checked rule recolours the text without touching the palette, so the ink is++ # read off the pixels: the one that stands out most from the ground.++ ink = self.strongest(image, rect, ratio, behind)++ size = widget.font().pointSizeF() if widget.font().pointSizeF() > 0 else widget.font().pixelSize() * 0.75++ bold = widget.font().weight() >= 700++ needed = 3.0 if size >= 18 or (size >= 14 and bold) else 4.5++ value = contrast(_rgb(ink), _rgb(behind))++ checked += 1++ if value < needed:++ failures.append(f"{label}: {type(widget).__name__} {text[:40]!r} {value:.2f} < {needed}")++ return checked, failures++++ def check_cards(self, image, label):++ """Every module card in view measures as `panel` in the palette in use."""++ palette = tokens.PALETTE if theme.is_dark() else tokens.PALETTE_LIGHT++ panel = QColor(palette["panel"])++ ratio = image.devicePixelRatio()++ page = self.window.stack.currentWidget()++ failures, cards = [], 0++ for widget in page.findChildren(QWidget):++ if widget.property("vernier") != "module" or not widget.isVisibleTo(self.window):++ continue++ point = widget.mapTo(self.window, QPoint(6, 6))++ if point.y() >= self.window.height():++ continue++ cards += 1++ measured = image.pixelColor(int(point.x() * ratio), int(point.y() * ratio))++ if max(abs(a - b) for a, b in zip(_rgb(measured), _rgb(panel))) > 3 / 255:++ failures.append(f"{label}: card at {point.x()},{point.y()} measures {measured.name()} not {panel.name()}")++ return cards, failures++++ def sweep(self, appearance):++ checked = cards = 0++ failures = []++ for key in KEYS:++ image = self.show_page(key)++ count, text_failures = self.check_text(image, f"{appearance}/{key}")++ panels, card_failures = self.check_cards(image, f"{appearance}/{key}")++ checked += count++ cards += panels++ failures += text_failures + card_failures++ if self.renders:++ folder = Path(self.renders)++ folder.mkdir(parents=True, exist_ok=True)++ image.save(str(folder / f"qt-{key}-{appearance}-{WIDTH}.png"))++ return checked, cards, failures++++ def test_every_page_reads_in_dark_and_in_light_chosen_from_another_page(self):++ self.choose("dark")++ self.window._select_page("design")++ self.choose("light")++ self.assertFalse(theme.is_dark())++ checked, cards, failures = self.sweep("light")++ self.assertGreater(checked, 100)++ self.assertGreater(cards, 10)++ self.assertEqual(failures, [])++ self.window._select_page("crossing")++ self.choose("dark")++ checked, cards, failures = self.sweep("dark")++ self.assertGreater(checked, 100)++ self.assertGreater(cards, 10)++ self.assertEqual(failures, [])++++ def test_system_switching_while_the_window_exists_repaints_pages_out_of_view(self):++ self.choose("system")++ for dark in (False, True, False):++ self.window._select_page("overview" if dark else "keyboard")++ with mock.patch.object(theme, "system_dark", return_value=dark):++ self.window._apply_appearance()++ self.settle()++ self.assertEqual(theme.is_dark(), dark)++ image = self.show_page("crossing")++ _count, text_failures = self.check_text(image, f"system-{dark}/crossing")++ _cards, card_failures = self.check_cards(image, f"system-{dark}/crossing")++ self.assertEqual(text_failures + card_failures, [])++ self.choose("dark")++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_audit_regressions.pyindex 0000000,0000000..514bba0new file mode 100644--- /dev/null+++ b/win_app/tests/test_audit_regressions.py@@@ -1,0 -1,0 +1,64 @@@++"""Page regressions use the audit's raster ink, containment and overlap measurements."""++++import json++import os++from pathlib import Path++import subprocess++import sys++import tempfile++import unittest++++ROOT = Path(__file__).resolve().parents[2]++++++class PageAuditRegressions(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ output = ROOT / "renders" / "regressions"++ output.mkdir(parents=True, exist_ok=True)++ cls.directory = tempfile.TemporaryDirectory(dir=output)++ cls.addClassCleanup(cls.directory.cleanup)++ environment = dict(os.environ, QT_QPA_PLATFORM="offscreen", QT_SCALE_FACTOR="1.0",++ QT_QPA_FONTDIR=str(ROOT / "win_app" / "assets"))++ result = subprocess.run(++ [sys.executable, str(ROOT / "scripts/ui_audit/qt_audit.py"), "--platform", "windows",++ "--output", cls.directory.name, "--states", "none,one-long,three-long,five-shared-edge",++ "--sizes", "640x600,1000x800,1600x1000"],++ env=environment, capture_output=True, text=True)++ if result.returncode:++ raise RuntimeError(result.stdout + result.stderr)++ cls.records = json.loads((Path(cls.directory.name) / "measurements-1.0.json").read_text())++++ def reject(self, pages, predicate):++ found = [(record["path"], flag) for record in self.records if record["page"] in pages++ for flag in record["flags"] if predicate(flag)]++ if found:++ self.fail(f"{len(found)} audit faults; first three: {found[:3]}")++++ def test_direction_tracks_do_not_overlap_or_leave_their_container(self):++ self.reject({"directions"}, lambda f: f["kind"] == "sibling-overlap" and++ f.get("first") == "This PC drives it" or++ f["kind"] == "outside-parent" and f.get("widget") == "Switch")++++ def test_remove_confirmation_ink_and_buttons_are_contained(self):++ self.reject({"remove-confirmation"}, lambda f:++ f["kind"] == "label-ink" and f.get("text", "").startswith("Remove ") or++ f["kind"] == "outside-parent" and f.get("widget") in {"QPushButton", "ElidingButton"})++++ def test_arrangement_diagram_fits_its_allocation(self):++ self.reject({"crossing"}, lambda f: f["kind"] == "outside-parent" and++ f.get("widget") == "ArrangementDiagram")++++ def test_fixed_minimum_controls_fit_keyboard_and_crossing_rows(self):++ self.reject({"keyboard", "crossing"}, lambda f: f["kind"] == "outside-parent" and++ f.get("widget") in {"QPushButton", "ElidingButton"})++++ def test_wrapped_help_ink_is_not_cut(self):++ starts = ("This screen decides", "Changing a side updates", "On a Mac, Ctrl arrives",++ "At the ", "Beamer cannot", "On Wayland")++ self.reject({"overview", "keyboard", "crossing", "design"}, lambda f:++ f["kind"] == "label-ink" and f.get("text", "").startswith(starts))++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_capture_portal.pyindex d6b1748,0000000..df705b2mode 100644,000000..100644--- a/win_app/tests/test_capture_portal.py+++ b/win_app/tests/test_capture_portal.py@@@ -1,535 -1,0 +1,561 @@@+"""Wayland capture on fakes: the barriers that stand for each kind of zone, the press at a barrier+(push, slide, back into the screen), and the capture thread against a scripted InputCapture portal+and libei: a push that crosses, input while away, and every way home (the sender bringing it home,+a move back, a key at the edge, a pause, the desktop ending it, a stop, a dead connection, a+stalled thread)."""++import os+import sys+import time+import unittest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import capture_portal+import desktop_portal+import portal+from core import return_edge+from core.return_edge import Rect+from portal_fakes import FakeBus, FakeDevice, FakeEi, vardict, wait_for++ONE = [Rect(0, 0, 1920, 1080)]+SESSION = "/org/freedesktop/portal/desktop/session/1_42/beamer2"+++class BarrierTest(unittest.TestCase):+ def test_a_whole_edge_on_one_display(self):+ self.assertEqual(capture_portal.barriers([return_edge.ReturnEdge("right")], ONE), [("right", (1920, 0, 1920, 1079))])+ self.assertEqual(capture_portal.barriers([return_edge.ReturnEdge("top")], ONE), [("top", (0, 0, 1919, 0))])++ def test_an_edge_between_two_displays_has_no_barrier(self):+ side_by_side = [Rect(0, 0, 1920, 1080), Rect(1920, 0, 1920, 1080)]+ self.assertEqual(capture_portal.barriers([return_edge.ReturnEdge("right")], side_by_side), [("right", (3840, 0, 3840, 1079))])+ self.assertEqual(capture_portal.barriers([return_edge.ReturnEdge("top")], side_by_side),+ [("top", (0, 0, 1919, 0)), ("top", (1920, 0, 3839, 0))])++ def test_a_staggered_display_leaves_the_uncovered_stretch_of_its_neighbour(self):+ staggered = [Rect(0, 0, 1920, 1080), Rect(1920, 200, 1280, 1024)]+ self.assertEqual(capture_portal.barriers([return_edge.ReturnEdge("right")], staggered),+ [("right", (1920, 0, 1920, 199)), ("right", (3200, 200, 3200, 1223))])++ def test_thirds_are_split_where_part_of_splits_them(self):+ found = capture_portal.barriers([return_edge.PartEdge("left", {"middle"})], ONE)+ self.assertEqual(found, [("left", (0, 360, 0, 719))])+ self.assertEqual(return_edge.part_of(359 / 1080), "start")+ self.assertEqual(return_edge.part_of(360 / 1080), "middle")+ self.assertEqual(return_edge.part_of(720 / 1080), "end")+ both = capture_portal.barriers([return_edge.PartEdge("bottom", {"start", "end"})], ONE)+ self.assertEqual(both, [("bottom", (0, 1080, 639, 1080)), ("bottom", (1280, 1080, 1919, 1080))])++ def test_a_corner_is_its_two_walls_as_far_as_the_corner_push_reaches(self):+ found = capture_portal.barriers([return_edge.CornerPush("top_right", "right")], ONE)+ self.assertEqual(sorted(found), [("right", (1920, 0, 1920, 8)), ("top", (1911, 0, 1919, 0))])+ model = return_edge.CornerPush("top_right", "right")+ self.assertTrue(model._at_edge(ONE, (1919, 8)) and model._at_edge(ONE, (1911, 0)))+ self.assertFalse(model._at_edge(ONE, (1919, 9)) or model._at_edge(ONE, (1910, 0)))++ def test_a_notch_stretch_has_none_and_a_repeat_is_placed_once(self):+ models = [return_edge.SpanEdge("top", lambda: (100, 200)), return_edge.ReturnEdge("left"), return_edge.ReturnEdge("left")]+ self.assertEqual(capture_portal.barriers(models, ONE), [("left", (0, 0, 0, 1079))])+++class Clock:+ def __init__(self):+ self.now = 100.0++ def __call__(self):+ return self.now+++class PressTest(unittest.TestCase):+ def test_a_push_holds_a_slide_moves_along_and_a_move_back_lets_go_where_it_ends(self):+ clock = Clock()+ press = capture_portal.Press("right", (1920.0, 500.0), ONE, clock)+ self.assertEqual(press.point, (1919, 500))+ self.assertTrue(press.feed(6, 0))+ self.assertEqual(press.point, (1919, 500))+ self.assertTrue(press.feed(3, -10))+ self.assertEqual(press.point, (1919, 490))+ self.assertTrue(press.feed(0, 4))+ self.assertEqual(press.point, (1919, 494))+ self.assertFalse(press.feed(-5, 2))+ self.assertEqual(press.point, (1914, 496))++ def test_travel_past_the_display_is_not_kept(self):+ press = capture_portal.Press("right", (1920.0, 1075.0), ONE, Clock())+ press.feed(0, 100)+ self.assertEqual(press.point, (1919, 1079))+ press.feed(0, -10)+ self.assertEqual(press.point, (1919, 1069))++ def test_a_pause_in_the_push_is_idle(self):+ clock = Clock()+ press = capture_portal.Press("left", (0.0, 10.0), ONE, clock)+ press.feed(-4, 0)+ clock.now += capture_portal.IDLE_SECONDS / 2+ self.assertFalse(press.idle())+ press.feed(0, 3) # a slide is not a push+ clock.now += capture_portal.IDLE_SECONDS+ self.assertTrue(press.idle())+++class MemoryTokens:+ def __init__(self, token=""):+ self.token = token++ def read(self):+ return self.token++ def write(self, token):+ self.token = token+++class Harness:+ """A Hooks on a fake portal, its callbacks recorded, and a sender stand-in that crosses after+ `push_to_cross` pushes, as the zone model does."""++ def __init__(self, version=1, models=None, push_to_cross=2, tokens=None):+ self.bus = FakeBus(versions={capture_portal.INTERFACE: version})+ self.bus.answers["CreateSession"] = (0, {"session_handle": SESSION, "capabilities": 3})+ self.bus.answers["GetZones"] = (0, {"zones": [(1920, 1080, 0, 0)], "zone_set": 7})+ self.bus.answers["SetPointerBarriers"] = (0, {"failed_barriers": []})+ self.bus.returns["CreateSession2"] = (vardict({"session_handle": SESSION}),)+ self.bus.returns["ConnectToEIS"] = (99,)+ self.ei = FakeEi()+ self.keys, self.mice, self.motions, self.homes, self.failures = [], [], [], [], []+ self.away = False+ self.models = models if models is not None else [return_edge.ReturnEdge("right")]+ self.push_to_cross = push_to_cross+ self.tokens = tokens or MemoryTokens()+ self.hooks = capture_portal.Hooks(self._key, self._mouse, self._motion, connect=lambda: self.bus,+ ei=lambda fd: self.ei, tokens=self.tokens)+ self.hooks.grab_while(lambda: self.away)+ self.hooks.barriers_from(lambda: self.models)+ self.hooks.on_home = lambda: self.homes.append(True) or setattr(self, "away", False)+ self.hooks.on_failure = self.failures.append+ self.pointer = FakeDevice("captured relative pointer", {1, 16, 32})+ self.keyboard = FakeDevice("captured keyboard", {4})++ def _key(self, name, down, vk, us):+ self.keys.append((name, down, vk))+ return True++ def _mouse(self, message, x, y, data):+ self.mice.append((message, data))+ return True++ def _motion(self, dx, dy):+ self.motions.append((dx, dy))+ if len(self.motions) >= self.push_to_cross:+ self.away = True++ def start(self):+ self.hooks.start()+ wait_for(lambda: self.bus.made("Enable"), what="the session to be enabled")++ def activate(self, x=1920.0, y=500.0, barrier=1, activation=3):+ # libei's start sequence is the portal's activation id.+ self.ei.feed(("start", self.pointer, activation), ("start", self.keyboard, activation))+ self.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"activation_id": activation, "cursor_position": (x, y), "barrier_id": barrier})))+ wait_for(lambda: self.hooks.holding, what="the capture to begin")++ def cross(self):+ self.activate()+ self.ei.feed(*[("motion", self.pointer, 10.0, 0.0)] * self.push_to_cross)+ wait_for(lambda: self.away and self.hooks._away, what="input to go away")++ def releases(self):+ return [(body[1]["activation_id"][1], body[1]["cursor_position"][1]) for body in self.bus.made("Release")]++[email protected](sys.platform == "win32", "the Wayland back ends select on pipes, which Windows cannot; they run only on Linux")+class HooksTest(unittest.TestCase):+ def setUp(self):+ desktop_portal._position = None+ desktop_portal._zones = []+ desktop_portal._regions = []+ desktop_portal._captured = False+ self.harness = None++ def tearDown(self):+ if self.harness is not None:+ self.harness.hooks.stop()++ def make(self, **kwargs):+ self.harness = Harness(**kwargs)+ return self.harness++ def test_the_barriers_go_on_the_zones_and_the_session_is_enabled(self):+ h = self.make()+ h.start()+ listed = h.bus.made("SetPointerBarriers")[0][2]+ self.assertEqual([item["position"] for item in listed], [("(iiii)", (1920, 0, 1920, 1079))])+ self.assertEqual(h.bus.made("SetPointerBarriers")[0][3], 7)+ self.assertEqual(desktop_portal.monitors(), ONE)++ def test_a_push_crosses_input_goes_away_and_comes_home_where_the_sender_lands_it(self):+ h = self.make()+ h.start()+ h.cross()+ self.assertEqual(h.motions, [(10, 0), (10, 0)])+ self.assertEqual(desktop_portal.position(), (1919, 500))+ h.ei.feed(("key", h.keyboard, 1, True), ("frame", h.keyboard, 0), ("key", h.keyboard, 1, False), ("frame", h.keyboard, 0),+ ("button", h.pointer, 0x110, True), ("scroll_discrete", h.pointer, 0, 120), ("frame", h.pointer, 0),+ ("motion", h.pointer, 2.5, -1.5), ("motion", h.pointer, 0.5, 0.5), ("frame", h.pointer, 0))+ wait_for(lambda: len(h.motions) >= 3 and len(h.keys) == 2, what="the input away")+ self.assertEqual(h.keys, [("esc", True, 1), ("esc", False, 1)])+ self.assertEqual(h.mice, [(capture_portal._BUTTONS[1][0], 0),+ (capture_portal.WM_MOUSEWHEEL, capture_portal._wheel_data(-capture_portal.WHEEL_DELTA))])+ self.assertEqual(h.motions[2:], [(2, -1), (1, 0)])+ self.assertEqual(h.releases(), [])+ desktop_portal.set_cursor_position(0, 300)+ h.away = False+ wait_for(lambda: h.releases(), what="the let-go")+ self.assertEqual(h.releases(), [(3, (0.0, 300.0))])+ self.assertFalse(h.hooks.holding)++ def test_a_let_go_waits_a_moment_for_the_landing_the_sender_reports_after_input_comes_home(self):+ h = self.make()+ h.start()+ h.cross()+ h.away = False+ time.sleep(capture_portal.LANDING_SECONDS / 3)+ desktop_portal.set_cursor_position(0, 777)+ wait_for(lambda: h.releases(), what="the let-go")+ self.assertEqual(h.releases(), [(3, (0.0, 777.0))])+++ def test_a_paused_keyboard_releases_keys_held_by_that_device(self):++ h = self.make()++ h.start()++ h.cross()++ h.ei.feed(("key", h.keyboard, 29, True), ("frame", h.keyboard, 0))++ wait_for(lambda: h.keys, what="the held key to be forwarded")++ h.ei.feed(("device_paused", h.keyboard))++ wait_for(lambda: len(h.keys) == 2, what="the paused device's held key to be released")++ self.assertEqual([(name, down) for name, down, _vk in h.keys], [("cmd", True), ("cmd", False)])++ self.assertEqual(h.hooks._names_down, {})+++ def test_moving_back_into_the_screen_lets_go_there_and_sends_nothing(self):+ h = self.make()+ h.start()- h.activate()- h.ei.feed(("motion", h.pointer, -5.0, 2.0))++ h.cross()++ h.ei.feed(("key", h.keyboard, 29, True), ("frame", h.keyboard, 0))++ wait_for(lambda: h.keys, what="the held key to be forwarded")++ h.away = False++ desktop_portal.set_cursor_position(0, 502)+ wait_for(lambda: h.releases(), what="the let-go")- self.assertEqual(h.releases(), [(3, (1914.0, 502.0))])- self.assertEqual(h.motions, [])++ self.assertEqual(h.releases(), [(3, (0.0, 502.0))])+ self.assertFalse(h.hooks.holding)++ self.assertEqual(h.hooks._names_down, {})++ def test_a_key_at_the_edge_lets_go_and_reaches_nobody(self):+ h = self.make()+ h.start()+ h.activate()+ h.ei.feed(("key", h.keyboard, 30, True), ("frame", h.keyboard, 0))+ wait_for(lambda: h.releases(), what="the let-go")+ self.assertEqual(h.keys, [])++ def test_a_pause_in_the_push_lets_go_where_it_rests(self):+ h = self.make(push_to_cross=99)+ h.start()+ h.activate(y=40.0)+ h.ei.feed(("motion", h.pointer, 4.0, 0.0))+ wait_for(lambda: h.releases(), timeout=capture_portal.IDLE_SECONDS + 1, what="the let-go")+ self.assertEqual(h.releases(), [(3, (1919.0, 40.0))])+ self.assertEqual(h.motions, [(4, 0)])++ def test_events_ahead_of_the_activation_are_read_once_it_says_which_barrier(self):+ h = self.make()+ h.start()+ h.ei.feed(("start", h.pointer, 5), ("motion", h.pointer, 10.0, 0.0))+ time.sleep(0.15)+ self.assertEqual(h.motions, [])+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"activation_id": 5, "cursor_position": (1920.0, 9.0), "barrier_id": 1})))+ wait_for(lambda: h.motions, what="the early push")+ self.assertEqual(h.motions, [(10, 0)])++ def test_what_arrives_after_a_let_go_is_not_replayed_into_the_next_capture(self):+ h = self.make()+ h.start()+ h.activate()+ h.ei.feed(("motion", h.pointer, -5.0, 0.0))+ wait_for(lambda: h.releases(), what="the let-go")+ h.ei.feed(("motion", h.pointer, 7.0, 0.0), ("stop", h.pointer), ("stop", h.keyboard))+ time.sleep(0.15)+ h.activate(activation=4)+ time.sleep(0.15)+ self.assertEqual(h.motions, [])++ def test_a_barrier_it_does_not_know_is_let_go_at_once(self):+ h = self.make()+ h.start()+ h.ei.feed(("start", h.pointer, 1))+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"activation_id": 8, "cursor_position": (1920.0, 9.0), "barrier_id": 77})))+ wait_for(lambda: h.releases(), what="the let-go")+ self.assertEqual(h.releases(), [(8, (1919.0, 9.0))])++ def test_the_desktop_ending_a_capture_while_input_is_away_brings_it_home(self):+ h = self.make()+ h.start()+ h.cross()+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Deactivated",+ (SESSION, vardict({"activation_id": 3, "cursor_position": (1000.0, 10.0)})))+ wait_for(lambda: h.homes, what="input home")+ self.assertFalse(h.hooks.holding)+ self.assertEqual(desktop_portal.position(), (1000, 10))+ self.assertEqual(h.releases(), [])++ def test_disabled_sets_the_barriers_again_and_enables_the_session(self):+ h = self.make()+ h.start()+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Disabled", (SESSION, {}))+ wait_for(lambda: len(h.bus.made("Enable")) >= 2, what="the session enabled again")+ self.assertEqual(len(h.bus.made("SetPointerBarriers")), 2)++ def test_held_edges_take_the_barriers_away_and_their_return_puts_them_back(self):+ h = self.make()+ h.start()+ models = h.models+ h.models = []+ wait_for(lambda: len(h.bus.made("SetPointerBarriers")) == 2, what="the barriers removed")+ self.assertEqual(h.bus.made("SetPointerBarriers")[1][2], [])+ enables = len(h.bus.made("Enable"))+ h.models = models+ wait_for(lambda: len(h.bus.made("SetPointerBarriers")) == 3, what="the barriers back")+ wait_for(lambda: len(h.bus.made("Enable")) == enables + 1, what="enabled again")++ def test_a_stop_while_input_is_away_lets_go_and_ends_the_connection(self):+ h = self.make()+ h.start()+ h.cross()+ h.hooks.stop()+ self.assertEqual(len(h.releases()), 1)+ self.assertTrue(h.bus.closed and h.ei.closed)+ self.assertFalse(h.hooks.holding)++ def test_a_dead_input_connection_lets_go_ends_the_session_and_says_why(self):+ h = self.make()+ h.start()+ h.cross()+ h.ei.feed(("disconnect",))+ wait_for(lambda: h.failures, what="the failure")+ self.assertIn("stopped letting Beamer capture", h.failures[0].sentence)+ wait_for(lambda: h.bus.closed, what="the connection closed")+ self.assertEqual(len(h.releases()), 1)++ def test_a_stalled_thread_holding_input_has_its_connection_ended(self):+ saved = capture_portal.STALL_SECONDS+ capture_portal.STALL_SECONDS = 0.3+ try:+ h = self.make()+ h.start()+ h.activate()+ stalled = h.hooks._on_motion++ def stall(dx, dy):+ time.sleep(1.0)+ stalled(dx, dy)++ h.hooks._on_motion = stall+ h.ei.feed(("motion", h.pointer, 10.0, 0.0))+ wait_for(lambda: h.bus.aborted, timeout=2, what="the watchdog")+ finally:+ capture_portal.STALL_SECONDS = saved++ def test_a_refusal_is_said_in_the_apps_words_after_start_returns(self):+ h = self.make()+ h.bus.answers["CreateSession"] = (1, {})+ h.hooks.start()+ wait_for(lambda: h.failures, what="the refusal")+ self.assertEqual(h.failures[0].sentence, capture_portal.REFUSED)+- def test_no_input_capture_portal_fails_the_start_in_the_apps_words(self):++ def test_an_input_capture_portal_reporting_zero_uses_v1_session_creation(self):++ h = self.make(version=0)++ with self.assertLogs(capture_portal.LOGGER, level="INFO") as logs:++ h.start()++ self.assertEqual(len(h.bus.made("CreateSession")), 1)++ self.assertEqual(h.bus.made("CreateSession2"), [])++ self.assertIn("Requesting InputCapture session", "\n".join(logs.output))++++ def test_a_zero_version_input_capture_portal_reports_its_create_error(self):+ h = self.make(version=0)- with self.assertRaises(capture_portal.CaptureUnavailable) as raised:++ h.bus.failures = {"CreateSession": portal.PortalError("CreateSession: UnknownMethod")}++ with self.assertLogs(capture_portal.LOGGER, level="ERROR") as logs:+ h.hooks.start()- self.assertEqual(raised.exception.sentence, capture_portal.NO_PORTAL)++ wait_for(lambda: h.failures, what="the failed CreateSession")++ self.assertIsInstance(h.failures[0], capture_portal.CaptureUnavailable)++ self.assertIn("CreateSession: UnknownMethod", h.failures[0].sentence)++ self.assertIn("CreateSession: UnknownMethod", "\n".join(logs.output))++ # Review fixes (Codex Sol and a cold Opus pass, 01-10-2026)++ def test_a_release_that_fails_ends_the_session_rather_than_leaving_input_captured(self):+ h = self.make()+ h.start()+ h.activate()++ def broken(body):+ raise portal.PortalError("Release failed")++ h.bus.returns["Release"] = broken+ h.ei.feed(("motion", h.pointer, -5.0, 0.0))+ wait_for(lambda: h.failures, what="the failure")+ wait_for(lambda: h.bus.closed, what="the connection closed")++ def test_input_sent_away_with_nothing_captured_is_brought_home(self):+ h = self.make()+ h.start()+ h.away = True # the tray, or a driven machine's move that passed input_held() a moment too early+ wait_for(lambda: h.homes, what="input home")+ self.assertFalse(h.away)++ def test_input_sent_away_from_another_thread_during_a_press_keeps_the_key_that_follows(self):+ h = self.make(push_to_cross=99)+ h.start()+ h.activate()+ h.away = True+ h.ei.feed(("key", h.keyboard, 1, True), ("frame", h.keyboard, 0))+ wait_for(lambda: h.keys, what="the key away")+ self.assertEqual(h.keys, [("esc", True, 1)])+ self.assertEqual(h.releases(), [])++ def test_the_desktop_ending_a_press_the_sender_already_took_away_brings_it_home(self):+ h = self.make(push_to_cross=99)+ h.start()+ h.activate()+ h.away = True+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Deactivated", (SESSION, vardict({"activation_id": 3})))+ wait_for(lambda: h.homes, what="input home")++ def test_a_barrier_request_the_portal_never_answers_ends_the_capture(self):+ saved = capture_portal.REQUEST_SECONDS+ capture_portal.REQUEST_SECONDS = 0.3+ try:+ h = self.make()+ h.bus.answers["SetPointerBarriers"] = None+ h.hooks.start()+ wait_for(lambda: h.failures, what="the failure")+ finally:+ capture_portal.REQUEST_SECONDS = saved++ def test_an_activation_with_no_id_is_still_let_go(self):+ h = self.make(push_to_cross=99)+ h.start()+ h.ei.feed(("start", h.pointer, 1))+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"cursor_position": (1920.0, 500.0), "barrier_id": 1})))+ wait_for(lambda: h.hooks.holding, what="the capture")+ h.ei.feed(("motion", h.pointer, -5.0, 0.0))+ wait_for(lambda: h.bus.made("Release"), what="the let-go")+ self.assertNotIn("activation_id", h.bus.made("Release")[0][1])++ def test_a_push_that_meets_two_barriers_at_once_finds_its_wall_from_the_pointer(self):+ h = self.make(models=[return_edge.CornerPush("top_right", "right")], push_to_cross=99)+ h.start()+ h.activate(x=1920.0, y=3.0, barrier=0)+ h.ei.feed(("motion", h.pointer, 4.0, -4.0))+ wait_for(lambda: h.motions, what="the corner push")+ self.assertTrue(h.hooks.holding)++ def test_input_from_an_earlier_activation_never_feeds_a_later_one(self):+ h = self.make()+ h.start()+ h.ei.feed(("start", h.pointer, 3), ("motion", h.pointer, 10.0, 0.0), ("motion", h.pointer, 10.0, 0.0),+ ("stop", h.pointer), ("start", h.pointer, 4))+ time.sleep(0.15)+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"activation_id": 4, "cursor_position": (1920.0, 9.0), "barrier_id": 1})))+ wait_for(lambda: h.hooks.holding, what="the capture")+ time.sleep(0.15)+ self.assertEqual(h.motions, [])++ def test_a_landing_reported_while_the_release_is_in_flight_still_places_the_pointer(self):+ h = self.make()+ h.start()+ h.cross()+ moved = []+ desktop_portal.set_mover(lambda x, y: moved.append((x, y)))++ def late_landing(body):+ desktop_portal.note_position(0, 640)+ return ()++ h.bus.returns["Release"] = late_landing+ h.away = False+ wait_for(lambda: moved, timeout=2, what="the late landing")+ self.assertEqual(moved, [(0, 640)])+ desktop_portal.set_mover(None)++ # Second review (Opus, 01-10-2026)++ def test_a_corner_push_reported_off_the_barrier_line_finds_its_wall(self):+ for corner, point, push in (("bottom_right", (1919.0, 1079.0), (4.0, 4.0)), ("top_right", (1950.0, 3.0), (4.0, -4.0))):+ h = self.make(models=[return_edge.CornerPush(corner, "right")], push_to_cross=99)+ h.start()+ h.activate(x=point[0], y=point[1], barrier=0)+ h.ei.feed(("motion", h.pointer, *push))+ wait_for(lambda: h.motions, what=f"the {corner} push")+ self.assertTrue(h.hooks.holding, corner)+ h.hooks.stop()++ def test_input_away_with_nothing_captured_keeps_being_brought_home(self):+ h = self.make()+ h.hooks.on_home = lambda: h.homes.append(True) # a sender slow to come home+ h.start()+ h.away = True+ wait_for(lambda: len(h.homes) >= 2, timeout=3, what="a second try")++ def test_a_newer_captures_input_ahead_of_its_signal_is_kept_for_it(self):+ h = self.make()+ h.start()+ h.activate(activation=3)+ h.ei.feed(("motion", h.pointer, -5.0, 0.0))+ wait_for(lambda: h.releases(), what="the let-go")+ h.ei.feed(("stop", h.pointer), ("stop", h.keyboard))+ time.sleep(0.1)+ # The next capture's input arrives before its Activated signal.+ h.ei.feed(("start", h.pointer, 4), ("motion", h.pointer, 10.0, 0.0))+ time.sleep(0.1)+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"activation_id": 4, "cursor_position": (1920.0, 9.0), "barrier_id": 1})))+ wait_for(lambda: h.motions, what="the newer capture's push")++ def test_a_capture_the_desktop_never_announces_is_let_go(self):+ h = self.make()+ h.start()+ h.ei.feed(("start", h.pointer, 6), ("motion", h.pointer, 10.0, 0.0))+ wait_for(lambda: h.releases(), timeout=capture_portal.EARLY_SECONDS + 1.5, what="the let-go")+ self.assertEqual(h.releases()[0][0], 6)++ def test_repeated_disabled_signals_do_not_spin(self):+ h = self.make()+ h.start()+ for _ in range(5):+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Disabled", (SESSION, {}))+ time.sleep(0.4)+ self.assertLessEqual(len(h.bus.made("SetPointerBarriers")), 2)++ def test_version_two_starts_with_the_kept_token_and_keeps_the_new_one(self):+ h = self.make(version=2, tokens=MemoryTokens("old"))+ h.bus.answers["Start"] = (0, {"capabilities": 3, "restore_token": "new"})+ h.start()+ self.assertEqual(h.bus.made("CreateSession"), [])+ options = h.bus.made("Start")[0][2]+ self.assertEqual((options["restore_token"], options["persist_mode"]), (("s", "old"), ("u", 2)))+ self.assertEqual(h.tokens.token, "new")++ def test_a_refusal_under_version_two_forgets_the_token(self):+ h = self.make(version=2, tokens=MemoryTokens("old"))+ h.bus.answers["Start"] = (1, {})+ h.hooks.start()+ wait_for(lambda: h.failures, what="the refusal")+ self.assertEqual(h.tokens.token, "")+++if __name__ == "__main__":+ unittest.main()diff --cc win_app/tests/test_click_focus.pyindex 0000000,0000000..8fa3956new file mode 100644--- /dev/null+++ b/win_app/tests/test_click_focus.py@@@ -1,0 -1,0 +1,195 @@@++"""Spec section 6: a click never leaves a focus ring; Tab, Shift-Tab and the arrows show one.++++A ring is anything the control draws differently with focus than without, so each check grabs the++control focused and again with focus cleared, offscreen, and compares the two."""++++from __future__ import annotations++++import os++import sys++import tempfile++import unittest++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"))++sys.path.insert(0, str(ROOT / "win_app" / "tests"))++++from PySide6.QtCore import QCoreApplication, QEvent, QPoint, Qt++from PySide6.QtTest import QTest++from PySide6.QtWidgets import QApplication, QLabel, QLineEdit, QPushButton, QWidget++++import pages_win++import theme++import widgets++from test_settings_layout_acceptance import SyntheticWindow, write_synthetic_settings++++PAGE_KEYS = tuple(key for key, _name, _purpose in pages_win.PAGES)++++++class ClickFocusTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ cls.app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ cls.app.setFont(theme.font(theme.TYPE["body"]))++ cls.app.setStyleSheet(theme.stylesheet())++++ def setUp(self):++ scratch = ROOT / "renders" / "test-working"++ scratch.mkdir(parents=True, exist_ok=True)++ self.folder = tempfile.TemporaryDirectory(prefix="beamer-click-focus-", dir=scratch)++ self.window = SyntheticWindow(write_synthetic_settings(Path(self.folder.name)))++ self.window.full_screen_timer.stop()++ self.window.refresh_timer.stop()++ self.window.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, True)++ self.window.resize(1100, 900)++ self.window.show()++ self.window.activateWindow()++ QApplication.setActiveWindow(self.window)++ 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(5):++ QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)++ QCoreApplication.sendPostedEvents(None, QEvent.Type.LayoutRequest)++ self.app.processEvents()++++ def ring_drawn(self, widget):++ self.settle()++ self.assertTrue(widget.hasFocus(), f"{widget!r} should hold focus for this check")++ focused = widget.grab().toImage()++ widget.clearFocus()++ self.settle()++ plain = widget.grab().toImage()++ widget.setFocus(Qt.FocusReason.OtherFocusReason)++ self.settle()++ return focused != plain++++ def press(self, widget):++ """A mouse press that takes focus, released off the control so nothing is triggered."""++ QTest.mousePress(widget, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier,++ widget.rect().center())++ QTest.mouseRelease(widget, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier,++ QPoint(-50, -50))++ self.settle()++++ def visible(self, kind, page, test=lambda _widget: True):++ self.window._select_page(page)++ self.settle()++ for widget in self.window.findChildren(kind):++ if widget.isVisibleTo(self.window) and widget.focusPolicy() & Qt.FocusPolicy.ClickFocus and test(widget):++ return widget++ return None++++ def controls(self):++ found = {}++ kinds = {++ "choice": (QPushButton, lambda w: w.property("vernier") == "choice"),++ "tile": (widgets._Tile, lambda _w: True),++ "swatch": (widgets._Swatch, lambda _w: True),++ "switch": (widgets.Switch, lambda _w: True),++ "remove": (QPushButton, lambda w: w.property("vernier") == "remove"),++ "primary": (QPushButton, lambda w: w.property("vernier") == "primary"),++ "button": (QPushButton, lambda w: w.property("vernier") in (None, "", "small")),++ "keycap": (QPushButton, lambda w: w.property("vernier") == "keycap"),++ }++ for name, (kind, test) in kinds.items():++ for page in PAGE_KEYS:++ widget = self.visible(kind, page, test)++ if widget is not None:++ found[name] = (page, widget)++ break++ if "remove" not in found:++ # Remove buttons exist only beside ignored inputs, which the synthetic settings lack.++ remove = QPushButton("Remove", self.window)++ remove.setProperty("vernier", "remove")++ remove.move(8, 8)++ remove.show()++ found["remove"] = (PAGE_KEYS[0], remove)++ return found++++ def test_a_press_on_each_control_type_leaves_no_ring(self):++ found = self.controls()++ self.assertTrue({"choice", "tile", "swatch", "switch", "remove", "button"} <= set(found), sorted(found))++ for name, (page, widget) in found.items():++ with self.subTest(control=name, page=page):++ self.window._select_page(page)++ self.settle()++ self.press(widget)++ if widget.hasFocus():++ self.assertFalse(self.ring_drawn(widget), name)++++ def test_tab_shows_a_ring_and_the_next_press_clears_it(self):++ page, choice = self.controls()["choice"]++ self.window._select_page(page)++ self.settle()++ self.press(choice)++ choice.setFocus(Qt.FocusReason.OtherFocusReason)++ QTest.keyClick(choice, Qt.Key.Key_Tab)++ self.settle()++ tabbed = QApplication.focusWidget()++ self.assertIsNotNone(tabbed)++ self.assertIsNot(tabbed, choice)++ if not isinstance(tabbed, QLineEdit):++ self.assertTrue(self.ring_drawn(tabbed), repr(tabbed))++ QTest.keyClick(tabbed, Qt.Key.Key_Backtab)++ self.settle()++ back = QApplication.focusWidget()++ self.assertTrue(self.ring_drawn(back), repr(back))++ words = next(w for w in self.window.findChildren(QLabel)++ if w.isVisibleTo(self.window) and w.focusPolicy() == Qt.FocusPolicy.NoFocus and w.width() > 20)++ self.press(words)++ self.assertIs(QApplication.focusWidget(), back, "a press on a label keeps focus where it was")++ self.assertFalse(self.ring_drawn(back), "but ends keyboard navigation")++ QTest.keyClick(back, Qt.Key.Key_Tab)++ QTest.keyClick(QApplication.focusWidget(), Qt.Key.Key_Backtab)++ self.settle()++ self.assertTrue(self.ring_drawn(QApplication.focusWidget()))++ self.press(choice)++ if choice.hasFocus():++ self.assertFalse(self.ring_drawn(choice))++ back.setFocus(Qt.FocusReason.OtherFocusReason)++ self.settle()++ self.assertFalse(self.ring_drawn(back), "a press ends keyboard navigation everywhere")++++ def test_other_keys_after_a_press_leave_the_ring_off(self):++ page, choice = self.controls()["choice"]++ self.window._select_page(page)++ self.settle()++ self.press(choice)++ choice.setFocus(Qt.FocusReason.OtherFocusReason)++ QTest.keyClick(choice, Qt.Key.Key_A)++ QTest.keyClick(choice, Qt.Key.Key_Tab, Qt.KeyboardModifier.ControlModifier)++ self.settle()++ self.assertFalse(self.ring_drawn(choice))++++ def test_arrows_count_as_navigation(self):++ self.assertTrue(widgets.is_navigation_key(Qt.Key.Key_Left, Qt.KeyboardModifier.NoModifier))++ self.assertTrue(widgets.is_navigation_key(Qt.Key.Key_Backtab, Qt.KeyboardModifier.ShiftModifier))++ self.assertFalse(widgets.is_navigation_key(Qt.Key.Key_Tab, Qt.KeyboardModifier.ControlModifier))++ self.assertFalse(widgets.is_navigation_key(Qt.Key.Key_Space, Qt.KeyboardModifier.NoModifier))++++ def test_a_line_edit_keeps_its_ring_while_typing(self):++ for page in PAGE_KEYS:++ field = self.visible(QLineEdit, page, lambda w: w.property("vernier") != "pair-code" and w.isEnabled())++ if field is not None:++ break++ self.assertIsNotNone(field)++ self.press(field)++ self.assertTrue(field.hasFocus())++ self.assertTrue(self.ring_drawn(field))++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_colour_pixels.pyindex 0000000,0000000..41b679dnew file mode 100644--- /dev/null+++ b/win_app/tests/test_colour_pixels.py@@@ -1,0 -1,0 +1,44 @@@++"""The Qt colour catalogue and native preview pixels on an offscreen platform."""++++import os++import sys++import unittest++from pathlib import Path++++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from tools.render_colour_choices import QtRenderer, NEW_COLOURS, colour_rows, sample++++++class ColourPixelTests(unittest.TestCase):++ def test_ring_arrival_preview_draws_the_new_bright_colour(self):++ renderer = QtRenderer()++ renderer.set_dark(False)++ from tools.render_colour_choices import sample++ _image, pixels = sample(renderer, 'switch:locator', 'citron')++ self.assertGreater(pixels, 0)++++ def test_every_colour_group_has_five_choices_and_mono_has_its_own_home(self):++ groups = colour_rows("qt")++ self.assertTrue(NEW_COLOURS <= {value for _group, values in groups for value, _title in values})++ self.assertEqual([values for name, values in groups if name == "Mono"], [[++ ("mono", "White"), ("mono_silver", "Silver"), ("mono_graphite", "Graphite"),++ ("mono_ink", "Ink"), ("mono_warm", "Warm grey")]])++ self.assertTrue(any(name == "Bright" for name, _values in groups))++ for name, values in groups:++ self.assertEqual(len(values), 5, name)++++ def test_every_colour_draws_visible_pixels_in_every_native_preview(self):++ renderer = QtRenderer()++ for dark in (False, True):++ renderer.set_dark(dark)++ for group, values in colour_rows("qt"):++ for colour, _name in values:++ for style in renderer.styles:++ with self.subTest(group=group, colour=colour, style=style, dark=dark):++ _image, changed = sample(renderer, style, colour)++ self.assertGreater(changed, 0)++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_crossing_matrix.pyindex 95ac2b9,5602ebd..f28af94--- a/win_app/tests/test_crossing_matrix.py+++ b/win_app/tests/test_crossing_matrix.py@@@ -229,7 -190,7 +229,7 @@@ class WhatIsSharedTests(unittest.TestCaline = pages_win.SCOPE["crossing"]self.assertNotIn("Two are shared", line)- self.assertIn("Only which side a machine is on is shared, with that machine", line)- self.assertIn("Only which side your Mac is on is shared", line)++ self.assertIn("Its side is shared with that machine", line)try:diff --cc win_app/tests/test_design_tiles.pyindex 0000000,0000000..39d77bfnew file mode 100644--- /dev/null+++ b/win_app/tests/test_design_tiles.py@@@ -1,0 -1,0 +1,211 @@@++"""Measured Design tile states and geometry, using synthetic settings offscreen."""++++import colorsys++import os++import tempfile++import unittest++from pathlib import Path++++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")++++try:++ from PySide6.QtCore import QCoreApplication, QEvent, QPoint, QPointF++ from PySide6.QtGui import QColor, QEnterEvent, QPalette++ from PySide6.QtWidgets import QApplication, QWidget++ import kvm_bridge_win++ import theme++ from test_settings_layout_acceptance import SyntheticWindow, write_synthetic_settings++except ImportError:++ kvm_bridge_win = None++++++def luminance(colour):++ channels = [channel / 255 for channel in colour.getRgb()[:3]]++ linear = [value / 12.92 if value <= .04045 else ((value + .055) / 1.055) ** 2.4++ for value in channels]++ return sum(value * weight for value, weight in zip(linear, (.2126, .7152, .0722)))++++++def accent_pixels(image, points):++ signal = QColor(theme.colour("signal"))++ hue, saturation, _ = colorsys.rgb_to_hsv(*[value / 255 for value in signal.getRgb()[:3]])++ count = 0++ for x, y in points:++ colour = image.pixelColor(x, y)++ pixel_hue, pixel_saturation, _ = colorsys.rgb_to_hsv(*[value / 255 for value in colour.getRgb()[:3]])++ distance = abs(pixel_hue - hue)++ if min(distance, 1 - distance) < .06 and pixel_saturation >= saturation * .65:++ count += 1++ return count++++++def border_points(image):++ scale = image.devicePixelRatio()++ inset, depth = round(12 * scale), max(1, round(3 * scale))++ width, height = image.width(), image.height()++ return [(x, y) for x in range(inset, width - inset) for y in range(depth)] + [++ (x, y) for x in range(depth) for y in range(inset, height - inset)]++++[email protected](kvm_bridge_win is None, "needs PySide6")++class DesignTilesTest(unittest.TestCase):++ def setUp(self):++ self.app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ self.app.setFont(theme.font(theme.TYPE["body"]))++ scratch = Path(__file__).resolve().parents[2] / "renders" / "test-working"++ scratch.mkdir(parents=True, exist_ok=True)++ self.folder = tempfile.TemporaryDirectory(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._select_page("design")++ self.window.show()++ self.choice = self.window.glow_style_choice++ self.settle()++++ def tearDown(self):++ self.window.server.stop()++ self.window.close()++ self.window.deleteLater()++ self.app.processEvents()++ self.folder.cleanup()++++ def settle(self):++ for _ in range(8):++ QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)++ QCoreApplication.sendPostedEvents(None, QEvent.Type.LayoutRequest)++ self.app.processEvents()++++ def hover(self, enabled):++ tile = self.choice.tile("beam")++ event = (QEnterEvent(QPointF(1, 1), QPointF(1, 1), QPointF(1, 1)) if enabled++ else QEvent(QEvent.Type.Leave))++ self.app.sendEvent(tile, event)++ self.settle()++++ def capture_tile(self, tile):++ image = self.window.grab().toImage()++ scale = image.devicePixelRatio()++ point = tile.mapTo(self.window, QPoint())++ crop = image.copy(round(point.x() * scale), round(point.y() * scale),++ round(tile.width() * scale), round(tile.height() * scale))++ crop.setDevicePixelRatio(scale)++ return crop++++ def rectangles(self):++ return {value: (tile.mapTo(self.choice.view, QPoint()).x(),++ tile.mapTo(self.choice.view, QPoint()).y(), tile.width(), tile.height())++ for group in self.choice.groups.values() for value, tile in group._tiles.items()}++++ def test_hover_is_neutral_and_selected_has_accent_and_an_extra_cue(self):++ self.window.resize(1200, 900)++ self.choice.set_value("beam")++ self.settle()++ unselected = self.capture_tile(self.choice.tile("glow"))++ self.choice.set_value("glow")++ self.hover(True)++ selected = self.capture_tile(self.choice.tile("glow"))++ hovered = self.capture_tile(self.choice.tile("beam"))++ self.assertEqual(accent_pixels(hovered, border_points(hovered)), 0,++ "hover's border contains the selection accent")++ self.assertGreater(accent_pixels(selected, border_points(selected)), 20)++ scale = selected.devicePixelRatio()++ badge = [(x, y) for x in range(selected.width() - round(26 * scale),++ selected.width() - round(4 * scale))++ for y in range(round(4 * scale), round(26 * scale))]++ badge_extra = accent_pixels(selected, badge) - accent_pixels(unselected, badge)++ middle = selected.width() // 2++ thicker_ring = accent_pixels(selected, [(middle, y) for y in range(round(4 * scale))])++ self.assertTrue(badge_extra >= 20 * scale * scale or thicker_ring >= round(3 * scale),++ f"selection has no extra cue: badge delta {badge_extra}, ring pixels {thicker_ring}")++++ def test_hover_background_brightens_in_both_appearances(self):++ previous = theme.is_dark()++ tile = self.choice.tile("beam")++ try:++ for dark in (True, False):++ theme.set_dark(dark)++ self.app.setStyleSheet(theme.stylesheet())++ self.hover(False)++ image = self.capture_tile(tile)++ scale = image.devicePixelRatio()++ rest = image.pixelColor(image.width() // 2, round(5 * scale))++ self.hover(True)++ image = self.capture_tile(tile)++ hovered = image.pixelColor(image.width() // 2, round(5 * scale))++ with self.subTest(dark=dark):++ self.assertGreater(luminance(hovered), luminance(rest))++ finally:++ theme.set_dark(previous)++ self.app.setStyleSheet(theme.stylesheet())++++ def test_hint_has_plain_secondary_text_and_accessible_contrast(self):++ hint = self.window.style_preview_hint++ self.assertEqual(hint.text(), "Hover to preview")++ foreground = hint.palette().color(QPalette.ColorRole.WindowText)++ self.assertEqual(foreground.name(), QColor(theme.colour("ink_2")).name())++ values = sorted((luminance(foreground), luminance(QColor(theme.colour("panel")))))++ contrast = (values[1] + .05) / (values[0] + .05)++ self.assertGreaterEqual(contrast, 4.5, f"hint contrast {contrast:.2f}:1")++++ def test_tile_dimensions_and_rows_match_at_every_width_and_state(self):++ for width in (320, 426, 512, 640, 720, 900, 1440, 1920):++ self.window.resize(width, 900)++ self.choice.set_value("glow")++ self.hover(False)++ self.settle()++ rest = self.rectangles()++ page = self.window.stack.currentWidget().widget()++ column = page.findChild(QWidget, "page_column")++ per_row = 3 if column.width() >= 600 else 2 if column.width() >= 400 else 1++ with self.subTest(width=width, state="all tile dimensions"):++ self.assertLessEqual(max(rect[2] for rect in rest.values()) - min(rect[2] for rect in rest.values()), 1)++ self.assertEqual(len({rect[3] for rect in rest.values()}), 1)++ with self.subTest(width=width, state="rest"):++ family_views = list(self.choice.group_views.values())++ self.assertEqual(len({view.x() for view in family_views}), 1,++ "style families must share one leading edge")++ self.assertEqual([view.y() for view in family_views],++ sorted(view.y() for view in family_views),++ "style families must follow catalogue order vertically")++ for title, group in self.choice.groups.items():++ rows = {}++ for value, tile in group._tiles.items():++ point = tile.mapTo(group.view, QPoint())++ rows.setdefault(point.y(), []).append((value, tile))++ self.assertEqual(max(map(len, rows.values())), per_row,++ f"{title} must have {per_row} choices per row")++ for row in rows.values():++ self.assertLessEqual(max(tile.width() for _v, tile in row) - min(tile.width() for _v, tile in row), 1)++ self.assertEqual(len({tile.height() for _v, tile in row}), 1)++ self.assertLessEqual(max(tile.width() for tile in group._tiles.values()) - min(tile.width() for tile in group._tiles.values()), 1)++ self.hover(True)++ with self.subTest(width=width, state="hover"):++ self.assertEqual(self.rectangles(), rest)++ self.hover(False)++ self.choice.set_value("beam")++ self.settle()++ with self.subTest(width=width, state="selected"):++ self.assertEqual(self.rectangles(), rest)++ for value, tile in ((value, tile) for group in self.choice.groups.values()++ for value, tile in group._tiles.items()):++ preview = tile.layout().itemAt(0).widget()++ with self.subTest(width=width, tile=value):++ self.assertAlmostEqual(preview.width() / preview.height(), 2, delta=.03)++++ def test_sidebar_has_no_ring_on_a_different_page(self):++ self.settle()++ for key, button in self.window.sidebar._buttons.items():++ with self.subTest(page=key):++ self.assertEqual(button.isChecked(), key == "design")++ if key != "design":++ self.assertFalse(button.hasFocus(), f"{key} kept focus after Design became current")++ image = button.grab().toImage()++ self.assertEqual(accent_pixels(image, border_points(image)), 0,++ f"{key} has an accent ring while Design is current")++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_effect_overlay.pyindex 8ddd48d,84ace05..22cb1af--- a/win_app/tests/test_effect_overlay.py+++ b/win_app/tests/test_effect_overlay.py@@@ -3,6 -3,6 +3,7 @@@ to draw and in what state, and the overimport mathimport os++import subprocessimport unittestfrom dataclasses import replacefrom types import SimpleNamespace@@@ -80,6 -77,6 +81,17 @@@ class ReplayTests(unittest.TestCase)pen.ops = list(ops)return pen++ @unittest.skipUnless(sys.platform == "win32", "Windows raster budget")++ def test_replay_sets_serial_rasterisation_before_the_first_paint(self):++ env = dict(os.environ)++ env.pop("QT_NO_GUI_THREADPOOL", None)++ result = subprocess.run(++ [sys.executable, "-c", "import sys; sys.path.insert(0, 'win_app'); import effect_overlay, os; print(os.environ.get('QT_NO_GUI_THREADPOOL'))"],++ cwd=os.path.dirname(os.path.dirname(effect_overlay.__file__)), env=env,++ capture_output=True, text=True, check=True,++ )++ self.assertEqual(result.stdout.strip(), "1")++def test_every_op_restores_opacity_and_composition(self):linear = gradient("linear", (0, 0, 10, 0))ops = [diff --cc win_app/tests/test_eliding_text.pyindex 0000000,0000000..d493d8cnew file mode 100644--- /dev/null+++ b/win_app/tests/test_eliding_text.py@@@ -1,0 -1,0 +1,192 @@@++"""Long machine names stay readable in the space the Qt audit measured."""++++import os++import sys++import unittest++from pathlib import Path++from types import MethodType, SimpleNamespace++from unittest import mock++++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "ui_audit"))++++from PySide6.QtCore import QCoreApplication, QEvent++from PySide6.QtWidgets import QApplication, QLabel, QPushButton, QStyle, QStyleOptionButton, QVBoxLayout++++import kvm_bridge_win as kvm++import machines_win++import qt_audit++import theme++import widgets++++++LONG_NAME = "Studio MacBook Pro with an exceptionally long machine name"++++++class ElidingTextGeometryTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ cls.app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ cls.app.setFont(theme.font(theme.TYPE["body"]))++++ def settle(self):++ for _ in range(3):++ QCoreApplication.sendPostedEvents(None, QEvent.Type.LayoutRequest)++ self.app.processEvents()++++ def make_button(self, text: str, text_width: int):++ button_type = getattr(widgets, "ElidingButton", QPushButton)++ button = button_type(text)++ button.setFont(theme.font(theme.TYPE["body"]))++ button.resize(1000, 48)++ option = QStyleOptionButton()++ button.initStyleOption(option)++ content = button.style().subElementRect(++ QStyle.SubElement.SE_PushButtonContents, option, button)++ horizontal_inset = button.width() - content.width()++ button.setFixedWidth(text_width + horizontal_inset)++ button.setFixedHeight(48)++ self.settle()++ return button++++ def test_audited_button_text_areas_elide_painted_text_and_keep_full_names(self):++ cases = (++ ("pairing discovery", 339,++ f"{LONG_NAME[:48]} · Windows · showing a code",++ " · Windows · showing a code"),++ ("Send input", 335, f"Send input to {LONG_NAME}", ""),++ ("machine picker", 135, LONG_NAME, ""),++ ("share recipient tile", 219, f"Middle\n{LONG_NAME}", ""),++ )++ for surface, text_width, full_text, suffix in cases:++ with self.subTest(surface=surface, text_width=text_width):++ button = self.make_button(full_text, text_width)++ set_suffix = getattr(button, "set_elision_suffix", None)++ if callable(set_suffix):++ set_suffix(suffix)++ button.setAccessibleName(f"Accessible: {full_text}")++ displayed = getattr(button, "displayed_text", button.text)()++ self.assertIn("…", displayed)++ if suffix:++ self.assertTrue(displayed.endswith(suffix))++ self.assertLessEqual(++ max(button.fontMetrics().horizontalAdvance(line)++ for line in displayed.splitlines()), text_width)++ self.assertEqual(button.text(), full_text)++ self.assertEqual(button.accessibleName(), f"Accessible: {full_text}")++ self.assertEqual(button.toolTip(), full_text)++ self.assertIsNone(qt_audit.text_measure(button))++++ def test_audited_peer_headings_elide_to_their_real_label_width(self):++ for title in (f"Ways from this screen to {LONG_NAME}", f"Jump to {LONG_NAME}"):++ with self.subTest(title=title):++ label_type = getattr(widgets, "ElidingLabel", QLabel)++ label = label_type(title)++ label.setFont(theme.font(theme.HEADING, 700))++ label.setFixedWidth(361)++ label.setFixedHeight(32)++ self.settle()++ displayed = getattr(label, "displayed_text", label.text)()++ self.assertIn("…", displayed)++ self.assertLessEqual(label.fontMetrics().horizontalAdvance(displayed), label.contentsRect().width())++ self.assertEqual(label.text(), title)++ self.assertEqual(label.toolTip(), title)++ self.assertIsNone(qt_audit.text_measure(label))++++ def test_three_machine_choices_keep_full_names_within_the_capped_column(self):++ items = tuple((str(index), LONG_NAME) for index in range(3))++ choice = widgets.Choice(items, 3, "0")++ choice.set_names("Machine")++ choice.view.resize(360, choice.view.heightForWidth(360))++ choice.view.show()++ self.addCleanup(choice.view.deleteLater)++ self.settle()++ self.assertLessEqual(choice.view.width(), 360)++ for button in choice._buttons.values():++ with self.subTest(machine=button.text()):++ self.assertLessEqual(button.geometry().right(), choice.view.width() - 1)++ displayed = getattr(button, "displayed_text", button.text)()++ self.assertEqual(displayed, button.text())++ self.assertGreaterEqual(button.height(), button.heightForWidth(button.width()))++ self.assertEqual(button.accessibleName(), f"Machine, {LONG_NAME}")++++ def test_replacing_machine_choices_hides_the_old_container_before_deferred_deletion(self):++ from PySide6.QtWidgets import QWidget++ holder = QWidget()++ slot = QVBoxLayout(holder)++ previous = widgets.Choice((), 1, "")++ slot.addWidget(previous.view)++ holder.show()++ self.addCleanup(holder.deleteLater)++ self.settle()++ owner = SimpleNamespace(_machine_items=(), machine_choice=previous, _machine_slot=slot,++ _choose_machine=lambda *_: None)++ kvm.WindowsApplication._rebuild_machine_choice(owner, (("first", LONG_NAME), ("second", "Desk")))++ self.assertTrue(previous.view.isHidden())++++ def test_short_machine_name_stays_readable_between_long_names(self):++ self.app.setStyleSheet(theme.stylesheet())++ choice = widgets.Choice((("first", LONG_NAME[:48]), ("short", "Desk"),++ ("third", "Laboratory Linux workstation with the external d")), 3, "first")++ choice.view.resize(360, choice.view.heightForWidth(360))++ choice.view.show()++ self.addCleanup(choice.view.deleteLater)++ self.settle()++ button = choice._buttons["short"]++ self.assertEqual(button.displayed_text(), "Desk",++ f"short choice allocated {button.width()}px in the audited 361px row")++++ def test_pairing_discovery_retains_the_separator_before_its_platform_and_status(self):++ panel = machines_win.PairingSheet(*([lambda *_: None] * 4))++ self.addCleanup(panel.deleteLater)++ panel.set_machines([dict(name=LONG_NAME[:48], platform="windows", address="192.0.2.10",++ pairing=3, pair_id="fixture")], lambda *_: "")++ button = panel.group.buttons()[0]++ button.resize(300, 32)++ displayed = button.displayed_text()++ self.assertIn("… · Windows", displayed)++++ def test_audit_keeps_source_text_when_elision_itself_cannot_fit(self):++ button = self.make_button(LONG_NAME, 1)++ button_text = getattr(button, "displayed_text", button.text)()++ button_finding = qt_audit.text_measure(button)++ if button_text != LONG_NAME:++ self.assertEqual(button_finding["source_text"], LONG_NAME)++++ label_type = getattr(widgets, "ElidingLabel", QLabel)++ label = label_type(LONG_NAME)++ label.setFixedSize(1, 28)++ self.settle()++ label_text = getattr(label, "displayed_text", label.text)()++ label_finding = qt_audit.text_measure(label)++ if label_text != LONG_NAME:++ self.assertEqual(label_finding["source_text"], LONG_NAME)++++ def test_linux_connection_guidance_does_not_name_windows(self):++ owner = SimpleNamespace(_firewall_action=lambda: None)++ layout = QVBoxLayout()++ with mock.patch.object(kvm, "sys", SimpleNamespace(platform="linux")):++ kvm.WindowsApplication._firewall_module(owner, layout)++ module = layout.itemAt(0).widget()++ copy = " ".join((module.eyebrow.text(), owner.firewall_note.text()))++ self.assertNotIn("Windows", copy)++ self.assertIn("Linux", copy)++++ def test_linux_appearance_guidance_names_the_linux_desktop(self):++ owner = SimpleNamespace(own_notes=[])++ owner._own_note = MethodType(kvm.WindowsApplication._own_note, owner)++ owner._row = kvm.WindowsApplication._row++ owner._appearance_chosen = lambda _choice: None++ with mock.patch.object(kvm, "sys", SimpleNamespace(platform="linux")):++ module = kvm.WindowsApplication._appearance_module(owner, kvm.default_config())++ self.addCleanup(module.deleteLater)++ copy = next(label.text() for label in module.findChildren(QLabel)++ if label.text().startswith("System follows"))++ self.assertIn("Linux", copy)++ self.assertNotIn("Windows", copy)++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_empty_choice_layout.pyindex 0000000,0000000..786bf26new file mode 100644--- /dev/null+++ b/win_app/tests/test_empty_choice_layout.py@@@ -1,0 -1,0 +1,53 @@@++"""An empty Choice survives a layout pass beside buttons that override their size hints.++++The machine choice is built empty whenever fewer than two machines are paired. Before++38eb92b its view divided by a zero column count in resizeEvent. On PySide6 6.11 an++exception inside a C++ virtual override during a layout pass does not surface as a++traceback: the next Python override Qt calls in the same pass (an ActionButton's++minimumSizeHint) segfaults in Shiboken::BindingManager::getOverride. The pass runs in a++subprocess so a crash fails this test instead of killing the runner.++"""++++import os++from pathlib import Path++import subprocess++import sys++import unittest++++WIN_APP = Path(__file__).resolve().parents[1]++++CHILD = """++import sys++sys.path[:0] = [sys.argv[1], str(__import__("pathlib").Path(sys.argv[1]).parent)]++from PySide6.QtWidgets import QApplication, QHBoxLayout, QVBoxLayout, QWidget++app = QApplication([])++import widgets++window = QWidget()++column = QVBoxLayout(window)++for columns in (1, 2):++ row = QHBoxLayout()++ column.addLayout(row)++ row.addWidget(widgets.Choice((), columns, "").view)++ row.addWidget(widgets.ActionButton("Pair"))++ row.addWidget(widgets.ActionButton("Forget"))++window.resize(640, 400)++window.grab()++window.resize(320, 600)++window.grab()++print("survived")++"""++++++class EmptyChoiceLayout(unittest.TestCase):++ def test_empty_choice_lays_out_without_error_or_crash(self):++ environment = dict(os.environ, QT_QPA_PLATFORM="offscreen",++ QT_QPA_FONTDIR=str(WIN_APP / "assets"))++ result = subprocess.run([sys.executable, "-X", "faulthandler", "-c", CHILD, str(WIN_APP)],++ env=environment, capture_output=True, text=True, timeout=120)++ self.assertNotIn("Error calling Python override", result.stderr)++ self.assertEqual(result.returncode, 0, result.stderr[-2000:])++ self.assertIn("survived", result.stdout)++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_hook_key_repeat.pyindex 498ba82,24266e2..e5e3463--- a/win_app/tests/test_hook_key_repeat.py+++ b/win_app/tests/test_hook_key_repeat.py@@@ -1,36 -1,32 +1,25 @@@- """kvm_bridge_win.py:2351 (`_on_hook_key`) cannot be imported here (it-"""kvm_bridge_win.py:1056-1071 (`_on_hook_key`) cannot be imported here (it--needs PySide6, Windows-only), so this drives its exact dispatch by hand--against the two pure-Python pieces it calls: `capture_win.Trigger.feed` and- `sender.LinkSender.on_key`. The dispatch replicated below is copied verbatim-`sender.MacSender.on_key`. The dispatch replicated below is copied verbatim--from `_on_hook_key`'s body."""++"""Run the app's actual hook decision with a real Trigger and LinkSender, without a window."""import timeimport unittest+import os+import sys++from typing import Optional++from types import SimpleNamespace++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))import capture_win-import protocol-import sender+from core import protocolfrom capture_win import Trigger-from fakes import FakeDesktop-from sender import MacSender+from links_rig import B, Rig, make_config++from core.tests.app_methods import load_methods++++Application = load_methods("win_app/kvm_bridge_win.py", "WindowsApplication", ["_on_hook_key"], globals())-def dispatch(trigger, mac_sender, name, down):- """`WindowsApplication._on_hook_key`, verbatim."""- action = trigger.feed(name, down, time.monotonic())- if action is not None:- if action == capture_win.TOGGLE:- mac_sender.toggle()- else:- mac_sender.set_redirecting(action == capture_win.REDIRECT)- return True- if trigger.claims(name, down, mac_sender.redirecting):- return True- return mac_sender.on_key(name, down)+def dispatch(trigger, link_sender, name, down, vk=None, us=None):- """`WindowsApplication._on_hook_key`, verbatim."""- action = trigger.feed(name, down, time.monotonic())- if action is not None:- if not link_sender.shortcut_armed:- return True- if action == capture_win.TOGGLE:- link_sender.toggle()- else:- link_sender.set_redirecting(action == capture_win.REDIRECT)- return True- if trigger.claims(name, down, link_sender.redirecting):- return True- return link_sender.on_key(name, down, vk, us)++ return Application._on_hook_key(SimpleNamespace(_trigger=trigger, sender=link_sender), name, down, vk, us)class HeldTriggerRepeatTests(unittest.TestCase):@@@ -76,31 -78,31 +65,46 @@@# Two taps while away toggle input home on the second down; that# tap's release must not reach Windows as a key-up with no key-down.trigger = Trigger("cmd_r", "double_tap", 300)- self.mac_sender.set_redirecting(True)- self.assertTrue(dispatch(trigger, self.mac_sender, "cmd_r", True))- self.assertTrue(dispatch(trigger, self.mac_sender, "cmd_r", False))- self.assertTrue(dispatch(trigger, self.mac_sender, "cmd_r", True))- self.assertFalse(self.mac_sender.redirecting)- self.assertTrue(dispatch(trigger, self.mac_sender, "cmd_r", False))+ self.link_sender.set_redirecting(True)+ self.assertTrue(dispatch(trigger, self.link_sender, "cmd_r", True))+ self.assertTrue(dispatch(trigger, self.link_sender, "cmd_r", False))+ self.assertTrue(dispatch(trigger, self.link_sender, "cmd_r", True))+ self.assertFalse(self.link_sender.redirecting)+ self.assertTrue(dispatch(trigger, self.link_sender, "cmd_r", False))# A later lone tap at home is an ordinary key again.- self.assertFalse(dispatch(trigger, self.mac_sender, "cmd_r", True))- self.assertFalse(dispatch(trigger, self.mac_sender, "cmd_r", False))+ self.assertFalse(dispatch(trigger, self.link_sender, "cmd_r", True))+ self.assertFalse(dispatch(trigger, self.link_sender, "cmd_r", False))def test_physical_release_never_reaches_on_key_so_no_keyup_is_sent(self):- dispatch(self.trigger, self.mac_sender, "alt_r", True)- dispatch(self.trigger, self.mac_sender, "alt_r", True) # the repeat- dispatch(self.trigger, self.mac_sender, "alt_r", False) # real release-- keyups = [- message- for message in list(self.mac_sender._outbound.queue)- if message.get("type") == protocol.MSG_KEYUP- and message.get("data", {}).get("key") == "alt_r"- ]- # RETURN swallows the release before sender.on_key ever sees it, so- # a key-down that did leak (proven above) is never balanced by a- # key-up -- the Mac is left with a phantom held key.- self.assertEqual(keyups, [])+ dispatch(self.trigger, self.link_sender, "alt_r", True)+ dispatch(self.trigger, self.link_sender, "alt_r", True) # the repeat+ dispatch(self.trigger, self.link_sender, "alt_r", False) # real release++ # The release is swallowed before sender.on_key ever sees it, so a+ # key-down that did leak (proven above) is never balanced by a+ # key-up -- the peer is left with a phantom held key.+ self.assertEqual(self.keys(protocol.MSG_KEYUP), [])+- def test_with_the_shortcut_off_the_trigger_is_swallowed_and_moves_nothing(self):- self.link_sender.update_config(make_config(crossing_methods=["edge"]))- self.assertTrue(dispatch(self.trigger, self.link_sender, "alt_r", True))- self.assertFalse(self.link_sender.redirecting)- self.assertEqual(self.rig.sent(B, "focus"), [])++ def test_shortcut_off_passes_the_key_without_switching_in_each_input_state(self):++ for style in ("double_tap", "hold"):++ for state in ("local", "receiving", "redirected"):++ with self.subTest(style=style, state=state):++ rig = Rig(crossing_methods=["edge"])++ trigger = Trigger("alt_r", style, 300)++ if state == "redirected":++ rig.sender.set_redirecting(True)++ rig.driven = state == "receiving"++ rig.flush()++ rig.links.sent.clear()++ for down in (True, False) * 2:++ self.assertEqual(dispatch(trigger, rig.sender, "alt_r", down), state == "redirected")++ self.assertEqual(rig.sender.redirecting, state == "redirected")++ self.assertEqual(rig.sent_home, [])++ self.assertEqual(rig.sent(B, "focus"), [])++ keys = [message for message in rig.sent(B) if message["type"] in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP)]++ expected = [{"type": kind, "data": {"key": "alt_r"}}++ for kind in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP) * 2]++ self.assertEqual(keys, expected if state == "redirected" else [])if __name__ == "__main__":diff --cc win_app/tests/test_ignored_inputs.pyindex 0741679,637650c..923fd36--- a/win_app/tests/test_ignored_inputs.py+++ b/win_app/tests/test_ignored_inputs.py@@@ -49,21 -65,15 +49,34 @@@ class SenderTests(unittest.TestCase)protocol.MSG_KEYDOWN, protocol.MSG_KEYUP, protocol.MSG_MOUSEDOWN, protocol.MSG_MOUSEUP)]- def test_an_ignored_key_reaches_this_pc_and_not_the_mac(self):+ def mouse(self, message, data=0):+ """`WindowsApplication._on_hook_mouse` for a button: the hook's message, then the sender's call."""+ event = capture_win.mouse_event(message, data)+ self.assertEqual(event[0], "button")+ return self.sender.on_button(event[1], event[2])++ def test_an_ignored_key_reaches_this_pc_and_not_the_peer(self):self.assertFalse(self.sender.on_key("f13", True, VK_F13))self.assertFalse(self.sender.on_key("f13", False, VK_F13))- self.assertEqual(self.drain(), [])+ self.assertEqual(self.sent(), [])+++ def test_local_release_after_return_clears_the_kept_key_for_its_next_press(self):++ self.sender.on_key("f13", True, VK_F13)++ self.sender.set_redirecting(False)++ self.sender.on_key("f13", False, VK_F13)++ self.configure([])++ self.sender.set_redirecting(True)++ self.assertTrue(self.sender.on_key("f13", True, VK_F13))++ self.assertTrue(self.sender.on_key("f13", False, VK_F13))++ self.assertEqual(self.sent(), [++ (protocol.MSG_KEYDOWN, {"key": "f13"}),++ (protocol.MSG_KEYUP, {"key": "f13"}),++ ])+- def test_any_other_key_still_goes_to_the_mac(self):+ def test_any_other_key_still_goes_to_the_peer(self):self.assertTrue(self.sender.on_key("a", True, VK_A))self.assertTrue(self.sender.on_key("a", False, VK_A))- self.assertEqual(self.drain(), [+ self.assertEqual(self.sent(), [(protocol.MSG_KEYDOWN, {"key": "a"}),(protocol.MSG_KEYUP, {"key": "a"}),])diff --cc win_app/tests/test_inject_portal.pyindex 0ab38bf,0000000..4f527e6mode 100644,000000..100644--- a/win_app/tests/test_inject_portal.py+++ b/win_app/tests/test_inject_portal.py@@@ -1,453 -1,0 +1,465 @@@+"""Wayland injection and its clipboard on fakes: key steps for a desktop that repeats keys itself+and whose keymap cannot change, the wheel in libei's units, and the RemoteDesktop session against+a scripted portal and libei: the remembered permission, the devices, the pointer kept on the+displays, keys and buttons let go, a refusal said in the app's words, and the clipboard both ways."""++import os+import sys+import threading+import time+import unittest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import clipboard_portal+import desktop_portal+import inject_portal+import portal+from inject_x11 import MAP, NO_REPEAT, PRESS, RELEASE, REPEAT+from portal_fakes import FakeBus, FakeDevice, FakeEi, vardict, wait_for++SESSION = "/org/freedesktop/portal/desktop/session/1_42/beamer2"+++class FakeKeymap:+ """A US keymap's letters and digits, as xkb_x11.Keymap answers: keycodes are evdev + 8, the+ Shift bit is 1 and Caps Lock 2."""++ KEYS = {38: ("a", "A"), 10: ("1", "!"), 39: ("s", "S")}+ min_keycode, max_keycode = 8, 255++ def keysym(self, keycode, mods, group):+ pair = self.KEYS.get(keycode)+ if pair is None:+ return 0+ return ord(pair[1] if mods & 1 else pair[0])++ def text(self, keysym):+ return chr(keysym) if keysym else None++ def empty(self, keycode):+ return keycode not in self.KEYS++ def core_mods(self, mask):+ return mask+++class StepsTest(unittest.TestCase):+ def test_a_key_with_shift_worked_around_it_is_let_go_at_once_and_repeat_and_map_mean_nothing(self):+ steps = [(NO_REPEAT, 38), (PRESS, 50), (PRESS, 38), (RELEASE, 50), (REPEAT, 38), (MAP, 200, 0x41, False)]+ self.assertEqual(inject_portal.wayland_steps(steps), [(42, True), (30, True), (30, False), (42, False)])++ def test_the_wheel_in_120ths_with_the_fraction_carried_and_pixels_as_they_are(self):+ carry = [0.0, 0.0]+ self.assertEqual(inject_portal.scroll_steps(1, 0, "line", carry), ("discrete", 0, -120))+ self.assertEqual(inject_portal.scroll_steps(0.004, 0, "line", carry), ("discrete", 0, 0))+ self.assertEqual(inject_portal.scroll_steps(0.005, -1, "line", carry), ("discrete", -120, -1))+ self.assertEqual(inject_portal.scroll_steps(-3.5, 2, "pixel", carry), ("pixels", 2.0, 3.5))++ def test_a_layout_with_no_key_for_a_character_has_no_spare_to_map(self):+ layout = inject_portal.WaylandLayout(FakeKeymap())+ self.assertEqual(layout.spare(), [])+ state = inject_portal.KeyState()+ self.assertEqual(inject_portal.plan_key("é", True, None, state, layout, 0, 0), [])+++class MemoryTokens:+ def __init__(self, token=""):+ self.token = token++ def read(self):+ return self.token++ def write(self, token):+ self.token = token++[email protected](sys.platform == "win32", "the Wayland back ends select on pipes, which Windows cannot; they run only on Linux")+class RemoteTest(unittest.TestCase):+ def setUp(self):+ desktop_portal._position = None+ desktop_portal._zones = []+ desktop_portal._regions = []+ desktop_portal._captured = False+ desktop_portal._mover = None+ self.problems = []+ inject_portal.on_problem = self.problems.append+ self.bus = FakeBus(versions={inject_portal.INTERFACE: 2, inject_portal.CLIPBOARD: 1})+ self.bus.answers["CreateSession"] = (0, {"session_handle": SESSION})+ self.bus.answers["Start"] = (0, {"devices": 3, "clipboard_enabled": True, "restore_token": "new"})+ self.bus.returns["ConnectToEIS"] = (99,)+ self.ei = FakeEi()+ self.tokens = MemoryTokens("old")+ self.remote = inject_portal.Remote(connect=lambda: self.bus, ei=lambda fd: self.ei, tokens=self.tokens,+ keymap=lambda text: FakeKeymap())+ inject_portal._remote = self.remote+ clipboard_portal.forget_sync()++ def tearDown(self):+ self.remote.stop()+ inject_portal._remote = None+ inject_portal.on_problem = None++ def up(self):+ self.remote.start()+ wait_for(self.remote.ready.is_set, what="the session")+ self.absolute = FakeDevice("absolute", {2, 16, 32}, regions=[(0, 0, 1920, 1080, 1.0)])+ self.pointer = FakeDevice("pointer", {1, 16, 32})+ self.keyboard = FakeDevice("keyboard", {4}, keymap="xkb_keymap {}")+ devices = (self.absolute, self.pointer, self.keyboard)+ self.ei.feed(("seat", 7), *[("device_added", d) for d in devices], *[("device_resumed", d) for d in devices])+ wait_for(lambda: len(self.ei.sends("start")) == 3, what="the devices to emulate")+ wait_for(lambda: self.remote.layout is not None, what="the layout")++ def test_the_session_asks_with_the_kept_permission_and_keeps_the_new_one(self):+ self.up()+ names = [method for _interface, method, _body in self.bus.calls if method not in ("Get",)]+ self.assertEqual(names[:5], ["CreateSession", "SelectDevices", "RequestClipboard", "Start", "ConnectToEIS"])+ options = self.bus.made("SelectDevices")[0][1]+ self.assertEqual((options["restore_token"], options["persist_mode"], options["types"]), (("s", "old"), ("u", 2), ("u", 3)))+ self.assertEqual(self.tokens.token, "new")+ self.assertEqual(desktop_portal.monitors()[0].width, 1920)+++ def test_clipboard_version_zero_still_requests_clipboard_before_start(self):++ self.bus.versions[inject_portal.CLIPBOARD] = 0++ self.up()++ self.assertEqual(len(self.bus.made("RequestClipboard")), 1)++++ def test_remote_desktop_version_zero_attempts_the_required_calls_without_v2_options(self):++ self.bus.versions[inject_portal.INTERFACE] = 0++ self.up()++ options = self.bus.made("SelectDevices")[0][1]++ self.assertNotIn("persist_mode", options)++ self.assertEqual(len(self.bus.made("ConnectToEIS")), 1)+++ def test_the_pointer_lands_moves_and_stays_on_the_displays(self):+ self.up()+ desktop_portal.set_cursor_position(100, 100)+ inject_portal.inject_mouse_move(10, -5)+ inject_portal.inject_mouse_move(5000, 0)+ wait_for(lambda: len(self.ei.sends("absolute")) == 3, what="three moves")+ self.assertEqual([item[2:] for item in self.ei.sends("absolute")], [(100.0, 100.0), (110.0, 95.0), (1919.0, 95.0)])+ self.assertEqual(desktop_portal.cursor_position(), (1919, 95))++ def test_nothing_is_moved_for_real_while_the_capture_holds_the_pointer(self):+ self.up()+ desktop_portal.set_captured(True)+ desktop_portal.set_cursor_position(300, 300)+ inject_portal.inject_mouse_button("left", True)+ wait_for(lambda: self.ei.sends("button"), what="the button")+ self.assertEqual(self.ei.sends("absolute"), [])+ self.assertEqual(desktop_portal.cursor_position(), (300, 300))++ def test_keys_play_by_evdev_code_with_shift_worked_around_and_all_are_let_go(self):+ self.up()+ inject_portal.inject_key("A", True)+ inject_portal.inject_key("A", False)+ inject_portal.inject_key("ctrl", True)+ inject_portal.inject_key("A", True) # under a chord the peer's own Shift is never touched+ inject_portal.inject_mouse_button("left", True)+ inject_portal.release_all()+ wait_for(lambda: len(self.ei.sends("button")) == 2, what="the release")+ keys = [item[2:] for item in self.ei.sends("key")]+ self.assertEqual(keys, [(42, True), (30, True), (30, False), (42, False), (29, True), (30, True),+ (29, False), (30, False)])+ self.assertEqual([item[2:] for item in self.ei.sends("button")], [(0x110, True), (0x110, False)])++ def test_text_is_typed_with_the_peers_modifiers_let_go_around_it(self):+ self.up()+ inject_portal.inject_key("ctrl", True)+ inject_portal.inject_text("a!")+ wait_for(lambda: len(self.ei.sends("key")) >= 9, what="the text")+ keys = [item[2:] for item in self.ei.sends("key")]+ self.assertEqual(keys, [(29, True), (29, False), (30, True), (30, False),+ (42, True), (2, True), (42, False), (2, False), (29, True)])++ def test_the_wheel_goes_out_as_clicks(self):+ self.up()+ inject_portal.inject_scroll(-2, 0, "line")+ wait_for(lambda: self.ei.sends("scroll_discrete"), what="the wheel")+ self.assertEqual(self.ei.sends("scroll_discrete")[0][2:], (0, 240))++ def test_a_refusal_forgets_the_permission_and_says_so_in_the_apps_words(self):+ self.bus.answers["Start"] = (1, {})+ self.remote.start()+ wait_for(lambda: self.problems, what="the refusal")+ self.assertEqual(self.problems, [inject_portal.REFUSED])+ self.assertEqual(self.tokens.token, "")+ self.assertIsNone(clipboard_portal.change_stamp())+ self.assertEqual(clipboard_portal.get_contents(), (None, None))++ def test_a_desktop_without_remote_control_over_libei_is_said_plainly(self):+ self.bus.versions[inject_portal.INTERFACE] = 1+ self.remote.start()+ wait_for(lambda: self.problems, what="the problem")+ self.assertEqual(self.problems, [inject_portal.NO_PORTAL])++ def test_beamers_clipboard_is_written_to_the_app_that_pastes_it(self):+ self.up()+ before = clipboard_portal.change_stamp()+ self.assertTrue(clipboard_portal.set_contents("hello\r\nthere", None))+ self.assertEqual(clipboard_portal.change_stamp(), before + 1)+ offered = self.bus.made("SetSelection")[0][1]["mime_types"][1]+ self.assertIn("text/plain;charset=utf-8", offered)+ read, write = os.pipe()+ self.bus.returns["SelectionWrite"] = (write,)+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionOwnerChanged",+ (SESSION, vardict({"mime_types": offered, "session_is_owner": True})))+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionTransfer", (SESSION, "text/plain;charset=utf-8", 4))+ with os.fdopen(read, "rb") as handle:+ self.assertEqual(handle.read(), b"hello\nthere")+ wait_for(lambda: self.bus.made("SelectionWriteDone"), what="the transfer to finish")+ self.assertEqual(self.bus.made("SelectionWriteDone")[0][1:], (4, True))+ self.assertEqual(clipboard_portal.change_stamp(), before + 1) # its own echo is no change+ self.assertEqual(clipboard_portal.changed_contents(), (None, None))++ def test_another_apps_copy_is_read_once_and_moves_the_stamp(self):+ self.up()+ before = clipboard_portal.change_stamp()+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionOwnerChanged",+ (SESSION, vardict({"mime_types": ["UTF8_STRING", "text/plain;charset=utf-8"], "session_is_owner": False})))+ wait_for(lambda: clipboard_portal.change_stamp() == before + 1, what="the copy")++ def selection(body):+ read, write = os.pipe()+ threading.Thread(target=lambda: (os.write(write, b"from another app"), os.close(write))).start()+ return (read,)++ self.bus.returns["SelectionRead"] = selection+ self.assertEqual(clipboard_portal.changed_contents(), ("from another app", None))+ self.assertEqual(self.bus.made("SelectionRead")[0][1], "text/plain;charset=utf-8")+ self.assertEqual(clipboard_portal.changed_contents(), (None, None))+ self.assertEqual(clipboard_portal.get_contents(), ("from another app", None))++ def test_an_app_that_never_hands_the_clipboard_over_costs_one_read(self):+ self.up()+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionOwnerChanged",+ (SESSION, vardict({"mime_types": ["text/plain"], "session_is_owner": False})))+ wait_for(lambda: self.remote.offered, what="the copy")+ read, write = os.pipe()+ self.bus.returns["SelectionRead"] = (read,)+ saved = clipboard_portal.TIMEOUT_SECONDS+ clipboard_portal.TIMEOUT_SECONDS = 0.2+ try:+ self.assertEqual(clipboard_portal._read_fd(read, clipboard_portal.TIMEOUT_SECONDS), None)+ finally:+ clipboard_portal.TIMEOUT_SECONDS = saved+ os.close(write)++ def test_the_session_closing_lets_go_and_says_so(self): # closed from the desktop+ self.up()+ inject_portal.inject_key("shift", True)+ wait_for(lambda: self.ei.sends("key"), what="the key")+ self.bus.emit(SESSION, portal.SESSION, "Closed", ())+ wait_for(lambda: self.problems, what="the problem")+ self.assertEqual(self.problems[0], inject_portal.CLOSED)+ self.assertEqual(self.ei.sends("key")[-1][2:], (42, False))+ self.assertTrue(self.ei.closed and self.bus.closed)+++ # Review fixes (Codex Sol and a cold Opus pass, 01-10-2026)++ def test_a_paste_the_portal_fails_costs_that_paste_and_not_the_session(self):+ self.up()+ clipboard_portal.set_contents("x", None)++ def broken(body):+ raise portal.PortalError("stale serial")++ self.bus.returns["SelectionWrite"] = broken+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionTransfer", (SESSION, "text/plain", 9))+ wait_for(lambda: self.bus.made("SelectionWriteDone"), what="the failed transfer answered")+ self.assertEqual(self.bus.made("SelectionWriteDone")[0][1:], (9, False))+ self.assertTrue(self.remote.ready.is_set())+ self.assertEqual(self.problems, [])++ def test_a_session_that_ended_opens_again_without_asking_but_a_refusal_stands(self):+ self.up()+ saved = inject_portal.RETRY_SECONDS+ inject_portal.RETRY_SECONDS = 0.0+ try:+ self.ei.feed(("disconnect",))+ wait_for(lambda: self.problems, what="the problem")+ wait_for(lambda: not self.remote.ready.is_set(), what="the session down")+ self.bus.closed = False+ self.ei = FakeEi()+ inject_portal.inject_key("ctrl", True)+ wait_for(self.remote.ready.is_set, what="the session again")+ finally:+ inject_portal.RETRY_SECONDS = saved++ def test_nothing_queues_once_the_desktop_has_refused(self):+ self.bus.answers["Start"] = (1, {})+ self.remote.start()+ wait_for(lambda: self.problems, what="the refusal")+ for _ in range(50):+ inject_portal.inject_mouse_move(1, 1)+ self.assertEqual(self.remote._commands.qsize(), 0)++ def test_input_sent_before_the_devices_resume_is_played_once_they_do(self):+ self.remote.start()+ wait_for(self.remote.ready.is_set, what="the session")+ inject_portal.inject_key("ctrl", True)+ time.sleep(0.2)+ self.keyboard = FakeDevice("keyboard", {4}, keymap="xkb_keymap {}")+ self.absolute = FakeDevice("absolute", {2, 16, 32}, regions=[(0, 0, 1920, 1080, 1.0)])+ self.ei.feed(("device_added", self.keyboard), ("device_added", self.absolute),+ ("device_resumed", self.keyboard), ("device_resumed", self.absolute))+ wait_for(lambda: self.ei.sends("key"), what="the held key")+ self.assertEqual(self.ei.sends("key")[0][1:], ("keyboard", 29, True))++ def test_buttons_and_the_wheel_go_to_the_devices_that_have_them(self):+ self.remote.start()+ wait_for(self.remote.ready.is_set, what="the session")+ motion = FakeDevice("motion", {1})+ buttons = FakeDevice("buttons", {32})+ wheel = FakeDevice("wheel", {16})+ keyboard = FakeDevice("keyboard", {4}, keymap="xkb_keymap {}")+ devices = (motion, buttons, wheel, keyboard)+ self.ei.feed(*[("device_added", d) for d in devices], *[("device_resumed", d) for d in devices])+ wait_for(lambda: len(self.ei.sends("start")) == 4, what="the devices")+ inject_portal.inject_mouse_button("left", True)+ inject_portal.inject_scroll(1, 0, "line")+ wait_for(lambda: self.ei.sends("scroll_discrete"), what="the wheel")+ self.assertEqual(self.ei.sends("button")[0][1], "buttons")+ self.assertEqual(self.ei.sends("scroll_discrete")[0][1], "wheel")++ def test_an_fd_answered_after_its_caller_gave_up_is_closed(self):+ self.up()+ read, write = os.pipe()+ gate = threading.Event()++ def slow(session):+ gate.wait(2)+ return read++ self.assertIsNone(self.remote.ask(slow, timeout=0.1, discard=os.close))+ gate.set()+ wait_for(lambda: _closed(read), what="the late fd closed")+ os.close(write)++ def test_a_paste_that_never_reads_is_given_up_on(self):+ self.up()+ saved = inject_portal.WRITE_SECONDS+ inject_portal.WRITE_SECONDS = 0.3+ try:+ clipboard_portal.set_contents("y" * 200000, None)+ read, write = os.pipe()+ self.bus.returns["SelectionWrite"] = (write,)+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionTransfer", (SESSION, "text/plain", 5))+ wait_for(lambda: self.bus.made("SelectionWriteDone"), what="the transfer given up")+ self.assertEqual(self.bus.made("SelectionWriteDone")[0][1:], (5, False))+ os.close(read)+ finally:+ inject_portal.WRITE_SECONDS = saved++ def test_input_after_a_stop_does_not_open_the_session_again(self):+ self.up()+ self.remote.stop()+ inject_portal.inject_key("ctrl", True)+ time.sleep(0.2)+ self.assertFalse(self.remote._thread is not None and self.remote._thread.is_alive())+++ # Second review (Opus, 01-10-2026)++ def test_a_button_held_on_a_device_the_desktop_removes_is_forgotten_not_played(self):+ self.up()+ inject_portal.inject_mouse_button("left", True)+ wait_for(lambda: self.ei.sends("button"), what="the press")+ holder = next(d for d in (self.pointer, self.absolute) if d.name == self.ei.sends("button")[0][1])+ self.ei.feed(("device_removed", holder))+ inject_portal.inject_mouse_button("left", False)+ inject_portal.inject_key("ctrl", True)+ wait_for(lambda: self.ei.sends("key"), what="the session carrying on")+ self.assertEqual(len(self.ei.sends("button")), 1)++ def test_a_release_is_admitted_however_full_the_queue(self):+ self.up()+ inject_portal.inject_key("ctrl", True)+ inject_portal.inject_mouse_button("left", True)+ wait_for(lambda: self.ei.sends("key") and self.ei.sends("button"), what="the presses")+ saved = inject_portal.MAX_PENDING+ inject_portal.MAX_PENDING = 0+ try:+ inject_portal.inject_mouse_move(5, 5) # dropped: the queue is full+ inject_portal.inject_key("ctrl", False)+ inject_portal.inject_mouse_button("left", False)+ wait_for(lambda: len(self.ei.sends("key")) == 2 and len(self.ei.sends("button")) == 2, what="the releases")+ finally:+ inject_portal.MAX_PENDING = saved+ self.assertEqual([item[2:] for item in self.ei.sends("key")], [(29, True), (29, False)])++ def test_a_missing_library_is_said_once_and_never_retried(self):+ def missing():+ raise RuntimeError("libei is not installed; Beamer needs it to capture and play input on Wayland")++ factory = lambda fd: self.ei # noqa: E731+ factory.preflight = missing+ self.remote._ei_factory = factory+ saved = inject_portal.RETRY_SECONDS+ inject_portal.RETRY_SECONDS = 0.0+ try:+ self.remote.start()+ wait_for(lambda: self.problems, what="the problem")+ for _ in range(5):+ inject_portal.inject_key("ctrl", True)+ time.sleep(0.05)+ self.assertEqual(len(self.problems), 1)+ self.assertIn("libei", self.problems[0])+ self.assertEqual(self.bus.made("CreateSession"), [])+ finally:+ inject_portal.RETRY_SECONDS = saved++ def test_a_session_the_user_stopped_from_the_desktop_stays_stopped(self):+ self.up()+ saved = inject_portal.RETRY_SECONDS+ inject_portal.RETRY_SECONDS = 0.0+ try:+ self.bus.emit(SESSION, portal.SESSION, "Closed", ())+ wait_for(lambda: self.problems, what="the problem")+ wait_for(lambda: not self.remote.ready.is_set(), what="the session down")+ self.bus.closed = False # a new connection could be made+ inject_portal.inject_key("ctrl", True)+ time.sleep(0.2)+ self.assertEqual(len(self.bus.made("CreateSession")), 1)+ finally:+ inject_portal.RETRY_SECONDS = saved++ def test_a_session_with_no_remembered_permission_is_not_reopened_to_ask_again(self):+ self.bus.answers["Start"] = (0, {"devices": 3, "clipboard_enabled": True}) # the box unticked: no token+ self.up()+ saved = inject_portal.RETRY_SECONDS+ inject_portal.RETRY_SECONDS = 0.0+ try:+ self.ei.feed(("disconnect",))+ wait_for(lambda: self.problems, what="the problem")+ wait_for(lambda: not self.remote.ready.is_set(), what="the session down")+ self.bus.closed = False # a new connection could be made+ inject_portal.inject_key("ctrl", True)+ time.sleep(0.2)+ self.assertEqual(len(self.bus.made("CreateSession")), 1)+ finally:+ inject_portal.RETRY_SECONDS = saved+++def _closed(fd):+ try:+ os.fstat(fd)+ except OSError:+ return True+ return False+++class DesktopTest(unittest.TestCase):+ def test_a_point_off_every_display_is_brought_to_the_nearest(self):+ displays = [desktop_portal.Rect(0, 0, 1920, 1080), desktop_portal.Rect(1920, 200, 1280, 1024)]+ self.assertEqual(desktop_portal.clamp_to(displays, 1920, 100), (1919, 100))+ self.assertEqual(desktop_portal.clamp_to(displays, 3300, 700.4), (3199, 700))+ self.assertEqual(desktop_portal.clamp_to(displays, 2500, 1500), (2500, 1223))+ self.assertEqual(desktop_portal.clamp_to([], 5, 6), (5, 6))+++if __name__ == "__main__":+ unittest.main()diff --cc win_app/tests/test_input_injector.pyindex dd17545,c3c3113..529260e--- a/win_app/tests/test_input_injector.py+++ b/win_app/tests/test_input_injector.py@@@ -278,6 -278,6 +278,21 @@@ class PlanKeyInputsNamedKeyTests(unitteplan = plan_key_inputs("not_a_real_key", True, set(), {}, fake_vk_lookup, fake_scan_lookup)self.assertEqual(plan, [])++ def test_release_all_releases_a_held_named_non_modifier_key(self):++ sent = []++ input_injector._mods_down.clear()++ input_injector._char_vk_down.clear()++ input_injector._named_down.clear()++ input_injector._buttons_down.clear()++ with mock.patch.object(input_injector, "_vk_key_scan", lambda _ch: -1), \++ mock.patch.object(input_injector, "_map_virtual_key", lambda _vk: 0x48), \++ mock.patch.object(input_injector, "_send_input", lambda *items: sent.extend(items)):++ input_injector.inject_key("left", True)++ input_injector.release_all()++ self.assertEqual(len(sent), 2)++ self.assertEqual(sent[0].union.ki.dwFlags, KEYEVENTF_EXTENDEDKEY)++ self.assertEqual(sent[1].union.ki.dwFlags, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP)++class PlanScrollUnitsLineModeTests(unittest.TestCase):def test_line_mode_scales_by_120_and_never_carries_a_remainder(self):diff --cc win_app/tests/test_layout_primitives.pyindex 0000000,0000000..d6f8d32new file mode 100644--- /dev/null+++ b/win_app/tests/test_layout_primitives.py@@@ -1,0 -1,0 +1,195 @@@++"""Control bounds and responsive rows in the application's actual typeface."""++++import os++import sys++import unittest++from pathlib import Path++++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++++from PySide6.QtCore import QCoreApplication, QEvent++from PySide6.QtGui import QAccessible, QAccessibleActionInterface++from PySide6.QtTest import QTest++from PySide6.QtWidgets import QApplication, QVBoxLayout, QWidget++++import theme++import widgets++++++class LayoutPrimitivesTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ cls.app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ cls.app.setFont(theme.font(theme.TYPE["body"]))++ cls.app.setStyleSheet(theme.stylesheet())++++ def mount(self, view, width):++ host = QWidget()++ layout = QVBoxLayout(host)++ layout.setContentsMargins(0, 0, 0, 0)++ layout.addWidget(view)++ host.resize(width, 600)++ host.show()++ self.addCleanup(host.deleteLater)++ self.settle()++ return host++++ def settle(self):++ for _ in range(8):++ QCoreApplication.sendPostedEvents(None, QEvent.Type.LayoutRequest)++ self.app.processEvents()++++ def test_segmented_group_keeps_its_cap_in_a_wide_parent(self):++ choice = widgets.Choice((("a", "Short"), ("b", "Normal"), ("c", "Long")), 3, "a")++ self.mount(choice.view, 880)++ self.assertLessEqual(choice.view.width(), 360)++ self.assertLessEqual(max(button.width() for button in choice._buttons.values()), 120)++++ def test_segmented_group_reflows_without_eliding_essential_options(self):++ choice = widgets.Choice((("a", "Same shortcuts"), ("b", "Same positions"),++ ("c", "Mac keyboard layout")), 3, "a")++ host = self.mount(choice.view, 160)++ self.assertLessEqual(host.width(), 160)++ self.assertLessEqual(choice.view.width(), 160)++ buttons = list(choice._buttons.values())++ self.assertEqual(len({button.x() for button in buttons}), 1)++ self.assertEqual(len({button.y() for button in buttons}), 3)++ for button in buttons:++ self.assertEqual(button.displayed_text(), button.text())++ self.assertGreaterEqual(button.height(), 30)++++ def test_long_switch_wraps_and_keeps_a_constant_track(self):++ switch = widgets.Switch("Hold this PC's edges while an app on it is full screen")++ host = self.mount(switch, 183)++ self.assertLessEqual(host.width(), 183)++ self.assertGreaterEqual(switch.height(), switch.fontMetrics().height() * 2)++ self.assertEqual(switch.TRACK.toTuple(), (34, 18))++++ def test_form_row_reserves_the_label_track_before_placing_controls(self):++ choice = widgets.Choice((("a", "Crossing"), ("b", "Shortcut and menu")), 2, "a")++ choice.set_width(240)++ row = widgets.FormRow(widgets.label("Style for", "key"), choice.view)++ host = self.mount(row, 627)++ host.layout().addStretch(1)++ self.settle()++ self.assertEqual(row.heading.width(), 180)++ self.assertGreaterEqual(choice.view.mapTo(row, choice.view.rect().topLeft()).x(), 196)++ self.assertGreaterEqual(row.height(), choice.view.heightForWidth(choice.view.width()))++ for width in (183, 528, 627, 848, 183, 627):++ host.resize(width, 600)++ self.settle()++ point = choice.view.mapTo(row, choice.view.rect().topLeft())++ if width + 32 >= 560:++ self.assertEqual(point.x(), 196)++ else:++ self.assertEqual(point.x(), 0)++ self.assertGreaterEqual(point.y(), row.heading.height() + 8)++++ def test_capped_segments_grow_together_to_keep_full_option_text(self):++ choice = widgets.Choice((("a", "Crossing"), ("b", "Shortcut and menu")), 2, "a")++ choice.set_width(240)++ self.mount(choice.view, 627)++ buttons = list(choice._buttons.values())++ self.assertEqual(len({button.height() for button in buttons}), 1)++ for button in buttons:++ self.assertGreaterEqual(button.height(), button.heightForWidth(button.width()))++++ def test_style_tiles_expose_checked_state_and_accessible_activation(self):++ choice = widgets.ChoiceTiles(++ [(key, key, "Quiet", QWidget()) for key in ("a", "b", "c")], "a", responsive=True)++ self.mount(choice.view, 848)++ chosen = QAccessible.queryAccessibleInterface(choice.tile("a"))++ other = QAccessible.queryAccessibleInterface(choice.tile("b"))++ self.assertTrue(chosen.state().checked)++ self.assertFalse(other.state().checked)++ self.assertIn(QAccessibleActionInterface.pressAction(), other.actionInterface().actionNames())++ other.actionInterface().doAction(QAccessibleActionInterface.pressAction())++ for _ in range(60):++ if choice.value == "b":++ break++ QTest.qWait(50)++ self.assertEqual(choice.value, "b")++ self.assertTrue(other.state().checked)++ self.assertFalse(chosen.state().checked)++++ def test_family_rows_distribute_rounding_remainder_to_the_final_edge(self):++ choice = widgets.ChoiceTiles(++ [(key, key, "Quiet", QWidget()) for key in ("a", "b", "c")], "a", responsive=True)++ self.mount(choice.view, 848)++ tiles = list(choice._tiles.values())++ self.assertEqual(tiles[0].x(), 0)++ self.assertEqual(tiles[-1].x() + tiles[-1].width(), choice.view.width())++ self.assertLessEqual(max(tile.width() for tile in tiles) - min(tile.width() for tile in tiles), 1)++++ def test_accessible_toggle_keeps_one_style_selected_and_notifies_once(self):++ changes = []++ choice = widgets.ChoiceTiles(++ [(key, key, "Quiet", QWidget()) for key in ("a", "b", "c")],++ "a", on_change=changes.append, responsive=True)++ self.mount(choice.view, 848)++ other = QAccessible.queryAccessibleInterface(choice.tile("b"))++ other.actionInterface().doAction(QAccessibleActionInterface.toggleAction())++ self.assertEqual(choice.value, "b")++ self.assertEqual([tile.isChecked() for tile in choice._tiles.values()], [False, True, False])++ self.assertEqual(changes, ["b"])++ other.actionInterface().doAction(QAccessibleActionInterface.toggleAction())++ self.assertTrue(choice.tile("b").isChecked())++ self.assertEqual(changes, ["b"])++ choice.set_value("c")++ self.assertEqual(changes, ["b"])++++ def test_accessible_colour_toggle_notifies_and_programmatic_change_stays_silent(self):++ changes = []++ choice = widgets.SwatchGroups(++ [("Mono", [(key, key, ["#ffffff", "#888888"]) for key in ("a", "b", "c")])],++ "a", on_change=changes.append)++ self.mount(choice.view, 848)++ other = QAccessible.queryAccessibleInterface(choice._swatches["b"])++ other.actionInterface().doAction(QAccessibleActionInterface.toggleAction())++ self.assertEqual(choice.value, "b")++ self.assertEqual(changes, ["b"])++ choice.set_value("c")++ self.assertEqual(choice.value, "c")++ self.assertEqual(changes, ["b"])++++ def test_corrected_breakpoints_settle_identically_in_both_resize_directions(self):++ for kind, count in (("style", 3), ("colour", 5)):++ view = widgets._FamilyChoices(kind)++ for _ in range(count):++ cell = QWidget() if kind == "colour" else widgets._Tile(lambda: None)++ if kind == "style":++ QVBoxLayout(cell).addWidget(QWidget())++ view.add_cell(cell)++ host = self.mount(view, 848)++ captured = {}++ widths = (399, 400, 401, 599, 600, 601, 879, 880, 881)++ for outer in (*widths, *reversed(widths)):++ host.resize(outer - 32, 600)++ self.settle()++ expected = ((3 if outer >= 600 else 2 if outer >= 400 else 1) if kind == "style"++ else (5 if outer >= 600 else 3 if outer >= 400 else 2))++ self.assertEqual(sum(cell.y() == 0 for cell in view.cells), expected)++ geometry = tuple(cell.geometry().getRect() for cell in view.cells)++ self.settle()++ self.assertEqual(geometry, tuple(cell.geometry().getRect() for cell in view.cells))++ if outer in captured:++ self.assertEqual(geometry, captured[outer])++ captured[outer] = geometry++ sidebar = widgets.Sidebar([(key, key, "") for key in ("a", "b")], lambda key: None)++ self.addCleanup(sidebar.deleteLater)++ for width in (639, 640, 641, 799, 800, 801, 801, 800, 799, 641, 640, 639):++ sidebar.set_window_width(width)++ self.assertEqual(sidebar.width(), 56 if width < 640 else 144 if width < 800 else 176)++ row = widgets.FormRow(widgets.label("Style for", "key"), QWidget())++ host = self.mount(row, 848)++ for outer in (559, 560, 561, 561, 560, 559):++ host.resize(outer - 32, 600)++ self.settle()++ self.assertEqual(row._box.direction(), QVBoxLayout.Direction.LeftToRight++ if outer >= 560 else QVBoxLayout.Direction.TopToBottom)++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_links.pyindex 7552aad,0000000..21f83f0mode 100644,000000..100644--- a/win_app/tests/test_links.py+++ b/win_app/tests/test_links.py@@@ -1,928 -1,0 +1,959 @@@+"""This PC's input going to its peers (WIRE.md sections 3 to 5): the zones, the owner's decisions+carried out, the key names, the clipboard and the way home, against links that only record."""++import queue+import threading+import time+import unittest++from links_rig import B, C, CAPS, HERE, Rig, edge_zone, make_config++import capture_win+import sender+from core import owner as owner_module+from core import protocol+from core.return_edge import Rect+from core.tests import pngs+from core.tests import responder_harness as harness+++def target_of(message):+ return protocol.read_id(message["data"]["target"])+++class DeadKeyRoutingTests(unittest.TestCase):+ def setUp(self):+ self.rig = Rig()+ self.sender = self.rig.sender++ def test_a_dead_key_is_swallowed_only_while_its_peer_is_live(self):+ self.sender.set_redirecting(True)+ sent = list(self.rig.sent(B))+ self.assertTrue(self.sender.on_dead_key())+ self.assertEqual(self.rig.sent(B), sent)++ self.rig.links.up_set.discard(B)+ self.assertFalse(self.sender.on_dead_key())+ self.assertFalse(self.sender.redirecting)+++class EdgeTests(unittest.TestCase):+ """The outward crossing: the zone's model, the gate and the pin, which is everything the hook+ thread does per mouse move."""++ def setUp(self):+ self.rig = Rig()+ self.sender = self.rig.sender++ def test_a_push_against_the_edge_takes_the_peer_with_the_edge_and_offset(self):+ self.rig.push(4)+ self.assertTrue(self.sender.redirecting)+ focus = self.rig.sent(B, "focus")[0]["data"]+ self.assertEqual(target_of(focus and {"data": focus}), B)+ self.assertEqual(focus["edge"], "right")+ self.assertAlmostEqual(focus["offset"], 500 / 1080, places=3)+ self.assertEqual(focus["resistance_px"], 40)+ self.assertEqual(focus["reach"], [])+++ def test_a_failed_cursor_read_skips_that_event_without_disabling_crossing(self):++ rig = Rig()++ reads = iter([PermissionError("access denied"), PermissionError("access denied")] + [(0, 500)] * 4)++++ def cursor_position():++ result = next(reads)++ if isinstance(result, Exception):++ raise result++ return result++++ rig.desktop.cursor_position = cursor_position++ with self.assertLogs("sender", level="WARNING") as logs:++ rig.push(1)++ rig.push(1)++ self.assertTrue(rig.sender.zone_models())++ rig.push(4)++++ self.assertEqual(len(logs.records), 1)++ self.assertTrue(rig.sender.redirecting)+++ def test_the_push_lights_the_edge_it_is_pressing(self):+ self.rig.push(4)+ self.assertTrue(self.rig.pressure)+ self.assertTrue(all(edge == "left" for edge, _p, _c, _part in self.rig.pressure))+ self.assertTrue(self.rig.pressure[-1][2])++ def test_part_of_the_edge_lights_only_the_third_it_is_pushing(self):+ rig = Rig(cursor=(0, 900), zones=[edge_zone(B, kind="part", parts=["middle", "end"])])+ rig.push(4)+ self.assertEqual({(edge, part) for edge, _p, _c, part in rig.pressure}, {("left", "end")})++ def test_the_third_is_measured_on_the_pointers_own_display(self):+ # The left display runs 200 to 1280 of a 1440-tall desktop: 1000 is its end third, though+ # on the desktop as a whole it would be the middle one.+ rig = Rig(cursor=(0, 1000), monitors=[Rect(0, 200, 1920, 1080), Rect(1920, 0, 2560, 1440)],+ zones=[edge_zone(B, kind="part", parts=["end"])])+ rig.push(4)+ self.assertEqual({part for _e, _p, _c, part in rig.pressure}, {"end"})++ def test_the_whole_edge_names_no_third(self):+ self.rig.push(4)+ self.assertEqual({part for _e, _p, _c, part in self.rig.pressure}, {None})++ def test_a_push_away_from_the_edge_never_crosses(self):+ self.rig.push(10, dx=20)+ self.assertFalse(self.sender.redirecting)++ def test_a_pointer_off_the_edge_never_crosses(self):+ self.rig.desktop.cursor = (900, 500)+ self.rig.push(10)+ self.assertFalse(self.sender.redirecting)++ def test_a_zone_that_is_off_never_crosses(self):+ rig = Rig(zones=[edge_zone(B, off=True)])+ rig.push(10)+ self.assertFalse(rig.sender.redirecting)++ def test_a_peer_that_does_not_accept_input_is_not_a_zone_to_cross_into(self):+ rig = Rig(up=())+ rig.bring_up(B, accepts=False)+ rig.push(10)+ self.assertFalse(rig.sender.redirecting)++ def test_a_zone_leads_to_its_own_peer(self):+ rig = Rig(+ entries=[harness.entry(B, "Mac", side="left"), harness.entry(C, "Other", side="top")],+ zones=[edge_zone(B), edge_zone(C)], up=(B, C), cursor=(900, 0),+ )+ rig.push(4, dx=0, dy=-20)+ self.assertEqual(rig.sender.owner, C)+ self.assertEqual(rig.sent(B, "focus"), [])++ def test_the_shortcut_can_be_turned_off_on_its_own(self):+ self.sender.update_config(make_config(crossing_methods=["edge"]))+ self.assertFalse(self.sender.shortcut_armed)+ self.sender.update_config(make_config(crossing_methods=["edge", "shortcut"]))+ self.assertTrue(self.sender.shortcut_armed)++ def test_a_held_edge_does_not_cross(self):+ self.sender.crossing_paused = True+ self.rig.push(10)+ self.assertFalse(self.sender.redirecting)++ def test_a_drag_to_the_edge_is_not_a_crossing(self):+ self.sender.on_button("left", True)+ self.rig.push(10)+ self.assertFalse(self.sender.redirecting)+++class CornerTests(unittest.TestCase):+ """The corner is for a machine whose whole edge is busy: it wants a diagonal push in an+ 8-pixel box, and nothing else."""++ def setUp(self):+ zone = {"peer": harness.protocol.id_text(B), "kind": "corner", "corner": "top_left", "edge": "left"}+ self.rig = Rig(cursor=(0, 0), zones=[zone])++ def test_a_diagonal_push_in_the_corner_crosses_at_the_end_nearest_it(self):+ self.rig.push(4, -20, -20)+ self.assertTrue(self.rig.sender.redirecting)+ focus = self.rig.sent(B, "focus")[0]["data"]+ self.assertEqual((focus["edge"], focus["offset"]), ("right", 0.0))++ def test_the_push_names_its_corner_for_the_effects(self):+ self.rig.push(4, -20, -20)+ self.assertEqual({part for _e, _p, _c, part in self.rig.pressure}, {"top_left"})++ def test_a_straight_push_along_the_edge_does_not(self):+ self.rig.push(10, -20, 0)+ self.assertFalse(self.rig.sender.redirecting)++ def test_the_same_diagonal_away_from_the_corner_does_not(self):+ self.rig.desktop.cursor = (900, 500)+ self.rig.push(10, -20, -20)+ self.assertFalse(self.rig.sender.redirecting)+++class TakingTests(unittest.TestCase):+ def setUp(self):+ self.rig = Rig()+ self.sender = self.rig.sender++ def test_the_shortcut_takes_the_first_peer_without_a_position(self):+ self.assertTrue(self.sender.set_redirecting(True))+ focus = self.rig.sent(B, "focus")[0]["data"]+ self.assertNotIn("edge", focus)+ self.assertEqual(focus["route"], 1)+ self.assertEqual(self.rig.redirects, [True])++ def test_the_clipboard_follows_the_take_and_goes_before_any_input(self):+ self.sender.set_redirecting(True)+ self.sender.on_key("a", True, 0x41, "a")+ kinds = [message["type"] for message in self.rig.sent(B)]+ self.assertEqual(kinds, ["focus", "clipboard", "keydown"])+ self.assertEqual(self.rig.sent(B, "clipboard")[0]["data"]["text"], "here")++ def test_noncomposable_dead_key_sequence_is_sent_as_text(self):+ self.sender.set_redirecting(True)+ self.assertTrue(self.sender.on_text("§a", 0x41))+ self.assertEqual(self.rig.sent(B, protocol.MSG_TEXT)[0]["data"]["text"], "§a")++ def test_noncomposable_dead_key_text_releases_and_restores_remote_modifiers(self):+ self.sender.set_redirecting(True)+ self.rig.flush()+ self.rig.links.sent.clear()+ self.assertTrue(self.sender.on_key("shift", True, 0x10))++ self.assertTrue(self.sender.on_text("§A", 0x41))++ self.assertEqual(+ [message["type"] for message in self.rig.sent(B)],+ [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP, protocol.MSG_TEXT, protocol.MSG_KEYDOWN],+ )++ def test_temporary_text_release_keeps_the_held_modifier_wire_name_if_style_changes(self):+ self.sender.set_redirecting(True)+ self.rig.accept_take()+ self.sender.on_key("cmd", True, 0xA2)+ self.rig.flush()+ original = self.rig.sent(B, protocol.MSG_KEYDOWN)[0]["data"]["key"]+ physical = self.sender._keys_down[0xA2]++ released = self.sender._key_message(B, {"type": protocol.MSG_KEYUP, "data": dict(physical)}, preserve=True)+ self.sender.update_config(make_config(modifier_style="positional"))+ restored = self.sender._key_message(B, {"type": protocol.MSG_KEYDOWN, "data": dict(physical)})++ self.assertEqual((released["data"]["key"], restored["data"]["key"]), (original, original))+++ def test_a_dropped_peer_forgets_held_key_names_before_reconnect(self):++ self.sender.set_redirecting(True)++ self.rig.accept_take()++ self.sender.on_key("ctrl", True, 0xA2)++ self.rig.flush()++ physical = self.sender._keys_down[0xA2]++ self.sender._forget_held(B)++ self.sender.update_config(make_config(modifier_style="positional"))++ pressed_again = self.sender._key_message(B, {"type": protocol.MSG_KEYDOWN, "data": dict(physical)})++ self.assertEqual(pressed_again["data"]["key"], "cmd")+++ def test_an_image_too_large_to_decode_is_not_sent_but_the_text_is(self):+ for image, sent in ((pngs.png(), True), (pngs.png(16384, 16384), False)):+ with self.subTest(sent=sent):+ rig = Rig()+ rig.clipboard.image = image+ rig.sender.set_redirecting(True)+ data = rig.sent(B, "clipboard")[0]["data"]+ self.assertEqual(data["text"], "here")+ self.assertEqual("image" in data, sent)++ def test_a_peer_without_the_clipboard_capability_is_sent_none(self):+ self.rig.links.caps_of[B] = frozenset()+ self.sender.set_redirecting(True)+ self.assertEqual(self.rig.sent(B, "clipboard"), [])++ def test_the_clipboard_is_not_sent_again_when_nothing_changed_here(self):+ self.sender.set_redirecting(True)+ self.rig.accept_take()+ self.sender.set_redirecting(False)+ self.sender.set_redirecting(True)+ self.rig.accept_take()+ self.assertEqual(len(self.rig.sent(B, "clipboard")), 1)+ self.rig.clipboard.text = "copied"+ self.rig.clipboard.stamp += 1+ self.sender.set_redirecting(False)+ self.sender.set_redirecting(True)+ self.assertEqual([m["data"]["text"] for m in self.rig.sent(B, "clipboard")], ["here", "copied"])++ def test_the_shortcut_with_no_link_up_says_so_and_stays(self):+ rig = Rig(up=())+ self.assertFalse(rig.sender.set_redirecting(True))+ self.assertFalse(rig.sender.redirecting)+ self.assertTrue(rig.alerts[-1].startswith("Cannot switch"))++ def test_a_refusal_brings_input_home_and_says_who_refused(self):+ self.sender.set_redirecting(True)+ self.rig.inbound(B, protocol.refuse_msg(1, "busy"))+ self.assertFalse(self.sender.redirecting)+ self.assertEqual(self.rig.alerts, ["Can't cross to Mac: it is driving another machine."])+ self.assertEqual(self.rig.redirects, [True, False])+ self.assertEqual(self.rig.arrivals, [])++ def test_a_refusal_names_the_machine_this_pcs_input_is_on(self):+ rig = Rig(entries=[harness.entry(B, "Mac", side="left"), harness.entry(C, "Rig", side="top")])+ rig.sender.set_redirecting(True)+ rig.inbound(B, protocol.refuse_msg(1, "busy", other=C))+ self.assertEqual(rig.alerts, ["Can't cross to Mac: it is driving Rig."])++ def test_the_shortcut_home_reports_where_the_pointer_is_and_lets_go(self):+ self.sender.set_redirecting(True)+ self.sender.set_redirecting(False)+ self.assertEqual(self.rig.arrivals, [(None, 0, 500)])+ targets = [target_of(m) for m in self.rig.sent(B, "focus")]+ self.assertEqual(targets, [B, HERE])+ self.assertEqual(self.rig.alerts, [])++ def test_no_answer_within_a_second_brings_input_home(self):+ clock = [1000.0]+ rig = Rig()+ rig.sender._clock = rig.sender._owner._clock = lambda: clock[0]+ rig.sender.set_redirecting(True)+ clock[0] += 1.1+ rig.sender.tick()+ self.assertFalse(rig.sender.redirecting)+ self.assertEqual(rig.alerts, ["Mac did not answer"])++ def test_the_link_dropping_brings_input_home(self):+ self.sender.set_redirecting(True)+ self.rig.drop(B)+ self.assertFalse(self.sender.redirecting)+ self.assertEqual(self.rig.alerts, ["Lost the link to Mac"])++ def test_a_link_gone_quiet_is_noticed_by_the_next_keystroke(self):+ self.sender.set_redirecting(True)+ self.rig.links.up_set.discard(B)+ self.assertFalse(self.sender.on_key("a", True, 0x41, "a"))+ self.assertFalse(self.sender.redirecting)+ self.assertIn(B, self.rig.links.closed)++ def test_a_send_that_fails_brings_input_home(self):+ self.sender.set_redirecting(True)+ self.rig.links.fail_input = True+ self.sender.on_key("a", True, 0x41, "a")+ self.rig.flush()+ self.assertFalse(self.sender.redirecting)++ def test_a_driven_machine_sends_its_driver_home_before_it_drives(self):+ self.rig.driven = True+ self.assertTrue(self.sender.set_redirecting(True))+ self.assertEqual(self.rig.sent_home, [True])+ self.assertFalse(self.sender.redirecting)+ self.rig.driven = False+ self.sender._stop_event.wait(0.3)+ self.assertTrue(self.sender.redirecting)++ def test_a_push_while_driven_sends_the_driver_home_and_then_crosses(self):+ self.rig.driven = True+ self.rig.push(4)+ self.assertEqual(self.rig.sent_home, [True])+ self.rig.driven = False+ self.sender._stop_event.wait(0.3)+ self.assertTrue(self.sender.redirecting)+ self.assertEqual(self.rig.sent(B, "focus")[0]["data"]["edge"], "right")++ def test_a_take_that_lost_the_race_to_a_peers_take_stays_home(self):+ # Away is set before `driven` is read: when the peer's take was decided in between, both+ # machines go home.+ self.sender.driven = lambda: self.sender.redirecting+ self.assertFalse(self.sender._go(B))+ self.assertFalse(self.sender.redirecting)++ def test_a_peer_taking_this_pc_while_input_is_away_brings_it_home(self):+ self.sender.set_redirecting(True)+ self.sender.set_receiving(True)+ self.assertFalse(self.sender.redirecting)+++class NamingTests(unittest.TestCase):+ def test_two_machines_of_one_name_are_told_apart_in_what_the_sender_says(self):+ rig = Rig(entries=[harness.entry(B, "Studio", side="left"), harness.entry(C, "Studio")], zones=[edge_zone(B)], up=())+ first, second = rig.sender._name(B), rig.sender._name(C)+ self.assertNotEqual(first, second)+ self.assertTrue(first.startswith("Studio (") and second.startswith("Studio ("))++ def test_a_machine_nobody_knows_is_the_other_machine(self):+ rig = Rig(up=())+ self.assertEqual(rig.sender._name(C), "The other machine")+++class OnwardTests(unittest.TestCase):+ """A hand-over from the machine this PC's input is on (section 5)."""++ def setUp(self):+ self.rig = Rig(+ entries=[harness.entry(B, "Mac", side="left"), harness.entry(C, "Other", side="top")],+ zones=[edge_zone(B), edge_zone(C)], up=(B, C),+ )+ self.sender = self.rig.sender+ self.sender.set_redirecting(True)+ self.rig.accept_take(B)++ def switch(self, to, route=None, **where):+ route = self.sender._owner.route if route is None else route+ self.rig.inbound(B, protocol.switch_v6(route, to, **where))++ def test_the_reach_names_the_peers_this_pc_can_follow_to(self):+ focus = self.rig.sent(B, "focus")[0]["data"]+ self.assertEqual(focus["reach"], [protocol.id_text(C)])++ def test_a_switch_to_another_peer_takes_it_then_lets_the_first_go(self):+ self.switch(C, edge="right", offset=0.25)+ takes = self.rig.sent(C, "focus")+ self.assertEqual((takes[0]["data"]["edge"], takes[0]["data"]["offset"]), ("right", 0.25))+ self.assertEqual(self.sender.owner, B)+ self.rig.inbound(C, protocol.accept_msg(self.sender._owner.route))+ self.assertEqual(self.sender.owner, C)+ lets_go = [target_of(m) for m in self.rig.sent(B, "focus")]+ self.assertEqual(lets_go[-1], C)++ def test_input_typed_while_a_peer_is_asked_waits_and_goes_to_the_new_machine(self):+ self.switch(C)+ self.sender.on_key("a", True, 0x41, "a")+ self.assertEqual([m["type"] for m in self.rig.sent(C) if m["type"] != "focus"], [])+ self.rig.inbound(C, protocol.accept_msg(self.sender._owner.route))+ self.assertEqual([m["data"]["key"] for m in self.rig.sent(C, "keydown")], ["a"])++ def test_text_during_chained_handover_brackets_a_modifier_waiting_to_be_replayed(self):+ self.switch(C)+ self.assertTrue(self.sender.on_key("shift", True, 0x10))+ self.assertTrue(self.sender.on_text("A", 0x41))++ self.rig.inbound(C, protocol.accept_msg(self.sender._owner.route))++ self.assertEqual(+ [message["type"] for message in self.rig.sent(C) if message["type"] in protocol.INPUT_TYPES],+ [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP, protocol.MSG_TEXT, protocol.MSG_KEYDOWN],+ )++ def test_text_replayed_after_a_refused_handover_brackets_the_current_machines_modifier(self):+ self.sender.on_key("shift", True, 0x10)+ self.rig.flush()+ self.switch(C)+ self.assertTrue(self.sender.on_text("^x", 0x58))++ self.rig.inbound(C, protocol.refuse_msg(self.sender._owner.route, "owned"))++ self.assertEqual(+ [message["type"] for message in self.rig.sent(B) if message["type"] in protocol.INPUT_TYPES],+ [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP, protocol.MSG_TEXT, protocol.MSG_KEYDOWN],+ )++ def test_text_replay_keeps_a_modifier_bracket_when_the_key_repeats_during_handover(self):+ self.sender.on_key("shift", True, 0x10)+ self.rig.flush()+ self.switch(C)+ self.assertTrue(self.sender.on_text("^x", 0x58))+ self.sender.on_key("shift", True, 0x10)++ self.rig.inbound(C, protocol.refuse_msg(self.sender._owner.route, "owned"))++ self.assertEqual(+ [message["type"] for message in self.rig.sent(B) if message["type"] in protocol.INPUT_TYPES],+ [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP, protocol.MSG_TEXT, protocol.MSG_KEYDOWN, protocol.MSG_KEYDOWN],+ )++ def test_a_switch_home_lands_the_pointer_and_reports_the_arrival(self):+ self.switch(HERE, edge="left", offset=0.5)+ self.assertFalse(self.sender.redirecting)+ self.assertEqual(self.rig.desktop.placed, [(0, 540)])+ self.assertEqual(self.rig.arrivals, [("left", 0, 540)])++ def test_the_log_names_the_edge_input_lands_at_both_ways(self):+ with self.assertLogs(sender.LOGGER, "INFO") as said:+ self.switch(C, edge="right", offset=0.25)+ self.rig.inbound(C, protocol.accept_msg(self.sender._owner.route))+ self.rig.inbound(C, protocol.switch_v6(self.sender._owner.route, HERE, edge="left", offset=0.5))+ self.assertTrue(any("input is on Other, at its right edge" in line for line in said.output), said.output)+ self.assertTrue(any("input returned to this PC (switch), at its left edge" in line for line in said.output), said.output)++ def test_a_switch_home_with_no_position_reports_where_the_pointer_is(self):+ self.switch(HERE)+ self.assertEqual(self.rig.arrivals, [(None, 0, 500)])++ def test_the_peer_sending_the_input_back_by_its_edge_is_not_an_alert(self):+ self.switch(HERE, edge="left", offset=0.5)+ self.assertEqual(self.rig.alerts, [])++ def test_a_raising_arrival_callback_only_logs(self):+ def boom(edge, x, y):+ raise RuntimeError("effect fell over")++ self.sender._arrival_callback = boom+ with self.assertLogs(sender.LOGGER, "ERROR"):+ self.switch(HERE, edge="left", offset=0.5)+ self.assertTrue(self.rig.desktop.placed)++ def test_a_hand_over_given_up_before_its_answer_closes_that_peers_link(self):+ # Its accept may still be on the way: the close is what ends that ownership (WIRE.md+ # section 5). Abandoned by the shortcut home here; the owner's tests cover every way.+ self.switch(C)+ self.assertEqual(self.rig.links.closed, [])+ self.sender.set_redirecting(False)+ self.rig.flush()+ self.assertEqual(self.rig.links.closed, [C])+ self.assertFalse(self.sender.redirecting)++ def test_a_hand_over_given_up_when_the_outbound_queue_is_full_still_closes_that_peers_link(self):+ # The close cannot wait in a queue that has no room: C would stay owned by nobody driving.+ self.switch(C)+ self.sender._outbound = queue.Queue(maxsize=1)+ self.sender._outbound.put_nowait(owner_module.Send(B, protocol.ping_msg()))+ self.sender.set_redirecting(False)+ self.assertIn(C, self.rig.links.closed)++ def test_a_peer_that_cannot_be_reached_leaves_the_input_where_it_is(self):+ self.switch(C)+ self.rig.inbound(C, protocol.refuse_msg(self.sender._owner.route, "owned"))+ self.assertEqual(self.sender.owner, B)+ self.assertEqual(self.rig.alerts[-1], "Can't cross to Other: another machine is driving it.")+ # And the machine in the way, named when the refusal says which one.+ self.sender._owner._left_out.clear()+ self.rig.drop(C)+ self.rig.bring_up(C)+ self.switch(C)+ self.rig.inbound(C, protocol.refuse_msg(self.sender._owner.route, "owned", other=B))+ self.assertEqual(self.rig.alerts[-1], "Can't cross to Other: it is being driven from Mac.")+++class KeyTests(unittest.TestCase):+ """Keys leave as the key table names them for the peer's platform (WIRE.md section 7)."""++ def setUp(self):+ self.rig = Rig()+ self.sender = self.rig.sender+ self.sender.set_redirecting(True)+ self.rig.accept_take()++ def keys(self):+ return [(m["type"], m["data"]["key"]) for m in self.rig.sent(B) if m["type"] in ("keydown", "keyup")]++ def test_ctrl_goes_to_a_mac_as_cmd_in_the_semantic_style(self):+ # The capture calls the physical Ctrl "cmd".+ self.sender.on_key("cmd", True, 0xA2)+ self.sender.on_key("c", True, 0x43, "c")+ self.sender.on_key("c", False, 0x43, "c")+ self.sender.on_key("cmd", False, 0xA2)+ self.assertEqual(self.keys(), [("keydown", "cmd"), ("keydown", "c"), ("keyup", "c"), ("keyup", "cmd")])++ def test_the_windows_key_goes_to_a_mac_as_ctrl_in_the_semantic_style(self):+ self.sender.on_key("ctrl", True, 0x5B)+ self.assertEqual(self.keys(), [("keydown", "ctrl")])++ def test_positional_keeps_each_key_in_its_place(self):+ self.sender.update_config(make_config(modifier_style="positional"))+ self.sender.on_key("cmd", True, 0xA2)+ self.sender.on_key("ctrl", True, 0x5B)+ self.assertEqual(self.keys(), [("keydown", "ctrl"), ("keydown", "cmd")])++ def test_mac_layout_sends_both_sides_of_each_modifier_to_the_mac_key(self):+ self.sender.update_config(make_config(modifier_style="mac_layout"))+ for name, vk in (("cmd", 0xA2), ("cmd_r", 0xA3), ("ctrl", 0x5B), ("ctrl_r", 0x5C),+ ("alt", 0xA4), ("alt_r", 0xA5)):+ self.sender.on_key(name, True, vk)+ self.sender.on_key(name, False, vk)+ self.assertEqual(+ self.keys(),+ [(kind, key) for key in ("ctrl", "ctrl_r", "alt", "alt_r", "cmd", "cmd_r")+ for kind in ("keydown", "keyup")],+ )++ def test_to_another_pc_every_key_goes_as_itself(self):+ rig = Rig(entries=[harness.entry(B, "Other PC", platform="windows", side="left")])+ rig.sender.set_redirecting(True)+ rig.accept_take()+ rig.sender.on_key("cmd", True, 0xA2)+ rig.sender.on_key("ctrl", True, 0x5B)+ self.assertEqual([m["data"]["key"] for m in rig.sent(B, "keydown")], ["ctrl", "cmd"])++ def test_a_peer_of_no_known_platform_is_a_pc_and_gets_every_key_as_itself(self):+ # WIRE.md section 7: the PC family is Windows, Linux, Android and any unknown platform.+ unknown = harness.entry(B, "Something", side="left")+ del unknown["platform"]+ rig = Rig(entries=[unknown])+ rig.sender.set_redirecting(True)+ rig.accept_take()+ rig.sender.on_key("cmd", True, 0xA2)+ rig.sender.on_key("ctrl", True, 0x5B)+ self.assertEqual([m["data"]["key"] for m in rig.sent(B, "keydown")], ["ctrl", "cmd"])++ def test_a_release_repeats_the_name_its_press_went_under(self):+ self.sender.on_key("A", True, 0x41, "a")+ self.sender.on_key("a", False, 0x41, "a")+ self.assertEqual(self.keys(), [("keydown", "A"), ("keyup", "A")])++ def test_us_travels_with_a_character(self):+ self.sender.on_key("с", True, 0x43, "c")+ self.assertEqual(self.rig.sent(B, "keydown")[0]["data"], {"key": "с", "us": "c"})++ def test_a_media_key_is_not_sent_to_a_peer_that_does_not_take_them(self):+ self.rig.links.caps_of[B] = CAPS - {"media_keys"}+ self.sender.on_key("volume_up", True, 0xAF)+ self.assertEqual(self.keys(), [])+ self.rig.links.caps_of[B] = CAPS+ self.sender.on_key("volume_up", True, 0xAF)+ self.assertEqual(self.keys(), [("keydown", "volume_up")])++ def test_a_key_pressed_at_home_is_released_at_home(self):+ rig = Rig()+ self.assertFalse(rig.sender.on_key("a", True, 0x41, "a"))+ rig.sender.set_redirecting(True)+ self.assertFalse(rig.sender.on_key("a", False, 0x41, "a"))+ self.assertEqual(rig.sent(B, "keyup"), [])++ def test_a_key_held_on_the_peer_is_released_there_and_its_physical_release_swallowed(self):+ self.sender.on_key("a", True, 0x41, "a")+ self.sender.set_redirecting(False)+ self.assertEqual(self.keys(), [("keydown", "a"), ("keyup", "a")])+ self.assertTrue(self.sender.on_key("a", False, 0x41, "a"))++ def test_a_key_on_the_ignored_list_stays_on_this_pc(self):+ self.sender.update_config(make_config(ignored_inputs=["key:65"]))+ self.assertFalse(self.sender.on_key("a", True, 0x41, "a"))+ self.assertEqual(self.keys(), [])+++class ReviewTests(unittest.TestCase):+ """What the cold reviews of step 5b found."""++ def two(self, **config):+ return Rig(+ entries=[harness.entry(B, "Mac", side="left"), harness.entry(C, "Other", side="top")],+ zones=[edge_zone(B), edge_zone(C)], up=(B, C), **config,+ )++ def start_worker(self, rig):+ import threading++ rig.sender._stop_event.clear()+ thread = threading.Thread(target=rig.sender._outbound_worker, daemon=True)+ thread.start()+ self.addCleanup(rig.sender._stop_event.set)++ def wait(self, predicate, timeout=3.0):+ import time++ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return True+ time.sleep(0.01)+ return predicate()++ def test_a_slow_clipboard_read_does_not_hold_up_the_take_of_another_peer(self):+ rig = self.two()+ rig.clipboard.slow_get = 1.0+ self.start_worker(rig)+ rig.sender.set_redirecting(True)+ rig.sender.on_message(B, protocol.accept_msg(rig.sender._owner.route))+ rig.sender.on_message(B, protocol.switch_v6(rig.sender._owner.route, C))+ self.assertTrue(self.wait(lambda: [m for t, m in rig.links.sent if t == C and m["type"] == "focus"], 0.4),+ "the take of the next peer waited for the clipboard read")++ def test_a_read_asked_for_again_waits_its_turn_behind_a_write_decided_before_it(self):+ rig = self.two()+ rig.clipboard.block_get = True+ rig.clipboard.block_set = True+ rig.sender._deliver(owner_module.SendClipboard(B))+ self.assertTrue(rig.clipboard.get_started.wait(1), "the first clipboard read never started")++ write = threading.Thread(+ target=rig.sender._deliver,+ args=(owner_module.SetClipboard(protocol.clipboard_msg("from there")),),+ daemon=True,+ )+ write.start()+ time.sleep(0.1)++ key = {"type": protocol.MSG_KEYDOWN, "data": {"key": "v"}}+ rig.sender._deliver(owner_module.SendClipboard(B))+ rig.sender._deliver(owner_module.Send(B, key))+ rig.clipboard.release_get.set()+ self.assertTrue(rig.clipboard.set_started.wait(1), "the clipboard write never started")+ rig.clipboard.release_set.set()+ write.join(1)+ self.assertFalse(write.is_alive(), "the clipboard write did not finish")+ self.assertTrue(self.wait(lambda: not rig.sender._clip_wait), "the peer's queued messages did not finish")++ sent = [m for peer, m in rig.links.sent if peer == B]+ clipboards = [m["data"]["text"] for m in sent if m["type"] == protocol.MSG_CLIPBOARD]+ self.assertEqual(clipboards, ["here", "from there"])+ self.assertEqual([m["type"] for m in sent[-3:]], [protocol.MSG_CLIPBOARD, protocol.MSG_CLIPBOARD, protocol.MSG_KEYDOWN])++ def test_what_follows_a_clipboard_read_for_that_peer_still_goes_after_it(self):+ rig = self.two()+ rig.clipboard.slow_get = 0.2+ self.start_worker(rig)+ rig.sender.set_redirecting(True)+ rig.sender.on_key("a", True, 0x41, "a")+ self.assertTrue(self.wait(lambda: [m for t, m in rig.links.sent if t == B and m["type"] == "keydown"]))+ self.assertEqual([m["type"] for t, m in rig.links.sent if t == B], ["focus", "clipboard", "keydown"])++ def test_pointer_moves_made_during_a_clipboard_read_go_one_by_one_as_made(self):+ # Never summed: the far machine's edge feels each move where its pointer is (return_edge).+ rig = self.two()+ rig.clipboard.slow_get = 0.3+ self.start_worker(rig)+ rig.sender.set_redirecting(True)+ for dx, dy in ((3, 1), (4, -2), (5, 0)):+ rig.sender.on_motion(dx, dy)+ self.assertTrue(self.wait(lambda: [m for t, m in rig.links.sent if t == B and m["type"] == "mousemove"]))+ self.assertTrue(self.wait(lambda: not rig.sender._clip_wait))+ moves = [m["data"] for t, m in rig.links.sent if t == B and m["type"] == "mousemove"]+ self.assertEqual([(m["dx"], m["dy"]) for m in moves], [(3, 1), (4, -2), (5, 0)])++ def test_a_link_lost_during_a_clipboard_read_drops_what_waited_and_a_retake_sends_the_clipboard_after_its_focus(self):+ rig = self.two()+ rig.clipboard.slow_get = 0.4+ self.start_worker(rig)+ rig.sender.set_redirecting(True)+ self.assertTrue(self.wait(lambda: rig.sender._clip_wait))+ rig.sender.on_key("a", True, 0x41, "a")+ self.assertTrue(self.wait(lambda: rig.sender._clip_wait.get(B)))+ rig.sender.on_link(B, False)+ rig.sender.on_link(B, True, accepts=True)+ mark = len(rig.links.sent)+ rig.sender.set_redirecting(True)+ self.assertTrue(self.wait(lambda: [m for t, m in rig.links.sent[mark:] if t == B and m["type"] == "clipboard"], 2.0))+ self.assertTrue(self.wait(lambda: not rig.sender._clip_wait))+ time.sleep(0.5)+ after = [m["type"] for t, m in rig.links.sent[mark:] if t == B]+ self.assertEqual(after, ["focus", "clipboard"])++ def test_a_peer_that_starts_accepting_input_arms_its_zone_at_once(self):+ rig = Rig(up=())+ rig.bring_up(B, accepts=False)+ rig.push(10)+ self.assertFalse(rig.sender.redirecting)+ rig.inbound(B, protocol.accepts_msg(True))+ rig.sender.tick()+ rig.push(4)+ self.assertTrue(rig.sender.redirecting)++ def test_every_auto_repeat_of_a_key_keeps_the_name_its_press_went_under(self):+ rig = Rig(modifier_style="positional")+ rig.sender.set_redirecting(True)+ rig.accept_take()+ rig.sender.on_key("cmd", True, 0xA2)+ rig.flush()+ rig.sender.update_config(make_config(modifier_style="semantic"))+ rig.sender.on_key("cmd", True, 0xA2)+ rig.sender.on_key("cmd", False, 0xA2)+ self.assertEqual([m["data"]["key"] for m in rig.sent(B) if m["type"] in ("keydown", "keyup")], ["ctrl"] * 3)++ def test_settings_from_a_peer_that_does_not_list_the_capability_are_ignored(self):+ rig = Rig()+ seen = []+ rig.sender.settings_callback = lambda peer, data: seen.append(data)+ rig.links.caps_of[B] = frozenset({"clipboard"})+ rig.inbound(B, protocol.settings_msg({"on": False, "set_at": 5, "by": ""}))+ self.assertEqual(seen, [])+ rig.links.caps_of[B] = CAPS+ rig.inbound(B, protocol.settings_msg({"on": False, "set_at": 5, "by": ""}))+ self.assertEqual(len(seen), 1)++ def test_a_peer_that_is_down_is_named_with_its_own_status_not_the_first_peers(self):+ rig = Rig(+ entries=[harness.entry(B, "Mac", side="left"), harness.entry(C, "Other", side="top")],+ zones=[edge_zone(B), edge_zone(C)], up=(B,),+ )+ rig.sender.on_status(rig.links.key_of(rig.settings.data["peers"][0]), True, "Connected to Mac")+ rig.sender.on_status(rig.links.key_of(rig.settings.data["peers"][1]), False, "Other is unreachable")+ rig.sender.go(C)+ self.assertEqual(rig.alerts, ["Cannot switch — Other is unreachable"])++ def test_stopping_sends_the_let_go_and_the_releases_first(self):+ rig = Rig()+ rig.sender._threads = []+ rig.sender.start(make_config(crossing_resistance_px=40))+ rig.sender.set_redirecting(True)+ rig.accept_take()+ rig.sender.on_key("a", True, 0x41, "a")+ rig.sender.stop()+ kinds = [m["type"] for _peer, m in rig.links.sent if m["type"] in ("keyup", "focus")]+ self.assertEqual(kinds[-2:], ["keyup", "focus"])++ def test_a_driver_that_cannot_be_sent_home_is_said_so_and_the_move_is_not_made(self):+ rig = Rig()+ rig.driven = True+ rig.sender.send_peer_home = lambda: False+ rig.sender.set_redirecting(True)+ self.assertTrue(rig.sender._stop_event.wait(0.2) or True)+ self.assertFalse(rig.sender.redirecting)+ self.assertTrue(self.wait(lambda: rig.alerts))+ self.assertTrue(rig.alerts[0].startswith("Cannot switch"))+++class MouseTests(unittest.TestCase):+ def setUp(self):+ self.rig = Rig()+ self.sender = self.rig.sender++ def test_nothing_is_swallowed_or_sent_while_input_is_this_pcs(self):+ self.assertFalse(self.sender.on_button("left", True))+ self.assertFalse(self.sender.on_wheel(1.0, 0.0))+ self.assertFalse(self.sender.on_pointer_move())+ self.sender.on_motion(5, 5)+ self.assertEqual(self.rig.sent(B), [])++ def test_everything_goes_to_the_peer_and_off_this_pc_while_it_has_input(self):+ self.sender.set_redirecting(True)+ self.rig.accept_take()+ self.rig.desktop.cursor = (0, 500)+ self.rig.desktop.cursor = (40, 60)+ self.assertTrue(self.sender.on_pointer_move())+ self.assertEqual(self.rig.desktop.placed[-1], (0, 500))+ self.sender.on_motion(3, -2)+ self.assertTrue(self.sender.on_button("left", True))+ self.assertTrue(self.sender.on_wheel(-1.0, 0.0))+ kinds = [m["type"] for m in self.rig.sent(B) if m["type"] not in ("focus", "clipboard")]+ self.assertEqual(kinds, ["mousemove", "mousedown", "scroll"])+ self.assertEqual(self.rig.sent(B, "mousemove")[0]["data"], {"dx": 3, "dy": -2})++ def test_a_button_pressed_here_is_released_here_after_input_left(self):+ self.assertFalse(self.sender.on_button("left", True))+ self.sender.set_redirecting(True)+ self.assertFalse(self.sender.on_button("left", False))++ def test_a_button_held_on_the_peer_is_released_there(self):+ self.sender.set_redirecting(True)+ self.sender.on_button("right", True)+ self.sender.set_redirecting(False)+ self.assertEqual([m["data"]["button"] for m in self.rig.sent(B, "mouseup")], ["right"])+ self.assertTrue(self.sender.on_button("right", False))++ def test_the_round_trip_is_the_links_while_input_is_there_and_none_at_home(self):+ self.rig.links.trip = 7+ self.assertIsNone(self.sender.round_trip_ms)+ self.sender.set_redirecting(True)+ self.assertEqual(self.sender.round_trip_ms, 7)+++class SettingsTests(unittest.TestCase):+ def test_a_machine_without_an_id_drives_nothing(self):+ rig = Rig(up=(), machine_id="")+ self.assertFalse(rig.sender.on_key("a", True, 0x41, "a"))+ self.assertFalse(rig.sender.set_redirecting(True))++ def test_the_links_are_told_the_peers_whenever_they_are_read(self):+ rig = Rig()+ rig.sender.refresh()+ self.assertEqual(len(rig.links.synced[-1]), 1)++ def test_a_peer_that_learns_its_id_gives_the_zones_a_target(self):+ migrated = harness.entry("", "Mac", side="left", from_1_4=True, linked=False)+ rig = Rig(entries=[migrated], zones=[edge_zone(B)], up=())+ rig.settings.data["zones"] = [{"peer": "", "kind": "edge"}]+ rig.settings.data["peers"][0]["id"] = protocol.id_text(B)+ rig.settings.data["zones"][0]["peer"] = protocol.id_text(B)+ rig.bring_up(B)+ rig.push(4)+ self.assertTrue(rig.sender.redirecting)++ def test_a_clipboard_set_by_a_peer_reaches_the_clipboard_only_from_a_machine_just_let_go(self):+ rig = Rig()+ rig.sender.set_redirecting(True)+ rig.accept_take()+ rig.sender.set_redirecting(False)+ rig.inbound(B, protocol.clipboard_msg("from the mac"))+ self.assertEqual(rig.clipboard.set_calls, [("from the mac", None)])+ rig.inbound(B, protocol.clipboard_msg("again"))+ self.assertEqual(len(rig.clipboard.set_calls), 1)++ def let_go_of_b(self):+ rig = Rig()+ rig.sender.set_redirecting(True)+ rig.accept_take()+ rig.sender.set_redirecting(False)+ return rig++ def test_a_clipboard_with_a_text_that_is_not_a_string_costs_nothing(self):+ rig = self.let_go_of_b()+ rig.bring_up(C)+ rig.sender._owner.on = C+ rig.inbound(B, {"type": protocol.MSG_CLIPBOARD, "data": {"text": 5}})+ self.assertEqual(rig.clipboard.set_calls, [])+ self.assertEqual(rig.sent(C, "clipboard"), [])+ self.assertEqual(rig.links.closed, [])+ self.assertTrue(rig.links.up(C))++ def test_a_clipboard_is_handed_to_the_owner_as_rebuilt_from_what_was_read(self):+ rig = self.let_go_of_b()+ taken = []+ rig.sender._owner.clipboard_arrived = lambda peer, began, message: taken.append(message) or []+ rig.inbound(B, {"type": protocol.MSG_CLIPBOARD, "data": {"text": "hi", "z": [{}, {}]}, "extra": 1})+ self.assertEqual(taken, [protocol.clipboard_msg("hi", None)])+ rig.inbound(B, {"type": protocol.MSG_CLIPBOARD, "data": {"text": 5}})+ self.assertEqual(len(taken), 1)+++class ArrangementTests(unittest.TestCase):+ def test_this_pcs_edge_and_stamp_travel_to_a_peer_with_this_pc_as_the_author(self):+ rig = Rig()+ self.assertTrue(rig.sender.send_arrangement(B, "left", 1790000001))+ message = rig.sent(B, "arrangement")[0]+ # way_back too, as every arrangement carries it (WIRE.md section 8).+ self.assertEqual({key: message["data"][key] for key in ("edge", "set_at", "by")},+ {"edge": "left", "set_at": 1790000001, "by": protocol.id_text(HERE)})+ self.assertIsInstance(message["data"]["way_back"], bool)++ def test_no_link_up_means_the_app_must_use_the_peers_own(self):+ rig = Rig(up=())+ self.assertFalse(rig.sender.send_arrangement(B, "left", 1790000001))++ def test_a_peers_arrangement_reaches_the_app(self):+ rig = Rig()+ seen = []+ rig.sender.arrangement_callback = lambda peer, read: seen.append((peer, read["edge"]))+ rig.inbound(B, protocol.arrangement_v6("right", 5, B))+ self.assertEqual(seen, [(B, "right")])++ def test_a_malformed_arrangement_is_ignored(self):+ rig = Rig()+ seen = []+ rig.sender.arrangement_callback = lambda peer, read: seen.append(read)+ rig.inbound(B, {"type": "arrangement", "data": {"edge": "up", "set_at": "x"}})+ self.assertEqual(seen, [])+++class WakeTests(unittest.TestCase):+ def setUp(self):+ self.woken = []+ self.rig = Rig(entries=[harness.entry(B, "Mac", side="left", hw="aa:bb:cc:dd:ee:ff")], up=())+ self.sender = self.rig.sender+ self.sender._wake_sender = lambda address, host=None: self.woken.append((address, host))++ def test_switching_with_the_peer_asleep_wakes_it(self):+ self.sender.set_redirecting(True)+ self.sender._stop_event.wait(0.2)+ self.assertEqual(self.woken, [("aa:bb:cc:dd:ee:ff", "192.168.77.9")])+ self.sender._stop_event.set()++ def test_a_peer_that_answered_and_refused_is_not_woken(self):+ self.rig.links.refusing.add(B)+ self.assertFalse(self.sender.wake(B))++ def test_a_peer_without_a_hardware_address_is_not_woken(self):+ self.rig.settings.data["peers"][0]["hw"] = ""+ self.sender.refresh()+ self.assertFalse(self.sender.wake(B))+++class SelfConnectionTests(unittest.TestCase):+ """The one way this PC could take its own daily link down: learning its own address as a peer's."""++ def test_loopback_and_this_pcs_own_addresses_are_refused(self):+ local = ["192.168.77.3"]+ for host in ("127.0.0.1", "", "0.0.0.0", "192.168.77.3"):+ self.assertTrue(sender.is_this_machine(host, local_addresses=local, address_towards=lambda h: "192.168.77.3"), host)++ def test_a_peers_address_is_not(self):+ self.assertFalse(sender.is_this_machine("192.168.77.5", local_addresses=["192.168.77.3"], address_towards=lambda h: "192.168.77.3"))++ def test_this_pcs_own_real_address_is_not_missed_when_enumeration_fails(self):+ self.assertTrue(sender.is_this_machine("192.168.77.3", local_addresses=[], address_towards=lambda h: h))++ def test_a_route_probe_that_fails_does_not_stop_the_link(self):+ def fail(host):+ raise OSError("no route")++ self.assertFalse(sender.is_this_machine("192.168.77.5", local_addresses=[], address_towards=fail))+++class CaptureTests(unittest.TestCase):+ def test_the_hook_translates_a_windows_message_into_the_neutral_calls(self):+ self.assertEqual(capture_win.mouse_event(capture_win.WM_LBUTTONDOWN, 0), ("button", "left", True))+ self.assertEqual(capture_win.mouse_event(capture_win.WM_MOUSEMOVE, 0), ("move",))+ self.assertEqual(capture_win.mouse_event(capture_win.WM_MOUSEWHEEL, 120 << 16), ("wheel", 1.0, 0.0))+ self.assertEqual(capture_win.mouse_event(capture_win.WM_MOUSEHWHEEL, 120 << 16), ("wheel", 0.0, 1.0))+ self.assertIsNone(capture_win.mouse_event(0x9999, 0))+++if __name__ == "__main__":+ unittest.main()diff --cc win_app/tests/test_locale_text.pyindex 0000000,0000000..5a26d21new file mode 100644--- /dev/null+++ b/win_app/tests/test_locale_text.py@@@ -1,0 -1,0 +1,40 @@@++import sys++import unittest++from pathlib import Path++from unittest import mock++++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++sys.path.append(str(Path(__file__).resolve().parents[2]))++++from PySide6.QtWidgets import QApplication, QMenu, QSystemTrayIcon++++import widgets++from core import locale++++++class VisibleTextTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ cls.app = QApplication.instance() or QApplication([])++++ def test_us_spelling_applies_at_widget_menu_tooltip_and_action_setters(self):++ notices = []++++ def capture(_tray, title, body, *_args):++ notices.append((title, body))++++ with mock.patch.object(locale, "is_us_region", return_value=True):++ with mock.patch.object(QSystemTrayIcon, "showMessage", capture):++ widgets.install_text_localisation()++ label = widgets.label("Colourful behaviour", "note")++ label.setText("Favourite centre")++ label.setToolTip("Organising a colourful favourite")++ menu = QMenu()++ action = menu.addAction("Minimise")++ action.setText("Initialising cancelled")++ QSystemTrayIcon().showMessage("Initialising", "Cancelled colourful behaviour")++++ self.assertEqual(label.text(), "Favorite center")++ self.assertEqual(label.toolTip(), "Organizing a colorful favorite")++ self.assertEqual(action.text(), "Initializing canceled")++ self.assertEqual(notices, [("Initializing", "Canceled colorful behavior")])diff --cc win_app/tests/test_page_column_geometry.pyindex 0000000,0000000..01b4720new file mode 100644--- /dev/null+++ b/win_app/tests/test_page_column_geometry.py@@@ -1,0 -1,0 +1,80 @@@++"""Centred scroll columns must follow the document after page and width changes."""++++import os++import sys++import unittest++from pathlib import Path++from types import MethodType, SimpleNamespace++++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++++from PySide6.QtCore import QCoreApplication, QEvent++from PySide6.QtWidgets import QApplication, QHBoxLayout, QStackedWidget, QWidget++++import kvm_bridge_win as kvm++import theme++++++class PageColumnGeometryTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ cls.app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ cls.app.setFont(theme.font(theme.TYPE["body"]))++++ def settle(self):++ for _ in range(5):++ QCoreApplication.sendPostedEvents(None, QEvent.Type.LayoutRequest)++ self.app.processEvents()++++ def test_centred_column_stays_in_document_after_hidden_page_resize(self):++ window = QWidget()++ window.setMinimumSize(640, 600)++ stack = QStackedWidget()++ row = QHBoxLayout(window)++ row.setContentsMargins(0, 0, 0, 0)++ row.setSpacing(0)++ sidebar = QWidget()++ sidebar.setFixedWidth(177)++ row.addWidget(sidebar)++ row.addWidget(stack)++ for index in range(5):++ owner = SimpleNamespace(++ scope_labels={}, _host="localhost-live.example.lan",++ _hide_addresses=lambda: False, _set_hide_addresses=lambda *_: None,++ _shown=lambda text: text, save=lambda: None, _firewall_action=lambda: None,++ )++ owner._firewall_module = MethodType(kvm.WindowsApplication._firewall_module, owner)++ scroll, layout = kvm.WindowsApplication._page_shell(++ owner, "Connection", "Reach this machine")++ kvm.WindowsApplication._connection_page(owner, layout, kvm.default_config())++ owner.firewall_note.setText(++ "Windows Firewall lets your other machines reach Beamer on port 24820 on this "++ "private network, and lets a new machine discover this PC.")++ layout.addStretch(1)++ stack.addWidget(scroll)++ self.addCleanup(window.deleteLater)++ window.resize(1000, 800)++ window.show()++ self.settle()++ for width in (640, 1600, 640, 1000, 640):++ window.resize(width, 600)++ self.settle()++ for index in range(stack.count()):++ stack.setCurrentIndex(index)++ self.settle()++ page = stack.currentWidget().widget()++ column = page.findChild(QWidget, "page_column")++ bounds = column.geometry()++ with self.subTest(width=width, page=index):++ self.assertLessEqual(bounds.right(), page.width() - 1,++ f"column {bounds.getRect()}, document {page.size().toTuple()}, "++ f"layout {page.layout().geometry().getRect()}")++ self.assertAlmostEqual(bounds.x(), (page.width() - column.width()) / 2, delta=1,++ msg=f"column {bounds.getRect()}, document {page.size().toTuple()}, "++ f"layout {page.layout().geometry().getRect()}")++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_pages_win.pyindex 343b103,c8a511a..e8525da--- a/win_app/tests/test_pages_win.py+++ b/win_app/tests/test_pages_win.py@@@ -91,8 -82,8 +91,10 @@@ class DesignGroupsTest(unittest.TestCasdef test_colours_are_grouped_as_the_styles_are(self):groups = pages_win.colour_groups()-- self.assertEqual([title for title, _items in groups], [title for title, _items in pages_win.style_groups()])-- self.assertEqual(tuple(value for _t, items in groups for value, _name in items), app_config.GLOW_COLOURS)++ self.assertEqual([title for title, _items in groups], ['Light', 'Mono', 'Membrane', 'Sparks', 'Instrument', 'Folio', 'Selvedge', 'Bright'])++ self.assertEqual(dict(groups)['Mono'], tuple((key, name) for key, (name, _stops) in effects.MONO_PACKS.items()))++ self.assertTrue(all(len(items) == 5 for title, items in groups))++ self.assertEqual(set(value for _t, items in groups for value, _name in items), set(app_config.GLOW_COLOURS))def test_effects_that_cannot_load_leave_only_the_classic_choices(self):real = effects._load@@@ -105,8 -96,8 +107,8 @@@styles, colours = pages_win.style_groups(), pages_win.colour_groups()finally:effects._load = real- self.assertEqual([title for title, _items in styles], ["Classic"])- self.assertEqual([title for title, _items in colours], ["Classic"])+ self.assertEqual([title for title, _items in styles], ["Light"])- self.assertEqual([title for title, _items in colours], ["Light"])++ self.assertEqual([title for title, _items in colours], ["Light", "Mono"])def test_only_the_new_effects_count_as_effects(self):self.assertFalse(pages_win.is_effect("glow"))@@@ -315,71 -312,42 +317,73 @@@ class CrossingPageTest(unittest.TestCasos.environ.setdefault("QT_QPA_PLATFORM", "offscreen")self.app = QApplication.instance() or QApplication([])- import diagramimport kvm_bridge_win-- self.reflect = kvm_bridge_win.WindowsApplication._reflect_ways- self.host = QWidget()- self.page = SimpleNamespace(- _config=app_config.default_config(),- way_boxes={way: QCheckBox(way) for way in pages_win.WAYS},- part_buttons={part: QPushButton() for part in ("start", "middle", "end")},- parts_note=widgets.label("", "note"),- # Inside a window that is never shown, as on a page before the window opens.- crossing_rows={key: QWidget(self.host) for key in ("edge", "parts", "corner", "dragging")},- resistance_module=QWidget(self.host),- shortcut_module=QWidget(self.host),- pause_row=QWidget(self.host),- ways_summary=widgets.label("", "note"),- edge_unlearned=QWidget(self.host),- arrangement_diagram=diagram.ArrangementDiagram(),- resistance_strip=diagram.PushStrip(),- )- for button in self.page.part_buttons.values():- button.setCheckable(True)+ import theme+ from core import protocol+ from core.tests import responder_harness as harness++ 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))+ self.peer = protocol.id_text(harness.B)+ settings["peers"] = [harness.entry(harness.B, "Mac", side="right")]+ settings["port"] = harness.free_port()+ app_config.write_settings(self.path, settings)+ self.page = kvm_bridge_win.WindowsApplication(self.path)+ self.page._send_to = lambda peer, message: True+ self.addCleanup(self.page.deleteLater)+ self.addCleanup(self.page.server.stop)++ def ways(self, methods=(), parts=("middle",), side=None):+ app_config.set_ways(self.path, self.peer, side=side, methods=list(methods), parts=list(parts), corner="top_left")+ self.page._pull_peer_fields()def shown(self):+ import motion+page = self.page- rows = {key for key, row in page.crossing_rows.items() if not row.isHidden()}- rows |= {"resistance"} - ({"resistance"} if page.resistance_module.isHidden() else set())- rows |= {"shortcut"} - ({"shortcut"} if page.shortcut_module.isHidden() else set())+ rows = {key for key, row in page.crossing_rows.items() if motion.target_shown(row)}+ rows |= {"resistance"} if motion.target_shown(page.resistance_module) else set()+ rows |= {"shortcut"} if motion.target_shown(page.shortcut_module) else set()return rows+ def test_the_native_titlebar_can_maximise_and_has_no_width_cap(self):+ from PySide6.QtCore import Qt++ self.assertTrue(self.page.windowFlags() & Qt.WindowType.WindowMaximizeButtonHint)+ self.assertEqual(self.page.maximumWidth(), 16777215)++ def test_crossing_controls_and_diagram_stay_in_a_capped_column(self):+ from PySide6.QtWidgets import QApplication+++ import tokens+++ self.page.resize(2560, 1440)+ self.page.show()+ self.page._select_page("crossing")+ QApplication.processEvents()+- self.assertLessEqual(self.page.arrangement_diagram.width(), 960)- self.assertLessEqual(max(button.width() for button in self.page.edge_choice._buttons.values()), 240)++ self.assertLessEqual(self.page.arrangement_diagram.width(), tokens.PAGE_CONTENT_MAX)++ self.assertLessEqual(max(button.width() for button in self.page.edge_choice._buttons.values()), tokens.PAGE_CONTENT_MAX / 4)++ def test_jump_placeholder_uses_body_text_with_the_hint_below(self):+ from PySide6.QtWidgets import QApplication++ self.page.resize(820, 700)+ self.page.show()+ self.page._select_page("crossing")+ QApplication.processEvents()++ self.assertEqual(self.page.jump_recorder.key.property("vernier"), "body")+ self.assertLess(self.page.jump_recorder.key.y(), self.page.jump_recorder.hint.y())+def test_rows_hide_and_come_back_with_the_ways(self):- self.page._config.crossing_methods = ["shortcut"]- self.reflect(self.page)+ self.ways()self.assertEqual(self.shown(), {"edge", "shortcut"})- self.page._config.crossing_methods = ["part"]- self.reflect(self.page)+ self.page._ways_changed("shortcut", False)+ self.ways(["part"])self.assertEqual(self.shown(), {"edge", "parts", "dragging", "resistance"})self.assertTrue(self.page.way_boxes["part"].isChecked())self.assertFalse(self.page.way_boxes["shortcut"].isChecked())@@@ -412,22 -404,14 +416,22 @@@def test_the_crossing_line_gives_the_first_reason_nothing_can_cross(self):line = pages_win.crossing_state_sentenceself.assertTrue(line(False, False, False, False, True, False, None).startswith("Not paired yet"))- self.assertTrue(line(True, False, True, False, True, False, None).startswith("Waiting to hear from your Mac"))- self.assertTrue(line(True, True, False, False, True, False, None).startswith("This PC drives your Mac is off"))- self.assertTrue(line(True, True, True, False, True, False, None).startswith("Not connected to your Mac"))+ self.assertTrue(line(True, False, True, False, True, False, None).startswith("Waiting to hear from the other machine"))+ self.assertTrue(line(True, True, False, False, True, False, None).startswith("This PC does not drive the other machine"))+ self.assertTrue(line(True, True, True, False, True, False, None).startswith("Not connected to the other machine"))self.assertTrue(line(True, True, True, True, False, False, None).startswith("Only the shortcut"))-- self.assertTrue(line(True, True, True, True, True, True, None).startswith("Paused."))- self.assertTrue(line(True, True, True, True, True, False, "Keynote").startswith("Off while Keynote"))++ self.assertTrue(line(True, True, True, True, True, True, None).startswith("Pauses pointer crossing"))+ self.assertEqual(line(True, True, True, True, True, False, "Keynote"),+ "Held: an app is full screen.")self.assertEqual(line(True, True, True, True, True, False, None), "On. Pause it to lean on an edge without switching.")+ def test_the_crossing_line_names_the_machine_it_is_given(self):+ line = pages_win.crossing_state_sentence+ self.assertTrue(line(True, True, True, False, True, False, None, "Studio Mac").startswith("Not connected to Studio Mac"))+ self.assertIn("Studio Mac", line(True, False, True, False, True, False, None, "Studio Mac"))+ self.assertIn("Studio Mac", line(True, True, False, False, True, False, None, "Studio Mac"))+ self.assertIn("pair a machine", line(False, False, False, False, True, False, None, "Studio Mac"))+def test_a_reason_shows_even_when_only_the_shortcut_is_on(self):self.assertTrue(pages_win.crossing_state_blocked(False, True, True, True))self.assertTrue(pages_win.crossing_state_blocked(True, False, True, True))diff --cc win_app/tests/test_pair_code_rendering.pyindex 0000000,0000000..b7649b2new file mode 100644--- /dev/null+++ b/win_app/tests/test_pair_code_rendering.py@@@ -1,0 -1,0 +1,258 @@@++import json++import math++import os++import sys++import unittest++from pathlib import Path++++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++++from PySide6.QtGui import QColor, QImage++from PySide6.QtWidgets import QApplication++++import machines_win++import theme++++++class PairCodeRenderingTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ cls.app = QApplication.instance() or QApplication([])++ previous_font = cls.app.font()++ previous_stylesheet = cls.app.styleSheet()++ cls.addClassCleanup(cls.app.setStyleSheet, previous_stylesheet)++ cls.addClassCleanup(cls.app.setFont, previous_font)++ theme.init_fonts()++ cls.app.setFont(theme.font(theme.TYPE["body"]))++ cls.app.setStyleSheet(theme.stylesheet())++++ def setUp(self):++ self.sheet = machines_win.PairingSheet(lambda: None, lambda: None, lambda *_: None, lambda *_: None)++ self.sheet.resize(432, 900)++ self.sheet.show()++ self.app.processEvents()++ self.addCleanup(self.sheet.deleteLater)++++ def _pixel_metrics(self, widget, digit):++ cells = widget.digit_cells()++ self.assertEqual(len(cells), 6)++ image = widget.grab().toImage().convertToFormat(QImage.Format.Format_ARGB32)++ scale = image.devicePixelRatio()++ result = []++ for index, cell in enumerate(cells):++ left = max(0, math.ceil(cell.left() * scale - 0.5))++ top = max(0, math.ceil(cell.top() * scale - 0.5))++ right = min(image.width(), math.ceil(cell.right() * scale - 0.5))++ bottom = min(image.height(), math.ceil(cell.bottom() * scale - 0.5))++ points = []++ for y in range(top, bottom):++ for x in range(left, right):++ colour = image.pixelColor(x, y)++ if colour.red() > 175 and colour.green() > 175 and colour.blue() > 165:++ points.append((x, y))++ if not points:++ result.append(None)++ continue++ ink_box = (min(x for x, _ in points), min(y for _, y in points),++ max(x for x, _ in points), max(y for _, y in points))++ box_centre = (cell.center().x() * scale, cell.center().y() * scale)++ ink_centre = ((ink_box[0] + ink_box[2] + 1) / 2,++ (ink_box[1] + ink_box[3] + 1) / 2)++ result.append({"digit": digit, "slot": index,++ "dx": round(ink_centre[0] - box_centre[0], 3),++ "dy": round(ink_centre[1] - box_centre[1], 3)})++ return result++++ def _save(self, widget, name):++ root = Path(__file__).resolve().parents[2] / "renders" / "qt"++ root.mkdir(parents=True, exist_ok=True)++ widget.grab().save(str(root / name))++++ def _save_atlas(self, images, name):++ from PySide6.QtGui import QPainter++++ first = images[0]++ atlas = QImage(first.width(), first.height() * len(images), QImage.Format.Format_ARGB32)++ atlas.fill(QColor(theme.colour("ground")))++ painter = QPainter(atlas)++ for index, image in enumerate(images):++ image.setDevicePixelRatio(1)++ painter.drawImage(0, index * image.height(), image)++ painter.end()++ root = Path(__file__).resolve().parents[2] / "renders" / "qt"++ root.mkdir(parents=True, exist_ok=True)++ atlas.save(str(root / name))++++ @staticmethod++ def _name(view, widget, width=None):++ scale = widget.grab().devicePixelRatio()++ width_tag = f"-{width}px" if width else ""++ return f"{view}{width_tag}-{scale:g}x.png"++++ def _assert_box_borders(self, widget):++ image = widget.grab().toImage().convertToFormat(QImage.Format.Format_ARGB32)++ scale = image.devicePixelRatio()++ edge = QColor(theme.colour("edge"))++ for cell in widget._cell_rectangles():++ self.assertGreaterEqual(cell.left(), 0, f"cell extends left of its widget: {cell}, {widget.size()}")++ self.assertLessEqual(cell.right(), widget.width(), f"cell extends right of its widget: {cell}, {widget.size()}")++ self.assertGreaterEqual(cell.top(), 0, f"cell extends above its widget: {cell}, {widget.size()}")++ self.assertLessEqual(cell.bottom(), widget.height(), f"cell extends below its widget: {cell}, {widget.size()}")++ x = round(cell.center().x() * scale)++ y = round(cell.top() * scale)++ found = False++ for px in range(x - 2, x + 3):++ for py in range(y - 2, y + 3):++ if not (0 <= px < image.width() and 0 <= py < image.height()):++ continue++ colour = image.pixelColor(px, py)++ if max(abs(colour.red() - edge.red()), abs(colour.green() - edge.green()),++ abs(colour.blue() - edge.blue())) < 24:++ found = True++ self.assertTrue(found, f"missing rendered cell border near {(x, y)}")++++ def test_typed_digits_are_ink_centred_in_six_boxes_for_every_digit(self):++ measurements = []++ for width in (432, 640):++ self.sheet.resize(width, 900)++ self.app.processEvents()++ samples = []++ for digit in "0123456789":++ with self.subTest(width=width, digit=digit):++ self.sheet.code.setText(digit * 6)++ self.app.processEvents()++ offsets = self._pixel_metrics(self.sheet.code, digit)++ self.assertTrue(all(offset is not None for offset in offsets), offsets)++ measurements.extend(offsets)++ samples.append(self.sheet.code.grab().toImage())++ self._save_atlas(samples, self._name("digits-typed", self.sheet.code, width))++ self.sheet.code.setText("012345")++ self.app.processEvents()++ self._save(self.sheet, self._name("sheet-typed", self.sheet, width))++ self._assert_box_borders(self.sheet.code)++ self.sheet.code.clear()++ self.app.processEvents()++ self._save(self.sheet, self._name("sheet-empty", self.sheet, width))++ self._assert_box_borders(self.sheet.code)++ self.assertTrue(all(offset is None for offset in self._pixel_metrics(self.sheet.code, "")))++ self._write_measurements("typed", measurements)++ self.assertTrue(all(abs(offset[axis]) <= 1 for offset in measurements for axis in ("dx", "dy")),++ measurements)++++ def test_shown_digits_are_ink_centred_in_six_boxes_for_every_digit(self):++ measurements = []++ for width in (432, 640):++ self.sheet.resize(width, 900)++ self.app.processEvents()++ samples = []++ for digit in "0123456789":++ with self.subTest(width=width, digit=digit):++ self.sheet.show_code(digit * 6, 60, "192.0.2.1:51820", None, "")++ self.app.processEvents()++ offsets = self._pixel_metrics(self.sheet.code_label, digit)++ self.assertTrue(all(offset is not None for offset in offsets), offsets)++ measurements.extend(offsets)++ samples.append(self.sheet.code_label.grab().toImage())++ self._save_atlas(samples, self._name("digits-shown", self.sheet.code_label, width))++ self.sheet.show_code("012345", 60, "192.0.2.1:51820", None, "")++ self.app.processEvents()++ self._save(self.sheet, self._name("sheet-shown", self.sheet, width))++ self._assert_box_borders(self.sheet.code_label)++ self._write_measurements("shown", measurements)++ self.assertTrue(all(abs(offset[axis]) <= 1 for offset in measurements for axis in ("dx", "dy")),++ measurements)++++ def test_pair_action_precedes_the_machines_list(self):++ module = machines_win.MachinesModule(*([lambda *_: None] * 5))++ module.resize(560, 300)++ module.show()++ self.app.processEvents()++ button_y = module.pair_button.mapTo(module, module.pair_button.rect().topLeft()).y()++ empty_y = module.empty.mapTo(module, module.empty.rect().topLeft()).y()++ self._save(module, self._name("machines-empty", module))++ self.assertLess(button_y, empty_y)++ entry = {"token": "test-machine", "name": "Studio", "platform": "macos", "port": 24820,++ "host": "192.0.2.10", "send": True, "allow_drive": False, "in_use": True}++ state = machines_win.peers_view.PeerState("amber", "Waiting", "Looking for Studio.")++ module.set_peers([(entry, "Studio", state, "Mac · 192.0.2.10 · port 24820")])++ self.app.processEvents()++ row = module.rows["test-machine"]++ button_y = module.pair_button.mapTo(module, module.pair_button.rect().topLeft()).y()++ row_y = row.mapTo(module, row.rect().topLeft()).y()++ self.assertLess(button_y, row_y)++ self._save(module, self._name("machines-filled", module))++++ def test_paste_and_backspace_keep_the_six_digit_editing_contract(self):++ from PySide6.QtCore import Qt++ from PySide6.QtTest import QTest++++ self.sheet.code.setFocus()++ self.app.clipboard().setText("123 456")++ QTest.keyClick(self.sheet.code, Qt.Key.Key_V, Qt.KeyboardModifier.ControlModifier)++ self.assertEqual(self.sheet.code.text(), "123456")++ self._save(self.sheet, self._name("sheet-typed-input", self.sheet, 432))++ QTest.keyClick(self.sheet.code, Qt.Key.Key_Backspace)++ self.assertEqual(self.sheet.code.text(), "12345")++++ def test_cell_click_shift_selection_drag_and_final_backspace_follow_visible_slots(self):++ from PySide6.QtCore import QPoint, Qt++ from PySide6.QtTest import QTest++++ code = self.sheet.code++ code.setText("123456")++ cells = code._cell_rectangles()++ point = lambda index, after=False: QPoint(round(cells[index].center().x() + (1 if after else -1)), round(cells[index].center().y()))++ QTest.mouseClick(code, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, point(0))++ QTest.mouseClick(code, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.ShiftModifier, point(3))++ self.assertEqual(code.selectedText(), "123")++++ code.setText("123456")++ QTest.mousePress(code, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, point(0))++ QTest.mouseMove(code, point(5, True))++ QTest.mouseRelease(code, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, point(5, True))++ self.assertEqual(code.selectedText(), "123456")++++ code.setText("123456")++ last = cells[5]++ QTest.mouseClick(code, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier,++ QPoint(round(last.right() - 1), round(last.center().y())))++ self.assertEqual(code.cursorPosition(), 6)++ QTest.keyClick(code, Qt.Key.Key_Backspace)++ self.assertEqual(code.text(), "12345")++++ code.setText("123456")++ code.setCursorPosition(6)++ QTest.mouseClick(code, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.ShiftModifier, point(2))++ self.assertEqual(code.selectedText(), "3456")++ QTest.mouseDClick(code, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, point(2))++ self.assertEqual(code.selectedText(), "3")++++ def test_shown_code_selection_uses_the_six_visible_cells(self):++ from PySide6.QtCore import QPoint, Qt++ from PySide6.QtTest import QTest++++ label = self.sheet.code_label++ self.sheet.show_code("123456", 60, "192.0.2.1:51820", None, "")++ cells = label._cell_rectangles()++ point = lambda index, after=False: QPoint(round(cells[index].center().x() + (1 if after else -1)), round(cells[index].center().y()))++ QTest.mousePress(label, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, point(0))++ QTest.mouseMove(label, point(5, True))++ QTest.mouseRelease(label, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, point(5, True))++ self.assertEqual(label.selectedText(), "123 456")++ QTest.mouseClick(label, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, point(5, True))++ QTest.mouseClick(label, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.ShiftModifier, point(2))++ self.assertEqual(label.selectedText(), "3 456")++ QTest.mouseDClick(label, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, point(2))++ self.assertEqual(label.selectedText(), "3")++++ def _write_measurements(self, state, measurements):++ scale = QApplication.primaryScreen().devicePixelRatio() if QApplication.primaryScreen() else 1++ path = Path(__file__).resolve().parents[2] / "renders" / "qt" / f"metrics-{state}-{scale:g}x.json"++ path.parent.mkdir(parents=True, exist_ok=True)++ path.write_text(json.dumps({"scale": scale, "measurements": measurements}, indent=2) + "\n")++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_pairing_window.pyindex 00c4fa8,d11b8a0..9108c29--- a/win_app/tests/test_pairing_window.py+++ b/win_app/tests/test_pairing_window.py@@@ -43,488 -24,35 +43,542 @@@ class MachinesWindowTest(unittest.TestCos.environ.setdefault("QT_QPA_PLATFORM", "offscreen")self.app = QApplication.instance() or QApplication([])theme.init_fonts()- config = Path(tempfile.mkdtemp()) / "config.json"- config.write_text(json.dumps({"host": "192.0.2.20", "port": 24820}))- self.window = kvm_bridge_win.WindowsApplication(config)- self.host = self.window.announcer.host- self.window.announcer.begin_pairing()- self.window._refresh_pairing()+ self.folder = Path(tempfile.mkdtemp())+ self.path = self.folder / "settings.json"+ self.window = None++ def tearDown(self):+ if self.window is not None:+ self.window.server.stop()+ self.window.deleteLater()++ def open(self, *entries, **top):+ settings = app_config.load_settings(self.path)+ settings["peers"] = list(entries)+ settings["port"] = harness.free_port()+ settings.update(top)+ app_config.write_settings(self.path, settings)+ self.window = kvm_bridge_win.WindowsApplication(self.path)+ self.stub(self.window)+ self.window._refresh_window()+ return self.window++ def stub(self, window):+ """No real listener, hook or link: what would start them is recorded instead."""+ self.calls = []+ window._start_receiver = lambda config: self.calls.append("receiver")+ window.hooks = SimpleNamespace(start=lambda: self.calls.append("hooks"), stop=lambda: self.calls.append("hooks off"))+ window.sender.start = lambda config: self.calls.append("sender")+ window.sender.stop = lambda: self.calls.append("sender off")++ def settings(self):+ return json.loads(self.path.read_text())++ def test_two_machines_with_one_name_show_the_end_of_their_ids(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "studio", TOKEN_B, "192.0.2.11", "windows"))+ labels = [row.name.text() for row in window.machines.rows.values()]+ self.assertEqual(labels, [f"Studio ({protocol.id_text(ID_A)[-4:]})", f"studio ({protocol.id_text(ID_B)[-4:]})"])+ self.assertEqual(window.machines.empty.isHidden(), True)++ def test_a_row_names_the_platform_and_address_and_a_state(self):+ window = self.open(peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"))+ row = next(iter(window.machines.rows.values()))+ self.assertEqual(row.where.text(), "Mac · 192.0.2.10 · port 24820")+ self.assertEqual(row.word.text(), "Waiting")+ self.assertIn("Studio Mac", row.detail.text())++ def test_the_direction_switches_start_under_a_closed_disclosure(self):+ window = self.open(peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"))+ row = next(iter(window.machines.rows.values()))+ self.assertFalse(row.directions.isChecked())+ self.assertTrue(row.direction_group.isHidden())+ row.directions.click()+ self.assertFalse(row.direction_group.isHidden())++ def test_the_send_button_names_the_only_machine_in_use(self):+ window = self.open(peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"),+ peer(ID_B, "Inactive", TOKEN_B, "192.0.2.11", in_use=False))+ window.sender.shortcut_target = lambda: None+ self.assertEqual(window._redirect_text(), "Send input to Studio Mac")++ def test_the_paired_announcement_omits_machines_not_in_use(self):+ window = self.open(peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"),+ peer(ID_B, "Inactive", TOKEN_B, "192.0.2.11", in_use=False))+ sent = []+ window._send_to = lambda ident, message: sent.append((ident, message)) or True+ window._send_paired()+ self.assertEqual(len(sent), 1)+ self.assertEqual(sent[0][0], ID_A)+ self.assertEqual(sent[0][1]["data"]["ids"], [])++ def test_any_token_from_1_4_x_asks_to_pair_again(self):+ # "A" * 43 has pairing's shape: 1.4.x kept no record of whether a token was paired or typed.+ for token in ("typed by hand", "A" * 43):+ with self.subTest(token=token):+ for name in ("config.json", "settings.json"):+ (self.folder / name).unlink(missing_ok=True)+ (self.folder / "config.json").write_text(json.dumps({+ "host": "192.0.2.20", "port": harness.free_port(), "auth_token": token, "paired_with": "MacBook Pro",+ "mac_host": "192.0.2.10", "mac_return_edge": "left"}))+ self.window = kvm_bridge_win.WindowsApplication(self.path)+ row = next(iter(self.window.machines.rows.values()))+ self.assertEqual(row.word.text(), "Pair again")+ self.window.server.stop()+ self.window.deleteLater()+ self.window = None++ def test_with_nothing_paired_the_list_says_so(self):+ self.window = kvm_bridge_win.WindowsApplication(self.path)+ self.assertFalse(self.window.machines.empty.isHidden())+ self.assertEqual(self.window.machines.empty.text(), "No machines paired yet.")+ self.assertFalse(self.window._paired)+ self.assertFalse(self.window.same_switch.isEnabled())++ def test_with_nothing_paired_appearance_and_speed_still_save(self):+ self.window = kvm_bridge_win.WindowsApplication(self.path)+ self.stub(self.window)+ self.window._appearance_chosen("dark")+ self.window._speed_changed("pointer_speed", 150)+ self.window._reverse_scroll_changed(True)+ self.window._persist()+ saved = self.settings()+ self.assertEqual((saved["appearance"], saved["pointer_speed"], saved["reverse_scroll"]), ("dark", 1.5, True))+ self.assertEqual(saved["peers"], [])+ again = kvm_bridge_win.WindowsApplication(self.path)+ self.stub(again)+ self.assertEqual((again._config.appearance, again._config.pointer_speed), ("dark", 1.5))+ again.deleteLater()++ def test_a_switch_writes_that_machines_entry_only(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))+ window._set_peer_send(TOKEN_B, False)+ window._set_peer_allow(TOKEN_A, False)+ by_name = {entry["name"]: entry for entry in self.settings()["peers"]}+ self.assertEqual((by_name["Laptop"]["send"], by_name["Laptop"]["allow_drive"]), (False, True))+ self.assertEqual((by_name["Studio"]["send"], by_name["Studio"]["allow_drive"]), (True, False))+ window._refresh_window()+ rows = list(window.machines.rows.values())+ self.assertEqual([(row.send.isChecked(), row.allow.isChecked()) for row in rows], [(True, False), (False, True)])++ def test_the_tray_send_items_omit_machines_not_in_use(self):+ entries = [+ peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"),+ peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"),+ peer(b"\x0c" * 15 + b"\x03", "Spare", protocol.id_text(bytes(range(2, 34))), "192.0.2.12"),+ ]+ window = self.open(*entries)+ window._edit_peer(protocol.id_text(bytes(range(2, 34))), in_use=False)+ window._after_peers_edit()+ window._refresh_tray_machines()+ self.assertEqual(list(window.machine_actions), [protocol.id_text(ID_A), protocol.id_text(ID_B)])++ def test_the_trays_ticks_change_every_machine_in_one_write(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))+ window._set_every_peer("allow_drive", False)+ self.assertEqual([entry["allow_drive"] for entry in self.settings()["peers"]], [False, False])+ window._refresh_window()+ self.assertFalse(window.drive_action.isChecked())+ self.assertTrue(window.send_action.isChecked())++ def test_removing_a_machine_takes_its_entry_and_zones_and_keeps_the_rest(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))+ settings = self.settings()+ settings["zones"] = [{"peer": protocol.id_text(ID_A), "kind": "edge"}, {"peer": protocol.id_text(ID_B), "kind": "edge", "off": True}]+ app_config.write_settings(self.path, settings)+ window._remove_peer(TOKEN_A)+ after = self.settings()+ self.assertEqual([entry["name"] for entry in after["peers"]], ["Laptop"])+ self.assertEqual([zone["peer"] for zone in after["zones"]], [protocol.id_text(ID_B)])+ self.assertEqual(list(window.machines.rows), [TOKEN_B])+ self.assertEqual(window._config.auth_token, TOKEN_B)++ def test_removing_the_last_machine_leaves_the_window_unpaired(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"))+ window._remove_peer(TOKEN_A)+ self.assertEqual(self.settings()["peers"], [])+ self.assertFalse(window._paired)+ self.assertFalse(window.same_switch.isEnabled())+ self.assertFalse(window.machines.empty.isHidden())+ window._refresh_window()++ def test_the_first_pairing_makes_the_window_paired(self):+ self.window = kvm_bridge_win.WindowsApplication(self.path)+ self.stub(self.window)+ entry = peer(ID_A, "Studio", TOKEN_A, "192.0.2.10")+ self.window._store_peer(entry, None)+ self.window._on_paired(entry)+ self.assertTrue(self.window._paired)+ self.assertEqual(list(self.window.machines.rows), [TOKEN_A])+ self.assertEqual(self.window.sheet.host_note.text(), "Paired with Studio.")++ def test_pairing_a_machine_starts_sending_when_nothing_could_send_before(self):+ (self.folder / "config.json").write_text(json.dumps({+ "host": "192.0.2.20", "port": harness.free_port(), "auth_token": "typed by hand", "paired_with": "MacBook Pro",+ "mac_host": "192.0.2.10", "mac_return_edge": "left"}))+ self.window = kvm_bridge_win.WindowsApplication(self.path)+ self.stub(self.window)+ self.assertNotIn("sender", self.calls)+ entry = peer(ID_A, "Studio", TOKEN_A, "192.0.2.10")+ self.window._store_peer(entry, self.window.book.peers()[0])+ self.window._on_paired(entry)+ self.assertIn("sender", self.calls)+ self.assertIn("hooks", self.calls)++ def test_removing_the_only_machine_that_could_be_sent_to_stops_sending(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))+ window._set_peer_send(TOKEN_B, False)+ self.calls.clear()+ window._remove_peer(TOKEN_A)+ self.assertIn("hooks off", self.calls)+ self.assertIn("sender off", self.calls)++ def input_on(self, window, peer):+ homes = []+ window.sender._owner = SimpleNamespace(on=peer, away=peer is not None)+ window.sender.set_redirecting = lambda value, came_home=True: homes.append(value)+ return homes++ def test_turning_send_off_for_the_machine_input_is_on_brings_it_home_first(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))+ homes = self.input_on(window, ID_A)+ window._set_peer_send(TOKEN_A, False)+ self.assertEqual(homes, [False])++ def test_turning_send_off_for_every_machine_brings_input_home_first(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))+ self.input_on(window, ID_A)+ order = []+ window.sender.set_redirecting = lambda value, came_home=True: order.append("home")+ refresh = window.sender.refresh+ window.sender.refresh = lambda: (order.append("links follow"), refresh())+ window._set_every_peer("send", False)+ self.assertEqual(order[0], "home")+ self.assertEqual([entry["send"] for entry in self.settings()["peers"]], [False, False])++ def test_input_comes_home_before_send_off_is_saved(self):+ # The links read `send` from the settings on their own each second: one that read it in+ # between would end itself with input still on its machine.+ from unittest import mock+ for turn_off in (lambda window: window._set_peer_send(TOKEN_A, False),+ lambda window: window._set_every_peer("send", False)):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"))+ self.input_on(window, ID_A)+ order = []+ window.sender.set_redirecting = lambda value, came_home=True: order.append("home")+ write = kvm_bridge_win.app_config.write_settings+ with mock.patch.object(kvm_bridge_win.app_config, "write_settings", side_effect=lambda *a, **k: (order.append("saved"), write(*a, **k))[1]):+ turn_off(window)+ self.assertEqual(order[:2], ["home", "saved"])++ def test_turning_send_on_for_every_machine_or_drive_off_leaves_input_where_it_is(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"))+ homes = self.input_on(window, ID_A)+ window._set_every_peer("send", True)+ window._set_every_peer("allow_drive", False)+ self.assertEqual(homes, [])++ def test_turning_send_off_for_another_machine_leaves_input_where_it_is(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))+ homes = self.input_on(window, ID_A)+ window._set_peer_send(TOKEN_B, False)+ self.assertEqual(homes, [])++ def test_the_connection_pages_port_is_this_pcs_and_leaves_every_machines_port_alone(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"))+ window.port_entry.setText("24830")+ window.save()+ after = self.settings()+ self.assertEqual(after["port"], 24830)+ self.assertEqual([entry["port"] for entry in after["peers"]], [24820])+ self.assertEqual(window._announced_port(), 24830)++ def test_the_port_a_pairing_proves_survives_the_last_machine_going(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), port=24830)+ window._remove_peer(TOKEN_A)+ self.assertFalse(window._paired)+ self.assertEqual(window._announced_port(), 24830)+ self.assertEqual(window._identity()["port"], 24830)++ def test_hide_addresses_holds_with_no_machine_paired(self):+ window = self.open(hide_addresses=True)+ self.assertTrue(window.hide_switch.isChecked())+ self.assertEqual(window._shown("Reach it at 192.0.2.5"), "Reach it at •••")+ window.hide_switch.setChecked(False)+ self.assertFalse(self.settings()["hide_addresses"])+ window.hide_switch.setChecked(True)+ self.assertTrue(self.settings()["hide_addresses"])++ def test_a_label_that_is_an_address_is_hidden_with_the_rest(self):+ window = self.open(peer(ID_A, "", TOKEN_A, "192.0.2.10"), hide_addresses=True)+ row = next(iter(window.machines.rows.values()))+ self.assertNotIn("192.0.2.10", row.name.text())+ self.assertNotIn("192.0.2.10", row.detail.text())++ def test_a_pairing_replaces_the_machine_it_was_meant_to_and_keeps_it_first(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))+ replaced = window.book.peers()[0]+ fresh = peer(b"\x0c" * 16, "Studio", protocol.id_text(bytes(range(2, 34))), "192.0.2.10")+ window._store_peer(fresh, replaced)+ self.assertEqual([entry["name"] for entry in self.settings()["peers"]], ["Studio", "Laptop"])+ self.assertEqual(self.settings()["peers"][0]["id"], protocol.id_text(b"\x0c" * 16))++ def test_a_pairing_does_not_replace_a_machine_that_linked_since_it_was_read(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))+ replaced = window.book.peers()[0]+ settings = self.settings()+ settings["peers"][0]["linked"] = True+ app_config.write_settings(self.path, settings)+ fresh = peer(b"\x0c" * 16, "Studio", protocol.id_text(bytes(range(2, 34))), "192.0.2.10")+ with self.assertRaises(Exception):+ window._store_peer(fresh, replaced)+ self.assertEqual([entry["token"] for entry in self.settings()["peers"]], [TOKEN_A, TOKEN_B])+ self.assertTrue(self.settings()["peers"][0]["linked"])++ def test_a_pairing_does_not_replace_a_machine_that_was_removed_since_it_was_read(self):+ window = self.open(peer(ID_A, "Studio", TOKEN_A, "192.0.2.10"), peer(ID_B, "Laptop", TOKEN_B, "192.0.2.11"))+ replaced = window.book.peers()[0]+ window._remove_peer(TOKEN_A)+ fresh = peer(b"\x0c" * 16, "Studio", protocol.id_text(bytes(range(2, 34))), "192.0.2.10")+ with self.assertRaises(Exception):+ window._store_peer(fresh, replaced)+ self.assertEqual([entry["token"] for entry in self.settings()["peers"]], [TOKEN_B])++ def test_pairing_the_mac_at_the_1_4_entrys_address_again_keeps_its_side_and_zones(self):+ # Every 1.4.x upgrader pairs again (no token migrates since 1.5.0), on purpose and at the+ # screen: where that Mac sits is not theirs to set a second time.+ migrated = {**peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"), "id": "", "from_1_4": True, "linked": False,+ "paired_at": 0, "side": "top", "side_set_at": 1_790_000_000}+ window = self.open(migrated, zones=[{"peer": "", "kind": "edge"}, {"peer": "", "kind": "corner",+ "corner": "top_left", "edge": "top", "off": True}])+ fresh = peer(b"\x0c" * 16, "Studio Mac", protocol.id_text(bytes(range(2, 34))), "192.0.2.10")+ window._store_peer(fresh, window.book.peers()[0])+ after = self.settings()+ new_id = protocol.id_text(b"\x0c" * 16)+ self.assertEqual([zone["peer"] for zone in after["zones"]], [new_id, new_id])+ self.assertEqual((after["peers"][0]["side"], after["peers"][0]["side_set_at"]), ("top", 1_790_000_000))++ def test_pairing_another_platform_at_that_address_keeps_nothing_of_it(self):+ migrated = {**peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"), "id": "", "from_1_4": True, "linked": False,+ "paired_at": 0, "side": "top", "side_set_at": 1_790_000_000}+ window = self.open(migrated, zones=[{"peer": "", "kind": "edge"}])+ fresh = peer(b"\x0c" * 16, "Studio PC", protocol.id_text(bytes(range(2, 34))), "192.0.2.10", platform="windows")+ window._store_peer(fresh, window.book.peers()[0])+ after = self.settings()+ # Only its own whole edge, which every machine paired starts with.+ self.assertEqual(after["zones"], [{"peer": protocol.id_text(b"\x0c" * 16), "kind": "edge"}])+ self.assertEqual(after["peers"][0]["side"], "")++[email protected](kvm_bridge_win is None, "needs PySide6")+class PairingSheetWindowTest(unittest.TestCase):+ def setUp(self):+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ self.app = QApplication.instance() or QApplication([])+ theme.init_fonts()+ folder = Path(tempfile.mkdtemp())+ self.path = folder / "settings.json"+ self.window = kvm_bridge_win.WindowsApplication(self.path)+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ spare = probe.getsockname()[1]+ # Its own TCP port, so a real Beamer or another suite on this machine never meets it.+ self.service = self.window.pairing = pairing.PairingService(+ "Test PC", b"\x09" * 16, "windows", lambda: 24820, self.window.book.peers, self.window._store_peer,+ on_paired=self.window.bridge.paired.emit, tcp_port=spare,+ )+ self.window._toggle_pairing_sheet()def tearDown(self):+ self.service.cancel_pairing()+ self.window.server.stop()self.window.deleteLater()- def test_a_mac_on_the_old_exchange_is_named_as_out_of_date(self):- self.host.handle({"type": "pair_request", "pair": self.host.pair_id, "pub": "AAAA", "proof": "BBBB"})+ def show_code(self):+ self.window._show_code()+ return self.service.code++ def test_showing_a_code_fills_the_sheet(self):+ code = self.show_code()+ self.assertEqual(self.window.sheet.code_label.text(), f"{code[:3]} {code[3:]}")+ self.assertTrue(self.window.sheet.code_showing)+ self.assertTrue(self.window.sheet.count_label.text().startswith("Expires in "))+++ def test_pairing_dialog_hides_the_qr_and_caption(self):++ from PySide6.QtGui import QImage++++ self.window.sheet.show_code("482913", 60, "This PC's address: 192.0.2.20 · port 24821",++ [[True, False], [False, True]], "")++ self.app.processEvents()++ self.assertTrue(self.window.sheet.qr.isHidden())++ self.assertTrue(self.window.sheet.qr_caption.isHidden())++ self.window.sheet.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, True)++ self.window.sheet.resize(700, 720)++ self.window.sheet.show()++ self.app.processEvents()++ image = QImage(self.window.sheet.size(), QImage.Format.Format_ARGB32_Premultiplied)++ image.fill(Qt.GlobalColor.transparent)++ self.window.sheet.render(image)++ destination = Path(os.environ.get("BEAMER_PAIRUI_RENDERS", "renders")) / "qt-pairing-dialog.png"++ destination.parent.mkdir(parents=True, exist_ok=True)++ self.assertTrue(image.save(str(destination)), f"could not save {destination} ({image.width()}x{image.height()})")+++ def test_pairing_code_text_is_centred_in_its_stretched_label(self):+ self.show_code()+ alignment = self.window.sheet.code_label.alignment()+ self.assertTrue(alignment & Qt.AlignmentFlag.AlignHCenter)+++ def test_entered_code_ink_is_centred_in_the_code_box(self):++ from PySide6.QtGui import QImage++++ code = self.window.sheet.code++ code.setFixedSize(240, 48)++ code.setText("408819")++ self.app.processEvents()++ image = QImage(code.size(), QImage.Format.Format_ARGB32_Premultiplied)++ image.fill(Qt.GlobalColor.transparent)++ code.render(image)++ contents = code.contentsRect().adjusted(4, 4, -4, -4)++ background = image.pixelColor(contents.left(), contents.top())++ ink = []++ for y in range(contents.top(), contents.bottom() + 1):++ for x in range(contents.left(), contents.right() + 1):++ colour = image.pixelColor(x, y)++ if (abs(colour.red() - background.red()) + abs(colour.green() - background.green())++ + abs(colour.blue() - background.blue())) > 24:++ ink.append((x, y))++ self.assertTrue(ink, "no code digits were rendered")++ left, right = min(x for x, _ in ink), max(x for x, _ in ink)++ top, bottom = min(y for _, y in ink), max(y for _, y in ink)++ ink_centre = ((left + right + 1) / 2, (top + bottom + 1) / 2)++ box_centre = (code.width() / 2, code.height() / 2)++ self.assertLessEqual(abs(ink_centre[0] - box_centre[0]), 1,++ f"code digits are off-centre horizontally: {ink_centre} vs {box_centre}")++ self.assertLessEqual(abs(ink_centre[1] - box_centre[1]), 1,++ f"code digits are off-centre vertically: {ink_centre} vs {box_centre}")+++ def test_cancelling_the_code_puts_the_button_back_and_says_nothing(self):+ self.show_code()+ self.window._cancel_code()+ self.assertFalse(self.window.sheet.code_showing)+ self.assertEqual(self.window.sheet.host_note.text(), "")++ def test_closing_the_sheet_cancels_a_code_that_is_up(self):+ self.show_code()+ self.window._toggle_pairing_sheet()+ self.assertIsNone(self.service.code)++ def test_a_wrong_code_ends_the_code_and_says_so(self):+ self.show_code()+ host = self.service.host+ client = pairing.PairingClient(host.pair_id, "000000" if host.code != "000000" else "000001", "Test machine",+ b"\x01" * 16, version=pairing.PAIRING_V3, platform="macos", port=24820)+ host.handle(client.start(), "192.0.2.50")+ host.handle(client.abort(), "192.0.2.50")self.window._refresh_pairing()- self.assertEqual(- self.window.pair_note.text(),- "The Mac runs a different version of Beamer. Update Beamer on both machines, then pair again.",- )+ self.assertIsNone(self.service.code)+ self.assertEqual(self.window.sheet.host_note.text(), peerlist.host_outcome_text("refused", None))++ def test_a_machine_on_the_old_exchange_is_listed_as_older_and_chosen_at_once(self):+ old = {"name": "Old Mac", "address": "192.0.2.60", "port": 24820, "reply_port": 24821, "pair_id": "x",+ "pairing": 2, "platform": None}+ self.window.sheet.set_machines([old])+ button = self.window.sheet.group.buttons()[0]+ self.assertIn("Older Beamer", button.text())+ button.click()+ self.assertEqual(self.window.sheet.pair_note.text(),+ peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_VERSION), "Old Mac"))++ STUDIO = {"name": "Studio", "address": "192.168.50.22", "port": 24820, "reply_port": 24821,+ "pair_id": "first", "pairing": 3, "platform": "windows"}++ def test_one_machine_heard_on_two_interfaces_shows_each_row_s_address(self):+ twice = [self.STUDIO, dict(self.STUDIO, address="169.254.3.7", pair_id="second")]+ self.window.sheet.set_machines(twice, self.window._shown)+ self.assertEqual([button.text() for button in self.window.sheet.group.buttons()], [+ "Studio · Windows · 192.168.50.22 · showing a code",+ "Studio · Windows · 169.254.3.7 · showing a code",+ ])++ def test_a_lone_machine_s_row_is_as_it_was(self):+ self.window.sheet.set_machines([self.STUDIO], self.window._shown)+ self.assertEqual(self.window.sheet.group.buttons()[0].text(), "Studio · Windows · showing a code")- def test_a_mac_that_had_the_wrong_code_ends_the_code(self):- client = pairing.PairingClient(self.host.pair_id, "000000" if self.host.code != "000000" else "000001", "Test Mac")- self.host.handle(client.start())- self.assertIsNotNone(self.window.announcer.code)- self.host.handle(client.abort())+ def test_the_addresses_follow_hide_addresses(self):+ twice = [self.STUDIO, dict(self.STUDIO, address="169.254.3.7", pair_id="second")]+ self.window.sheet.set_machines(twice, self.window._shown)+ self.window._config.hide_addresses = True+ self.window.sheet.set_machines(twice, self.window._shown)+ texts = [button.text() for button in self.window.sheet.group.buttons()]+ self.assertEqual(len(texts), 2)+ self.assertFalse([text for text in texts if "192.168.50.22" in text or "169.254.3.7" in text], texts)++ def test_only_a_machine_showing_a_code_is_listed(self):+ quiet = {"name": "Quiet", "address": "192.0.2.61", "port": 24820, "reply_port": 24821, "pair_id": None,+ "pairing": 3, "platform": "macos"}+ self.window.sheet.set_machines([quiet])+ self.assertEqual(self.window.sheet.group.buttons(), [])+ self.assertFalse(self.window.sheet.none_heard.isHidden())++ def test_pair_waits_for_a_chosen_machine_or_an_address_and_six_digits(self):+ sheet = self.window.sheet+ self.assertFalse(sheet.pair_button.isEnabled())+ sheet.address.setText("192.0.2.70")+ sheet._typed_address("192.0.2.70")+ sheet._typed_code("482 913")+ self.assertEqual(sheet.code.text(), "482913")+ self.assertTrue(sheet.pair_button.isEnabled())++ def test_the_machine_pair_sends_is_the_one_last_heard_not_the_one_first_listed(self):+ first = {"name": "Mac", "address": "192.0.2.60", "port": 24820, "reply_port": 1, "pair_id": "old", "pairing": 3, "platform": "macos"}+ self.window.sheet.set_machines([first])+ self.window.sheet.group.buttons()[0].click()+ self.window.sheet.set_machines([dict(first, pair_id="new")])+ self.assertEqual(self.window.sheet.chosen_machine()["pair_id"], "new")++ def test_pair_stays_off_while_a_pairing_is_under_way(self):+ sheet = self.window.sheet+ sheet.address.setText("192.0.2.70")+ sheet._typed_address("192.0.2.70")+ sheet.code.setText("482913")+ sheet._typed_code("482913")+ self.assertTrue(sheet.pair_button.isEnabled())+ sheet.busy(True)+ sheet._typed_code("482913")+ self.assertFalse(sheet.pair_button.isEnabled())+ sheet.busy(False)+ self.assertTrue(sheet.pair_button.isEnabled())++ def test_a_pair_error_hides_an_address_when_addresses_are_hidden(self):+ self.window._config = kvm_bridge_win.default_config()+ self.window._config.hide_addresses = True+ self.window._pairing_target = "192.0.2.70"+ self.window._on_pair_finished(None, pairing.PairingError("no_answer"))+ self.assertNotIn("192.0.2.70", self.window.sheet.pair_note.text())++ def test_a_failed_pairing_says_why_in_the_peers_name(self):+ self.window._pairing_target = "Studio"+ self.window._on_pair_finished(None, pairing.PairingError(pairing.ERROR_REFUSED))+ self.assertEqual(self.window.sheet.pair_note.text(),+ peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_REFUSED), "Studio"))++ def test_the_code_shows_a_qr_unless_addresses_are_hidden(self):++ from unittest import mock++ from core import feature_flags++ with mock.patch.object(feature_flags, "PAIRING_QR_VISIBLE", True):++ self._qr_unless_addresses_hidden()++++ def _qr_unless_addresses_hidden(self):+ self.window._code_address = "192.0.2.5"+ self.window._pairing_address = lambda: "192.0.2.5"+ self.show_code()+ self.assertFalse(self.window.sheet.qr.isHidden())+ self.assertIn("192.0.2.5", self.window.sheet.address_note.text())+ self.window._config = kvm_bridge_win.default_config()+ self.window._config.hide_addresses = Trueself.window._refresh_pairing()- self.assertIsNone(self.window.announcer.code)- self.assertEqual(- self.window.pair_note.text(),- "A wrong code was entered, so that code is cancelled. Pair again for a fresh one.",- )+ self.assertTrue(self.window.sheet.qr.isHidden())+ self.assertNotIn("192.0.2.5", self.window.sheet.address_note.text())+ self.assertIn("Hide addresses", self.window.sheet.qr_caption.text())if __name__ == "__main__":diff --cc win_app/tests/test_phone_settings.pyindex 0000000,0000000..a2febb4new file mode 100644--- /dev/null+++ b/win_app/tests/test_phone_settings.py@@@ -1,0 -1,0 +1,105 @@@++"""Sender-only phones survive the Windows/Linux settings and legacy flat view."""++++import copy++import json++import sys++import tempfile++import unittest++from dataclasses import replace++from pathlib import Path++++ROOT = Path(__file__).resolve().parents[2]++sys.path.insert(0, str(ROOT))++sys.path.insert(0, str(ROOT / "win_app"))++++import app_config++from core import protocol++++++def peer(number, phone=False, **fields):++ return {++ "id": protocol.id_text(bytes([number]) * 16), "name": "Phone" if phone else "Desktop",++ "platform": "ios" if phone else "macos", "token": app_config._b64(bytes([number]) * 32),++ "host": "" if phone else "192.0.2.20", "port": 0 if phone else 24820, "hw": "",++ "send": not phone, "allow_drive": True, "in_use": True, "side": "", "side_set_at": 0,++ "side_by": "", "jump_key": "", "paired_with": [], "paired_at": 1, "linked": True,++ "from_1_4": False, **fields,++ }++++++class PhoneSettingsTests(unittest.TestCase):++ def setUp(self):++ directory = tempfile.TemporaryDirectory(dir=ROOT)++ self.addCleanup(directory.cleanup)++ self.path = Path(directory.name) / "settings.json"++ self.phone = peer(2, phone=True)++ self.desktop = peer(3)++ self.other = peer(4)++++ def put(self, peers, zones=()):++ settings = app_config.migrate(None, machine_id=protocol.id_text(bytes([1]) * 16))++ settings.update(peers=copy.deepcopy(peers), zones=copy.deepcopy(list(zones)))++ app_config._write_json(self.path, settings)++ return settings++++ def positions(self):++ return ([self.phone, self.desktop, self.other], [self.desktop, self.phone, self.other],++ [self.desktop, self.other, self.phone], [self.phone])++++ def test_flat_round_trip_skips_phones_in_every_position(self):++ for peers in self.positions():++ with self.subTest(order=[p["port"] for p in peers]):++ before = self.put(peers)++ config = app_config.load_config(self.path)++ desktop = next((p for p in peers if p["port"]), None)++ self.assertEqual(config.auth_token, desktop["token"] if desktop else "")++ self.assertEqual(config.mac_host, desktop["host"] if desktop else "")++ app_config.save_config(self.path, replace(config, hide_addresses=True))++ after = app_config.load_settings(self.path)++ self.assertEqual(after["peers"], before["peers"])++ self.assertTrue(after["hide_addresses"])++++ def test_new_flat_pairing_replaces_first_desktop_and_keeps_phone(self):++ for peers in self.positions():++ with self.subTest(order=[p["port"] for p in peers]):++ self.put(peers)++ config = app_config.load_config(self.path)++ app_config.save_config(self.path, replace(config, auth_token="new legacy pair", mac_host="192.0.2.30"))++ after = app_config.load_settings(self.path)["peers"]++ self.assertEqual(next(p for p in after if p["port"] == 0), self.phone)++ self.assertEqual(next(p for p in after if p["port"] != 0)["token"], "new legacy pair")++++ def test_legacy_reimport_never_replaces_a_zero_port_entry(self):++ for peers in self.positions():++ with self.subTest(order=[p["port"] for p in peers]):++ peers = copy.deepcopy(peers)++ next(p for p in peers if p["port"] == 0)["from_1_4"] = True++ settings = self.put(peers)++ legacy = app_config.config_to_dict(app_config.default_config())++ legacy.update(auth_token="legacy re-pair", mac_host="192.0.2.30")++ app_config.remigrate(settings, legacy)++ self.assertEqual(next(p for p in settings["peers"] if p["port"] == 0), next(p for p in peers if p["port"] == 0))++ self.assertTrue(any(p["token"] == "legacy re-pair" and p["port"] != 0 for p in settings["peers"]))++++ def test_load_and_write_clear_phone_targets_and_keep_permissions(self):++ forbidden = {"host": "192.0.2.40", "send": True, "hw": "aa:bb:cc:dd:ee:ff",++ "side": "right", "side_set_at": 50, "side_by": self.desktop["id"], "jump_key": "ctrl+f2"}++ for writing in (False, True):++ with self.subTest(writing=writing):++ phone = dict(self.phone, allow_drive=False, in_use=False, **forbidden)++ settings = self.put([phone, self.desktop], [{"peer": phone["id"], "kind": "edge"}])++ if writing:++ app_config.write_settings(self.path, settings)++ result = app_config.load_settings(self.path)++ self.assertEqual(result["peers"][0], dict(self.phone, allow_drive=False, in_use=False))++ self.assertFalse(any(zone.get("peer") == phone["id"] for zone in result["zones"]))++ self.assertEqual(json.loads(self.path.read_text())["peers"][0], result["peers"][0])++++ def test_phone_cannot_gain_a_hardware_address(self):++ self.put([self.phone])++ self.assertFalse(app_config.set_peer_hardware_address(self.path, self.phone["id"], "aa:bb:cc:dd:ee:ff"))++ self.assertEqual(app_config.load_settings(self.path)["peers"], [self.phone])++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_phone_ui.pyindex 0000000,0000000..310d00anew file mode 100644--- /dev/null+++ b/win_app/tests/test_phone_ui.py@@@ -1,0 -1,0 +1,226 @@@++"""Sender-only phone decisions without creating a window or installing input hooks."""++++import sys++import unittest++from contextlib import nullcontext++from pathlib import Path++from types import SimpleNamespace++from typing import Optional++++sys.path.append(str(Path(__file__).resolve().parents[2]))++sys.path.append(str(Path(__file__).resolve().parents[1]))++++from core import peerlist, protocol, settings_sync++from core.tests.app_methods import load_methods++import pages_win++import peers_view++import sender++++PHONE = protocol.id_text(bytes(range(16)))++DESKTOP = protocol.id_text(bytes(range(16, 32)))++++++def entries():++ return [dict(id=PHONE, token=protocol.id_text(bytes(range(32))), name="My phone", platform="ios", port=0,++ send=True, allow_drive=True, in_use=True),++ dict(id=DESKTOP, token=protocol.id_text(bytes(range(32, 64))), name="Desktop", platform="windows", port=24820,++ send=True, allow_drive=True, in_use=True)]++++++def application(*methods, **extra):++ namespace = dict(Optional=Optional, Config=SimpleNamespace, peerlist=peerlist,++ protocol=protocol, settings_sync=settings_sync, pages_win=pages_win,++ Qt=SimpleNamespace(ItemDataRole=SimpleNamespace(UserRole=1)), **extra)++ namespace["TRIGGER_KEYS"] = ()++ return load_methods("win_app/kvm_bridge_win.py", "WindowsApplication", methods, namespace)()++++++class Control:++ def __init__(self, text=""):++ self.value = text++ self.checked = False++ self.visible = True++ self.enabled = True++++ def text(self): return self.value++ def setText(self, text): self.value = text++ def isChecked(self): return self.checked++ def setChecked(self, value): self.checked = value++ def blockSignals(self, value): pass++ def setVisible(self, value): self.visible = value++ def setEnabled(self, value): self.enabled = value++ def setToolTip(self, value): self.tooltip = value++ def setAccessibleName(self, value): self.accessible = value++ def isVisibleTo(self, parent): return self.visible++++++class PhoneUiTests(unittest.TestCase):++ def test_phone_is_never_woken_even_with_stale_hardware(self):++ attempts = []++ threads = SimpleNamespace(Thread=lambda **fields: SimpleNamespace(start=lambda: attempts.append(fields)))++ link = load_methods("win_app/sender.py", "LinkSender", ["wake"],++ dict(Optional=Optional, threading=threads))()++ peer = protocol.read_id(PHONE)++ link._peers = {peer: dict(entries()[0], hw="aa:bb:cc:dd:ee:ff")}++ link.links = SimpleNamespace(up=lambda peer: False, refused=lambda peer: False)++ link._wake_lock, link._waking = nullcontext(), set()++ link._wake_worker = lambda *args: None++ self.assertFalse(link.wake(peer))++ self.assertEqual(attempts, [])++++ def test_phone_never_learns_hardware_even_with_a_stale_host(self):++ looked_up = []++ link = load_methods("win_app/sender.py", "LinkSender", ["_learn_hardware"], {})()++ peer = protocol.read_id(PHONE)++ link._peers = {peer: dict(entries()[0], host="192.0.2.1", hw="")}++ link._mac_lookup = lambda host: looked_up.append(host) or ""++ link._learn_hardware(peer)++ self.assertEqual(looked_up, [])++++ def test_phone_is_never_dialled_even_with_a_saved_host(self):++ made = []++ class Link:++ def __init__(self, token, *args, **kwargs): made.append(token)++ links = sender.LinkSet(SimpleNamespace(_hardware=None, _book=None, _identity=None),++ is_local=lambda host: False, link_class=Link)++ peers = entries()++ peers[0]["host"] = "192.0.2.1"++ peers[1]["host"] = "192.0.2.2"++ links.sync(peers)++ self.assertEqual(made, [peers[1]["token"]])++++ def test_crossing_choice_and_settings_exclude_phone_even_with_stale_zone(self):++ app = application("_crossing_machines", "_crossing_settings")++ app._peer_entries = entries()++ app._zone_entries = [dict(peer=PHONE), dict(peer=DESKTOP)]++ app._config = SimpleNamespace(machine_id="own")++ app._shown = lambda text: text++ self.assertEqual(app._crossing_machines(), [(DESKTOP, "Desktop")])++ self.assertEqual(app._crossing_settings()["peers"], [entries()[1]])++ self.assertEqual(app._crossing_settings()["zones"], [dict(peer=DESKTOP)])++++ def test_same_and_match_capabilities_ignore_phone_advertisements(self):++ app = application("_peer_caps", "_design_peer_caps")++ phone, desktop = protocol.read_id(PHONE), protocol.read_id(DESKTOP)++ app._peer_entries = entries()++ app.sender = SimpleNamespace(peers_up=lambda: [phone, desktop],++ links=SimpleNamespace(caps=lambda peer: {"settings", "design_sync"}))++ app.server = SimpleNamespace(links=lambda: [phone, desktop], caps_of=lambda peer: {"settings", "design_sync"})++ self.assertEqual(set(app._peer_caps()), {desktop})++ self.assertEqual(set(app._design_peer_caps()), {DESKTOP})++++ def test_phone_settings_never_apply_even_when_advertised(self):++ app = application("_on_settings")++ app._peer_entries = entries()++ app.book = SimpleNamespace(peers=lambda: app._peer_entries)++ class Config:++ @property++ def same_on_both(self):++ raise AssertionError("phone settings must be ignored before reading local settings")++ app._config = Config()++ app._design_states = {}++ app._on_settings(PHONE, {"design_sync": {}})++ self.assertEqual(app._design_states, {})++++ def test_match_choices_ignore_phone(self):++ class Model:++ def __init__(self, parent): self.items = []++ def appendRow(self, item): self.items.append(item)++++ class Item(Control):++ def setData(self, value, role): self.data = value++++ app = application("_refresh_design_follow", "_lock_followed_design", QStandardItemModel=Model, QStandardItem=Item)++ app._peer_entries = entries()++ app._config = SimpleNamespace(design_follow_peer="", same_on_both=False)++ app._design_states = {PHONE: {}, DESKTOP: {}}++ app._design_peer_caps = lambda: {PHONE: {"design_sync"}, DESKTOP: {"design_sync"}}++ app._shown = lambda text: text++ choice = app.design_follow_choice = Control()++ choice.setModel = lambda model: setattr(choice, "model", model)++ choice.findData = lambda value, role: 0++ choice.setCurrentIndex = lambda value: None++ app.design_follow_note = Control()++ app._refresh_design_follow()++ self.assertEqual([item.data for item in choice.model.items], ["", DESKTOP])++++ def test_bulk_send_does_not_enable_phone_but_receive_can_be_toggled(self):++ settings = {"peers": entries()}++ settings["peers"][0]["send"] = False++ fake_config = SimpleNamespace(SETTINGS_LOCK=nullcontext(), load_settings=lambda path: settings,++ write_settings=lambda path, value: None)++ app = application("_set_every_peer", app_config=fake_config)++ app.config_path = "synthetic"++ app.sender = SimpleNamespace(owner=None)++ app._after_peers_edit = lambda: None++ app._set_every_peer("send", True)++ self.assertFalse(settings["peers"][0]["send"])++ app._set_every_peer("allow_drive", False)++ self.assertFalse(settings["peers"][0]["allow_drive"])++++ def test_phone_only_tray_has_no_send_direction(self):++ app = application("_refresh_tray_directions")++ app._peer_entries = entries()[:1]++ app._shown = lambda text: text++ app.drive_action, app.send_action = Control(), Control()++ app._refresh_tray_directions()++ self.assertTrue(app.drive_action.enabled)++ self.assertFalse(app.send_action.enabled)++ self.assertFalse(app.send_action.checked)++++ def test_tray_send_input_targets_never_offer_a_phone(self):++ class Action(Control):++ def __init__(self, text, parent):++ super().__init__(text)++ self.triggered = SimpleNamespace(connect=lambda callback: None)++ app = application("_refresh_tray_machines", QAction=Action)++ app._peer_entries = entries()++ other = dict(entries()[1], id=protocol.id_text(bytes(range(32, 48))),++ token="another-desktop", name="Another desktop")++ app._peer_entries.append(other)++ app._shown = lambda text: text++ app.machine_actions = {}++ app.tray_menu = SimpleNamespace(insertAction=lambda before, action: None)++ app.pause_action = object()++ app.redirect_action = Control()++ app.sender = SimpleNamespace(owner=None, redirecting=False)++ app._refresh_tray_machines()++ self.assertEqual(set(app.machine_actions), {DESKTOP, other["id"]})++ self.assertTrue(all("phone" not in action.text() for action in app.machine_actions.values()))++++ def test_same_announcements_ignore_phone_even_with_advertised_capabilities_and_side(self):++ from core import return_edge++ app = application("_announce", return_edge=return_edge)++ phone = dict(entries()[0], send=False, side="left", side_set_at=10)++ app.book = SimpleNamespace(peers=lambda: [phone])++ app._config = SimpleNamespace(machine_id=DESKTOP)++ app._peer_caps = lambda: {protocol.read_id(PHONE): {"settings", "design_sync"}}++ self.assertEqual(app._announce(protocol.read_id(PHONE)), [])++++ def test_phone_row_has_name_platform_remove_and_in_use_without_directions(self):++ row = load_methods("win_app/machines_win.py", "PeerRow", ["refresh", "_ask"],++ dict(KEEP_NOTE="kept"))()++ for name in ("name", "word", "where", "detail", "confirm_text", "in_use", "send", "allow",++ "remove_button", "directions", "direction_group", "confirm"):++ setattr(row, name, Control())++ row.led = SimpleNamespace(set_tone=lambda tone: None)++ row.confirm.visible = False++ row.refresh(entries()[0], "My phone", SimpleNamespace(tone="signal", word="Linked", detail="Connected"), "iPhone")++ self.assertEqual(row.name.text(), "My phone")++ self.assertEqual(row.where.text(), "iPhone")++ self.assertFalse(row.directions.visible)++ self.assertFalse(row.direction_group.visible)++ row._ask(False)++ self.assertFalse(row.directions.visible)++ self.assertTrue(row.in_use.visible)++ self.assertTrue(row.remove_button.visible)++++ def test_phone_waits_and_links_instead_of_showing_pair_again(self):++ for up, word in ((False, "Waiting"), (True, "Linked")):++ state = peers_view.describe(entries()[0], "My phone", up=up, driving=False,++ input_there=False, kind="", status="", waking=False)++ self.assertEqual(state.word, word)++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_qt_polish.pyindex 0000000,0000000..82b6113new file mode 100644--- /dev/null+++ b/win_app/tests/test_qt_polish.py@@@ -1,0 -1,0 +1,182 @@@++"""Measurements for the campaign's Qt polish faults, using synthetic settings only."""++++import unittest++++from PySide6.QtCore import QPoint, QRect, QRectF, Qt++from PySide6.QtGui import QColor, QFontInfo, QFontMetrics, QImage, QPainter, QPalette++from PySide6.QtWidgets import QLabel, QWidget++++import test_settings_layout_acceptance as acceptance++import diagram++import effect_previews++import pages_win++import theme++import widgets++++++class QtPolishTests(unittest.TestCase):++ setUpClass = acceptance.SettingsLayoutAcceptance.__dict__["setUpClass"]++ setUp = acceptance.SettingsLayoutAcceptance.setUp++ tearDown = acceptance.SettingsLayoutAcceptance.tearDown++ settle = acceptance.SettingsLayoutAcceptance.settle++ set_size = acceptance.SettingsLayoutAcceptance.set_size++ page_scroll = acceptance.SettingsLayoutAcceptance.page_scroll++++ def test_01_selected_segment_has_dark_text_on_light_with_contrast(self):++ self.set_size(900)++ for dark in (False, True):++ theme.set_dark(dark)++ self.window.setStyleSheet(theme.stylesheet())++ self.page_scroll("design")++ button = self.window.design_mode_choice._buttons["crossing"]++ self.settle()++ image = self.window.grab().toImage()++ dpr = image.devicePixelRatio()++ point = button.mapTo(self.window, QPoint())++ image = image.copy(round(point.x() * dpr), round(point.y() * dpr),++ round(button.width() * dpr), round(button.height() * dpr))++ bg = image.pixelColor(image.width() // 2, round(5 * image.devicePixelRatio()))++ self.assertGreater(bg.lightnessF(), .7)++ # Measure actual painted glyph ink, rather than merely the stylesheet palette.++ centre = image.copy(round(12 * image.devicePixelRatio()), round(10 * image.devicePixelRatio()),++ image.width() - round(24 * image.devicePixelRatio()),++ image.height() - round(20 * image.devicePixelRatio()))++ ink = min((centre.pixelColor(x, y) for x in range(centre.width())++ for y in range(centre.height())), key=lambda c: c.lightnessF())++ def luminance(colour):++ values = [v / 12.92 if v <= .04045 else ((v + .055) / 1.055) ** 2.4++ for v in colour.getRgbF()[:3]]++ return sum(v * w for v, w in zip(values, (.2126, .7152, .0722)))++ self.assertGreaterEqual((luminance(bg) + .05) / (luminance(ink) + .05), 4.5)++++ def test_02_segments_measure_longest_label_and_never_wrap(self):++ for width in (320, 640, 900, 1440, 1920):++ self.set_size(width)++ for key, *_ in pages_win.PAGES:++ column = self.page_scroll(key).widget().findChild(QWidget, "page_column")++ for view in column.findChildren(widgets._SegmentedView):++ if not view.isVisible():++ continue++ widths = [button.width() for button in view.buttons]++ self.assertLessEqual(max(widths, default=0) - min(widths, default=0), 1)++ for button in view.buttons:++ with self.subTest(width=width, page=key, text=button.text()):++ required = button.fontMetrics().horizontalAdvance(button.text()) + 16++ longest = max(b.fontMetrics().horizontalAdvance(b.text()) + 16 for b in view.buttons)++ if longest <= view.width():++ self.assertGreaterEqual(button.width(), required)++ self.assertEqual(button.height(), 30)++ else:++ # Full machine names can be longer than the entire narrow column.++ self.assertGreaterEqual(button.height(), button.heightForWidth(button.width()))++++ def test_03_form_controls_follow_label_track_exactly(self):++ for width in (900, 1440, 1920):++ self.set_size(width)++ self.page_scroll("design")++ for row in self.window.look_module.findChildren(widgets.FormRow):++ control = row.holder.layout().itemAt(0).widget()++ self.assertEqual(control.mapTo(row, QPoint()).x(), 196)++++ def test_04_hover_hint_is_plain_secondary_text(self):++ self.assertEqual(self.window.style_preview_hint.text(), "Hover to preview")++++ def test_05_effect_layer_preserves_screen_transform(self):++ # Identical screen/pointer scene with and without a pen in its own layer.++ scene = {"screens": [(100, 0, 100, 100, "windows")], "pens": [], "pointer": None, "notch": None}++ def paint(pens):++ image = QImage(300, 120, QImage.Format.Format_ARGB32_Premultiplied)++ image.fill(QColor("magenta"))++ painter = QPainter(image)++ painter.translate(50, 10)++ effect_previews.paint_scene(painter, __import__("PySide6.QtCore", fromlist=["QRectF"]).QRectF(0, 0, 200, 100),++ __import__("PySide6.QtCore", fromlist=["QRectF"]).QRectF(100, 0, 200, 100),++ dict(scene, pens=pens), 10, False)++ painter.end()++ return image++ from unittest.mock import patch++ with patch.object(effect_previews, "replay", lambda painter, _: painter.fillRect(QRectF(100, 0, 10, 10), QColor("cyan"))):++ self.assertEqual(paint([object()]).pixelColor(55, 15), QColor("cyan"))++++ def test_06_peer_actions_are_together_at_right_edge(self):++ self.set_size(1920)++ self.page_scroll("overview")++ for row in self.window.machines.rows.values():++ self.assertLessEqual(row.directions.x() - (row.in_use.x() + row.in_use.width()), 16)++ self.assertAlmostEqual(row.remove_button.x() + row.remove_button.width(), row.width(), delta=1)++++ def test_07_parts_are_segmented_and_corners_use_two_columns(self):++ self.assertIsInstance(self.window.crossing_rows["parts"].holder.layout().itemAt(0).widget(), widgets._SegmentedView)++ self.set_size(1440)++ self.page_scroll("crossing")++ view = self.window.corner_choice.view++ view.show()++ self.settle()++ self.assertLessEqual(len({button.y() for button in view.buttons}), 2)++++ def test_08_every_legend_way_has_a_description(self):++ self.assertTrue(all(description for _, _, description in pages_win.WAY_ROWS))++++ def test_09_headers_and_diagram_labels_wrap(self):++ self.assertTrue(self.window.ways_module.eyebrow.wordWrap())++ self.assertTrue(self.window.jump_heading.wordWrap())++ strip = self.window.resistance_strip++ strip.resize(400, 44)++ strip.set_other_name("Other machine")++ metrics = QFontMetrics(theme.font(theme.TYPE["small"], 600))++ width = strip.target_width() if hasattr(strip, "target_width") else strip.MAC++ self.assertGreaterEqual(width, metrics.horizontalAdvance("Other machine") + 12)++ strip.set_other_name("Synthetic workstation with a long machine name")++ strip.resize(160, 44)++ needed = metrics.boundingRect(QRect(0, 0, round(strip.target_width() - 8), 10000),++ int(Qt.TextFlag.TextWrapAnywhere), strip._other)++ self.assertGreaterEqual(strip.heightForWidth(160), needed.height() + 4)++++ def test_10_status_uses_hanken_with_normal_tracking(self):++ self.page_scroll("overview")++ labels = [self.window.location_readout, *[row.word for row in self.window.machines.rows.values()]]++ for item in labels:++ self.assertEqual(QFontInfo(item.font()).family(), theme.sans())++ self.assertIn(item.font().letterSpacing(), (0, 100))++++ def test_11_narrow_rows_have_readable_targets_and_whole_diagram(self):++ self.set_size(320)++ self.page_scroll("overview")++ for row in self.window.machines.rows.values():++ self.assertGreaterEqual(row.word.mapTo(row, QPoint()).y(), row.name.mapTo(row, QPoint()).y() + row.name.height())++ for button in (row.directions, row.remove_button):++ self.assertGreaterEqual(button.width(), button.fontMetrics().horizontalAdvance(button.text()) + 16)++ self.assertGreaterEqual(button.height(), 30)++ self.page_scroll("crossing")++ drawing = self.window.arrangement_diagram++ self.assertFalse(self.window.ways_pair.beside())++ self.assertGreaterEqual(drawing.width(), 120)++ pc, screens, _ = drawing._drawing(drawing.width())++ for rect in [pc, *screens.values()]:++ self.assertGreaterEqual(rect[0], 0)++ self.assertLessEqual(rect[0] + rect[2], drawing.width() + 1)++ metrics = QFontMetrics(theme.font(theme.TYPE["small"], 600))++ for key, rect in screens.items():++ needed = metrics.boundingRect(QRect(0, 0, max(1, round(rect[2] - 8)), 10000),++ int(Qt.TextFlag.TextWrapAnywhere), drawing._labels[key])++ self.assertLessEqual(needed.height(), rect[3] - 4)++ self.assertLessEqual(needed.width(), rect[2] - 8 + 1)++ self.assertGreaterEqual(self.window.jump_recorder.height(), self.window.jump_recorder.heightForWidth(self.window.jump_recorder.width()))++++ def test_12_rail_ends_above_footer_at_minimum_height(self):++ self.set_size(320, 300)++ sidebar = self.window.sidebar++ footer = self.window.footer_note.parentWidget()++ for child in [*sidebar._buttons.values(), sidebar.foot]:++ self.assertLessEqual(child.mapTo(self.window, QPoint()).y() + child.height(), footer.y())++++ def test_13_full_document_background_is_opaque(self):++ import render_settings_layout as render++ page = self.page_scroll("design").widget()++ image = render.capture_document(page) if hasattr(render, "capture_document") else page.grab().toImage()++ self.assertEqual(image.pixelColor(0, 0).alpha(), 255)++ self.assertEqual(image.pixelColor(0, 0).name(), theme.colour("ground"))++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_real_font.pyindex 0000000,0000000..c45d2ddnew file mode 100644--- /dev/null+++ b/win_app/tests/test_real_font.py@@@ -1,0 -1,0 +1,99 @@@++"""Keep the real-font full-window resize path safe in an isolated Qt process."""++++import os++import subprocess++import sys++import unittest++++++def _run_real_font_window():++ os.environ["QT_QPA_PLATFORM"] = "offscreen"++ from pathlib import Path++ import tempfile++++ root = Path(__file__).resolve().parents[2]++ sys.path[:0] = [str(root / "win_app"), str(root)]++ from PySide6.QtCore import Qt++ from PySide6.QtWidgets import QApplication++++ import app_config++ import kvm_bridge_win++ import theme++ import tokens++ from core import protocol++ from core.tests import responder_harness as harness++++ class NullSignal:++ def connect(self, _callback):++ pass++++ class NullAction:++ def __init__(self):++ self.triggered = NullSignal()++++ def __getattr__(self, _name):++ return lambda *_args, **_kwargs: None++++ class NullTray:++ def __getattr__(self, _name):++ return lambda *_args, **_kwargs: None++++ class RenderWindow(kvm_bridge_win.WindowsApplication):++ def _build_tray(self):++ self.tray = NullTray()++ self.header_action = NullAction()++ self.open_action = NullAction()++ self.status_action = NullAction()++ self.redirect_action = NullAction()++ self.pause_action = NullAction()++ self.drive_action = NullAction()++ self.send_action = NullAction()++ self.tray_menu = NullTray()++++ app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ app.setFont(theme.font(theme.TYPE["body"]))++ assert theme.sans() == tokens.UI_FAMILY++ work_root = Path(__file__).resolve().parents[2] / "renders" / "test-working"++ work_root.mkdir(parents=True, exist_ok=True)++ with tempfile.TemporaryDirectory(dir=work_root) as directory:++ config_path = Path(directory) / "settings.json"++ settings = app_config.migrate(None, machine_id=protocol.id_text(harness.HERE))++ settings["port"] = harness.free_port()++ app_config.write_settings(config_path, settings)++ window = RenderWindow(config_path)++ window.refresh_timer.stop()++ window.full_screen_timer.stop()++ window._select_page("design")++ window.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, True)++ window.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)++ try:++ window.show()++ window.resize(640, 760)++ app.processEvents()++ finally:++ window.server.stop()++ window.close()++++[email protected](sys.platform == "win32", "the stack overflow is in Windows Qt offscreen")++class RealFontResizeTests(unittest.TestCase):++ def test_full_design_window_resizes_with_the_bundled_font(self):++ environment = os.environ.copy()++ environment["BEAMER_REAL_FONT_CHILD"] = "1"++ environment["QT_QPA_PLATFORM"] = "offscreen"++ result = subprocess.run(++ [sys.executable, __file__],++ env=environment,++ capture_output=True,++ text=True,++ timeout=45,++ )++ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)++++++if __name__ == "__main__":++ if os.environ.get("BEAMER_REAL_FONT_CHILD"):++ _run_real_font_window()++ else:++ unittest.main()diff --cc win_app/tests/test_same_on_both.pyindex f70acd1,0000000..90735efmode 100644,000000..100644--- a/win_app/tests/test_same_on_both.py+++ b/win_app/tests/test_same_on_both.py@@@ -1,340 -1,0 +1,390 @@@+"""Same on all machines in the real window: the Overview switch, a Mac's settings arriving, and a+change here going out. Built offscreen from a synthetic config as test_style_for builds it, which+starts no receiver, hooks or announcer; the two links' sends are recorded instead."""++import json+import os+import tempfile+import unittest+from pathlib import Path+from unittest import mock++try:+ from PySide6.QtWidgets import QApplication++ import kvm_bridge_win+ import pages_win+ from core import settings_sync+ import theme+ import app_config+ from app_config import load_config+ from core import protocol+ from core.tests import responder_harness as harness+except ImportError: # PySide6 is only in the Windows venv+ kvm_bridge_win = None+++def mac_message(on, set_at, by=None, **values):+ base = dict(shortcut=False, resistance_px=60,+ block_while_dragging=False, trigger_key="alt_r", trigger_style="hold", double_tap_ms=400,+ glow_style="beam", glow_colour="ocean", effect_length="long", shortcut_arrival=False,+ shortcut_arrival_style="locator")+ base.update(values)+ return settings_sync.message_data(on, set_at, base, by=by or protocol.id_text(harness.B))++[email protected](kvm_bridge_win is None, "needs PySide6")+class SameOnBothTest(unittest.TestCase):+ def setUp(self):+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ self.app = QApplication.instance() or QApplication([])+ theme.init_fonts()+ folder = Path(tempfile.mkdtemp())+ self.path = folder / "settings.json"+ (folder / "config.json").write_text(json.dumps({+ "host": "192.168.1.20", "port": harness.free_port(), "auth_token": "synthetic", "paired_with": "MacBook Pro",+ "mac_host": "192.168.1.10", "mac_return_edge": "left", "edge_glow": True,+ }))+ self.window = kvm_bridge_win.WindowsApplication(self.path)+ self.sent = []+ self.peers = {harness.B: {"settings"}, harness.C: {"settings"}}+ self.window._peer_caps = lambda: dict(self.peers)+ self.window._send_to = lambda peer, message: self.sent.append((peer, message["data"])) or True+ self.window._refresh_window()++ def tearDown(self):+ self.window.server.stop()+ self.window.deleteLater()++ def pair_peer(self, peer: str) -> None:+ settings = app_config.load_settings(self.path)+ settings["peers"][0]["id"] = peer+ app_config.write_settings(self.path, settings)+ self.window._refresh_peers()++ def test_off_by_default_with_each_page_its_own(self):+ self.assertFalse(self.window.same_switch.isChecked())+ self.assertEqual(self.window.scope_labels["design"].text(), pages_win.SCOPE["design"])++ def test_full_screen_hold_switch_names_this_pcs_edges(self):+ self.assertEqual(self.window.hold_switch.text(), "Hold this PC's edges while an app on it is full screen")+ def test_this_pcs_design_state_is_announced_when_same_is_off(self):+ data = self.window._same_state()++ self.assertFalse(data["on"])+ self.assertEqual(data["design_sync"]["values"]["effect_size"], "medium")+ self.assertEqual(set(data["design_sync"]["values"]), set(settings_sync.DESIGN_KEYS))++ def test_a_followed_design_is_applied_and_renamed_as_this_pcs_state(self):+ peer = protocol.id_text(harness.B)+ self.pair_peer(peer)+ self.window._config.design_follow_peer = peer+ received = settings_sync.message_data(+ False, 100, by=peer,+ design_state={"set_at": 200, "by": peer,+ "values": {"effect_length": "long"}},+ )++ self.window._on_settings(peer, received)++ self.assertEqual(self.window._config.effect_length, "long")- self.assertEqual((self.window._config.design_set_at, self.window._config.design_by), (200, peer))++ self.assertGreater(self.window._config.design_set_at, 200)++ self.assertEqual(self.window._config.design_by, self.window._config.machine_id)+ self.assertEqual(self.sent[-1][1]["design_sync"]["values"]["effect_length"], "long")++ def test_a_design_state_in_a_malformed_settings_envelope_is_dropped_whole(self):+ peer = protocol.id_text(harness.B)+ self.pair_peer(peer)+ self.window._config.design_follow_peer = peer+ state = {"set_at": 200, "by": peer, "values": {"effect_length": "long"}}++ for outer in ({"on": "no"}, {"set_at": True}, {"by": "not an id"}):+ received = settings_sync.message_data(False, 100, by=peer, design_state=state)+ received.update(outer)+ self.window._on_settings(peer, received)++ self.assertEqual(self.window._config.effect_length, "normal")+ self.assertNotIn(peer, self.window._design_states)+ self.assertEqual(self.sent, [])++ def test_follow_accepts_the_leaders_next_change_after_this_pc_reannounces(self):+ peer = protocol.id_text(harness.B)+ self.pair_peer(peer)+ config = self.window._config+ config.design_follow_peer = peer+ config.design_set_at = 50+ config.design_by = peer++ for stamp, length in ((100, "long"), (101, "short")):+ received = settings_sync.message_data(+ False, stamp - 50, by=peer,+ design_state={"set_at": stamp, "by": peer, "values": {"effect_length": length}},+ )+ self.window._on_settings(peer, received)++ self.assertEqual(self.window._config.effect_length, "short")- self.assertEqual((self.window._config.design_set_at, self.window._config.design_by), (101, peer))++ self.assertGreater(self.window._config.design_set_at, 101)++ self.assertEqual(self.window._config.design_by, self.window._config.machine_id)+ self.assertEqual(self.sent[-1][1]["design_sync"]["values"]["effect_length"], "short")+ self.assertEqual((self.sent[-1][1]["design_sync"]["set_at"], self.sent[-1][1]["design_sync"]["by"]),- (101, peer))++ (self.window._config.design_set_at, self.window._config.machine_id))++ def test_followed_size_updates_the_control_without_saving_a_local_edit(self):+ peer = protocol.id_text(harness.B)+ self.pair_peer(peer)+ self.window._config.design_follow_peer = peer+ received = settings_sync.message_data(+ False, 100, by=peer,+ design_state={"set_at": 200, "by": peer, "values": {"effect_size": "large"}},+ )++ self.window._on_settings(peer, received)++ self.assertEqual(self.window.size_choice.value, "large")+ self.assertEqual(self.window._config.effect_size, "large")+ self.assertEqual(self.sent[-1][1]["design_sync"]["values"]["effect_size"], "large")++ def test_same_on_design_change_is_announced_with_a_new_local_design_stamp(self):+ source = protocol.id_text(harness.C)+ config = self.window._config+ config.same_on_both = True+ config.same_set_at = 10+ config.same_by = source+ config.design_set_at = 20+ config.design_by = config.machine_id+ config.effect_length = "short"+ received = mac_message(True, 11, by=source, effect_length="long")+ received["design_sync"] = {+ "set_at": 100, "by": source, "values": {"effect_length": "long"},+ }++ self.window._on_settings(source, received)++ self.assertEqual(self.window._config.effect_length, "long")+ self.assertGreater(self.window._config.design_set_at, 100)+ self.assertEqual(self.window._config.design_by, self.window._config.machine_id)+ self.assertEqual(self.sent[-1][1]["design_sync"]["set_at"], self.window._config.design_set_at)+ self.assertNotEqual(self.sent[-1][1]["design_sync"]["by"], source)++ def test_same_off_from_another_machine_resumes_the_cached_followed_design(self):+ leader = protocol.id_text(harness.B)+ other = protocol.id_text(harness.C)+ self.pair_peer(leader)+ config = self.window._config+ config.same_on_both = True+ config.same_set_at = 10+ config.same_by = other+ config.design_follow_peer = leader+ config.effect_length = "short"+ self.window._design_states[leader] = {+ "set_at": 100, "by": leader, "values": {"effect_length": "long"},+ }+ apply_followed = mock.Mock(wraps=self.window._apply_followed_design)+ self.window._apply_followed_design = apply_followed++ self.window._on_settings(other, settings_sync.message_data(False, 11, by=other))++ apply_followed.assert_called_once()+ self.assertEqual(self.window._config.effect_length, "long")+ self.assertEqual(self.sent[-1][1]["design_sync"]["values"]["effect_length"], "long")+ self.assertEqual((self.sent[-1][1]["design_sync"]["set_at"], self.sent[-1][1]["design_sync"]["by"]),- (100, protocol.id_text(harness.B)))++ (self.window._config.design_set_at, self.window._config.machine_id))+- def test_editing_a_design_control_stops_following(self):- self.window._config.design_follow_peer = protocol.id_text(harness.B)++ def follow(self, **values):++ peer = protocol.id_text(harness.B)++ self.pair_peer(peer)++ for key, value in values.items():++ setattr(self.window._config, key, value)++ self.window._config.design_follow_peer = peer++ self.window._reflect_config(self.window._config)+ self.window._design_seen = self.window._design_fields()- self.window.length_choice.set_value("short")- self.window._apply_look()++ self.window._refresh_design_follow()++ return peer++++ def followed_controls(self):++ w = self.window++ return [*w.length_choice._buttons.values(), *w.size_choice._buttons.values(), w.landing_toggle,++ *(w.glow_style_choice.tile(value) for value in self.window.effect_stills),++ *(w.switch_style_choice.tile(value) for value in self.window.switch_stills),++ *w.glow_colour_choice._swatches.values()]++++ def test_following_locks_the_followed_design_controls_under_a_banner(self):++ self.follow()++++ self.assertFalse(any(control.isEnabled() for control in self.followed_controls()))++ for control in (self.window.length_choice.view, self.window.size_choice.view,++ self.window.glow_colour_choice.view, self.window.landing_toggle):++ self.assertAlmostEqual(control.graphicsEffect().opacity(), 0.45)++ for choice in (self.window.glow_style_choice, self.window.switch_style_choice):++ for tiles in choice.groups.values():++ self.assertAlmostEqual(tiles.view.graphicsEffect().opacity(), 0.45)++ self.assertTrue(self.window.glow_toggle.isEnabled())++ self.assertFalse(self.window.follow_banner.isHidden())++ self.assertEqual(self.window.follow_banner_label.text(), "Following MacBook Pro's design")++++ def test_a_click_on_a_locked_control_changes_nothing_and_keeps_following(self):++ peer = self.follow(effect_length="long")++ self.sent.clear()++++ self.window.length_choice._buttons["short"].click()++ self.window.landing_toggle.click()++++ self.assertEqual(self.window.length_choice.value, "long")++ self.assertEqual(self.window._config.effect_length, "long")++ self.assertEqual(self.window._config.design_follow_peer, peer)++ self.assertEqual(self.sent, [])++++ def test_stop_following_unlocks_the_controls_and_keeps_the_shown_design(self):++ self.follow(effect_length="long", glow_colour="ocean")++++ self.window.stop_follow_button.click()++ self.assertEqual(self.window._config.design_follow_peer, "")- self.assertEqual(self.sent[-1][1]["design_sync"]["values"]["effect_length"], "short")++ self.assertTrue(all(control.isEnabled() for control in self.followed_controls()))++ self.assertTrue(self.window.follow_banner.isHidden())++ self.assertEqual((self.window.length_choice.value, self.window._config.effect_length), ("long", "long"))++ self.assertEqual((self.window.glow_colour_choice.value, self.window._config.glow_colour), ("ocean", "ocean"))++ self.assertEqual(self.sent[-1][1]["design_sync"]["values"]["effect_length"], "long")++ def test_unpairing_the_followed_machine_resets_the_selection(self):+ peer = protocol.id_text(harness.B)+ self.window._config.design_follow_peer = peer+ with mock.patch.object(self.window.book, "peers", return_value=[]), \+ mock.patch.object(self.window.book, "zones", return_value=[]):+ self.window._refresh_peers()++ self.assertEqual(self.window._config.design_follow_peer, "")++ def test_same_on_all_machines_keeps_precedence_over_a_followed_design(self):+ peer = protocol.id_text(harness.B)+ self.pair_peer(peer)+ self.window._config.design_follow_peer = peer+ self.window._config.same_on_both = True+ self.window._config.same_set_at = 100+ received = settings_sync.message_data(+ True, 101, settings_sync.pc_values(self.window._config), by=peer,+ design_state={"set_at": 202, "by": peer,+ "values": {"effect_length": "long"}},+ )++ self.window._on_settings(peer, received)++ self.assertEqual(self.window._config.effect_length, "normal")+ self.assertEqual(self.window._config.design_follow_peer, protocol.id_text(harness.B))++ def test_an_older_peer_is_disabled_in_match_design_with(self):- self.window._peer_entries = [{"id": protocol.id_text(harness.B), "name": "Old PC"}]++ self.window._peer_entries = [harness.entry(harness.B, "Old PC")]+ self.peers = {harness.B: {"settings"}}++ self.window._design_peer_caps = lambda: {protocol.id_text(harness.B): {"settings"}}++ self.window._refresh_design_follow()++ self.assertFalse(self.window.design_follow_choice.model().item(1).isEnabled())+ self.assertIn("Needs beta.6 or later", self.window.design_follow_choice.itemText(1))++ def test_the_macs_settings_arrive_on_this_pcs_fields_and_controls(self):+ self.window._on_settings(protocol.id_text(harness.B), mac_message(True, 100))+ config = self.window._config+ self.assertTrue(config.same_on_both)+ self.assertNotIn("shortcut", config.crossing_methods)+ self.assertEqual((config.glow_style, config.glow_colour, config.effect_length), ("beam", "ocean", "long"))+ self.assertEqual((config.trigger_style, config.double_tap_ms, config.shortcut_arrival), ("hold", 400, False))+ self.assertTrue(config.edge_glow)+ self.assertEqual(load_config(self.path).glow_style, "beam")+ self.assertEqual(self.window.resistance_slider.value(), 60)+ self.assertFalse(self.window.landing_toggle.isChecked())+ self.window._refresh_window()+ self.assertTrue(self.window.same_switch.isChecked())+ self.assertEqual(self.window.scope_labels["crossing"].text(),- "Kept the same as MacBook Pro. Change it on any machine.")++ "Resistance, drag protection and Shortcut stay in step. Ways and jump keys below are local; each side is shared with its paired machine.")+ # Applying what arrived is not a change made here: it goes on to the other peer and never back.+ self.assertEqual([peer for peer, _data in self.sent], [harness.C])++ def test_an_older_message_changes_nothing(self):+ self.window._on_settings(protocol.id_text(harness.B), mac_message(True, 100))+ self.window._on_settings(protocol.id_text(harness.B), mac_message(True, 90, glow_style="glow"))+ self.assertEqual(self.window._config.glow_style, "beam")++ def test_a_state_a_peer_already_holds_is_not_sent_on_again(self):+ self.window._on_settings(protocol.id_text(harness.B), mac_message(True, 100))+ self.sent.clear()+ self.window._on_settings(protocol.id_text(harness.C), mac_message(True, 100))+ self.assertEqual(self.sent, [])++ def test_a_peer_without_the_settings_capability_is_sent_none(self):+ self.peers[harness.C] = set()+ self.window.same_switch.setChecked(True)+ self.assertEqual([peer for peer, _data in self.sent], [harness.B])++ def test_turning_it_on_here_sends_this_pcs_values_to_every_peer_that_takes_them(self):+ self.window.same_switch.setChecked(True)+ self.assertEqual([peer for peer, _data in self.sent], [harness.B, harness.C])+ data = self.sent[0][1]+ self.assertTrue(data["on"])+ self.assertIs(data["crossing"]["shortcut"], True)++ def test_a_change_here_while_on_is_stamped_and_sent_and_one_to_this_pcs_own_is_not(self):+ self.window.same_switch.setChecked(True)+ stamp = self.window._config.same_set_at+ self.sent.clear()+ self.window._config.same_set_at = stamp - 10+ self.window._config.edge_glow = False+ self.window._persist()+ self.assertEqual(self.sent, [])+ self.window._config.effect_length = "short"+ self.window._persist()+ self.assertEqual(len(self.sent), 2)+ self.assertGreaterEqual(self.window._config.same_set_at, stamp)+ self.assertEqual(self.window._config.same_by, self.window._config.machine_id)+ self.assertEqual(self.sent[0][1]["design"]["effect_length"], "short")++ def test_a_save_after_a_link_replaced_the_first_peer_does_not_bring_the_old_pairing_back(self):+ # A fold removed the entry migrated from 1.4.x; the window still holds its token.+ settings = app_config.load_settings(self.path)+ settings["peers"] = [harness.entry(harness.B, "Mac", linked=True, token=harness.TOKENS[harness.B])]+ settings["zones"] = []+ app_config.write_settings(self.path, settings)+ self.window._config.effect_length = "short"+ self.assertTrue(self.window._persist())+ saved = app_config.load_settings(self.path)+ self.assertEqual([peer["token"] for peer in saved["peers"]], [harness.TOKENS[harness.B]])+ self.assertEqual(self.window._config.auth_token, harness.TOKENS[harness.B])++ def test_a_state_that_goes_on_is_forwarded_with_this_pcs_direct_design_state(self):+ self.peers = {harness.B: {"settings"}, harness.C: {"settings"}}+ message = mac_message(True, 100)+ self.window._on_settings(protocol.id_text(harness.B), message)+ self.assertEqual(len(self.sent), 1)+ self.assertEqual(self.sent[0][0], harness.C)+ forwarded = self.sent[0][1]+ self.assertEqual({key: value for key, value in forwarded.items() if key != "design_sync"},+ {key: value for key, value in message.items() if key != "design_sync"})+ self.assertEqual(forwarded["design_sync"]["by"], self.window._config.machine_id)++ def test_a_design_change_here_while_off_announces_its_local_state(self):+ self.window._config.effect_length = "short"+ self.window._persist()+ self.assertEqual(len(self.sent), 2)+ self.assertTrue(all(message["design_sync"]["values"]["effect_length"] == "short"+ for _peer, message in self.sent))++ def test_announcing_carries_a_chosen_arrangement_the_peers_it_may_send_to_and_the_settings(self):+ settings = app_config.load_settings(self.path)+ settings["peers"][0]["id"] = protocol.id_text(harness.B)+ inactive = dict(settings["peers"][0], id=protocol.id_text(harness.C), token="inactive", in_use=False)+ settings["peers"].append(inactive)+ app_config.write_settings(self.path, settings)+ self.peers = {harness.B: {"settings"}}+ messages = self.window._announce(harness.B)+ self.assertEqual([m["type"] for m in messages], ["paired", "settings"])+ self.assertEqual(messages[0]["data"]["ids"], [])+ settings["peers"][0].update(side="left", side_set_at=500, side_by=self.window._config.machine_id)+ app_config.write_settings(self.path, settings)+ messages = self.window._announce(harness.B)+ self.assertEqual(messages[0]["type"], "arrangement")+ self.assertEqual(messages[0]["data"]["edge"], "left")+ self.assertEqual(messages[0]["data"]["set_at"], 500)+++if __name__ == "__main__":+ unittest.main()diff --cc win_app/tests/test_settings_behaviour.pyindex 0000000,0000000..edb2b0cnew file mode 100644--- /dev/null+++ b/win_app/tests/test_settings_behaviour.py@@@ -1,0 -1,0 +1,53 @@@++"""Windows settings decisions with in-memory configuration and no Qt window."""++++from core.tests.settings_behaviour import SettingsBehaviourTests as _SettingsBehaviourTests++from core.tests.app_methods import load_methods++from core import settings_sync, peerlist++from types import SimpleNamespace++from unittest import TestCase++++++class WindowsSettingsBehaviourTests(_SettingsBehaviourTests):++ platform = "win"++++ def setUp(self):++ super().setUp()++ self.app.parts_choice = SimpleNamespace(view=SimpleNamespace(refresh_metrics=lambda: None))++++++del _SettingsBehaviourTests++++++class SameCompatibilityTests(TestCase):++ def test_old_peer_status_disables_same_but_an_unobserved_peer_does_not(self):++ namespace = dict(settings_sync=settings_sync, peerlist=peerlist,++ widgets=SimpleNamespace(set_role=lambda note, role: setattr(note, "role", role)))++ cls = load_methods("win_app/kvm_bridge_win.py", "WindowsApplication", ["_show_same"], namespace)++ for capabilities, enabled, checked, old in (({}, True, True, False),++ ({"new": {"settings"}}, True, True, False),++ ({"old": set()}, False, False, True),++ ({"new": {"settings"}, "old": set()}, False, False, True)):++ with self.subTest(capabilities=capabilities):++ app = cls()++ app._config = SimpleNamespace(same_on_both=True)++ app._paired = True++ app._peer_caps = lambda: capabilities++ switch = SimpleNamespace(checked=True, enabled=True, blockSignals=lambda on: None)++ switch.isChecked = lambda: switch.checked++ switch.setChecked = lambda on: setattr(switch, "checked", on)++ switch.setEnabled = lambda on: setattr(switch, "enabled", on)++ app.same_switch = switch++ app.same_note = SimpleNamespace(++ setText=lambda text: setattr(app.same_note, "text", text),++ setToolTip=lambda text: setattr(app.same_note, "tool_tip", text),++ )++ app._peer_entries = [{"token": "desktop", "name": "Desktop", "port": 24820}]++ app._shown = lambda text: text++ app.scope_labels = {}++ app.own_notes = []++ app._refresh_design_follow = lambda: None++ app._show_same()++ self.assertEqual(switch.enabled, enabled)++ self.assertEqual(switch.checked, checked)++ self.assertEqual("too old" in app.same_note.text, old)++ self.assertEqual(app.same_note.role, "note-amber" if old else "note")diff --cc win_app/tests/test_settings_layout_acceptance.pyindex 0000000,0000000..0e08b3enew file mode 100644--- /dev/null+++ b/win_app/tests/test_settings_layout_acceptance.py@@@ -1,0 -1,0 +1,531 @@@++"""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,++ 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_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/tests/test_settings_migration.pyindex 9220d89,0000000..22a3c72mode 100644,000000..100644--- a/win_app/tests/test_settings_migration.py+++ b/win_app/tests/test_settings_migration.py@@@ -1,714 -1,0 +1,724 @@@+"""The Windows app's settings.json and its migration from 1.4.x's config.json (WIRE.md section 1+and section 8)."""++import base64+import hashlib+import hmac+import importlib.util+import itertools+import json+import os+import sys+import tempfile+import unittest+from dataclasses import asdict, replace+from pathlib import Path+from unittest import mock++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import app_config+from app_config import ConfigError++FIXTURES = Path(__file__).resolve().parent / "fixtures"+++def b64(data: bytes) -> str:+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")+++LEGACY = json.loads((FIXTURES / "config_1_4_3.json").read_text(encoding="utf-8"))+PAIRED = LEGACY["auth_token"]+OTHER = b64(bytes(range(1, 33)))+THIRD = b64(bytes(range(2, 34)))+PEER_ID = b64(bytes([7]) * 16)+OTHER_ID = b64(bytes([8]) * 16)+OWN_ID = b64(bytes([9]) * 16)++# What a migrated entry is, for the fixture: every field of section 1's table.+MIGRATED_PEER = {+ "id": "", "name": "MacBook Pro", "platform": "macos", "host": "192.0.2.10", "port": 24820,+ "hw": "aa:bb:cc:dd:ee:ff", "send": True, "allow_drive": True, "in_use": True, "side": "left", "side_set_at": 1790000000,+ "paired_with": [], "paired_at": 0, "linked": False, "from_1_4": True,+}++MOVED_OR_DROPPED = (+ "host", "mac_host", "auth_token", "paired_with", "mac_hardware_address", "send_to_mac", "allow_mac_to_drive",+ "mac_return_edge", "arrangement_set_at", "crossing_methods", "crossing_edge_parts", "crossing_corner",+ "mac_resistance_px",+)+++class Folder(unittest.TestCase):+ """A settings folder holding 1.4.3's config.json, and the path of the settings.json beside it."""++ legacy = LEGACY++ def setUp(self):+ self._directory = tempfile.TemporaryDirectory()+ self.addCleanup(self._directory.cleanup)+ self.folder = Path(self._directory.name)+ self.legacy_path = self.folder / "config.json"+ self.path = self.folder / "settings.json"+ if self.legacy is not None:+ self.write_legacy(self.legacy)++ def write_legacy(self, raw):+ self.legacy_path.write_text(json.dumps(raw, indent=2) + "\n", encoding="utf-8")+ os.utime(self.legacy_path, ns=(1_700_000_000_000_000_000, 1_700_000_000_000_000_000))++ def settings(self):+ return json.loads(self.path.read_text(encoding="utf-8"))++ def put(self, settings):+ self.path.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8")+++class MigrationTests(Folder):+ def test_the_paths_are_settings_json_and_the_old_file_beside_it(self):+ self.assertEqual(app_config.default_config_path().name, "settings.json")+ self.assertEqual(app_config.legacy_config_path(self.path), self.legacy_path)++ def test_1_4_3s_config_becomes_the_settings_section_1_says_field_by_field(self):+ settings = app_config.load_settings(self.path)+ self.assertEqual(settings, self.settings())+ self.assertEqual(settings["schema"], 6)+ self.assertEqual(settings["name"], "")+ self.assertEqual(settings["port"], 24820)+ self.assertIs(settings["shortcut"], True)+ self.assertEqual(settings["migrated_token_sha256"], hashlib.sha256(PAIRED.encode()).hexdigest())+ self.assertEqual(len(settings["peers"]), 1)+ self.assertEqual(settings["peers"][0], {**MIGRATED_PEER, "token": PAIRED, "side_by": settings["machine_id"]})+ for key in MOVED_OR_DROPPED:+ self.assertNotIn(key, settings)+ for key, value in LEGACY.items():+ if key not in MOVED_OR_DROPPED and key != "port":+ self.assertEqual(settings[key], value, key)++ def test_peer_in_use_must_be_a_boolean(self):+ settings = app_config.load_settings(self.path)+ settings["peers"][0]["in_use"] = "yes"+ self.put(settings)+ with self.assertRaises(app_config.SettingsFileError):+ app_config.load_settings(self.path)++ def test_jump_key_must_be_a_recorded_chord_and_round_trips(self):+ settings = app_config.load_settings(self.path)+ settings["peers"][0]["jump_key"] = "ctrl+shift+2"+ app_config.write_settings(self.path, settings)+ self.assertEqual(app_config.load_settings(self.path)["peers"][0]["jump_key"], "ctrl+shift+2")+ settings["peers"][0]["jump_key"] = "nonsense"+ with self.assertRaises(app_config.SettingsFileError):+ app_config.write_settings(self.path, settings)++ def test_load_rejects_a_malformed_jump_key(self):+ settings = app_config.load_settings(self.path)+ settings["peers"][0]["jump_key"] = "ctrl"+ self.put(settings)+ with self.assertRaises(app_config.SettingsFileError):+ app_config.load_settings(self.path)++ def test_jump_key_clash_is_refused_without_saving_and_can_be_cleared(self):+ settings = app_config.load_settings(self.path)+ peer_id = settings["peers"][0]["id"]+ app_config.set_jump_key(self.path, peer_id, "ctrl+shift+2", "alt_r")+ with self.assertRaises(app_config.ConfigError):+ app_config.set_jump_key(self.path, peer_id, "ctrl+alt+2", "alt_r")+ self.assertEqual(app_config.load_settings(self.path)["peers"][0]["jump_key"], "ctrl+shift+2")+ app_config.set_jump_key(self.path, peer_id, "", "alt_r")+ self.assertEqual(app_config.load_settings(self.path)["peers"][0]["jump_key"], "")++ def test_the_machine_id_is_sixteen_random_bytes_in_b64_and_never_zero(self):+ ids = set()+ for _ in range(3):+ self.path.unlink(missing_ok=True)+ ids.add(app_config.load_settings(self.path)["machine_id"])+ self.assertEqual(len(ids), 3)+ for machine_id in ids:+ self.assertEqual(len(machine_id), 22)+ raw = base64.urlsafe_b64decode(machine_id + "==")+ self.assertEqual((len(raw), b64(raw)), (16, machine_id))+ self.assertNotEqual(raw, bytes(16))++ def test_an_id_of_sixteen_zero_bytes_is_drawn_again(self):+ draws = iter([bytes(16), bytes([5]) * 16])+ with mock.patch.object(app_config.os, "urandom", lambda count: next(draws)):+ self.assertEqual(app_config.new_machine_id(), b64(bytes([5]) * 16))++ def test_side_by_is_this_machines_id_only_when_a_side_was_ever_set(self):+ self.write_legacy({**LEGACY, "arrangement_set_at": 0})+ settings = app_config.load_settings(self.path)+ self.assertEqual((settings["peers"][0]["side_set_at"], settings["peers"][0]["side_by"]), (0, ""))++ def test_the_old_default_port_moves_down_and_a_chosen_one_stays(self):+ self.write_legacy({**LEGACY, "port": 51820})+ self.assertEqual(app_config.load_settings(self.path)["port"], 24820)+ self.assertEqual(app_config.load_settings(self.path)["peers"][0]["port"], 24820)+ self.path.unlink()+ self.write_legacy({**LEGACY, "port": 9000})+ settings = app_config.load_settings(self.path)+ self.assertEqual((settings["port"], settings["peers"][0]["port"]), (9000, 9000))++ def test_the_saved_key_style_survives_each_way(self):+ for style in app_config.MODIFIER_STYLES:+ with self.subTest(style=style):+ self.path.unlink(missing_ok=True)+ self.write_legacy({**LEGACY, "modifier_style": style})+ self.assertEqual(app_config.load_settings(self.path)["modifier_style"], style)+ self.assertEqual(app_config.load_config(self.path).modifier_style, style)++ def test_a_config_from_main_before_milestone_2_migrates_with_its_same_on_both(self):+ self.write_legacy({**LEGACY, "same_on_both": True, "same_set_at": 1790000500, "hold_full_screen": False})+ settings = app_config.load_settings(self.path)+ self.assertEqual((settings["same_on_both"], settings["same_set_at"], settings["hold_full_screen"]),+ (True, 1790000500, False))+ config = app_config.load_config(self.path)+ self.assertEqual((config.same_on_both, config.same_set_at, config.hold_full_screen), (True, 1790000500, False))++ def test_a_field_1_4_x_did_not_have_takes_its_default(self):+ self.write_legacy({key: value for key, value in LEGACY.items() if key != "hide_addresses"})+ self.assertNotIn("hide_addresses", app_config.load_settings(self.path))+ self.assertIs(app_config.load_config(self.path).hide_addresses, False)++ def test_the_old_file_is_kept_byte_for_byte_and_its_time_unchanged(self):+ before = (self.legacy_path.read_bytes(), self.legacy_path.stat().st_mtime_ns)+ app_config.load_settings(self.path)+ config = app_config.load_config(self.path)+ for day in range(3):+ app_config.save_config(self.path, replace(config, pointer_speed=1.0 + day / 10))+ self.assertEqual((self.legacy_path.read_bytes(), self.legacy_path.stat().st_mtime_ns), before)++ def test_starting_again_changes_nothing(self):+ first = app_config.load_settings(self.path)+ raw = self.path.read_bytes()+ mtime = self.path.stat().st_mtime_ns+ self.assertEqual(app_config.load_settings(self.path), first)+ app_config.load_config(self.path)+ self.assertEqual((self.path.read_bytes(), self.path.stat().st_mtime_ns), (raw, mtime))++ def test_a_failure_before_the_rename_leaves_no_settings_and_the_next_start_migrates(self):+ with mock.patch.object(app_config.os, "replace", side_effect=OSError("disk gone")):+ with self.assertRaises(OSError):+ app_config.load_settings(self.path)+ self.assertFalse(self.path.exists())+ self.assertEqual(sorted(entry.name for entry in self.folder.iterdir()), ["config.json"])+ self.assertEqual(len(app_config.load_settings(self.path)["peers"]), 1)++ def test_a_failure_while_loading_the_config_is_an_error_the_app_can_show(self):+ with mock.patch.object(app_config.os, "replace", side_effect=OSError("disk gone")):+ with self.assertRaises(ConfigError):+ app_config.load_config(self.path)++ def test_1_4_3s_own_loader_reads_the_kept_file_and_gets_the_pairing_back(self):+ app_config.load_config(self.path)+ app_config.save_config(self.path, replace(app_config.load_config(self.path), glow_style="glow"))+ spec = importlib.util.spec_from_file_location("app_config_1_4_3", FIXTURES / "app_config_1_4_3.py")+ old = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(old)+ config = old.load_config(self.legacy_path)+ self.assertEqual((config.auth_token, config.mac_host, config.paired_with, config.mac_return_edge),+ (PAIRED, "192.0.2.10", "MacBook Pro", "left"))+ self.assertEqual(config.glow_style, "beam")++ def test_a_typed_token_migrates_and_is_not_a_paired_one(self):+ self.write_legacy({**LEGACY, "auth_token": "a word typed into 1.4.x"})+ peer = app_config.load_settings(self.path)["peers"][0]+ self.assertEqual(peer["token"], "a word typed into 1.4.x")+ self.assertFalse(app_config.is_paired_token(peer["token"]))+ self.assertTrue(app_config.is_paired_token(PAIRED))++ def test_a_token_is_paired_only_when_it_decodes_to_32_bytes_and_encodes_back(self):+ self.assertFalse(app_config.is_paired_token(PAIRED + "="))+ self.assertFalse(app_config.is_paired_token(PAIRED[:-1]))+ self.assertFalse(app_config.is_paired_token(PAIRED[:-1] + "9"))+ self.assertFalse(app_config.is_paired_token(""))+ self.assertFalse(app_config.is_paired_token(None))++ def test_the_key_id_is_the_first_16_bytes_of_hkdf_of_the_token(self):+ prk = hmac.new(b"beamer-link-v6", PAIRED.encode(), hashlib.sha256).digest()+ expected = hmac.new(prk, b"beamer-key-id" + b"\x01", hashlib.sha256).digest()[:16]+ self.assertEqual(app_config.key_id(PAIRED), expected)+++class NeverPairedTests(Folder):+ legacy = {**LEGACY, "auth_token": ""}++ def test_an_empty_token_makes_no_peer_and_no_zone(self):+ settings = app_config.load_settings(self.path)+ self.assertEqual((settings["peers"], settings["zones"], settings["migrated_token_sha256"]), ([], [], ""))++ def test_the_app_sees_an_unpaired_config(self):+ with self.assertRaises(ConfigError):+ app_config.load_config(self.path)++ def test_an_unpaired_machine_can_still_save_its_own_settings(self):+ config = app_config.load_config(self.path, unpaired_ok=True)+ self.assertEqual(config.auth_token, "")+ app_config.save_config(self.path, replace(config, appearance="dark", pointer_speed=1.5, hide_addresses=True))+ settings = self.settings()+ self.assertEqual((settings["peers"], settings["zones"]), ([], []))+ self.assertEqual((settings["appearance"], settings["pointer_speed"], settings["hide_addresses"]), ("dark", 1.5, True))+ again = app_config.load_config(self.path, unpaired_ok=True)+ self.assertEqual((again.appearance, again.pointer_speed, again.hide_addresses), ("dark", 1.5, True))+ with self.assertRaises(ConfigError):+ app_config.load_config(self.path)++ def test_a_save_with_no_token_never_makes_a_peer_or_touches_one(self):+ paired = replace(app_config.default_config(), auth_token=PAIRED, mac_host="192.0.2.10", paired_with="Mac")+ app_config.save_config(self.path, paired)+ before = self.settings()["peers"]+ app_config.save_config(self.path, replace(app_config.default_config(), appearance="light"))+ after = self.settings()+ self.assertEqual(after["peers"], before)+ self.assertEqual(after["appearance"], "light")++ def test_pairing_then_keeps_the_machine_id_and_makes_the_peer(self):+ machine_id = app_config.load_settings(self.path)["machine_id"]+ config = replace(app_config.default_config(), auth_token=PAIRED, mac_host="192.0.2.10", paired_with="Mac")+ app_config.save_config(self.path, config)+ settings = self.settings()+ self.assertEqual(settings["machine_id"], machine_id)+ self.assertEqual((settings["peers"][0]["token"], settings["peers"][0]["host"], settings["peers"][0]["name"]),+ (PAIRED, "192.0.2.10", "Mac"))+ self.assertEqual(app_config.load_config(self.path).machine_id, machine_id)+++class NoOldFileTests(Folder):+ legacy = None++ def test_a_missing_config_gives_defaults_and_no_peer(self):+ settings = app_config.load_settings(self.path)+ self.assertEqual(settings["peers"], [])+ self.assertEqual(settings["schema"], 6)+ self.assertEqual(settings["port"], app_config.protocol.DEFAULT_PORT)+ self.assertTrue(self.path.exists())++ def test_an_unparseable_config_gives_defaults_and_no_crash(self):+ for text in ("{not json", "[1, 2]", "", "null"):+ with self.subTest(text=text):+ self.path.unlink(missing_ok=True)+ self.legacy_path.write_text(text, encoding="utf-8")+ self.assertEqual(app_config.load_settings(self.path)["peers"], [])++ def test_a_settings_file_that_does_not_parse_is_an_error_and_is_left_alone(self):+ self.path.write_text("{not json", encoding="utf-8")+ with self.assertRaises(ConfigError):+ app_config.load_settings(self.path)+ self.assertEqual(self.path.read_text(encoding="utf-8"), "{not json")++ def test_a_settings_file_for_another_schema_is_refused_and_left_alone(self):+ self.path.write_text(json.dumps({"schema": 7, "peers": []}), encoding="utf-8")+ with self.assertRaises(ConfigError):+ app_config.load_settings(self.path)+++class ReadingAnOddFileTests(Folder):+ def test_a_file_the_app_cannot_use_is_a_settings_error_with_the_path_and_is_left_alone(self):+ app_config.load_settings(self.path)+ good = self.settings()+ for bad in ({**good, "schema": 7}, {**good, "peers": [1]}, {**good, "zones": ["edge"]}, {**good, "peers": {}}):+ with self.subTest(bad=bad):+ self.put(bad)+ raw = self.path.read_bytes()+ with self.assertRaises(app_config.SettingsFileError):+ app_config.load_config(self.path)+ with self.assertRaises(app_config.SettingsFileError):+ app_config.save_config(self.path, replace(app_config.default_config(), auth_token=PAIRED))+ self.assertEqual(self.path.read_bytes(), raw)+ self.assertTrue(issubclass(app_config.SettingsFileError, ConfigError))++ def test_a_zone_with_no_parts_or_a_bad_corner_reads_as_the_defaults(self):+ settings = app_config.load_settings(self.path)+ settings["zones"] = [{"peer": "", "kind": "part"}, {"peer": "", "kind": "corner", "corner": "middle"}]+ self.put(settings)+ config = app_config.load_config(self.path)+ self.assertEqual((config.crossing_edge_parts, config.crossing_corner), (["middle"], "top_left"))++ def test_a_config_that_cannot_be_read_is_not_taken_for_a_missing_one(self):+ real = Path.read_text++ def refuse(path, *args, **kwargs):+ if path.name == "config.json":+ raise PermissionError("locked")+ return real(path, *args, **kwargs)++ with mock.patch.object(Path, "read_text", refuse):+ with self.assertRaises(ConfigError):+ app_config.load_config(self.path)+ self.assertFalse(self.path.exists())++ def test_a_settings_path_named_config_json_is_refused_not_overwritten(self):+ with self.assertRaises(ConfigError):+ app_config.load_settings(self.folder / "config.json")+ self.assertEqual(json.loads(self.legacy_path.read_text(encoding="utf-8")), LEGACY)++ def test_fields_this_version_does_not_know_survive_a_save(self):+ settings = app_config.load_settings(self.path)+ settings["later"] = {"a": 1}+ settings["peers"][0]["later"] = 2+ settings["zones"][0]["later"] = 3+ self.put(settings)+ app_config.save_config(self.path, replace(app_config.load_config(self.path), pointer_speed=2.0))+ again = self.settings()+ self.assertEqual((again["later"], again["peers"][0]["later"], again["zones"][0]["later"]), ({"a": 1}, 2, 3))++ def test_the_machine_name_is_saved(self):+ app_config.load_settings(self.path)+ app_config.save_config(self.path, replace(app_config.load_config(self.path), name="Rig"))+ self.assertEqual(app_config.load_config(self.path).name, "Rig")+++class OverlapTests(Folder):+ """Two zones in use never cover one stretch (WIRE.md section 8), as on the Mac; a corner inside an edge is fine."""++ def refused(self, change):+ settings = app_config.load_settings(self.path)+ change(settings)+ self.put(settings)+ raw = self.path.read_bytes()+ with self.assertRaises(app_config.SettingsFileError):+ app_config.load_config(self.path)+ with self.assertRaises(app_config.SettingsFileError):+ app_config.save_config(self.path, replace(app_config.default_config(), auth_token=PAIRED))+ self.assertEqual(self.path.read_bytes(), raw)++ def zone(self, settings, kind):+ return next(zone for zone in settings["zones"] if zone["kind"] == kind)++ def test_the_edge_and_its_thirds_in_use_together_are_refused(self):+ self.refused(lambda s: self.zone(s, "part").pop("off", None) or self.zone(s, "edge").pop("off", None))++ def test_two_part_zones_sharing_a_third_are_refused_and_disjoint_ones_are_not(self):+ def two_parts(s, second):+ self.zone(s, "edge")["off"] = True+ self.zone(s, "part").pop("off", None)+ self.zone(s, "part")["parts"] = ["start"]+ s["zones"].append({"peer": "", "kind": "part", "parts": second})+ self.refused(lambda s: two_parts(s, ["start", "end"]))+ self.path.unlink()+ settings = app_config.load_settings(self.path)+ two_parts(settings, ["end"])+ self.put(settings)+ app_config.load_config(self.path)++ def test_zones_turned_off_cover_nothing(self):+ settings = app_config.load_settings(self.path)+ settings["zones"].append({"peer": "", "kind": "edge", "off": True})+ self.put(settings)+ app_config.load_config(self.path)++ def test_two_peers_whose_edges_face_the_same_side_cannot_both_have_the_edge_zone_on(self):+ def second_peer(s):+ s["peers"][0]["id"] = PEER_ID+ s["zones"] = [{**zone, "peer": PEER_ID} for zone in s["zones"]]+ self.zone(s, "edge").pop("off", None)+ self.zone(s, "part")["off"] = True+ s["peers"].append({**s["peers"][0], "id": OTHER_ID, "token": OTHER, "from_1_4": False})+ s["zones"].append({"peer": OTHER_ID, "kind": "edge"})+ self.refused(second_peer)++ def test_a_corner_inside_the_edge_is_fine_and_two_of_one_corner_are_not(self):+ settings = app_config.load_settings(self.path)+ self.zone(settings, "edge").pop("off", None)+ self.zone(settings, "corner").pop("off", None)+ self.put(settings)+ app_config.load_config(self.path)+ self.refused(lambda s: s["zones"].append({**self.zone(s, "corner")}))+++class ZonesFromMethodsTests(Folder):+ def migrated(self, **fields):+ self.path.unlink(missing_ok=True)+ self.write_legacy({**LEGACY, **fields})+ return app_config.load_settings(self.path)++ def test_every_combination_of_methods_gives_its_zones_and_off_flags(self):+ for count in range(5):+ for methods in itertools.combinations(app_config.METHODS, count):+ with self.subTest(methods=methods):+ settings = self.migrated(crossing_methods=list(methods), crossing_corner="top_left",+ crossing_edge_parts=["middle", "end"], mac_return_edge="left")+ self.assertIs(settings["shortcut"], "shortcut" in methods)+ self.assertEqual([zone["kind"] for zone in settings["zones"]], ["edge", "part", "corner"])+ # The whole edge covers its thirds, so with both on the thirds stand down (WIRE.md section 8).+ in_use = [m for m in methods if not (m == "part" and "edge" in methods)]+ for zone in settings["zones"]:+ self.assertEqual(zone["peer"], "")+ self.assertEqual(zone.get("off", False), zone["kind"] not in in_use, zone)+ self.assertEqual(settings["zones"][1]["parts"], ["middle", "end"])+ self.assertEqual(settings["zones"][2]["corner"], "top_left")++ def test_a_corner_crosses_the_side_as_1_4_x_did_whichever_edges_it_touches(self):+ # 1.4.x built the PC's corner push with the return edge (sender.py: CornerPush(corner, self._edge)).+ for corner, side in (("top_left", "left"), ("top_left", "top"), ("bottom_right", "bottom"),+ ("top_right", "left"), ("bottom_left", "right"), ("top_left", "bottom"),+ ("bottom_right", "top")):+ with self.subTest(corner=corner, side=side):+ settings = self.migrated(crossing_corner=corner, mac_return_edge=side)+ self.assertEqual(settings["zones"][2]["edge"], side)++ def test_a_corner_with_no_side_yet_crosses_its_own_left_or_right_edge(self):+ for corner, edge in (("top_left", "left"), ("bottom_right", "right")):+ with self.subTest(corner=corner):+ self.assertEqual(self.migrated(crossing_corner=corner, mac_return_edge="")["zones"][2]["edge"], edge)++ def test_there_is_no_notch_zone_on_windows(self):+ self.assertNotIn("notch", [zone["kind"] for zone in self.migrated()["zones"]])+++class ConfigViewTests(Folder):+ def test_the_app_sees_the_same_config_as_before_but_for_what_the_spec_drops(self):+ config = app_config.load_config(self.path)+ expected = app_config.config_from_dict(dict(LEGACY))+ skipped = {"host", "mac_resistance_px", "machine_id", "name"}+ self.assertEqual({k: v for k, v in asdict(config).items() if k not in skipped},+ {k: v for k, v in asdict(expected).items() if k not in skipped})++ def test_the_config_carries_the_machine_id_and_name(self):+ config = app_config.load_config(self.path)+ self.assertEqual(config.machine_id, self.settings()["machine_id"])+ self.assertEqual(config.name, "")++ def test_this_pcs_address_is_read_live_not_saved(self):+ with mock.patch.object(app_config, "local_address_towards", return_value="192.0.2.20") as towards:+ self.assertEqual(app_config.load_config(self.path).host, "192.0.2.20")+ towards.assert_called_once_with("192.0.2.10")+ with mock.patch.object(app_config, "local_address_towards", side_effect=OSError):+ self.assertEqual(app_config.load_config(self.path).host, "")+ self.assertNotIn("host", self.settings())++ def test_a_config_loaded_with_no_zones_names_no_ways_but_the_shortcut(self):+ settings = app_config.load_settings(self.path)+ settings["zones"] = []+ self.put(settings)+ self.assertEqual(app_config.load_config(self.path).crossing_methods, ["shortcut"])+++class SavingTests(Folder):+ def setUp(self):+ super().setUp()+ self.config = app_config.load_config(self.path)+++ def test_trigger_changes_cannot_overwrite_an_existing_jump_key(self):++ settings = app_config.load_settings(self.path)++ settings["peers"][0]["jump_key"] = "alt+f13"++ app_config.write_settings(self.path, settings)++ before = self.path.read_bytes()++ for key in ("alt_r", "f13"):++ with self.subTest(key=key), self.assertRaises(app_config.ConfigError):++ app_config.save_config(self.path, replace(self.config, trigger_key=key))++ self.assertEqual(self.path.read_bytes(), before)+++ def test_a_save_round_trips_every_field_the_app_keeps(self):+ changed = replace(self.config, glow_style="glow", glow_colour="mono",+ crossing_methods=["part", "shortcut"], crossing_edge_parts=["middle"],+ crossing_corner="bottom_left", crossing_resistance_px=40, mac_return_edge="right",+ send_to_mac=False, allow_mac_to_drive=False, paired_with="Studio", mac_host="192.0.2.11",+ mac_hardware_address="11:22:33:44:55:66", modifier_style="semantic", hide_addresses=True)+ app_config.save_config(self.path, changed)+ again = app_config.load_config(self.path)+ # The ways across are each peer's, written by set_ways, never by a save of the flat view.+ ways = {"crossing_methods", "crossing_edge_parts", "crossing_corner", "mac_return_edge", "arrangement_set_at"}+ skipped = {"host", "mac_resistance_px"} | ways+ self.assertEqual({k: v for k, v in asdict(again).items() if k not in skipped},+ {k: v for k, v in asdict(changed).items() if k not in skipped})+ self.assertEqual({k: getattr(again, k) for k in ways}, {k: getattr(self.config, k) for k in ways})++ def test_a_save_writes_the_shortcut_and_no_zone_and_not_the_old_names(self):+ before = self.settings()["zones"]+ app_config.save_config(self.path, replace(self.config, crossing_methods=["edge"], crossing_corner="bottom_left"))+ settings = self.settings()+ for key in MOVED_OR_DROPPED:+ self.assertNotIn(key, settings)+ self.assertIs(settings["shortcut"], False)+ self.assertEqual(settings["zones"], before)++ def test_turning_a_way_off_keeps_its_zone_and_its_setting(self):+ app_config.set_ways(self.path, "", methods=["edge"], parts=["start", "end"], corner="top_right")+ app_config.set_ways(self.path, "", methods=["part"], parts=["start", "end"], corner="top_right")+ settings = self.settings()+ self.assertEqual([(zone["kind"], zone.get("off", False)) for zone in settings["zones"]],+ [("edge", True), ("part", False), ("corner", True)])+ again = app_config.load_config(self.path)+ self.assertEqual((again.crossing_methods, again.crossing_edge_parts), (["part", "shortcut"], ["start", "end"]))++ def test_the_machine_id_and_the_migrated_hash_never_change_in_a_save(self):+ before = self.settings()+ app_config.save_config(self.path, replace(self.config, pointer_speed=2.0))+ after = self.settings()+ self.assertEqual((after["machine_id"], after["migrated_token_sha256"], after["schema"]),+ (before["machine_id"], before["migrated_token_sha256"], 6))+ app_config.save_config(self.path, replace(self.config, machine_id=OWN_ID))+ self.assertEqual(self.settings()["machine_id"], before["machine_id"])++ def test_this_pcs_address_and_the_macs_resistance_are_not_saved(self):+ app_config.save_config(self.path, replace(self.config, host="192.0.2.99", mac_resistance_px=77))+ settings = self.settings()+ self.assertNotIn("host", settings)+ self.assertNotIn("mac_resistance_px", settings)++ def test_a_side_is_stamped_by_this_machine_only_when_set_here_never_by_a_save(self):+ settings = self.settings()+ settings["peers"][0]["side_by"] = OTHER_ID+ self.put(settings)+ app_config.save_config(self.path, replace(self.config, pointer_speed=2.0, mac_return_edge="top",+ arrangement_set_at=1790000005))+ self.assertEqual((self.settings()["peers"][0]["side"], self.settings()["peers"][0]["side_by"]), ("left", OTHER_ID))+ app_config.set_ways(self.path, "", side="top", methods=["edge"], parts=["middle"], corner="top_left")+ self.assertEqual((self.settings()["peers"][0]["side"], self.settings()["peers"][0]["side_by"]),+ ("top", settings["machine_id"]))++ def test_a_changed_port_moves_this_machines_and_the_one_peers_together(self):+ app_config.save_config(self.path, replace(self.config, port=25000))+ settings = self.settings()+ self.assertEqual((settings["port"], settings["peers"][0]["port"]), (25000, 25000))++ def test_a_peers_own_port_is_left_alone_when_the_port_did_not_change(self):+ settings = self.settings()+ settings["peers"][0]["port"] = 24900+ self.put(settings)+ app_config.save_config(self.path, replace(app_config.load_config(self.path), pointer_speed=2.0))+ self.assertEqual(self.settings()["peers"][0]["port"], 24900)++ def test_a_new_pairing_replaces_the_first_peer_and_points_its_zones_at_the_empty_id(self):+ settings = self.settings()+ app_config.learn_peer_id(settings, 0, PEER_ID)+ self.put(settings)+ app_config.save_config(self.path, replace(app_config.load_config(self.path), auth_token=OTHER, paired_with="Other",+ mac_host="192.0.2.30"))+ peer = self.settings()["peers"][0]+ self.assertEqual((peer["token"], peer["name"], peer["host"], peer["id"]), (OTHER, "Other", "192.0.2.30", ""))+ self.assertEqual((peer["linked"], peer["from_1_4"], peer["paired_at"], peer["paired_with"]), (False, True, 0, []))+ self.assertEqual({zone["peer"] for zone in self.settings()["zones"]}, {""})++ def test_other_peers_and_their_zones_survive_every_save(self):+ settings = self.settings()+ extra = {**MIGRATED_PEER, "id": OTHER_ID, "name": "Laptop", "platform": "windows", "token": THIRD,+ "from_1_4": False, "linked": True, "side": "right", "side_by": OTHER_ID}+ settings["peers"].append(extra)+ settings["zones"].append({"peer": OTHER_ID, "kind": "edge"})+ self.put(settings)+ config = app_config.load_config(self.path)+ app_config.save_config(self.path, replace(config, crossing_methods=[], glow_style="glow"))+ app_config.save_config(self.path, replace(config, auth_token=OTHER))+ after = self.settings()+ self.assertEqual(after["peers"][1], extra)+ self.assertIn({"peer": OTHER_ID, "kind": "edge"}, after["zones"])+ self.assertEqual(len(after["peers"]), 2)++ def test_a_save_is_atomic_a_new_file_renamed_over_the_old(self):+ before = self.path.read_bytes()+ with mock.patch.object(app_config.os, "replace", side_effect=OSError("disk gone")):+ with self.assertRaises(OSError):+ app_config.save_config(self.path, replace(self.config, pointer_speed=2.0))+ self.assertEqual(self.path.read_bytes(), before)+ self.assertEqual(sorted(entry.name for entry in self.folder.iterdir()), ["config.json", "settings.json"])+++class LearningTheIdTests(Folder):+ def setUp(self):+ super().setUp()+ self.settings_ = app_config.load_settings(self.path)++ def test_the_first_link_fills_the_id_in_and_rewrites_the_zones(self):+ app_config.learn_peer_id(self.settings_, 0, PEER_ID)+ self.assertEqual(self.settings_["peers"][0]["id"], PEER_ID)+ self.assertEqual({zone["peer"] for zone in self.settings_["zones"]}, {PEER_ID})++ def test_zones_of_other_peers_are_not_touched(self):+ self.settings_["peers"].append({**MIGRATED_PEER, "id": OTHER_ID, "from_1_4": False, "token": THIRD})+ self.settings_["zones"].append({"peer": OTHER_ID, "kind": "edge"})+ app_config.learn_peer_id(self.settings_, 0, PEER_ID)+ self.assertEqual([zone["peer"] for zone in self.settings_["zones"]], [PEER_ID] * 3 + [OTHER_ID])++ def test_it_refuses_this_machines_own_id_a_duplicate_a_bad_one_and_an_entry_that_has_one(self):+ self.settings_["peers"].append({**MIGRATED_PEER, "id": OTHER_ID, "from_1_4": False, "token": THIRD})+ for bad in (self.settings_["machine_id"], OTHER_ID, bytes(16).hex(), b64(bytes(16)), PEER_ID + "="):+ with self.subTest(bad=bad), self.assertRaises(ConfigError):+ app_config.learn_peer_id(self.settings_, 0, bad)+ app_config.learn_peer_id(self.settings_, 0, PEER_ID)+ with self.assertRaises(ConfigError):+ app_config.learn_peer_id(self.settings_, 0, b64(bytes([4]) * 16))+ self.assertEqual(self.settings_["peers"][0]["id"], PEER_ID)+++class PairingAgainUnder1_4Tests(Folder):+ def start(self):+ return app_config.load_settings(self.path)++ def test_a_changed_token_replaces_the_migrated_entry_and_updates_the_hash(self):+ settings = self.start()+ app_config.learn_peer_id(settings, 0, PEER_ID)+ settings["peers"][0].update(linked=True, paired_with=[OWN_ID], paired_at=5)+ self.put(settings)+ self.write_legacy({**LEGACY, "auth_token": OTHER, "paired_with": "Studio", "mac_host": "192.0.2.40"})+ again = self.start()+ peer = again["peers"][0]+ self.assertEqual((peer["token"], peer["name"], peer["host"]), (OTHER, "Studio", "192.0.2.40"))+ self.assertEqual((peer["id"], peer["linked"], peer["paired_with"], peer["from_1_4"]), ("", False, [], True))+ self.assertEqual({zone["peer"] for zone in again["zones"]}, {""})+ self.assertEqual(again["migrated_token_sha256"], hashlib.sha256(OTHER.encode()).hexdigest())+ self.assertEqual(again["machine_id"], settings["machine_id"])+ self.assertEqual(self.settings(), again)++ def test_an_unchanged_token_does_nothing(self):+ self.start()+ raw = self.path.read_bytes()+ self.write_legacy({**LEGACY, "pointer_speed": 3.0})+ self.start()+ self.assertEqual(self.path.read_bytes(), raw)++ def test_peers_added_under_1_5_0_are_untouched(self):+ settings = self.start()+ extra = {**MIGRATED_PEER, "id": OTHER_ID, "name": "Laptop", "token": THIRD, "from_1_4": False, "side_by": "", "side": "bottom"}+ settings["peers"].append(extra)+ settings["zones"].append({"peer": OTHER_ID, "kind": "edge"})+ self.put(settings)+ self.write_legacy({**LEGACY, "auth_token": OTHER})+ again = self.start()+ self.assertEqual([peer["token"] for peer in again["peers"]], [OTHER, THIRD])+ self.assertEqual(again["peers"][1], extra)+ self.assertIn({"peer": OTHER_ID, "kind": "edge"}, again["zones"])++ def test_a_peer_the_user_removed_stays_removed_while_the_old_file_is_unchanged(self):+ settings = self.start()+ settings["peers"], settings["zones"] = [], []+ self.put(settings)+ for _ in range(3):+ self.assertEqual(self.start()["peers"], [])++ def test_a_removed_peer_comes_back_when_the_user_pairs_again_under_1_4_x(self):+ settings = self.start()+ settings["peers"], settings["zones"] = [], []+ self.put(settings)+ self.write_legacy({**LEGACY, "auth_token": OTHER})+ again = self.start()+ self.assertEqual([peer["token"] for peer in again["peers"]], [OTHER])+ self.assertEqual([zone["kind"] for zone in again["zones"]], ["edge", "part", "corner"])+ self.assertEqual({zone["peer"] for zone in again["zones"]}, {""})++ def test_a_token_whose_key_id_is_another_entrys_is_not_migrated_but_the_hash_moves_on(self):+ settings = self.start()+ settings["peers"].append({**MIGRATED_PEER, "id": OTHER_ID, "token": OTHER, "from_1_4": False, "side_by": ""})+ self.put(settings)+ self.write_legacy({**LEGACY, "auth_token": OTHER})+ again = self.start()+ self.assertEqual([peer["token"] for peer in again["peers"]], [PAIRED, OTHER])+ self.assertEqual(again["migrated_token_sha256"], hashlib.sha256(OTHER.encode()).hexdigest())++ def test_a_typed_token_is_migrated_even_beside_another_typed_one(self):+ self.write_legacy({**LEGACY, "auth_token": "typed one"})+ self.start()+ self.write_legacy({**LEGACY, "auth_token": "typed two"})+ self.assertEqual(self.start()["peers"][0]["token"], "typed two")++ def test_an_emptied_token_migrates_nothing(self):+ self.start()+ raw = self.path.read_bytes()+ self.write_legacy({**LEGACY, "auth_token": ""})+ self.start()+ self.assertEqual(self.path.read_bytes(), raw)+++if __name__ == "__main__":+ unittest.main()diff --cc win_app/tests/test_style_for.pyindex 0ab87f7,b881757..badc93e--- a/win_app/tests/test_style_for.py+++ b/win_app/tests/test_style_for.py@@@ -9,10 -9,9 +9,11 @@@ import unittesfrom pathlib import Pathtry:-- from PySide6.QtWidgets import QApplication++ from PySide6.QtCore import QPoint++ from PySide6.QtWidgets import QApplication, QWidgetimport kvm_bridge_win+ from core.tests import responder_harness as harnessimport themeexcept ImportError: # PySide6 is only in the Windows venvkvm_bridge_win = None@@@ -24,18 -23,17 +25,26 @@@ class StyleForTest(unittest.TestCase)os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")self.app = QApplication.instance() or QApplication([])theme.init_fonts()- folder = Path(tempfile.mkdtemp())- config = Path(tempfile.mkdtemp()) / "config.json"- config.write_text(json.dumps({- "host": "192.168.1.20", "port": 24820, "auth_token": "synthetic", "paired_with": "MacBook Pro",++ self.app.setFont(theme.font(theme.TYPE["body"]))++ scratch = Path(__file__).resolve().parents[2] / "renders" / "test-working"++ scratch.mkdir(parents=True, exist_ok=True)++ self.folder = tempfile.TemporaryDirectory(dir=scratch)++ folder = Path(self.folder.name)+ (folder / "config.json").write_text(json.dumps({+ "host": "192.168.1.20", "port": harness.free_port(), "auth_token": "synthetic", "paired_with": "MacBook Pro","mac_host": "192.168.1.10", "mac_return_edge": "left", "shortcut_arrival": True,}))- self.window = kvm_bridge_win.WindowsApplication(config)+ self.window = kvm_bridge_win.WindowsApplication(folder / "settings.json")++ self.window.full_screen_timer.stop()++ self.window.refresh_timer.stop()self.window._select_page("design")self.window._refresh_window()def tearDown(self):+ self.window.server.stop()++ self.window.close()self.window.deleteLater()++ self.folder.cleanup()def shown(self):return {name for name, choice in (("crossing", self.window.glow_style_choice),@@@ -50,6 -48,6 +59,67 @@@self.assertEqual(self.window.design_mode_choice.value, choice)self.assertEqual(self.shown(), {choice})++ def test_style_hint_is_visible(self):++ self.assertEqual(self.window.style_preview_hint.text(), "Hover to preview")++++ def test_selected_marker_is_in_tile_grab(self):++ from PySide6.QtGui import QColor++++ choice = self.window.glow_style_choice++ choice.set_value("beam")++ self.app.processEvents()++ tile = choice.tile("beam")++ image = tile.grab().toImage()++ sample = image.pixelColor(image.width() // 2, 1)++ signal = QColor(theme.colour("signal"))++ distance = sum(abs(a - b) for a, b in zip(++ (sample.red(), sample.green(), sample.blue()), (signal.red(), signal.green(), signal.blue())))++ self.assertLess(distance, 60,++ "the selected-tile edge is not visible in the tile's own grab")++++ def test_hover_edge_is_neutral(self):++ from PySide6.QtCore import QPointF++ from PySide6.QtGui import QColor, QEnterEvent++++ choice = self.window.glow_style_choice++ tile = choice.tile("beam")++ self.app.sendEvent(tile, QEnterEvent(QPointF(1, 1), QPointF(1, 1), QPointF(1, 1)))++ self.app.processEvents()++ image = tile.grab().toImage()++ sample = image.pixelColor(image.width() // 2, 1)++ signal = QColor(theme.colour("signal"))++ distance = sum(abs(a - b) for a, b in zip(++ (sample.red(), sample.green(), sample.blue()), (signal.red(), signal.green(), signal.blue())))++ self.assertGreater(distance, 60, "the hovered-tile edge must not use the selection accent")++++ def test_style_families_stay_horizontal_and_wrap_at_spec_widths(self):++ choice = self.window.glow_style_choice++ self.window.show()++ for width in (320, 426, 512, 640, 720, 900, 1440, 1920):++ self.window.resize(width, 900)++ for _ in range(6):++ self.app.processEvents()++ column = self.window.stack.currentWidget().widget().findChild(QWidget, "page_column")++ per_row = 3 if column.width() >= 600 else 2 if column.width() >= 400 else 1++ group_views = list(choice.group_views.values())++ self.assertEqual(len({view.x() for view in group_views}), 1)++ y_positions = [view.y() for view in group_views]++ self.assertEqual(y_positions, sorted(y_positions))++ for title, group in choice.groups.items():++ rows = {}++ for tile in group._tiles.values():++ point = tile.mapTo(group.view, QPoint())++ rows.setdefault(point.y(), []).append(tile)++ with self.subTest(width=width, family=title):++ self.assertEqual(max(map(len, rows.values())), per_row)++ self.assertLessEqual(max(tile.width() for tile in group._tiles.values()) - min(tile.width() for tile in group._tiles.values()), 1)++ 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)++ for tile in group._tiles.values():++ preview = tile.layout().itemAt(0).widget()++ self.assertAlmostEqual(preview.width() / preview.height(), 2.0, delta=0.03)++if __name__ == "__main__":unittest.main()diff --cc win_app/tests/test_theme.pyindex 729dcd8,729dcd8..58ad72f--- a/win_app/tests/test_theme.py+++ b/win_app/tests/test_theme.py@@@ -43,5 -43,5 +43,26 @@@ class WantsDarkTests(unittest.TestCase)self.assertFalse(theme.wants_dark("sepia", False))[email protected](theme is None, "PySide6 is not installed")++class StylesheetApplicationTests(unittest.TestCase):++ def test_identical_application_stylesheet_is_not_repolished(self):++ class Application:++ def __init__(self):++ self.value = ""++ self.applied = []++++ def styleSheet(self):++ return self.value++++ def setStyleSheet(self, value):++ self.value = value++ self.applied.append(value)++++ app = Application()++ self.assertTrue(theme.apply_stylesheet(app))++ self.assertFalse(theme.apply_stylesheet(app))++ self.assertEqual(app.applied, [theme.stylesheet()])++++if __name__ == "__main__":unittest.main()diff --cc win_app/tests/test_ui_geometry.pyindex 0000000,0000000..ee778ebnew file mode 100644--- /dev/null+++ b/win_app/tests/test_ui_geometry.py@@@ -1,0 -1,0 +1,94 @@@++"""Regression bounds from the rc.2 offscreen audit, using production fonts and ink checks."""++++import os++import sys++import unittest++from pathlib import Path++from types import SimpleNamespace++++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++++from PySide6.QtCore import QCoreApplication, QEvent++from PySide6.QtWidgets import QApplication, QScrollArea, QVBoxLayout, QWidget++++import diagram++import machines_win++import theme++import widgets++from scripts.ui_audit.qt_audit import measure, text_measure++++++class AuditGeometryTests(unittest.TestCase):++ @classmethod++ def setUpClass(cls):++ cls.app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ cls.app.setFont(theme.font(theme.TYPE["body"]))++ cls.app.setStyleSheet(theme.stylesheet())++++ def settle(self):++ for _ in range(6):++ QCoreApplication.sendPostedEvents(None, QEvent.Type.LayoutRequest)++ self.app.processEvents()++++ def page(self, item, width=800, height=160):++ scroll = QScrollArea()++ scroll.setWidgetResizable(True)++ root = QWidget()++ layout = QVBoxLayout(root)++ layout.setContentsMargins(0, 0, 0, 0)++ layout.addWidget(item)++ layout.addStretch(1)++ scroll.setWidget(root)++ scroll.resize(width, height)++ scroll.show()++ self.addCleanup(scroll.deleteLater)++ self.settle()++ return scroll++++ def test_wrapped_note_allocates_height_for_its_actual_width(self):++ note = widgets.label(++ "This screen decides, including when another machine drives it. On, a full-screen app here "++ "holds pointer crossings; shortcuts and jump keys still work. Off, another machine's pointer "++ "can go home or onward through the configured ways.", "note", wrap=True)++ self.page(note)++ self.assertIsNone(text_measure(note), f"actual note size {note.size().toTuple()}: {text_measure(note)}")++++ def test_choice_children_fit_their_allocated_row(self):++ choice = widgets.Choice((("auto", "Automatic"), ("same", "Same keys"), ("swap", "Swap keys")), 3, "auto")++ module = widgets.Module("Modifier keys")++ module.body.addWidget(choice.view)++ self.page(module, height=85)++ self.assertFalse(measure(module), measure(module))++++ def peer(self):++ row = machines_win.PeerRow("synthetic", *([lambda *_: None] * 4))++ row.refresh({"port": 24820}, "Studio MacBook Pro with an exceptionally long mach",++ SimpleNamespace(tone="off", word="Waiting", detail="Waiting for this machine."), "Mac")++ return row++++ def test_direction_switches_have_separate_uncropped_tracks(self):++ row = self.peer()++ row.directions.setChecked(True)++ self.page(row, width=700, height=160)++ self.assertFalse(measure(row.direction_group), measure(row.direction_group))++++ def test_confirmation_ink_and_controls_fit(self):++ row = self.peer()++ row._ask(True)++ self.page(row, width=700, height=160)++ self.assertFalse(measure(row.confirm), measure(row.confirm))++++ def test_diagram_reports_required_height_before_parent_allocation(self):++ drawing = diagram.ArrangementDiagram()++ drawing.set_machines([dict(key="desk", label="Desk", side="right", methods=["edge"],++ parts=["middle"], corner="top_right", chosen=True)], "F13", "double_tap", True)++ self.assertTrue(drawing.hasHeightForWidth())++ for width in (254, 361, 800):++ drawing.resize(width, 100)++ self.assertGreaterEqual(drawing.heightForWidth(width), drawing._height())++++++if __name__ == "__main__":++ unittest.main()diff --cc win_app/tests/test_wide_layout.pyindex b0d3ee2,0000000..b6459c6mode 100644,000000..100644--- a/win_app/tests/test_wide_layout.py+++ b/win_app/tests/test_wide_layout.py@@@ -1,42 -1,0 +1,191 @@@+import os+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+- from PySide6.QtWidgets import QApplication++from PySide6.QtCore import QPoint++from PySide6.QtWidgets import QApplication, QWidget++import diagram+import theme+import widgets+++class WideLayoutTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.app = QApplication.instance() or QApplication([])+ theme.init_fonts()++ cls.app.setFont(theme.font(theme.TYPE["body"]))+- def test_wrapped_paragraphs_keep_a_readable_measure(self):++ def test_wrapped_paragraphs_use_the_layout_width_for_their_measure(self):+ paragraph = widgets.label("A long settings explanation.", "note", wrap=True)+- self.assertEqual(paragraph.maximumWidth(), 560)++ self.assertGreater(paragraph.maximumWidth(), 560)++ def test_the_arrangement_diagram_uses_more_width_on_a_wide_page(self):+ drawing = diagram.ArrangementDiagram()+ drawing.set_machines(+ [{"key": "desk", "label": "Desk", "side": "right", "methods": ["edge"],+ "parts": [], "chosen": True}],+ "Right Ctrl", "hold", True,+ )++ narrow = drawing._drawing(640.0)[0][2]+ wide = drawing._drawing(1440.0)[0][2]+ self.assertGreater(wide, narrow)+++++class WindowsPageWidthTest(unittest.TestCase):++ """One centred 880-DIP section column and horizontal style-family rows."""++++ WIDTHS = (320, 426, 512, 640, 720, 900, 1100, 1440, 1920)++++ def setUp(self):++ import tempfile++ from pathlib import Path++++ import app_config++ import kvm_bridge_win++ import pages_win++ from core import protocol++ from core.tests import responder_harness as harness++++ self.pages = pages_win++ self.app = QApplication.instance() or QApplication([])++ theme.init_fonts()++ self.app.setFont(theme.font(theme.TYPE["body"]))++ scratch = Path(__file__).resolve().parents[2] / "renders" / "test-working"++ scratch.mkdir(parents=True, exist_ok=True)++ directory = tempfile.TemporaryDirectory(dir=scratch)++ self.addCleanup(directory.cleanup)++ path = Path(directory.name) / "settings.json"++ settings = app_config.migrate(None, machine_id=protocol.id_text(harness.HERE))++ settings["peers"] = [harness.entry(harness.B, "Mac", side="right")]++ settings["port"] = harness.free_port()++ app_config.write_settings(path, settings)++ self.window = kvm_bridge_win.WindowsApplication(path)++ self.window.full_screen_timer.stop()++ self.window.refresh_timer.stop()++ self.window._send_to = lambda peer, message: True++ self.addCleanup(self.window.deleteLater)++ self.addCleanup(self.window.server.stop)++++ def column_width(self, key):++ self.window._select_page(key)++ # A scrollbar that comes or goes narrows the viewport, which refits the column: let that settle.++ for _ in range(5):++ self.app.processEvents()++ scroll = self.window.stack.currentWidget()++ column = scroll.widget().findChild(QWidget, "page_column")++ return column.width()++++ def test_every_page_uses_the_same_centred_column_and_section_edges(self):++ for width in self.WIDTHS:++ self.window.resize(width, 900)++ self.window.show()++ for _ in range(6):++ self.app.processEvents()++ self.assertEqual(self.window.width(), width)++ for key, _, _ in self.pages.PAGES:++ with self.subTest(width=width, page=key):++ self.column_width(key)++ scroll = self.window.stack.currentWidget()++ page = scroll.widget()++ column = page.findChild(QWidget, "page_column")++ expected = min(880, page.width() - 48)++ self.assertAlmostEqual(column.width(), expected, delta=1)++ self.assertAlmostEqual(column.x(), (page.width() - expected) / 2, delta=1)++ sections = [widget for widget in page.findChildren(QWidget)++ if widget.property("vernier") == "module" and widget.isVisible()]++ self.assertTrue(sections)++ for section in sections:++ self.assertAlmostEqual(section.mapTo(page, QPoint()).x(), column.x(), delta=1)++ self.assertAlmostEqual(section.width(), column.width(), delta=1)++ self.assertLessEqual(page.width(), scroll.viewport().width() + 1)++++ def test_the_crossing_diagram_sits_beside_its_ways_once_the_column_holds_both(self):++ # Both blocks at their minimums, with the gap, must fit before they sit beside each other.++ for (width, height) in ((1366, 900), (1920, 1000), (2560, 1440), (1440, 3440)):++ with self.subTest(window=(width, height)):++ self.window.resize(width, height)++ self.window.show()++ self.column_width("crossing")++ pair = self.window.ways_pair++ self.assertGreaterEqual(pair.width(), pair.needed())++ self.assertTrue(pair.beside())++ self.assertEqual(pair.first.y(), pair.second.y())++ self.assertLess(pair.first.x(), pair.second.x())++ self.assertIs(pair.first.parentWidget(), pair)++ self.assertIs(pair.second.parentWidget(), pair)++ self.assertTrue(pair.first.isVisible() and pair.second.isVisible())++++ def test_the_crossing_pair_stacks_below_the_width_both_need(self):++ self.window.resize(320, 900)++ self.window.show()++ self.column_width("crossing")++ pair = self.window.ways_pair++ self.assertLess(pair.width(), pair.needed())++ self.assertFalse(pair.beside())++ self.assertLess(pair.first.y(), pair.second.y())++++ def test_style_families_form_horizontal_equal_tile_rows_at_each_breakpoint(self):++ for width in self.WIDTHS:++ with self.subTest(width=width):++ self.window.resize(width, 900)++ self.window.show()++ self.column_width("design")++ for _ in range(6):++ self.app.processEvents()++ column = self.window.stack.currentWidget().widget().findChild(QWidget, "page_column")++ per_row = 3 if column.width() >= 600 else 2 if column.width() >= 400 else 1++ family_views = list(self.window.glow_style_choice.group_views.values())++ family_x = [view.x() for view in family_views]++ family_y = [view.y() for view in family_views]++ self.assertEqual(len(set(family_x)), 1, f"families must share a leading edge: {family_x}")++ self.assertEqual(family_y, sorted(family_y), "families must follow catalogue order vertically")++ for title, choices in self.window.glow_style_choice.groups.items():++ positions = {}++ for tile in choices._tiles.values():++ point = tile.mapTo(choices.view, QPoint())++ positions.setdefault(point.y(), []).append(tile)++ self.assertEqual(max(map(len, positions.values())), per_row,++ f"{title} should have {per_row} tiles per row")++ for row in positions.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 choices._tiles.values()) - min(tile.width() for tile in choices._tiles.values()), 1)++++ def test_unfixed_choice_tiles_keep_sharing_their_row(self):++ choices = widgets.ChoiceTiles(++ (("one", "One", "First", QWidget()), ("two", "Two", "Second", QWidget())), "one"++ )++ choices.view.resize(400, 120)++ choices.view.show()++ self.app.processEvents()++ widths = [tile.width() for tile in choices._tiles.values()]++ self.assertGreater(min(widths), 96)++ self.assertAlmostEqual(widths[0], widths[1], delta=1)++ self.assertEqual(sum(widths) + 10, choices.view.width())++ choices.view.deleteLater()++++ def test_every_page_column_fills_a_window_too_narrow_for_the_minimum(self):++ for width in (320, 426, 512):++ self.window.resize(width, 700)++ self.window.show()++ for key, _, _ in self.pages.PAGES:++ with self.subTest(width=width, page=key):++ self.column_width(key)++ scroll = self.window.stack.currentWidget()++ page = scroll.widget()++ column = page.findChild(QWidget, "page_column")++ self.assertAlmostEqual(column.width(), page.width() - 48, delta=1)+++++if __name__ == "__main__":+ unittest.main()diff --cc win_app/theme.pyindex 2c161e2,49915e6..c19848a--- a/win_app/theme.py+++ b/win_app/theme.py@@@ -24,21 -24,21 +24,16 @@@ RADIUS = tokens.RADIU_sans = "Segoe UI"_mono = "Consolas"--# Derived here because tokens.py has no value for them: the heading size inside a module (the--# Windows status word, 22px, between body and status_word_narrow), and the countdown numeral.++# The heading size inside a module (the Windows status word, 22px, between body and status_word_narrow).HEADING = 22.0--COUNT = 30.0--# The sidebar's fixed width. Windows does not reflow it with the window the way the Mac's--# does; a fixed width leaves 640 - SIDEBAR_WIDTH - 1 of content, which every page's grid is--# laid out to fit.--# 176, not 168, so the foot's kalkmancode.co.uk/beamer fits as Windows draws it.SIDEBAR_WIDTH = 176# The pairing code sits beside the countdown and the Pair button, in a page narrowed by the# sidebar -- tokens.TYPE["code"] (92px, shared with the Mac's own pairing card) does not fit# that row at 640 wide, so this page uses its own smaller size.PAIRING_CODE = 48.0++PAIRING_ENTRY = 20.0# One tone per receiver state, shared by the LED, the tray dot and the heading.STATE_TONE = {@@@ -189,17 -188,17 +184,23 @@@ def repolish(widget) -> Nonedef stylesheet() -> str:values = dict(P)++ ink = tuple(int(P["ink"][index:index + 2], 16) for index in (1, 3, 5))values.update(++ tile_hover_border=f"rgba({ink[0]}, {ink[1]}, {ink[2]}, 46)",++ tile_hover_background=P["well"] if _dark else P["panel"],sans=_sans,mono=_mono,body=round(TYPE["body"]),note=round(TYPE["note"]),small=round(TYPE["small"]),field_mono=round(TYPE["field_mono"]),++ pairing_entry=round(PAIRING_ENTRY),button=round(TYPE["button"]),r_field=round(RADIUS["field"]),r_button=round(RADIUS["button"]),r_keycap=round(RADIUS["keycap"]),++ selected_bg=tokens.PALETTE["ink"],++ selected_ink=tokens.PALETTE["ground"],)return _TEMPLATE.format(**values)@@@ -211,6 -210,6 +212,7 @@@ QWidget {}}QWidget[vernier="rack"] {{ background: {rule}; }}QFrame[vernier="module"] {{ background: {panel}; border: 0; }}++QFrame[vernier="banner"] {{ background: {well}; border: 1px solid {rule}; border-radius: {r_button}px; }}QFrame[vernier="commit"] {{ background: {ground}; border: 0; border-top: 1px solid {rule}; }}QWidget[vernier="plain"] {{ background: transparent; }}QWidget[vernier="rule"] {{ background: {rule}; }}@@@ -228,7 -227,7 +230,7 @@@ QLabel[vernier="note-live"] {{ color: {QLabel[vernier="note-quiet"] {{ color: {ink_3}; font-size: {note}px; }}QLabel[vernier="key"] {{ color: {ink_2}; font-size: {note}px; }}QLabel[vernier="mono"] {{ color: {ink_2}; font-family: "{mono}"; font-size: {note}px; }}--QLabel[vernier="readout"] {{ color: {ink}; font-family: "{mono}"; font-size: {note}px; font-weight: 700; }}++QLabel[vernier="readout"] {{ color: {ink}; font-family: "{sans}"; font-size: {note}px; font-weight: 700; }}QLabel[vernier="code"] {{ color: {ink}; }}QLabel[vernier="code-idle"] {{ color: {ink_3}; }}QLabel[vernier="count"] {{ color: {ink}; }}@@@ -245,19 -244,19 +247,19 @@@ QPushButton {padding: 7px 12px;}}QPushButton:hover {{ border-color: {ink_3}; }}--QPushButton:focus {{ border: 2px solid {signal}; padding: 6px 11px; }}++QPushButton[keyboard_ring="true"]:focus {{ border: 2px solid {signal}; padding: 6px 11px; }}QPushButton:disabled {{ color: {ink_3}; border-color: {rule}; background: {panel}; }}QPushButton[vernier="primary"] {{ background: {ink}; border-color: {ink}; color: {ground}; }}QPushButton[vernier="primary"]:hover {{ background: {ink_2}; border-color: {ink_2}; }}--QPushButton[vernier="primary"]:focus {{ border: 2px solid {signal}; }}++QPushButton[vernier="primary"][keyboard_ring="true"]:focus {{ border: 2px solid {signal}; }}QPushButton[vernier="primary"]:disabled {{ background: {well}; border-color: {rule}; color: {ink_3}; }}QPushButton[vernier="live"] {{ background: {signal}; border-color: {signal}; color: {ground}; }}--QPushButton[vernier="live"]:focus {{ border: 2px solid {ink}; }}++QPushButton[vernier="live"][keyboard_ring="true"]:focus {{ border: 2px solid {ink}; }}QPushButton[vernier="small"] {{ font-size: {small}px; padding: 4px 10px; }}--QPushButton[vernier="small"]:focus {{ padding: 3px 9px; }}++QPushButton[vernier="small"][keyboard_ring="true"]:focus {{ padding: 3px 9px; }}QPushButton[vernier="choice"] {{ color: {ink_2}; font-size: {small}px; font-weight: 400; padding: 4px 8px; }}--QPushButton[vernier="choice"]:checked {{ background: {ink}; border-color: {ink}; color: {ground}; font-weight: 600; }}--QPushButton[vernier="choice"]:focus {{ padding: 3px 7px; }}++QPushButton[vernier="choice"]:checked {{ background: {selected_bg}; border-color: {selected_bg}; color: {selected_ink}; font-weight: 600; }}++QPushButton[vernier="choice"][keyboard_ring="true"]:focus {{ padding: 3px 7px; }}QPushButton[vernier="choice"]:disabled {{ color: {ink_3}; border-color: {rule}; background: {panel}; }}QPushButton[vernier="choice"]:checked:disabled {{ background: {well}; border-color: {rule}; color: {ink_2}; }}@@@ -268,12 -267,12 +270,12 @@@ QPushButton[vernier="page"] {color: {ink_2};font-size: {body}px;font-weight: 500;-- padding: 8px 12px;++ padding: 8px 12px 8px 38px;text-align: left;}}QPushButton[vernier="page"]:hover {{ background: {well}; color: {ink}; }}QPushButton[vernier="page"]:checked {{ background: {well}; color: {ink}; font-weight: 700; }}--QPushButton[vernier="page"]:focus {{ border: 1px solid {signal}; padding: 7px 11px; }}++QPushButton[vernier="page"][keyboard_ring="true"]:focus {{ border: 0; padding: 8px 12px 8px 38px; }}QPushButton[vernier="foot"] {{background: transparent;@@@ -285,7 -284,7 +287,8 @@@text-align: left;}}QPushButton[vernier="foot"]:hover {{ color: {ink_2}; }}--QPushButton[vernier="foot"]:focus {{ border: 1px solid {signal}; padding: 11px 3px 13px 15px; }}++QPushButton[vernier="foot"][rail="true"] {{ padding: 0; text-align: center; }}++QPushButton[vernier="foot"][keyboard_ring="true"]:focus {{ border: 1px solid {signal}; padding: 11px 3px 13px 15px; }}QPushButton[vernier="keycap"] {{background: {ground};border: 1px solid {edge};@@@ -294,7 -293,7 +297,9 @@@padding: 0;}}QPushButton[vernier="keycap"]:hover {{ border-color: {ink_3}; }}--QPushButton[vernier="keycap"]:focus {{ border-color: {signal}; }}++/* Gating :focus on keyboard_ring raised the generic ring's specificity above these base rules,++ which used to win the tie by coming later; the keycap and tile restate their own focus look. */++QPushButton[vernier="keycap"][keyboard_ring="true"]:focus {{ border: 1px solid {signal}; border-bottom: 3px solid {signal}; padding: 0; }}QPushButton[vernier="keycap-live"] {{background: {ground};border: 1px solid {signal};@@@ -306,11 -305,11 +311,11 @@@ QLabel[vernier="keycap"] {{ color: {inkQLabel[vernier="keycap-live"] {{ color: {signal}; }}QLabel[vernier="small"] {{ color: {ink_3}; font-size: {small}px; }}QLabel[vernier="tile-name"] {{ color: {ink}; font-size: {body}px; font-weight: 600; }}--QFrame[vernier="tile"] {{ background: {ground}; border: 1px solid {rule}; border-radius: {r_button}px; }}--QFrame[vernier="tile"]:hover {{ border-color: {edge}; }}--QFrame[vernier="tile"]:focus {{ border: 2px solid {signal}; }}--QFrame[vernier="tile-on"] {{ background: {ground}; border: 1px solid {edge}; border-radius: {r_button}px; }}--QFrame[vernier="tile-on"]:focus {{ border: 2px solid {signal}; }}++QPushButton[vernier="tile"], QPushButton[vernier="tile-on"] {{ background: {ground}; border: 1px solid {rule}; border-radius: {r_button}px; padding: 0; }}++QPushButton[vernier="tile"]:hover {{ background: {tile_hover_background}; border: 1px solid {tile_hover_border}; }}++QPushButton[vernier="tile"][keyboard_ring="true"]:focus, QPushButton[vernier="tile-on"][keyboard_ring="true"]:focus {{ border: 1px solid {rule}; padding: 0; }}++QPushButton[vernier="tile"][keyboard_ring="true"]:focus:hover {{ border: 1px solid {tile_hover_border}; }}++QLabel[vernier="preview-hint"] {{ color: {ink_2}; font-size: {note}px; }}QFrame[vernier="entry"] {{ background: {well}; border: 1px solid {rule}; border-radius: {r_field}px; }}QPushButton[vernier="remove"] {{background: transparent;@@@ -321,7 -320,7 +326,7 @@@padding: 2px 6px;}}QPushButton[vernier="remove"]:hover {{ color: {fault}; }}--QPushButton[vernier="remove"]:focus {{ border: 1px solid {signal}; padding: 1px 5px; }}++QPushButton[vernier="remove"][keyboard_ring="true"]:focus {{ border: 1px solid {signal}; padding: 1px 5px; }}QCheckBox {{ background: transparent; color: {ink}; font-size: {body}px; spacing: 8px; }}QCheckBox::indicator {{ width: 16px; height: 16px; border: 1px solid {edge}; border-radius: 3px; background: {well}; }}QCheckBox::indicator:hover {{ border-color: {ink_3}; }}@@@ -348,9 -347,9 +353,11 @@@ QLineEdit {lineedit-password-character: 8226;}}QLineEdit:focus {{ border: 2px solid {signal}; padding: 5px 7px; }}++QLineEdit[vernier="pair-code"] {{ background: transparent; border: 0; border-radius: 0; color: transparent; font-family: "{mono}"; font-size: {pairing_entry}px; padding: 0; selection-background-color: {signal_dim}; }}++QLineEdit[vernier="pair-code"]:focus {{ border: 0; padding: 0; }}QScrollArea {{ background: {ground}; border: 0; }}--QScrollBar:vertical {{ background: {ground}; width: 10px; margin: 0; }}++QScrollBar:vertical {{ background: {ground}; width: 16px; margin: 0; }}QScrollBar::handle:vertical {{ background: {edge}; border-radius: 3px; min-height: 32px; margin: 2px; }}QScrollBar::handle:vertical:hover {{ background: {ink_3}; }}QScrollBar:horizontal {{ height: 0; }}@@@ -371,6 -370,6 +378,14 @@@ QMenu::separator {{ height: 1px; backgr"""++def apply_stylesheet(app) -> bool:++ current = stylesheet()++ if app.styleSheet() == current:++ return False++ app.setStyleSheet(current)++ return True++++def apply_titlebar(hwnd: int) -> None:"""Paints the native title bar at hwnd in Vernier's current ground, light or dark, so it stopsfollowing the user's accent colour."""diff --cc win_app/tokens.pyindex e10a308,dbb5b81..a1ecd5b--- a/win_app/tokens.py+++ b/win_app/tokens.py@@@ -96,6 -96,6 +96,7 @@@ PALETTES ="ocean": ("#288cff", "#6446ff", "#1eb9aa", "#3c6eff"),"sunset": ("#ff7828", "#ff3264", "#ffb43c", "#f03278"),"mono": ("#ebebeb", "#969696", "#ebebeb"),++ "aurora": ("#53dc91", "#9572eb", "#43c5b4"),}# Letter spacing as a fraction of the font size, for the uppercase tracked labels.@@@ -115,8 -115,6 +116,18 @@@ RADIUS =MODULE_PADDING = (14.0, 16.0)RACK_GAP = 1.0MIN_WINDOW = {"mac": (640, 540), "windows": (640, 600)}+READING_WIDTH = 560.0+PAGE_CONTENT_WIDTH = 960.0++# The page column is this share of the free width (window minus sidebar), clamped between the++# minimum and the maximum, centred, and never wider than the free width itself.++PAGE_CONTENT_MIN = 960.0++PAGE_CONTENT_MAX = 1600.0++PAGE_CONTENT_SHARE = 0.75++SIDE_BY_SIDE_GAP = 24.0++CROSSING_ARRANGEMENT_MIN_WIDTH = 254.0++CROSSING_WAYS_MIN_WIDTH = 354.0++DESIGN_TILE_SETS_MIN_WIDTH = 258.0++DESIGN_STYLE_CONTROLS_MIN_WIDTH = 240.0# Mass-spring parameters (mass 1) for everything that moves. The notch island integrates two of# these, width and depth; a trackpad tick adds `tick_velocity` points per second to the width.diff --cc win_app/widgets.pyindex 9c9f3b5,b5fd4dc..b1491d3--- a/win_app/widgets.py+++ b/win_app/widgets.py@@@ -3,20 -3,20 +3,30 @@@ LED, the 60-segment countdown and the sfrom __future__ import annotations--from PySide6.QtCore import QEvent, QRect, QRectF, QSize, Qt--from PySide6.QtGui import QColor, QFontMetrics, QLinearGradient, QPainter, QPen++from PySide6.QtCore import QEvent, QObject, QRect, QRectF, QSignalBlocker, QSize, Qt++from PySide6.QtGui import QAction, QColor, QFont, QFontMetrics, QLinearGradient, QPainter, QPalette, QPenfrom PySide6.QtWidgets import (++ QAbstractButton,QApplication,++ QBoxLayout,QButtonGroup,QCheckBox,QFrame,QGraphicsOpacityEffect,QGridLayout,++ QGroupBox,QHBoxLayout,QLabel,++ QLayout,QPushButton,QSizePolicy,QSlider,++ QSystemTrayIcon,++ QToolTip,++ QStyle,++ QStyleOptionButton,++ QStyleOptionFrame,++ QStylePainter,QVBoxLayout,QWidget,)@@@ -24,28 -24,25 +34,262 @@@import motionimport themeimport tokens++from core.locale import americanise+from core import ways as core_waysLEFT_CTRL_VK = 0xA2# The smallest a Segmented cell or small button is drawn, so each is a fair target.--MIN_TARGET = 28++MIN_TARGET = 30++++++def set_dimmed(view: QWidget, dimmed: bool) -> None:++ if dimmed:++ current = view.graphicsEffect()++ if isinstance(current, QGraphicsOpacityEffect) and current.opacity() == 0.45:++ return++ effect = QGraphicsOpacityEffect(view)++ effect.setOpacity(0.45)++ view.setGraphicsEffect(effect)++ elif isinstance(view.graphicsEffect(), QGraphicsOpacityEffect):++ view.setGraphicsEffect(None)++++_NAVIGATION_KEYS = {Qt.Key.Key_Tab, Qt.Key.Key_Backtab, Qt.Key.Key_Left, Qt.Key.Key_Right,++ Qt.Key.Key_Up, Qt.Key.Key_Down}++_SHORTCUT_MODIFIERS = (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier++ | Qt.KeyboardModifier.MetaModifier)++++++def is_navigation_key(key, modifiers) -> bool:++ """Tab, Shift-Tab and the arrows turn focus rings on (spec section 6), as on the Mac. Any++ other key, a shortcut included, leaves them as the last click left them: off."""++ return key in _NAVIGATION_KEYS and not modifiers & _SHORTCUT_MODIFIERS++++++class _KeyboardNavigation(QObject):++ """The one app-wide answer to "is the user moving focus by keyboard": on for a navigation++ key, off for any mouse press. The stylesheet's :focus rings match only a widget whose++ `keyboard_ring` property is true, which is kept in step on the focused widget alone, so a++ change repolishes one widget rather than the window."""++++ def __init__(self, app) -> None:++ super().__init__(app)++ self.active = False++ app.installEventFilter(self)++++ def eventFilter(self, watched, event) -> bool:++ kind = event.type()++ if kind == QEvent.Type.KeyPress and is_navigation_key(event.key(), event.modifiers()):++ self.set(True)++ elif kind in (QEvent.Type.MouseButtonPress, QEvent.Type.MouseButtonDblClick):++ self.set(False)++ elif kind == QEvent.Type.FocusIn and isinstance(watched, QWidget):++ self._mark(watched)++ return False++++ def set(self, active: bool) -> None:++ if active == self.active:++ return++ self.active = active++ focused = QApplication.focusWidget()++ if focused is not None:++ self._mark(focused)++++ def _mark(self, widget) -> None:++ # Qt's own focus rectangle keys off this window attribute, which Tab sets and only a++ # click that moves focus clears; a click on a label left it set, so it follows the state.++ widget.window().setAttribute(Qt.WidgetAttribute.WA_KeyboardFocusChange, self.active)++ if bool(widget.property("keyboard_ring")) != self.active:++ widget.setProperty("keyboard_ring", self.active)++ widget.style().unpolish(widget)++ widget.style().polish(widget)++ widget.update()++ for child in widget.findChildren(QWidget):++ child.update()++++++def keyboard_navigation() -> _KeyboardNavigation:++ app = QApplication.instance()++ navigation = app.findChild(_KeyboardNavigation)++ return navigation if navigation is not None else _KeyboardNavigation(app)++++++def focus_ring_visible(widget) -> bool:++ return widget.hasFocus() and keyboard_navigation().activedef label(text: str, role: str, wrap: bool = False) -> QLabel:-- item = QLabel(text)++ item = QLabel(americanise(text))item.setProperty("vernier", role)item.setWordWrap(wrap)- if wrap and role in {"note", "note-quiet", "note-amber"}:- item.setMaximumWidth(tokens.READING_WIDTH)return item++def install_text_localisation() -> None:++ """Route Qt's visible text setters through the shared spelling map."""++ from PySide6.QtWidgets import QMessageBox, QMenu++++ def wrap(cls, method, positions=(0,)):++ original = getattr(cls, method)++ if getattr(original, "_beamer_localised", False):++ return++++ def setter(self, *args, **kwargs):++ args = list(args)++ for position in positions:++ if position < len(args) and isinstance(args[position], str):++ args[position] = americanise(args[position])++ return original(self, *args, **kwargs)++++ setter._beamer_localised = True++ setattr(cls, method, setter)++++ def wrap_static(cls, method, positions):++ original = getattr(cls, method)++ if getattr(original, "_beamer_localised", False):++ return++++ def setter(*args, **kwargs):++ args = list(args)++ for position in positions:++ if position < len(args) and isinstance(args[position], str):++ args[position] = americanise(args[position])++ return original(*args, **kwargs)++++ setter._beamer_localised = True++ setattr(cls, method, staticmethod(setter))++++ for cls, method in (++ (QLabel, "setText"), (QAbstractButton, "setText"), (QGroupBox, "setTitle"),++ (QMenu, "setTitle"), (QMenu, "addAction"), (QWidget, "setToolTip"),++ (QAction, "setText"), (QMessageBox, "setText"), (QMessageBox, "setInformativeText"),++ (QMessageBox, "setDetailedText"),++ (QSystemTrayIcon, "setToolTip"), (QSystemTrayIcon, "showMessage"),++ ):++ wrap(cls, method, (0, 1) if method == "showMessage" else (0,))++ for method in ("critical", "information", "question", "warning"):++ wrap_static(QMessageBox, method, (1, 2))++ wrap_static(QToolTip, "showText", (1,))++++def set_role(widget: QWidget, role: str) -> None:if widget.property("vernier") != role:widget.setProperty("vernier", role)theme.repolish(widget)++def _elide_lines(text: str, metrics: QFontMetrics, width: int) -> str:++ """Elide each painted line independently, preserving line structure and the source string."""++ return "\n".join(metrics.elidedText(line, Qt.TextElideMode.ElideRight, max(0, width))++ for line in text.split("\n"))++++++def _elide_with_suffix(text: str, suffix: str, metrics: QFontMetrics, width: int) -> str:++ """Keep a machine row's platform/status suffix visible while its leading name is elided."""++ suffix_width = metrics.horizontalAdvance(suffix)++ if not suffix or not text.endswith(suffix) or suffix_width >= width:++ return _elide_lines(text, metrics, width)++ leading = text[:-len(suffix)]++ return _elide_lines(leading, metrics, width - suffix_width) + suffix++++++def _elision_tooltip(widget: QWidget, source: str, displayed: str) -> None:++ """Expose the complete text on hover when this widget has to elide it, without replacing a++ deliberate tooltip supplied by its caller."""++ previous = getattr(widget, "_elision_tooltip", None)++ current = widget.toolTip()++ if current and current != previous:++ return++ tooltip = source if displayed != source else ""++ if current != tooltip:++ widget.setToolTip(tooltip)++ widget._elision_tooltip = tooltip or None++++++class ElidingButton(QPushButton):++ """A native QPushButton that paints an end ellipsis while retaining its complete Qt text."""++++ def __init__(self, text: str = "", parent: QWidget | None = None) -> None:++ super().__init__(text, parent)++ self._elision_suffix = ""++ policy = self.sizePolicy()++ policy.setHorizontalPolicy(QSizePolicy.Policy.Preferred)++ self.setSizePolicy(policy)++++ def set_elision_suffix(self, suffix: str) -> None:++ if suffix != self._elision_suffix:++ self._elision_suffix = suffix++ self.updateGeometry()++ self.update()++++ def displayed_text(self) -> str:++ option = QStyleOptionButton()++ self.initStyleOption(option)++ content = self.style().subElementRect(++ QStyle.SubElement.SE_PushButtonContents, option, self)++ displayed = _elide_with_suffix(self.text(), self._elision_suffix,++ self.fontMetrics(), content.width())++ _elision_tooltip(self, self.text(), displayed)++ return displayed++++ def minimumSizeHint(self) -> QSize:++ size = super().minimumSizeHint()++ metrics = self.fontMetrics()++ text_width = max((metrics.horizontalAdvance(line.replace("&", ""))++ for line in self.text().split("\n")), default=0)++ ellipsis_width = metrics.horizontalAdvance("…")++ size.setWidth(max(ellipsis_width, size.width() - text_width + ellipsis_width))++ return size++++ def paintEvent(self, _event) -> None:++ painter = QStylePainter(self)++ option = QStyleOptionButton()++ self.initStyleOption(option)++ option.text = self.displayed_text()++ painter.drawControl(QStyle.ControlElement.CE_PushButton, option)++++++class ElidingLabel(QLabel):++ """A single-line label that paints an end ellipsis while retaining its complete Qt text."""++++ def __init__(self, text: str = "", parent: QWidget | None = None) -> None:++ super().__init__(text, parent)++ self.setWordWrap(False)++++ def displayed_text(self) -> str:++ content = self.contentsRect().adjusted(self.margin(), self.margin(),++ -self.margin(), -self.margin())++ indent = self.indent()++ if indent > 0:++ content.adjust(indent, 0, 0, 0)++ displayed = _elide_lines(self.text(), self.fontMetrics(), content.width())++ _elision_tooltip(self, self.text(), displayed)++ return displayed++++ def minimumSizeHint(self) -> QSize:++ size = super().minimumSizeHint()++ metrics = self.fontMetrics()++ text_width = max((metrics.horizontalAdvance(line) for line in self.text().split("\n")),++ default=0)++ ellipsis_width = metrics.horizontalAdvance("…")++ size.setWidth(max(ellipsis_width, size.width() - text_width + ellipsis_width))++ return size++++ def paintEvent(self, _event) -> None:++ option = QStyleOptionFrame()++ self.initStyleOption(option)++ painter = QStylePainter(self)++ painter.drawPrimitive(QStyle.PrimitiveElement.PE_Widget, option)++ content = self.contentsRect().adjusted(self.margin(), self.margin(),++ -self.margin(), -self.margin())++ indent = self.indent()++ if indent > 0:++ content.adjust(indent, 0, 0, 0)++ alignment = QStyle.visualAlignment(self.layoutDirection(), self.alignment())++ painter.setFont(self.font())++ painter.setPen(self.palette().color(self.foregroundRole()))++ painter.drawText(content, alignment, self.displayed_text())++++def refresh_colours(root: QWidget) -> None:"""Re-paints every colour under `root` after theme.set_dark() swaps the palette: `update()`for a widget that reads theme.colour() at paint time (nearly all of them), plus that widget's@@@ -63,6 -60,6 +307,8 @@@ class Eyebrow(QLabel)super().__init__(text, parent)self.setProperty("vernier", "eyebrow")self.setFont(theme.eyebrow_font())++ self.setWordWrap(True)++ self.setMinimumWidth(0)class Module(QFrame):@@@ -72,14 -69,14 +318,180 @@@super().__init__(parent)self.setProperty("vernier", "module")self.body = QVBoxLayout(self)-- vertical, horizontal = (round(v) for v in tokens.MODULE_PADDING)-- self.body.setContentsMargins(horizontal, vertical, horizontal, horizontal)++ self.body.setContentsMargins(16, 16, 16, 16)self.body.setSpacing(12)self.eyebrow = Eyebrow(title)self.body.addWidget(self.eyebrow)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)++ 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)@@@ -139,30 -136,30 +551,74 @@@ def rule(vertical: bool = True) -> QWidreturn widget++class SideBySide(QWidget):++ """Two blocks beside each other once the width holds both at their minimums, one above the other++ below that. Only the direction of one box layout changes, so the widgets never re-parent."""++++ def __init__(self, first: QWidget, second: QWidget, gap: int = 24, parent: QWidget | None = None) -> None:++ super().__init__(parent)++ self.setProperty("vernier", "plain")++ self._box = QBoxLayout(QBoxLayout.Direction.TopToBottom, self)++ self._box.setContentsMargins(0, 0, 0, 0)++ self._box.setSpacing(gap)++ self._box.addWidget(first, 1)++ self._box.addWidget(second, 1)++ self.first = first++ self.second = second++ self.gap = gap++ self._beside = False++ policy = self.sizePolicy()++ policy.setHeightForWidth(True)++ self.setSizePolicy(policy)++++ def heightForWidth(self, width: int) -> int:++ beside = width >= self.needed()++ room = max(1, (width - self.gap) // 2 if beside else width)++ heights = [child.heightForWidth(room) if child.hasHeightForWidth() else child.sizeHint().height()++ for child in (self.first, self.second)]++ return max(heights) if beside else sum(heights) + self.gap++++ def needed(self) -> int:++ return self.first.minimumSizeHint().width() + self.second.minimumSizeHint().width() + self.gap++++ def beside(self) -> bool:++ return self._beside++++ def resizeEvent(self, event) -> None:++ super().resizeEvent(event)++ beside = self.width() >= self.needed()++ if beside != self._beside:++ self._beside = beside++ self._box.setDirection(QBoxLayout.Direction.LeftToRight if beside else QBoxLayout.Direction.TopToBottom)++++class Choice:"""A row of exclusive Vernier choice buttons, `columns` wide. Pick a divisor of`len(items)` so a wrap never orphans one. `on_change(value)` fires only on a realclick -- never on `set_value`, so refreshing from an incoming setting cannot loop back."""-- def __init__(self, items, columns: int, current: str, on_change=None, parent: QWidget | None = None) -> None:-- self.view = QWidget(parent)-- self.view.setProperty("vernier", "plain")-- grid = QGridLayout(self.view)-- grid.setContentsMargins(0, 0, 0, 0)-- grid.setSpacing(4)++ def __init__(self, items, columns: int, current: str, on_change=None, parent: QWidget | None = None,++ exclusive=True) -> None:++ self.view = _SegmentedView(parent)self._buttons: dict = {}for index, (value, text) in enumerate(items):-- button = QPushButton(text)++ button = ActionButton(text, self.view)++ button.setMaximumWidth(16777215)button.setProperty("vernier", "choice")button.setCheckable(True)-- button.setAutoExclusive(True)++ button.setAutoExclusive(exclusive)button.setCursor(Qt.CursorShape.PointingHandCursor)button.setMinimumHeight(MIN_TARGET)button.setChecked(value == current)if on_change is not None:button.clicked.connect(lambda _checked=False, v=value: on_change(v))-- grid.addWidget(button, index // columns, index % columns)++ self.view.buttons.append(button)self._buttons[value] = button++ self.view.columns = columns if columns < len(self.view.buttons) else 0++ self.view.refresh_metrics()++++ def set_width(self, width):++ self.view.refresh_metrics()@propertydef value(self):@@@ -183,6 -180,6 +639,7 @@@def set_enabled(self, enabled: bool) -> None:for button in self._buttons.values():button.setEnabled(enabled)++ set_dimmed(self.view, not enabled)def set_names(self, prefix: str) -> None:"""Each cell's accessible name leads with what the row chooses: "Where your Mac is, Left"."""@@@ -190,20 -187,20 +647,73 @@@button.setAccessibleName(f"{prefix}, {button.text()}")--class _Tile(QFrame):++class _TileOutline(QWidget):++ def __init__(self, tile):++ super().__init__(tile)++ self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)++ self.setProperty("vernier", "plain")++++ def paintEvent(self, event):++ tile = self.parentWidget()++ selected = tile.isChecked()++ focused = focus_ring_visible(tile)++ if not selected and not focused:++ return++ painter = QPainter(self)++ painter.setRenderHint(QPainter.RenderHint.Antialiasing)++ painter.setBrush(Qt.BrushStyle.NoBrush)++ if selected:++ painter.setPen(QPen(QColor(theme.colour("signal")), 2))++ painter.drawRoundedRect(QRectF(self.rect()).adjusted(1, 1, -1, -1),++ tokens.RADIUS["button"], tokens.RADIUS["button"])++ x = self.width() - 20++ painter.drawLine(x, 12, x + 3, 15)++ painter.drawLine(x + 3, 15, x + 9, 8)++ if focused:++ painter.setPen(QPen(QColor(theme.colour("ink")), 2))++ painter.drawRoundedRect(QRectF(self.rect()).adjusted(5, 5, -5, -5), 2, 2)++++++class _Tile(QPushButton):"""One tile of ChoiceTiles: the whole tile is the control, by click or by Space from Tab."""def __init__(self, choose, parent: QWidget | None = None) -> None:super().__init__(parent)self._choose = choose++ self._hovered = False++ self.setCheckable(True)++ self.toggled.connect(lambda _checked=False: choose())self.setProperty("vernier", "tile")self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)self.setCursor(Qt.CursorShape.PointingHandCursor)---- def mousePressEvent(self, event) -> None:-- if event.button() == Qt.MouseButton.LeftButton and self.isEnabled():-- self._choose()-- super().mousePressEvent(event)++ self.outline = _TileOutline(self)++++ def paintEvent(self, event):++ painter = QStylePainter(self)++ option = QStyleOptionButton()++ self.initStyleOption(option)++ option.text = ""++ if self._hovered:++ option.state |= QStyle.StateFlag.State_MouseOver++ painter.drawControl(QStyle.ControlElement.CE_PushButton, option)++++ def enterEvent(self, event):++ self._hovered = True++ self.update()++ super().enterEvent(event)++++ def leaveEvent(self, event):++ self._hovered = False++ self.update()++ super().leaveEvent(event)++++ def focusInEvent(self, event):++ super().focusInEvent(event)++ self.outline.update()++++ def focusOutEvent(self, event):++ super().focusOutEvent(event)++ self.outline.update()def keyPressEvent(self, event) -> None:if event.key() in (Qt.Key.Key_Space, Qt.Key.Key_Return, Qt.Key.Key_Enter):@@@ -211,6 -208,6 +721,19 @@@returnsuper().keyPressEvent(event)++ def resizeEvent(self, event) -> None:++ super().resizeEvent(event)++ self.outline.setGeometry(self.rect())++ self.outline.raise_()++++ def hasHeightForWidth(self) -> bool:++ layout = self.layout()++ return layout is not None and layout.hasHeightForWidth()++++ def heightForWidth(self, width: int) -> int:++ layout = self.layout()++ return layout.totalHeightForWidth(width) if layout is not None else self.sizeHint().height()++class ChoiceTiles:"""One of several, as tiles side by side: each a live preview over its name and a line saying@@@ -218,37 -215,37 +741,60 @@@the signal focus border inside it still shows. `on_change(value)` fires only on a real choice,never on `set_value`."""-- def __init__(self, items, current, on_change=None, parent: QWidget | None = None) -> None:++ def __init__(self, items, current, on_change=None, parent: QWidget | None = None,++ tile_width: int | None = None, vertical: bool = False, responsive: bool = False) -> None:self.on_change = on_changeself.value = None-- self.view = QWidget(parent)++ self.view = _FamilyChoices("style", parent) if responsive else QWidget(parent)self.view.setProperty("vernier", "plain")-- row = QHBoxLayout(self.view)-- row.setContentsMargins(0, 0, 0, 0)-- row.setSpacing(10)++ row = None++ if not responsive:++ row = (QVBoxLayout if vertical else QHBoxLayout)(self.view)++ row.setContentsMargins(0, 0, 0, 0)++ row.setSpacing(8 if vertical else 10)++ if tile_width is not None:++ row.setAlignment(Qt.AlignmentFlag.AlignLeft)self._tiles: dict = {}self._titles: dict = {}for value, title, detail, preview in items:tile = _Tile(lambda v=value: self._chosen(v))++ if vertical:++ policy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)++ policy.setHeightForWidth(True)++ tile.setSizePolicy(policy)++ if tile_width is not None:++ tile.setFixedWidth(tile_width)self._titles[value] = titletile.setAccessibleName(title)tile.setAccessibleDescription(detail)column = QVBoxLayout(tile)++ column.setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint)column.setContentsMargins(8, 8, 8, 12)column.setSpacing(6)column.addWidget(preview)-- column.addSpacing(4)-- column.addWidget(label(title, "tile-name"))++ if not vertical:++ column.addSpacing(4)++ column.addWidget(label(title, "tile-name", wrap=tile_width is not None))column.addWidget(label(detail, "small", wrap=True))-- column.addStretch(1)-- row.addWidget(tile, 1)++ if vertical:++ column.setSpacing(6)++ column.insertSpacing(1, 4)++ else:++ column.addStretch(1)++ if responsive:++ self.view.add_cell(tile)++ else:++ row.addWidget(tile, 0 if vertical or tile_width is not None else 1)self._tiles[value] = tileself.set_value(current)def set_value(self, value) -> None:self.value = valuefor candidate, tile in self._tiles.items():++ with QSignalBlocker(tile):++ tile.setChecked(candidate == value)set_role(tile, "tile-on" if candidate == value else "tile")++ tile.outline.update()title = self._titles[candidate]tile.setAccessibleName(f"{title}, selected" if candidate == value else title)@@@ -256,7 -253,7 +802,6 @@@return self._tiles.get(value)def set_enabled(self, enabled: bool) -> None:-- # Faded whole, previews included, as the Mac's tiles are.fade = QGraphicsOpacityEffect(self.view)fade.setOpacity(1.0 if enabled else 0.45)self.view.setGraphicsEffect(None if enabled else fade)@@@ -265,17 -262,17 +810,74 @@@def _chosen(self, value) -> None:if value == self.value:++ self.set_value(value)returnself.set_value(value)if self.on_change is not None:self.on_change(value)++class _FamilyChoices(QWidget):++ """A family's logical tracks; height measurement never mutates its children."""++++ def __init__(self, kind, parent=None):++ super().__init__(parent)++ self.kind = kind++ self.cells = []++ policy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)++ policy.setHeightForWidth(True)++ self.setSizePolicy(policy)++++ def add_cell(self, cell):++ cell.setParent(self)++ self.cells.append(cell)++++ def _tracks(self, width):++ outer = width + 32++ columns = ((3 if outer >= 600 else 2 if outer >= 400 else 1) if self.kind == "style"++ else (5 if outer >= 600 else 3 if outer >= 400 else 2))++ gap = 12 if self.kind == "style" else 8++ cell_width = max(1, (width - gap * (columns - 1) + columns - 1) // columns)++ if len(self.cells) == 1:++ columns, cell_width = 1, min(width, 152)++ if self.kind == "style":++ height = max(round(cell_width * 116 / 152), round((cell_width - 16) / 2) + 64)++ else:++ height = max((cell.heightForWidth(cell_width) for cell in self.cells), default=60)++ height = max(60, height)++ return columns, gap, cell_width, height++++ def heightForWidth(self, width):++ columns, gap, _, height = self._tracks(width)++ rows = (len(self.cells) + columns - 1) // columns++ return rows * height + max(0, rows - 1) * gap++++ def sizeHint(self):++ return QSize(600, self.heightForWidth(600))++++ def minimumSizeHint(self):++ return QSize(0, 0)++++ def resizeEvent(self, event):++ super().resizeEvent(event)++ columns, gap, width, height = self._tracks(self.width())++ for index, cell in enumerate(self.cells):++ track = index % columns++ room = self.width() - gap * (columns - 1)++ left = round(track * room / columns) + track * gap++ right = round((track + 1) * room / columns) + track * gap++ if len(self.cells) == 1:++ left, right = 0, width++ cell.setGeometry(left, (index // columns) * (height + gap), right - left, height)++ if self.kind == "style":++ cell.layout().itemAt(0).widget().setFixedHeight(++ max(1, round((cell.contentsRect().width() - 16) / 2)))++class _Swatch(QPushButton):"""A colour chip over its name. The name wraps onto a second line rather than widen the grid:at the window's minimum width five chips a row have about 65px each."""-- CHIP = 24++ CHIP = 28MIN_WIDTH = 44NAME_GAP = 4@@@ -329,7 -326,7 +931,7 @@@radius = tokens.RADIUS["field"]# The chosen chip's ink ring is SwatchGroups', outside the chip; focus is this signal# border on the chip itself, so the two can be told apart when they fall on one chip.-- if self.hasFocus():++ if focus_ring_visible(self):painter.setPen(QPen(QColor(theme.colour("signal")), 2))painter.drawRoundedRect(chip.adjusted(1, 1, -1, -1), radius, radius)else:@@@ -342,14 -339,14 +944,20 @@@Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop | Qt.TextFlag.TextWordWrap,self.text(),)++ if chosen:++ painter.setPen(QPen(QColor("#161714"), 4))++ x, y = round(chip.right() - 16), round(chip.center().y() - 3)++ painter.drawLine(x, y + 3, x + 3, y + 6)++ painter.drawLine(x + 3, y + 6, x + 9, y)++ painter.setPen(QPen(QColor("#ffffff"), 2))++ painter.drawLine(x, y + 3, x + 3, y + 6)++ painter.drawLine(x + 3, y + 6, x + 9, y)class TileGroups:"""ChoiceTiles in titled groups with one value across all of them: `groups` is (title, items)-- with ChoiceTiles' items. `on_change(value)` fires only on a real choice. One ring marks the-- chosen tile and slides to the next, across groups."""---- RING_OUTSET = 3++ with ChoiceTiles' items. `on_change(value)` fires only on a real choice. Each selected tile++ draws its own accent border."""def __init__(self, groups, current, on_change=None, parent: QWidget | None = None) -> None:self.on_change = on_change@@@ -357,26 -354,26 +965,27 @@@self.view = QWidget(parent)self.view.setProperty("vernier", "plain")column = QVBoxLayout(self.view)-- # Room for the ring outside the outermost tiles.-- room = self.RING_OUTSET + 1-- column.setContentsMargins(room, room, room, room)-- column.setSpacing(6)++ column.setContentsMargins(0, 0, 0, 0)++ column.setSpacing(20)self.groups: dict = {}++ self.group_views: dict = {}++ group_views = []for index, (title, items) in enumerate(groups):-- if index:-- column.addSpacing(8)-- column.addWidget(label(title, "key"))-- tiles = ChoiceTiles(items, current, on_change=self._chosen)-- column.addWidget(tiles.view)++ group_view = QWidget()++ group_view.setProperty("vernier", "plain")++ group_column = QVBoxLayout(group_view)++ group_column.setContentsMargins(0, 0, 0, 0)++ group_column.setSpacing(6)++ group_column.addWidget(label(title, "key"))++ tiles = ChoiceTiles(items, current, on_change=self._chosen, responsive=True)++ group_column.addWidget(tiles.view)self.groups[title] = tiles-- outset = self.RING_OUTSET-- self.ring = motion.Ring(-- self.view,-- lambda tile: QRectF(tile.rect()).adjusted(-outset + 0.5, -outset + 0.5, outset - 0.5, outset - 0.5),-- lambda: theme.colour("ink"),-- tokens.RADIUS["button"] + outset,-- )-- self.ring.follow(self.tile(current))++ self.group_views[title] = group_view++ group_views.append((title, group_view))++ column.addWidget(group_view)++ self.grid = self.view++ self.grid._rows = [view for _, view in group_views]++ self.ring = Nonedef tile(self, value):return next((tile for tiles in self.groups.values() if (tile := tiles.tile(value)) is not None), None)@@@ -385,7 -382,7 +994,8 @@@self.value = valuefor tiles in self.groups.values():tiles.set_value(value)-- self.ring.follow(self.tile(value))++ if self.ring is not None:++ self.ring.follow(self.tile(value))def set_enabled(self, enabled: bool) -> None:for tiles in self.groups.values():@@@ -409,19 -406,19 +1019,26 @@@ class SwatchGroupsdef __init__(self, groups, current, on_change=None, parent: QWidget | None = None) -> None:self.view = QWidget(parent)self.view.setProperty("vernier", "plain")-- grid = QGridLayout(self.view)-- grid.setContentsMargins(0, 0, 0, 0)-- grid.setHorizontalSpacing(6)-- grid.setVerticalSpacing(2)++ column = QVBoxLayout(self.view)++ column.setContentsMargins(0, 0, 0, 0)++ column.setSpacing(20)self._group = QButtonGroup(self.view)self._group.setExclusive(True)self._swatches: dict = {}-- widest = max(len(items) for _title, items in groups)++ self.group_views = {}for row, (title, items) in enumerate(groups):++ family = QWidget()++ family.setProperty("vernier", "plain")++ body = QVBoxLayout(family)++ body.setContentsMargins(0, 0, 0, 0)++ body.setSpacing(8)heading = label(title, "key")-- if row:-- heading.setContentsMargins(0, 8, 0, 0)-- grid.addWidget(heading, row * 2, 0, 1, widest)++ body.addWidget(heading)++ choices = _FamilyChoices("colour")++ choices.setProperty("vernier", "plain")++ body.addWidget(choices)++ self.group_views[title] = choices++ column.addWidget(family)for index, (value, name, colours) in enumerate(items):swatch = _Swatch(colours, name)swatch.setAutoExclusive(False)@@@ -429,11 -426,11 +1046,9 @@@swatch.setChecked(value == current)swatch.toggled.connect(lambda on, s=swatch: on and self.ring.follow(s))if on_change is not None:-- swatch.clicked.connect(lambda _checked=False, v=value: on_change(v))-- grid.addWidget(swatch, row * 2 + 1, index)++ swatch.toggled.connect(lambda on, v=value: on and on_change(v))++ choices.add_cell(swatch)self._swatches[value] = swatch-- for index in range(widest):-- grid.setColumnStretch(index, 1)self.ring = motion.Ring(self.view,lambda swatch: swatch.chip_rect().adjusted(-2.5, -2.5, 2.5, 2.5),@@@ -449,14 -446,14 +1064,17 @@@def set_value(self, value) -> None:swatch = self._swatches.get(value)if swatch is not None and not swatch.isChecked():-- swatch.setChecked(True)++ with QSignalBlocker(swatch):++ swatch.setChecked(True)++ self.ring.follow(swatch)def set_enabled(self, enabled: bool) -> None:for swatch in self._swatches.values():swatch.setEnabled(enabled)++ set_dimmed(self.view, not enabled)--class InputRecorder(QPushButton):++class InputRecorder(ActionButton):"""A keycap that records the next key or mouse button pressed. Clicking arms it; while armed anapplication-wide filter takes the next key or non-left button and hands `on_record` a("key", virtual key) or ("button", name) pair, and a left click anywhere disarms it. The key is@@@ -486,19 -483,19 +1104,28 @@@self.setProperty("vernier", "keycap")self.setCursor(Qt.CursorShape.PointingHandCursor)self.setAccessibleName(self._spoken(title))-- self.setFixedHeight(42 if mono else 36)-- row = QHBoxLayout(self)++ self.setMaximumWidth(16777215)++ self.setMinimumHeight(42 if mono else 36)++ row = QBoxLayout(QBoxLayout.Direction.TopToBottom, self)++ self._content = rowrow.setContentsMargins(12, 0, 12, 0)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)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)++++ 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@@@ -567,102 -564,6 +1194,110 @@@return False- class JumpKeyRecorder(QPushButton):++class JumpKeyRecorder(ActionButton):+ """Records a modifier chord and keeps its local spelling for one peer."""++ def __init__(self, on_record, on_arm=None, parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self.on_record = on_record++ self.setMaximumWidth(16777215)+ self.on_arm = on_arm+ self.value = ""+ self.armed = False+ self.setProperty("vernier", "keycap")+ self.setCursor(Qt.CursorShape.PointingHandCursor)+ self.setMinimumHeight(52)+ row = QVBoxLayout(self)+ row.setContentsMargins(12, 5, 12, 5)+ row.setSpacing(2)- self.key = label("Choose a key combination", "body")- self.hint = label("Click, then press a key combination", "small")++ self.key = label("Choose a key combination", "body", wrap=True)++ self.hint = label("Click, then press a key combination", "small", wrap=True)+ self.key.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)+ self.hint.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)+ row.addWidget(self.key)+ row.addWidget(self.hint)+ self.clicked.connect(self._toggle)+ self._names = {"ctrl": "Win", "cmd": "Ctrl", "alt": "Alt", "shift": "Shift"}+++ def heightForWidth(self, width):++ room = max(1, width - 24)++ return max(52, sum(item.heightForWidth(room) for item in (self.key, self.hint)) + 12)++++ def sizeHint(self):++ return QSize(280, self.heightForWidth(280))+++ def set_value(self, value: str) -> None:+ self.value = value or ""+ shown = " ".join(self._names.get(part, part.upper() if len(part) == 1 else part.replace("_", " ").title())+ for part in self.value.split("+")) if self.value else "Choose a key combination"+ self.setAccessibleName(f"Jump straight here key, {shown}")+ if not self.armed:+ self.key.setText(shown)+ set_role(self.key, "keycap" if self.value else "body")++ def cancel(self) -> None:+ if not self.armed:+ return+ self.armed = False+ QApplication.instance().removeEventFilter(self)+ if self.on_arm is not None:+ self.on_arm(False)+ self.set_value(self.value)+ set_role(self.key, "keycap" if self.value else "body")+ self.hint.setText("Click, then press a key combination")+ set_role(self, "keycap")++ def _toggle(self) -> None:+ if self.armed:+ self.cancel()+ return+ self.armed = True+ self.key.setText("Press a key combination…")+ set_role(self.key, "keycap-live")+ self.hint.setText("Click again to cancel")+ set_role(self, "keycap-live")+ QApplication.instance().installEventFilter(self)+ if self.on_arm is not None:+ self.on_arm(True)++ def eventFilter(self, watched, event) -> bool:+ if not self.armed:+ return False+ if event.type() == QEvent.Type.KeyPress:+ modifiers = event.modifiers()+ held = []+ for flag, name in ((Qt.KeyboardModifier.ControlModifier, "cmd"),+ (Qt.KeyboardModifier.AltModifier, "alt"),+ (Qt.KeyboardModifier.ShiftModifier, "shift"),+ (Qt.KeyboardModifier.MetaModifier, "ctrl")):+ if modifiers & flag:+ held.append(name)+ key = event.text().lower()+ if not key or len(key) != 1 or not key.isprintable() or key == " ":+ value = event.key()+ key = next((f"f{i}" for i in range(1, 25) if value == getattr(Qt.Key, f"Key_F{i}")), "")+ names = {Qt.Key.Key_Backspace: "backspace", Qt.Key.Key_Delete: "delete", Qt.Key.Key_Left: "left",+ Qt.Key.Key_Right: "right", Qt.Key.Key_Up: "up", Qt.Key.Key_Down: "down",+ Qt.Key.Key_Home: "home", Qt.Key.Key_End: "end", Qt.Key.Key_PageUp: "page_up",+ Qt.Key.Key_PageDown: "page_down", Qt.Key.Key_Insert: "insert", Qt.Key.Key_Tab: "tab",+ Qt.Key.Key_Return: "enter", Qt.Key.Key_Enter: "enter", Qt.Key.Key_Escape: "esc",+ Qt.Key.Key_Space: "space"}+ key = key or names.get(value, "")+ chord = core_ways.jump_chord(held, key)+ if chord:+ self.cancel()+ self.set_value(chord)+ self.on_record(chord)+ return True+ if event.type() == QEvent.Type.KeyRelease:+ return True+ if event.type() == QEvent.Type.MouseButtonPress:+ inside = isinstance(watched, QWidget) and (watched is self or self.isAncestorOf(watched))+ self.cancel()+ return inside+ return False++class PageButton(QPushButton):"""One entry in the sidebar's page list, with an optional tone dot for a page thatneeds attention."""@@@ -674,6 -575,6 +1309,59 @@@self.setAutoExclusive(True)self.setCursor(Qt.CursorShape.PointingHandCursor)self._dot = None++ self._rail = False++ self._keyboard_ring = False++ self._page_key = ""++ self.setMinimumHeight(36)++ self.setAccessibleName(text)++++ def minimumSizeHint(self):++ return QSize(0, 36)++++ def keyPressEvent(self, event):++ if event.key() in (Qt.Key.Key_Up, Qt.Key.Key_Down, Qt.Key.Key_Left, Qt.Key.Key_Right):++ direction = -1 if event.key() in (Qt.Key.Key_Up, Qt.Key.Key_Left) else 1++ self._sidebar.navigate(self._page_key, direction)++ return++ if event.key() in (Qt.Key.Key_Space, Qt.Key.Key_Return, Qt.Key.Key_Enter):++ self._sidebar.navigate(self._page_key, 0)++ return++ super().keyPressEvent(event)++++ def _icon(self, painter):++ x = (self.width() - 18) / 2 if self._rail else 12++ y = (self.height() - 18) / 2++ painter.save()++ painter.translate(x, y)++ painter.setBrush(Qt.BrushStyle.NoBrush)++ painter.setPen(QPen(QColor(theme.colour("ink" if self.isChecked() else "ink_2")), 1.4))++ key = self._page_key++ if key == "overview":++ painter.drawRoundedRect(QRectF(1, 2, 12, 9), 1, 1)++ painter.drawLine(7, 11, 7, 15)++ painter.drawLine(3, 15, 11, 15)++ painter.drawRoundedRect(QRectF(11, 8, 6, 7), 1, 1)++ elif key == "crossing":++ painter.drawLine(1, 6, 16, 6)++ painter.drawLine(12, 2, 16, 6)++ painter.drawLine(12, 10, 16, 6)++ painter.drawLine(16, 13, 1, 13)++ painter.drawLine(5, 9, 1, 13)++ painter.drawLine(5, 17, 1, 13)++ elif key == "keyboard":++ painter.drawRoundedRect(QRectF(0, 3, 18, 12), 2, 2)++ for row in (6, 9):++ for col in (4, 8, 12, 16):++ painter.drawPoint(col, row)++ painter.drawLine(5, 12, 13, 12)++ elif key == "design":++ painter.drawEllipse(QRectF(2, 2, 14, 14))++ painter.drawLine(9, 2, 9, 16)++ painter.drawLine(2, 9, 16, 9)++ else:++ painter.drawRoundedRect(QRectF(1, 5, 10, 7), 3, 3)++ painter.drawRoundedRect(QRectF(7, 7, 10, 7), 3, 3)++ painter.restore()def set_dot(self, tone: str | None) -> None:if tone != self._dot:@@@ -681,11 -582,11 +1369,26 @@@self.update()def paintEvent(self, event) -> None:-- super().paintEvent(event)-- if self._dot is None:-- return++ native = QStylePainter(self)++ option = QStyleOptionButton()++ self.initStyleOption(option)++ if self._rail:++ option.text = ""++ native.drawControl(QStyle.ControlElement.CE_PushButton, option)++ native.end()painter = QPainter(self)painter.setRenderHint(QPainter.RenderHint.Antialiasing)++ self._icon(painter)++ if self.isChecked():++ painter.setPen(Qt.PenStyle.NoPen)++ painter.setBrush(QColor(theme.colour("signal")))++ painter.drawRect(QRectF(0, 7, 2, self.height() - 14))++ if self._keyboard_ring and self.isChecked() and self.hasFocus():++ painter.setBrush(Qt.BrushStyle.NoBrush)++ painter.setPen(QPen(QColor(theme.colour("signal")), 2))++ painter.drawRoundedRect(QRectF(self.rect()).adjusted(2, 2, -2, -2), 4, 4)++ if self._dot is None:++ returnpainter.setPen(Qt.PenStyle.NoPen)painter.setBrush(QColor(theme.colour(self._dot)))size = 6@@@ -699,29 -600,29 +1402,38 @@@ class Sidebar(QWidget)def __init__(self, pages, on_select, foot: str = "", on_foot=None, foot_tip: str = "", parent: QWidget | None = None) -> None:super().__init__(parent)self.setProperty("vernier", "sidebar")++ self._on_select = on_select++ self._selected = ""++ keyboard_navigation()++ QApplication.instance().installEventFilter(self)++ QApplication.instance().focusChanged.connect(self._focus_changed)outer = QVBoxLayout(self)outer.setContentsMargins(0, 0, 0, 0)outer.setSpacing(0)link = QWidget()link.setProperty("vernier", "plain")-- link_layout = QHBoxLayout(link)-- link_layout.setContentsMargins(16, 16, 16, 16)-- link_layout.setSpacing(8)++ self._link_layout = QHBoxLayout(link)++ self._link_layout.setContentsMargins(16, 16, 16, 16)++ self._link_layout.setSpacing(8)self.link_led = Led()-- link_layout.addWidget(self.link_led, 0, Qt.AlignmentFlag.AlignVCenter)++ self._link_layout.addWidget(self.link_led, 0, Qt.AlignmentFlag.AlignVCenter)self.link_word = label("", "sidebar-link")-- link_layout.addWidget(self.link_word, 1)++ self._link_layout.addWidget(self.link_word, 1)outer.addWidget(link)outer.addWidget(rule(vertical=False))list_layout = QVBoxLayout()++ self._list_layout = list_layoutlist_layout.setContentsMargins(8, 8, 8, 8)list_layout.setSpacing(2)self._buttons: dict = {}for key, name, _purpose in pages:button = PageButton(name)-- button.clicked.connect(lambda _checked=False, k=key: on_select(k))++ button._sidebar = self++ button._page_key = key++ button.setToolTip(name)++ button.clicked.connect(lambda _checked=False, k=key: self._pointer_select(k))list_layout.addWidget(button)self._buttons[key] = buttonlist_layout.addStretch(1)@@@ -734,19 -635,19 +1446,102 @@@self.foot.setCursor(Qt.CursorShape.PointingHandCursor)self.foot.setToolTip(foot_tip or "Open in your browser")self.foot.setAccessibleName(foot.replace("\n", ", "))++ self._foot_text = footif on_foot is not None:self.foot.clicked.connect(on_foot)outer.addWidget(self.foot)++ @property++ def keyboard_mode(self) -> bool:++ return keyboard_navigation().active++++ @keyboard_mode.setter++ def keyboard_mode(self, active: bool) -> None:++ keyboard_navigation().set(active)++def select(self, key: str) -> None:++ self._selected = keybutton = self._buttons.get(key)if button is not None and not button.isChecked():button.setChecked(True)++ focused = QApplication.focusWidget()++ if button is not None and self.keyboard_mode and focused in self._buttons.values():++ button.setFocus(Qt.FocusReason.ShortcutFocusReason)++ elif not self.keyboard_mode:++ for other in self._buttons.values():++ other.clearFocus()++ self._update_rings()++++ def _update_rings(self):++ for key, button in self._buttons.items():++ button._keyboard_ring = self.keyboard_mode and key == self._selected++ button.update()++ for tile in self.window().findChildren(_Tile):++ tile.outline.update()++++ def _focus_changed(self, old, new):++ if new in self._buttons.values():++ selected = self._buttons.get(self._selected)++ if not self.keyboard_mode:++ new.clearFocus()++ elif selected is not None and new is not selected:++ selected.setFocus(Qt.FocusReason.TabFocusReason)++ self._update_rings()++++ def _pointer_select(self, key):++ self.keyboard_mode = False++ self._on_select(key)++ self.select(key)++++ def navigate(self, key, direction):++ keys = list(self._buttons)++ self.keyboard_mode = True++ target = keys[(keys.index(key) + direction) % len(keys)]++ self._on_select(target)++ self._buttons[target].setFocus(Qt.FocusReason.ShortcutFocusReason)++ self.select(target)++++ def eventFilter(self, watched, event):++ if isinstance(watched, QWidget) and watched.window() is self.window():++ if event.type() == QEvent.Type.MouseButtonPress:++ self.keyboard_mode = False++ for button in self._buttons.values():++ button.clearFocus()++ self._update_rings()++ elif event.type() == QEvent.Type.KeyPress and is_navigation_key(event.key(), event.modifiers()):++ self.keyboard_mode = True++ self._update_rings()++ return False++++ def set_window_width(self, width):++ rail = width < 640++ self.setFixedWidth(56 if rail else 144 if width < 800 else 176)++ self.link_word.setVisible(not rail)++ self._link_layout.setContentsMargins(24 if rail else 16, 4 if rail else 16,++ 24 if rail else 16, 4 if rail else 16)++ self._list_layout.setContentsMargins(6 if rail else 8, 3 if rail else 8,++ 6 if rail else 8, 3 if rail else 8)++ for button in self._buttons.values():++ button._rail = rail++ button.update()++ if hasattr(self, "foot"):++ self.foot.setProperty("rail", rail)++ self.foot.setText("" if rail else self._foot_text)++ self.foot.setFixedHeight(20 if rail else 58)++ if rail:++ from pathlib import Path++ from PySide6.QtGui import QIcon++ self.foot.setIcon(QIcon(str(Path(__file__).resolve().parent / "Beamer.ico")))++ else:++ from PySide6.QtGui import QIcon++ self.foot.setIcon(QIcon())++ theme.repolish(self.foot)def set_link(self, tone: str, word: str) -> None:self.link_led.set_tone(tone)if self.link_word.text() != word:self.link_word.setText(word)++ self.link_led.setToolTip(word)def set_dots(self, marks: dict) -> None:for key, button in self._buttons.items():@@@ -783,11 -684,11 +1578,22 @@@ class Switch(QCheckBox)def __init__(self, text: str, parent: QWidget | None = None) -> None:super().__init__(text, parent)self.setCursor(Qt.CursorShape.PointingHandCursor)-- self.setMinimumHeight(24)++ self.setMinimumHeight(30)++ policy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)++ policy.setHeightForWidth(True)++ self.setSizePolicy(policy)def sizeHint(self) -> QSize:text = self.fontMetrics().horizontalAdvance(self.text())-- return QSize(text + 12 + self.TRACK.width() + 4, max(24, self.TRACK.height() + 6))++ return QSize(text + 12 + self.TRACK.width() + 4, 30)++++ def minimumSizeHint(self) -> QSize:++ return QSize(44, 30)++++ def heightForWidth(self, width):++ bounds = self.fontMetrics().boundingRect(++ QRect(0, 0, max(1, width - 50), 10000), int(Qt.TextFlag.TextWordWrap), self.text())++ return max(30, bounds.height())def hitButton(self, pos) -> bool:return self.rect().contains(pos)@@@ -804,7 -705,7 +1610,7 @@@self.TRACK.width(),self.TRACK.height() - 1,)-- if self.hasFocus():++ if focus_ring_visible(self):painter.setPen(QColor(theme.colour("signal")))painter.setBrush(Qt.BrushStyle.NoBrush)painter.drawRoundedRect(track.adjusted(-2, -2, 2, 2), 11, 11)@@@ -819,4 -720,4 +1625,5 @@@painter.setPen(QColor(theme.colour("ink")))painter.setFont(self.font())text_rect = QRectF(0, 0, track.left() - 12, self.height())-- painter.drawText(text_rect, Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, self.text())++ painter.drawText(text_rect, Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft |++ Qt.TextFlag.TextWordWrap, self.text())