One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.5.0-beta.2
Toby Kalkman147ad08cde35
diff --git a/.gitignore b/.gitignoreindex c9e23ff..3814199 100644--- a/.gitignore+++ b/.gitignore@@ -17,5 +17,5 @@ mac_app/build/mac_app/dist/-# Rendered on demand from docs/*.html; reaches the other machine via Syncthing+# Rendered documents, never committeddocs/pdf/diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 8814de0..e1b17ea 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -12,8 +12,9 @@ They hold your machines' names and local network addresses, so look them over fi## 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. 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. 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.## Pull requestsdiff --git a/PAIRING.md b/PAIRING.mdindex 8054515..5cffd02 100644--- a/PAIRING.md+++ b/PAIRING.md@@ -202,10 +202,13 @@ keeps every one.spoken any more, in either direction.- The link's wire protocol is not changed by it. Machines paired by an earlier Beamer staypaired, and the two can be updated one at a time; both need 1.4.3 to pair afresh.+- Pairing version 3, in 1.5.0, is this exchange with machine ids, platform and port bound in,+ the `known` and `full` refusals, pairing over TCP and the QR's second secret: WIRE.md+ section 6. Versions 2 and 3 never pair.## The vectors-`mac_app/tests/pairing_vectors.json`, with an identical copy in `win_app/tests`:+`core/tests/pairing_vectors.json`:- `cpace_draft`: the draft's own X25519 vector, so the core is proved against the IETF'snumbers before anything of Beamer's is added;@@ -216,5 +219,5 @@ keeps every one.- `wrong_code`: an answer made under another code, which the requester must refuse and abort;- `name_cut`: a 60 code point name and the 48 it is cut to.-No vector covers retransmission, expiry, or rules 2 and 3; `mac_app/tests/test_pairing_cpace.py`+No vector covers retransmission, expiry, or rules 2 and 3; `core/tests/test_pairing_cpace.py`and the loopback tests in `mac_app/tests/test_pairing.py` do.diff --git a/VERSION b/VERSIONindex 591650a..5b50064 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.5.0-beta.1+1.5.0-beta.2diff --git a/WIRE.md b/WIRE.mdnew file mode 100644index 0000000..c8e7ee3--- /dev/null+++ b/WIRE.md@@ -0,0 +1,1306 @@+# 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. Any other token (one a user typed into 1.4.x) is a **typed token**,+ and never links (section 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`.+- **Malformed messages.** A message is malformed when it is not an object, 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. 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 until its first link |+| `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 |++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`. The link finds+ it by its key id like any other entry, and its first link fills the id in (section 2). Zones+ for it name it by `""`, and the save that learns its id rewrites them.+- **An entry with a typed token** is kept and shown, but never linked: it is not dialled, the+ responder never matches its key id, and Overview asks the user to pair that machine again.+- **Removing a peer** deletes its entry, token included, closes its links at once, and ends its+ ownership if it holds it (section 4). The peer is told nothing; 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 has no key id (section 2), so it is never refused by that check; it is migrated,+and never links.++**The peer's id** is unknown after the migration, because 1.4.x never had one. The first+version 6 link between the two fills it in, from the `hello` or `welcome` the existing token+authenticated (section 2, the handshake).++## 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. The key id is only ever computed for a token made by+pairing: a key id is an offline test of its token, harmless for 256 random bits and fatal for a+typed word, so a typed token is never used for a link at all (section 1).++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.+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.+3. Reads the other 56 bytes, and looks up the entry whose token (a token made by pairing) 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.+8. Checks the `id` in `hello`. When it is this machine's own, or when the entry has an id and+ this is not it, 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.+ When the entry has `id: ""` (the one migrated from 1.4.x), it checks again in one step under a+ lock that the entry still has `id: ""` (if it has an id by then, it goes on as for an entry+ that has one), and then:+ - When another entry has this id, is a desktop (`port` not 0) and has the `platform` the+ migration gave the migrated entry, that machine was paired again after the upgrade somewhere+ its saved `host` did not match (section 6), and still dials under the 1.4.x token, which+ only it holds. The migrated entry is **folded** into that one: it is removed; that entry+ takes its `side`, `side_set_at` and `side_by` when it has never had a side (`side_set_at`+ 0); each of its zones moves to that entry unless that entry has a zone of the same kind,+ which wins; one pass over the zones in use, other peers' first, then that entry's own, then+ the moved ones, turns `off` any that would cover a stretch already covered (section 8); and+ the settings are saved. It sends `welcome`, so the other side folds its own migrated entry+ in its step 7, and closes: the pairing the link came under is gone. It tells the user:+ "*name* linked from *address* under its Beamer 1.4 pairing, *old name*, which is now part of+ *name*." When another entry has this id but is a phone or of another platform, it answers+ `wrong_id`.+ - Otherwise it writes the id, sets `linked`, and saves. It tells the user once: "Linked with+ *name* at *address* for the first time on Beamer 1.5.0."+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 never dials an entry with a typed token.+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; when the entry has an id, that id. On a+ failure it closes, sending nothing more, and says a different Beamer answered at that address.+ If the entry had `id: ""`, it does what the responder does in its step 8, under the lock: when+ another entry has that id and the fold's conditions hold, it folds the migrated entry into it,+ closes sending nothing more, and tells the user the same; when another entry has it and they+ do not, it closes and says a different Beamer answered; otherwise it writes the id and sets+ `linked`. If the entry had an id, 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.+- 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 in the last 10 seconds (allowing 30 more for a large one still arriving). 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 plaintext that is not a+ JSON object) 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 keeps Same on all machines (`settings`) |++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.+- **The migrated entry trusts its token.** Whoever first authenticates with a 1.4.x token claims+ the empty-id entry, with whatever id its `hello` or `welcome` names. That is no more than the+ token already allowed under version 5, but a token made by 1.4.2's pairing, which could be+ attacked offline, is only as safe as that pairing was. The notice in step 8 shows which+ machine and address claimed it. A holder that names the id of another desktop entry of the+ migrated entry's platform folds the migrated entry into that one instead (step 8): the 1.4.x+ pairing is gone, as a claim would have taken it, and its zones lead to a machine already+ paired, never to the holder. The fold's notice names the machine, the address and the pairing+ folded.++## 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.+ Over either, 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`.+- **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 a number from 0.0 to 1.0 (clamped) along that edge of the responder |+| `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"`. An initiator treats+any other `why` as a refusal it cannot name.++`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 |++### 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, or from home.** A desktop's pointer pushes through one of its+zones (section 8) to peer P, or the shortcut or a menu picks P. The owner raises the route and+sends P the taking `focus`, then its clipboard, then input, without waiting: a refusal sends the+input home, and whatever reached P in the meantime was dropped there. No answer within 1 second+also sends it home.++**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.+ - It ignores an `accept` whose route is not that of a take it sent. One 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).+ - Anything else that moves the input while it waits (a send-home from B, a lost link, the+ owner's own shortcut) ends the wait and cancels its timer.+- `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: `reach` already stops a zone firing for+an owner that could not follow it, so the zone could be offered and the page name the pairings+that are missing. A zone never leads to a phone.++### 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 within 10 seconds of that let-go; any other is dropped. 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'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 (`id: ""`, `from_1_4` true) is replaced 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). Left beside the new entry, it would be+ folded into it on the first link under its token (section 2, step 8). It is replaced, never counted, under the+ rule in item 5, and its zones go with it rather than moving to the new id. Never by `name`:+ a name is whatever the pairing machine chose, so anyone who saw the code could take the old+ peer's and evict a 1.4.x pair that still links, and with its zones receive the input that+ crosses them. Pairing proves the code, not which machine that entry was.+ - 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, 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"`, `"+"`).+- **`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 |+|---|---|---|---|+| 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` |+| PC right Control | `ctrl_r` | `cmd_r` | `ctrl_r` |+| PC Windows or Super | `cmd` | `ctrl` | `cmd` |+| PC right Windows or Super | `cmd_r` | `ctrl_r` | `cmd_r` |+| PC Alt | `alt` | `alt` | `alt` |+| PC right Alt or AltGr | `alt_r` | `alt_r` | `alt_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.+- 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.+- 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 until its id is learnt. 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 not+ counted, because it fires on a dwell and 1.4.x let it stand beside the edge. 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`.+- **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.++**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",+ "shortcut_arrival": true, "shortcut_arrival_style": "match"}}}+```++- `on` is a boolean, `set_at` an integer of unix seconds, `by` the machine that made the change.+ `crossing` and `design` are present only when `on` is true.+- The values, each left out by a receiver that cannot hold it, the rest still applied:++ | 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.++## 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 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`.++## 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).++## Decided++Decided on 30-09-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; the empty-id lookup is gone, since a migrated+ token has a key id from the start; key ids are unique across entries; typed tokens must be+ paired again (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.** Follows from 1: 1.5.0 has no token field, and a migrated typed token+ never links; 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).++## 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 --git a/core/keytable.py b/core/keytable.pynew file mode 100644index 0000000..4de3b0c--- /dev/null+++ b/core/keytable.py@@ -0,0 +1,81 @@+"""The key table of WIRE.md section 7: which wire name a physical key sends to a peer.++Pure. A physical name says which key was pressed on the sender's own keyboard, not what 1.4.x's+Windows capture called it: "ctrl" is the Control key and "cmd" the Command, Windows or Super key,+each with an "_r" for the right-hand one. Everything else goes out as itself."""++from typing import Mapping, Optional, Union++MAC_PLATFORMS = frozenset({"macos", "ios"})++STYLES = ("semantic", "positional")++# Across families, Semantic: the everyday shortcuts line up (Command-C arrives as Control-C).+# 1.4.x's DEFAULT_KEY_MAP on the Mac and the Windows capture names on Windows.+_MAC_SEMANTIC = {"ctrl": "cmd", "ctrl_r": "cmd", "cmd": "ctrl", "cmd_r": "ctrl", "alt": "alt", "alt_r": "alt"}+_MAC_POSITIONAL = {"ctrl": "ctrl", "ctrl_r": "ctrl", "cmd": "cmd", "cmd_r": "cmd", "alt": "alt", "alt_r": "alt"}+_PC_SEMANTIC = {"ctrl": "cmd", "ctrl_r": "cmd_r", "cmd": "ctrl", "cmd_r": "ctrl_r"}+_PC_POSITIONAL: dict = {}++_ACROSS = {+ (True, "semantic"): _MAC_SEMANTIC,+ (True, "positional"): _MAC_POSITIONAL,+ (False, "semantic"): _PC_SEMANTIC,+ (False, "positional"): _PC_POSITIONAL,+}+++def is_mac(platform: str) -> bool:+ return platform in MAC_PLATFORMS+++def wire_name(physical: str, own_platform: str, peer_platform: str, style: Union[str, Mapping[str, str]]) -> str:+ """The name `physical` travels as from `own_platform` to `peer_platform`.++ `style` is "semantic" or "positional", or a map a user wrote by hand (the Mac's `key_map`),+ which applies across families only."""+ own_mac = is_mac(own_platform)+ if isinstance(style, str):+ if style not in STYLES:+ raise ValueError(f"key style must be one of: {', '.join(STYLES)}")+ table = _ACROSS[(own_mac, style)]+ else:+ table = style+ if own_mac == is_mac(peer_platform):+ return physical+ return table.get(physical, physical)+++# A Linux sender reads evdev codes (linux/input-event-codes.h). Modifiers first, then the named+# keys of section 7 that have a code. The numpad Enter is `enter`, so two codes share it.+EVDEV_NAMES = {+ 29: "ctrl", 97: "ctrl_r",+ 125: "cmd", 126: "cmd_r",+ 56: "alt", 100: "alt_r",+ 42: "shift", 54: "shift_r",+ 58: "caps_lock",+ 14: "backspace", 15: "tab", 28: "enter", 96: "enter", 1: "esc", 57: "space",+ 111: "delete", 110: "insert", 102: "home", 107: "end", 104: "page_up", 109: "page_down",+ 105: "left", 106: "right", 103: "up", 108: "down",+ 127: "menu", 99: "print_screen", 119: "pause", 69: "num_lock", 70: "scroll_lock",+ 158: "browser_back", 159: "browser_forward",+ 113: "volume_mute", 114: "volume_down", 115: "volume_up",+ 163: "media_next", 165: "media_prev", 166: "media_stop", 164: "media_play_pause",+}+EVDEV_NAMES.update({59 + i: f"f{i + 1}" for i in range(10)})+EVDEV_NAMES.update({87: "f11", 88: "f12"})+EVDEV_NAMES.update({183 + i: f"f{13 + i}" for i in range(12)})++SPEC_NAMES = frozenset(+ {"shift", "shift_r", "ctrl", "ctrl_r", "alt", "alt_r", "cmd", "cmd_r", "caps_lock",+ "backspace", "tab", "enter", "esc", "space", "delete", "insert", "home", "end", "page_up", "page_down",+ "left", "right", "up", "down", "menu", "print_screen", "pause", "num_lock", "scroll_lock",+ "browser_back", "browser_forward",+ "volume_mute", "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause"}+ | {f"f{i}" for i in range(1, 25)}+)+++def evdev_physical(code: int) -> Optional[str]:+ """The physical name of an evdev key code, or None for a character key or a code with no name."""+ return EVDEV_NAMES.get(code)diff --git a/core/link.py b/core/link.pynew file mode 100644index 0000000..c36b0e2--- /dev/null+++ b/core/link.py@@ -0,0 +1,815 @@+"""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)`;+`notice(text)` for the one-time notice a migrated pairing gives."""++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,+ notice=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, notice)+ 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._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):+ host, port = entry.get("host"), entry.get("port")+ if 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) if self.key_id is not None else None+ 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 _notify(self, text):+ callback = self._callbacks[3]+ if callback is None or self._muted:+ return+ try:+ callback(text)+ except Exception:+ LOGGER.exception("notice 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, saved = 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")+ if outcome == receiver.FOLDED:+ shown = saved.get("name") or host+ old = saved["folded"].get("name") or "unnamed"+ self._notify(f"{shown} linked from {host} under its Beamer 1.4 pairing, {old}, which is now part of {shown}.")+ raise LinkEnded(f"{shown} is paired again; the earlier pairing was folded into it", "removed")+ if outcome == receiver.FIRST_LINK:+ self._notify(f"Linked with {welcome['name']} at {host} for the first time on Beamer 1.5.0.")+ 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+ 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+ 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` and `address`. 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."""+ 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 entry.get("send") is not True or not entry.get("name"):+ return+ address = next((m["address"] for m in machines if m.get("name") == entry["name"] and m.get("address") and m["address"] != entry.get("host")), None)+ if address is None:+ return+ self._followed_at = now+ 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 --git a/core/owner.py b/core/owner.pynew file mode 100644index 0000000..5e97d54--- /dev/null+++ b/core/owner.py@@ -0,0 +1,408 @@+"""The owner: where this machine's input goes, as WIRE.md sections 4 and 5 describe it.++Pure, with no sockets, no threads, no platform code and no `time`: the clock is passed in, so the+same machine serves the Mac, Windows, Linux and (ported) the phones, and every routing rule is+tested without a link. The app feeds it events and carries out the actions each one returns, in+order:++- `go(peer, edge, offset)`: this machine's own zone, shortcut or menu picks a peer, or home+ (`None` or this machine's id).+- `switch`, `accept`, `refuse` and `accepts`: those messages' `data` from a peer, already+ validated by the protocol layer.+- `link_up(peer, accepts)` once a link's handshake is done (`accepts` from its `welcome`), and+ `link_down(peer)` when it ends for any reason, its watchdog and a failed send included.+- `input(message)`: every input message this machine captures (`keydown`, `mousemove`, ...),+ without a `seq`; the link adds that.+- `clipboard_changed()` when this machine's clipboard changes by its own hand (never when it is+ set from a peer), and `clipboard_arrived(peer, began_at, message)` for a peer's `clipboard`.+- `tick()` at `deadline()`, or at any time: the one-second waits and the three seconds a peer that+ could not be reached is left out of `reach`.++The actions: `Send` a message on the link this machine opened to a peer; `SendClipboard` (this+machine's clipboard, to that peer); `SetClipboard` (here); `Moved` (the input is now on a peer, or+home, and why, which is what the app captures, lands and says by); `Unreachable` (a hand-over+that did not happen, to say so); and `LOCAL` (let this input event through on this machine).+An input event that returns nothing is swallowed or held: the app suppresses it.++`away` is what the responder's `busy` refusal asks: true from the moment a take is sent until it+is refused, times out or is let go.+"""++from dataclasses import dataclass+from typing import Optional++TAKE_WAIT = 1.0 # seconds a take waits for its `accept`+LEFT_OUT = 3.0 # seconds a peer that did not take a hand-over stays out of `reach`+CLIPBOARD_AFTER = 10.0 # seconds after a let-go that the machine let go may send its clipboard+TAKE_MEMORY = 30.0 # seconds a take is remembered, so a late `accept` can still be let go+REFUSALS = ("owned", "not_allowed", "busy", "sent_home", "malformed")++_DOWNS = {"keydown": "keyup", "mousedown": "mouseup"}+_UPS = ("keyup", "mouseup")+++@dataclass(frozen=True)+class Send:+ peer: str+ message: dict+++@dataclass(frozen=True)+class SendClipboard:+ peer: str+++@dataclass(frozen=True)+class SetClipboard:+ message: dict+++@dataclass(frozen=True)+class Moved:+ to: Optional[str] # None: home+ left: Optional[str] # the machine the input left, None when it left home+ why: str # "asked", "switch", a refusal's `why`, "refused", "no_answer", "link_lost"+ edge: Optional[str] = None # where to land the pointer, when the move says+ offset: Optional[float] = None+++@dataclass(frozen=True)+class Unreachable:+ peer: str+ why: str # a refusal's `why`, "refused", "no_answer", "link_lost", "unreachable"+++@dataclass(frozen=True)+class Local:+ pass+++LOCAL = Local()+++@dataclass+class _Wait:+ """A take this machine is waiting on an answer for."""+ peer: str+ route: int+ due: float+ chain: bool # a hand-over from the machine the input is on, holding the input+ reach: list+ edge: Optional[str] = None+ offset: Optional[float] = None+++def _ident(message):+ """What a press is known by, so its release can be matched: the key's name or the button."""+ kind, data = message.get("type"), message.get("data") or {}+ if kind in ("keydown", "keyup"):+ return ("key", data.get("key"))+ if kind in ("mousedown", "mouseup"):+ return ("button", data.get("button"))+ return None+++def _release(message):+ return {"type": _DOWNS[message["type"]], "data": dict(message["data"])}+++class Owner:+ def __init__(self, own_id, clock, resistance_px=120):+ self.own_id = own_id+ self.resistance_px = resistance_px # None for a phone, which has no hand at an edge+ self.route = 0+ self.on = None # the peer this machine's input is on, None at home+ self.reach_sent = [] # the `reach` last sent there+ self._clock = clock+ self._visit_route = 0 # the route of the take that began the current visit+ self._links = set()+ self._accepting = set()+ self._wait = None+ self._held = []+ self._left_out = {} # peer: until when+ self._takes = {} # route: (peer, when sent)+ self._pressed = {} # peer: {ident: the release}, in the order pressed+ self._swallow = set() # presses whose physical release goes nowhere+ self._here = set() # presses let through here, whose release is let through too+ self._let_go = {} # peer: when it was let go, for its one clipboard+ self._clipboard_at = set() # peers known to hold this machine's clipboard as it is++ @property+ def away(self):+ return self.on is not None++ def deadline(self):+ times = list(self._left_out.values())+ if self._wait is not None:+ times.append(self._wait.due)+ return min(times) if times else None++ def reach_for(self, target):+ now = self._clock()+ return sorted(peer for peer in self._links & self._accepting+ if peer not in (target, self.own_id) and self._left_out.get(peer, now) <= now)++ # Links++ def link_up(self, peer, accepts):+ # A second link from a peer replaces the first, and ends its ownership there.+ actions = self.link_down(peer) if peer in self._links else []+ self._links.add(peer)+ self._set_accepting(peer, accepts)+ return actions + self._refresh_reach()++ def accepts(self, peer, accepts):+ if peer not in self._links:+ return []+ self._set_accepting(peer, accepts)+ return self._refresh_reach()++ def link_down(self, peer):+ self._links.discard(peer)+ self._accepting.discard(peer)+ if peer == self.on:+ return self._come_home("link_lost")+ if self._wait is not None and self._wait.chain and self._wait.peer == peer:+ return self._not_taken(peer, "link_lost")+ self._forget_pressed(peer)+ return self._refresh_reach()++ def _set_accepting(self, peer, accepts):+ if accepts:+ self._accepting.add(peer)+ else:+ self._accepting.discard(peer)++ # Moves++ def go(self, peer, edge=None, offset=None):+ if peer is None or peer == self.own_id:+ return self._come_home("asked") if self.on is not None else []+ if peer == self.on:+ if self._wait is not None and self._wait.chain:+ # The machine being left disarmed its zones for the hand-over: re-arm it.+ self._wait = None+ return self._stay() + self._replay_held()+ return []+ if peer not in self._links & self._accepting:+ return [Unreachable(peer, "unreachable")]+ left = self.on+ self._wait = None+ self.route += 1+ actions = self._let_go_of(left, peer) if left is not None else []+ actions += self._take(peer, edge, offset, chain=False)+ self._arrive(peer, self._wait.reach)+ actions += self._clipboard_to(peer)+ actions.append(Moved(peer, left, "asked", edge, offset))+ return actions + self._replay_held()++ def switch(self, peer, data):+ if peer != self.on:+ return []+ route, nxt = data.get("route"), data.get("next")+ edge, offset = data.get("edge"), data.get("offset")+ if nxt == self.own_id:+ if not isinstance(route, int) or route < self._visit_route:+ return []+ return self._come_home("switch", edge, offset)+ if route != self.route or (self._wait is not None and self._wait.chain):+ return []+ if nxt not in self.reach_sent or nxt not in self._links & self._accepting:+ return self._not_taken(nxt, "unreachable")+ self.route += 1+ return self._take(nxt, edge, offset, chain=True)++ def accept(self, peer, data):+ route = data.get("route")+ took = self._takes.get(route)+ if took is None or took[0] != peer:+ return []+ wait = self._wait+ if wait is not None and wait.peer == peer and wait.route == route:+ self._wait = None+ if not wait.chain:+ return []+ left = self.on+ actions = self._let_go_of(left, peer)+ self._arrive(peer, wait.reach)+ actions += self._clipboard_to(peer)+ actions.append(Moved(peer, left, "switch", wait.edge, wait.offset))+ return actions + self._replay_held() + self._refresh_reach()+ if peer == self.on:+ return []+ # It took this machine's input after the wait for it ended: let it go again.+ return [Send(peer, {"type": "focus", "data": {"route": self.route, "target": self.on or self.own_id}})]++ def refuse(self, peer, data):+ route = data.get("route")+ why = data.get("why") if data.get("why") in REFUSALS else "refused"+ wait = self._wait+ if wait is not None and wait.chain:+ if peer == wait.peer and route == wait.route:+ return self._not_taken(peer, why)+ return []+ # The take's own route too: a re-arm sent before its answer came raised the route past it.+ if peer == self.on and (route == self.route or (wait is not None and route == wait.route)):+ return self._come_home(why)+ return []++ def tick(self):+ now = self._clock()+ actions = []+ wait = self._wait+ if wait is not None and now >= wait.due:+ if wait.chain:+ actions += self._not_taken(wait.peer, "no_answer")+ else:+ actions += self._come_home("no_answer")+ expired = [peer for peer, until in self._left_out.items() if until <= now]+ for peer in expired:+ del self._left_out[peer]+ if expired:+ actions += self._refresh_reach()+ return actions++ # Input++ def input(self, message):+ kind, ident = message.get("type"), _ident(message)+ if ident in self._here:+ # Pressed while the input was here, so released here, never held for a hand-over:+ # a held event cannot be let through later.+ if kind in _UPS:+ self._here.discard(ident)+ return [LOCAL]+ return [LOCAL] if self.on is None else []+ if self._wait is not None and self._wait.chain:+ self._held.append(message)+ return []+ return self._route(message, replay=False)++ def _route(self, message, replay):+ kind, ident = message.get("type"), _ident(message)+ if ident in self._swallow:+ if kind in _UPS:+ self._swallow.discard(ident)+ return []+ if self.on is None:+ if not replay:+ if kind in _DOWNS:+ self._here.add(ident)+ return [LOCAL]+ # Held for a hand-over that ended at home: the event cannot be given back, so a press+ # goes nowhere and so does its release.+ if kind in _DOWNS:+ self._swallow.add(ident)+ return []+ pressed = self._pressed.setdefault(self.on, {})+ if kind in _DOWNS:+ pressed[ident] = _release(message)+ elif kind in _UPS:+ pressed.pop(ident, None)+ return [Send(self.on, message)]++ def _replay_held(self):+ held, self._held = self._held, []+ return [action for message in held for action in self._route(message, replay=True)]++ # Clipboard++ def clipboard_changed(self):+ self._clipboard_at = set()++ def clipboard_arrived(self, peer, began_at, message):+ let_go = self._let_go.pop(peer, None)+ if let_go is None or began_at - let_go > CLIPBOARD_AFTER:+ return []+ self._clipboard_at = {peer}+ actions = [SetClipboard(message)]+ if self.on is not None:+ self._clipboard_at.add(self.on)+ actions.append(Send(self.on, message))+ return actions++ def expects_clipboard(self, peer, began):+ """Whether a frame from `peer` that began at `began` could be the one clipboard of its let-go,+ by `clipboard_arrived`'s own rule, however long it then took to arrive. A link asks this,+ without the app's lock, before it reads a frame too large for any other message."""+ let_go = self._let_go.get(peer)+ return let_go is not None and began - let_go <= CLIPBOARD_AFTER++ def _clipboard_to(self, peer):+ if peer in self._clipboard_at:+ return []+ self._clipboard_at.add(peer)+ return [SendClipboard(peer)]++ # The pieces++ def _take(self, peer, edge, offset, chain):+ reach = self.reach_for(peer)+ data = {"route": self.route, "target": peer}+ if edge is not None:+ data["edge"], data["offset"] = edge, offset+ if self.resistance_px is not None:+ data["resistance_px"] = self.resistance_px+ data["reach"] = reach+ now = self._clock()+ for route in [route for route, (_, when) in self._takes.items() if now - when > TAKE_MEMORY]:+ del self._takes[route]+ self._takes[self.route] = (peer, now)+ self._wait = _Wait(peer, self.route, now + TAKE_WAIT, chain, reach, edge, offset)+ return [Send(peer, {"type": "focus", "data": data})]++ def _arrive(self, peer, reach):+ self.on = peer+ self.reach_sent = reach+ self._visit_route = self.route++ def _let_go_of(self, peer, target):+ """The owner's releases of everything it pressed there, then the let-go `focus`."""+ pressed = self._pressed.pop(peer, {})+ self._swallow.update(pressed)+ self._let_go[peer] = self._clock()+ return [Send(peer, release) for release in pressed.values()] + [+ Send(peer, {"type": "focus", "data": {"route": self.route, "target": target}})]++ def _forget_pressed(self, peer):+ self._swallow.update(self._pressed.pop(peer, {}))++ def _come_home(self, why, edge=None, offset=None):+ left = self.on+ if self._wait is not None and not self._wait.chain:+ # Never taken: a clipboard sent after the take was dropped there.+ self._clipboard_at.discard(left)+ self._wait = None+ self.route += 1+ if left in self._links:+ actions = self._let_go_of(left, self.own_id)+ else:+ self._forget_pressed(left)+ actions = []+ self.on = None+ self.reach_sent = []+ actions.append(Moved(None, left, why, edge, offset))+ return actions + self._replay_held()++ def _not_taken(self, peer, why):+ """A hand-over from the machine the input is on did not happen: re-arm it without `peer`."""+ self._wait = None+ if peer is not None:+ self._left_out[peer] = self._clock() + LEFT_OUT+ return self._stay() + [Unreachable(peer, why)] + self._replay_held()++ def _stay(self):+ self.route += 1+ self.reach_sent = self.reach_for(self.on)+ data = {"route": self.route, "target": self.on, "stay": True}+ if self.resistance_px is not None:+ data["resistance_px"] = self.resistance_px+ data["reach"] = self.reach_sent+ return [Send(self.on, {"type": "focus", "data": data})]++ def _refresh_reach(self):+ if self.on is None or (self._wait is not None and self._wait.chain):+ return []+ if self.reach_for(self.on) == self.reach_sent:+ return []+ return self._stay()diff --git a/core/pairing.py b/core/pairing.pyindex 52196d6..05709f9 100644--- a/core/pairing.py+++ b/core/pairing.py@@ -1,5 +1,4 @@-"""LAN discovery and pairing, shared by mac_app and win_app (two identical copies; the Mac-test suite checks they match byte for byte).+"""LAN discovery and pairing, shared by both apps.The host (the PC) broadcasts a small UDP beacon -- hostname, Beamer TCP port, and a randompairing id while a code is on screen -- and the requester (the Mac) lists what it hears. Pairing@@ -41,18 +40,31 @@ What this protects against, and what it does not:code it depends on is single-use and lives a minute, so there is one computation to time percode on the PC and one per attempt on the Mac, and the PC's answer leaves a fixed time afterthe 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 annotationsimport base64+import contextlibimport hashlibimport hmac+import ipaddressimport jsonimport logging+import osimport queueimport secretsimport socket+import structimport threadingimport time@@ -112,7 +124,33 @@ MSG_FIND = "find"ERROR_NOT_PAIRING = "not_pairing"ERROR_REFUSED = "refused"ERROR_VERSION = "version"-_ERRORS = (ERROR_NOT_PAIRING, ERROR_REFUSED, ERROR_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@@ -133,6 +171,16 @@ 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))@@ -205,17 +253,23 @@ def _session_id(pair_id: str, nonce: bytes) -> bytes:return _lv_cat(pair_id.encode("utf-8"), nonce)-def _party(role: bytes, identity: bytes, name: str) -> bytes:+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."""- return _lv_cat(role, identity, name.encode("utf-8"))+ 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) -> bytes:- return _x25519(scalar, _generator(code.encode("utf-8"), CHANNEL, sid))+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) -> tuple:+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 arethe 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()@@ -224,7 +278,99 @@ def _keys(sid: bytes, shared: bytes, ya: bytes, ada: bytes, yb: bytes, adb: bytedef 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))+ 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,+ "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."""+ if theirs == own:+ return True, None+ wanted = _b64(theirs)+ for known in peers:+ if known.get("id") != wanted:+ continue+ 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):+ """The entry migrated from 1.4.x (`id: ""`) that a fresh pairing with the machine at `address`+ replaces, or None: left beside the new entry, its first link would be answered wrong_id.+ ⚠ Matched by its saved host alone, never by name: a name is whatever the pairing machine+ chose, so anyone who saw the code could otherwise evict a 1.4.x pair that still links."""+ if not address:+ return None+ for known in peers:+ if known.get("id") == "" and known.get("from_1_4") is True and known.get("host") == address:+ 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:@@ -264,29 +410,109 @@ def beacon_msg(name: str, port: int, pair_id: str = None) -> dict:return message-class PairingHost:- """The PC's half: holds at most one live code and answers the exchange. Pure -- the- Announcer owns the socket, and the clock and the randomness are injected for the tests and- the vectors."""+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 __init__(self, clock=time.monotonic, name: str = "", identity: bytes = b"", entropy=secrets.token_bytes):++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 = clockself.name = name[:MAX_NAME_CHARS]self.identity = identityself._entropy = entropy+ self.version = version+ self.platform = platform+ self.port = port+ self._peers = peers or list+ self.store = store+ self.wall = wallself.code = Noneself.pair_id = Noneself.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 = Noneself._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" -- for the- # window to say so; None while a code is live or after a deliberate cancel.+ # 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@propertydef active(self) -> bool:@@ -302,26 +528,49 @@ class PairingHost: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 Noneself.expires_at = self.clock() + CODE_LIFETIME_SECONDSself._bound = Noneself._last = Noneself.fresh_answer = Falseself.outcome = None+ self.known = Nonereturn self.codedef cancel(self) -> None:self.code = Noneself.pair_id = None+ self.qr_secret = Noneself.expires_at = 0.0self._bound = Noneself.outcome = None- def handle(self, message: dict):- """The reply to one datagram, or None when it deserves no answer. A successful pairing- leaves the token in `self.paired` as (token, requester_name); the caller stores it."""+ 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@@ -329,15 +578,17 @@ class PairingHost:if not isinstance(pair_id, str) or not pair_id.isascii() or not 0 < len(pair_id) <= MAX_PAIR_ID_CHARS:return Noneif kind == MSG_PAIR_START:- return self._start(message, pair_id)+ return self._start(message, pair_id, address, via)if kind == MSG_PAIR_CONFIRM:- return self._confirm(message, pair_id)+ 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) -> dict:- sent = [message.get(field) for field in ("pair", "v", "nonce", "share", "name", "id")]+ 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.@@ -351,13 +602,19 @@ class PairingHost:# 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)- if message.get("v") != PAIRING_VERSION:+ 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_BYTESor len(share) != SHARE_BYTES@@ -366,20 +623,30 @@ class PairingHost: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)- requester = _party(ROLE_REQUESTER, identity, name)- host = _party(ROLE_HOST, self.identity, self.name)# 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)+ 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, 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 = Trueanswer = {"type": MSG_PAIR_ANSWER,@@ -390,6 +657,9 @@ class PairingHost:"name": self.name,"id": _b64(self.identity),}+ if self.v3:+ answer["platform"] = self.platform+ answer["port"] = self.portself._bound = {"sent": sent,"answer": answer,@@ -397,23 +667,66 @@ class PairingHost:"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) -> dict:- sent = [pair_id, message.get("tag")]+ 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 Nonetry:tag = _unb64(message.get("tag"))except PairingError:tag = b""if not hmac.compare_digest(tag, bound["requester_tag"]):- return self._end(MSG_PAIR_DONE, sent, pair_id, ERROR_REFUSED, "refused")+ # 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"])+ 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()@@ -438,39 +751,72 @@ class PairingHost:class PairingClient:- """The Mac's half of one attempt: builds the start, checks the answer, confirms, and yields- the token once the host says it has stored it."""-- def __init__(self, pair_id: str, code: str, name: str, identity: bytes = b"", entropy=secrets.token_bytes):+ """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_idself.name = name[:MAX_NAME_CHARS]self.identity = identity+ self.platform = platform+ self.port = port+ self.qr_secret = qr_secretself._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)+ self._share = _share(code, self._sid, self._scalar, CHANNEL_V3 if self.v3 else CHANNEL, qr_secret or b"")self._answered = False+ self._known = Falseself._token = Noneself._done_tag = None# The host's name and identity as the exchange bound them; None until its tag checks out.self.host_name = Noneself.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_V3def start(self) -> dict:- return {+ message = {"type": MSG_PAIR_START,"pair": self.pair_id,- "v": PAIRING_VERSION,+ "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 messagedef accept(self, answer: dict) -> dict:"""The pair_confirm to send back, or PairingError naming why not. It judges one answerand no more: each answer it judged would be another guess at the code for whoever is- answering."""+ 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:@@ -483,30 +829,52 @@ class PairingClient: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)- requester = _party(ROLE_REQUESTER, self.identity, self.name)- host = _party(ROLE_HOST, identity, name)+ 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, 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 excif not hmac.compare_digest(tag, host_tag):raise PairingError(ERROR_REFUSED)+ if self.v3:+ self._check_host(identity, name, platform)self._token = tokenself._done_tag = done_tagself.host_name = nameself.host_identity = identity+ self.host_platform = platform+ self.host_port = portreturn {"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 PC+ """What to send a host whose answer failed: a confirmation that cannot pass, so the hostdrops the code and says a wrong one was entered instead of showing it for the rest of- its minute."""- return {"type": MSG_PAIR_CONFIRM, "pair": self.pair_id, "tag": ""}+ 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 messagedef finish(self, done: dict) -> str:- """The agreed token, once the host's pair_done proves it stored the same one."""+ """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:@@ -517,8 +885,15 @@ class PairingClient:raise PairingError(ERROR_REFUSED) from excif 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 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)@@ -584,6 +959,22 @@ 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@@ -647,19 +1038,7 @@ class Announcer:@staticmethoddef _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+ return _due(last, host, now)def _run(self) -> None:try:@@ -714,7 +1093,8 @@ class Announcer:if message is None:continueif message.get("type") == MSG_FIND:- # At most one answer per address per interval, so the port is no amplifier.+ # 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)@@ -842,7 +1222,13 @@ class Discovery:raise PairingError(ERROR_VERSION)if not isinstance(pc.get("pair_id"), str):raise PairingError(ERROR_NOT_PAIRING)- target = (pc["address"], pc["reply_port"])+ 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.@@ -857,32 +1243,37 @@ class Discovery:# second guess. It is the code that is remembered, not the pairing id, which a# beacon can forge.raise PairingError(ERROR_REFUSED)- client = PairingClient(pc["pair_id"], code, name or machine_name())- while True:- try:- self._replies.get_nowait()- except queue.Empty:- break- self._awaiting = (target[0], client.pair_id)- answer = self._ask(sock, target, client.pair_id, client.start(), MSG_PAIR_ANSWER)- try:- confirm = client.accept(answer)- except PairingError:- # Only an answer that claimed to be good can have tested a guess. A refusal- # tests nothing, and a stale pairing id draws one from an honest PC.- if answer.get("ok") is True:- self._failed[code] = self.clock() + FAILED_CODE_SECONDS- try:- sock.sendto(encode(client.abort()), target)- except OSError:- pass- raise- token = client.finish(self._ask(sock, target, client.pair_id, confirm, MSG_PAIR_DONE))- return token, client.host_name+ yieldfinally:self._awaiting = Noneself._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 = (target[0], client.pair_id)+ answer = self._ask(sock, target, client.pair_id, client.start(), MSG_PAIR_ANSWER)+ confirm = self._judge(client, answer, code, lambda abort: sock.sendto(encode(abort), target))+ return client.finish(self._ask(sock, target, client.pair_id, confirm, MSG_PAIR_DONE))+def _ask(self, sock, target, pair_id: str, message: dict, reply_type: str) -> dict:"""Sends one datagram until the first reply of `reply_type` from `target` comes back.The first one decides: the caller judges it and never waits for a better one."""@@ -965,18 +1356,23 @@ class Discovery: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+ return Nonetry:name.encode("utf-8")except UnicodeError:# Half a surrogate pair is JSON a parser accepts and text no window can show.- return- entry = {+ return None+ return {"name": name[:64] or address[0],"address": address[0],"port": port,@@ -986,6 +1382,8 @@ class Discovery:"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@@ -1001,3 +1399,562 @@ class Discovery:wanted = self._finding[0] if self._finding else Nonedel 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_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._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 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):+ sock.sendto(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:+ sock.sendto(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._awaiting == (address[0], message.get("pair")):+ try:+ self._replies.put_nowait((message, address))+ except queue.Full:+ pass++ 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)+ 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 --git a/core/peerlist.py b/core/peerlist.pynew file mode 100644index 0000000..fb7bb9c--- /dev/null+++ b/core/peerlist.py@@ -0,0 +1,149 @@+"""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 _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."""+ 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 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."""+ 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+ an id no entry has any more go with it, as the entry migrated from 1.4.x's do (`id` empty); a+ machine paired again under its own id keeps its zones."""+ 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+ _drop_orphan_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 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 --git a/core/protocol.py b/core/protocol.pyindex 426f286..47f62fc 100644--- a/core/protocol.py+++ b/core/protocol.py@@ -1,26 +1,18 @@-"""Wire protocol shared by mac_app/bridge.py and win_app/receiver.py.--The link is encrypted and authenticated with ChaCha20-Poly1305; the shared-token never crosses the wire, and a peer that cannot produce a valid tag does-not hold it.--A connection opens with one cleartext preamble each way -- WIRE_MAGIC, one-version byte, and that side's 8-byte nonce prefix, drawn fresh per connection--- so a version mismatch produces a readable status instead of undecryptable-garbage. Each direction then has its own key, HKDF-SHA256 over the token with-the sender's prefix and the receiver's prefix in `info`, so nothing is sealed-until the peer's preamble is in. Every frame after that is a 4-byte big-endian-length, then a 4-byte big-endian counter, then the ciphertext with its tag; the-length covers the counter and ciphertext. The nonce is prefix + counter, each-side counting its own frames from 1, and the receiver rejects any counter that-is not the next one.--What that stops: a frame played again, dropped or reordered inside a-connection fails the counter; a whole recorded connection played into a new-one fails the tag, because the receiver's fresh prefix is part of the key its-peer had to seal under; a side's own frames reflected back fail the tag,-because the two directions' keys differ. What it does not give is forward-secrecy: anyone who later learns the token can read a recording made before.+"""The link's wire, version 6 (WIRE.md is the specification): the handshake, the keys, the+frames, and a builder and a validator for every message, shared by both apps' initiator+(core/link.py) and responder (core/receiver.py).++A connection opens with one cleartext preamble each way: WIRE_MAGIC, the version byte, that side's+8-byte nonce prefix drawn fresh per connection, the pair's key id and an ephemeral X25519 share.+Each direction's key is HKDF-SHA256 over the pairing token and the X25519 result, bound to both+preambles and the direction, so a recording cannot be read later even by someone who learns the+token. Every frame after that is a 4-byte big-endian length, a 4-byte big-endian counter, then+ChaCha20-Poly1305 ciphertext with its tag; the nonce is prefix + counter, each side counting its+own frames from 1, and the receiver rejects any counter that is not the next one.++Version 5 (Beamer 1.4.x) is no longer spoken. Its preamble is still read far enough to refuse it+in words the older peer shows (the short reply); core/tests/v5_link.py keeps a frozen copy for the+vector replay and the refusal tests."""import base64@@ -28,7 +20,9 @@ import binasciiimport hashlibimport hmacimport json+import mathimport os+import reimport socketimport structimport threading@@ -38,6 +32,8 @@ from nacl.bindings import (crypto_aead_chacha20poly1305_ietf_ABYTES,crypto_aead_chacha20poly1305_ietf_decrypt,crypto_aead_chacha20poly1305_ietf_encrypt,+ crypto_scalarmult,+ crypto_scalarmult_base,)from nacl.exceptions import CryptoError@@ -48,10 +44,9 @@ MAX_COUNTER = 0xFFFFFFFF# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing# pairing and a mixed-version pair for no gain.WIRE_MAGIC = b"BEAMY"-PREAMBLE_SIZE = len(WIRE_MAGIC) + 1 + NONCE_PREFIX_SIZE-# 5: per-connection keys bound to both prefixes (1.4.1). 4 keyed every connection alike from the-# token, so a recorded connection could be played into a new one whole.-PROTOCOL_VERSION = 5+# 6: the key id and an ephemeral X25519 share in the preamble, keys with forward secrecy (1.5.0).+# 5 (1.4.1 to 1.4.x) keyed each connection from the token and both prefixes only.+LINK_VERSION = 6# Both ports sit below 49152 on purpose. Windows and macOS both hand out 49152-65535 as# ephemeral ports, and Windows lets WinNAT reserve whole 100-port blocks from that range that@@ -63,7 +58,6 @@ PAIRING_PORT = 24821# What DEFAULT_PORT used to be. A config still carrying it was never chosen by# anyone, so it is migrated rather than honoured; a port a user picked is left alone.LEGACY_DEFAULT_PORT = 51820-KEY_SALT = b"beamer-link-v5"KEY_INFO = b"beamer-frames"CLIPBOARD_MAX_BYTES = 256 * 1024# The clipboard goes out ahead of the focus message on every switch, sealed as one frame and@@ -78,6 +72,11 @@ CLIPBOARD_IMAGE_PNG = "png"# back on the reply stream. A 1MB cap there dropped the link on every return with a screenshot on# the clipboard.MAX_FRAME_BYTES = 16 * 1024 * 1024+# A message that is not a clipboard fits in far less. The largest is `text`: 4096 bytes of UTF-8,+# which as JSON escapes is at most 6 bytes a character, about 24 KiB; hello, welcome, settings,+# focus and paired are each a few KiB at most. A frame over this from a peer that may not send a+# clipboard is authenticated, so the counter stays in step, but never parsed.+SMALL_MESSAGE_BYTES = 64 * 1024# The first frame each way is a hello or a welcome of a few dozen bytes. Anything larger before# authentication is not a Beamer, so it is refused before it is read.HELLO_MAX_BYTES = 4096@@ -141,8 +140,8 @@ class VersionMismatch(ProtocolError):when the peer sent no preamble at all -- an older Beamer that opened with alength-prefixed cleartext frame instead."""- def __init__(self, peer_version):- super().__init__(f"peer speaks wire version {peer_version!r}, expected {PROTOCOL_VERSION}")+ def __init__(self, peer_version, expected=LINK_VERSION):+ super().__init__(f"peer speaks wire version {peer_version!r}, expected {expected}")self.peer_version = peer_version@@ -152,96 +151,6 @@ def hkdf_sha256(key_material: bytes, salt: bytes, info: bytes) -> bytes:return hmac.new(extracted, info + b"\x01", hashlib.sha256).digest()-def derive_key(token: str, sender_prefix: bytes, receiver_prefix: bytes) -> bytes:- """The key for the frames one side seals and the other opens, on one- connection only: both prefixes are drawn fresh per connection, and their- order is the direction."""- return hkdf_sha256(token.encode("utf-8"), KEY_SALT, KEY_INFO + bytes(sender_prefix) + bytes(receiver_prefix))---class SecureSession:- """One connection's cipher state for both directions. Build a new one per- connection: it draws a fresh nonce prefix and starts both counters at zero.- Neither key exists until accept_preamble, so nothing can be sealed or- opened before the peer's prefix is known.- `send_lock` serialises sealing, and send_msg holds it across the write too,- so counters are never reused and frames reach the wire in counter order;- `open` is expected to run on a single reader thread per connection."""-- def __init__(self, token: str, prefix: bytes = None):- self._token = token- self.prefix = os.urandom(NONCE_PREFIX_SIZE) if prefix is None else bytes(prefix)- if len(self.prefix) != NONCE_PREFIX_SIZE:- raise ValueError("nonce prefix must be 8 bytes")- self.send_lock = threading.RLock()- self._send_counter = 0- self._send_key = None- self.peer_prefix = None- self._recv_key = None- self._recv_counter = 0-- def preamble(self) -> bytes:- return WIRE_MAGIC + bytes([PROTOCOL_VERSION]) + self.prefix-- def accept_preamble(self, data: bytes) -> None:- if len(data) != PREAMBLE_SIZE or not data.startswith(WIRE_MAGIC):- raise VersionMismatch(None)- version = data[len(WIRE_MAGIC)]- if version != PROTOCOL_VERSION:- raise VersionMismatch(version)- peer_prefix = data[len(WIRE_MAGIC) + 1:]- if self.peer_prefix is not None:- raise ProtocolError("second preamble on one connection")- # Equal prefixes would make both directions one key.- if peer_prefix == self.prefix:- raise ProtocolError("peer echoed this side's nonce prefix")- with self.send_lock:- self._send_key = derive_key(self._token, self.prefix, peer_prefix)- self._recv_key = derive_key(self._token, peer_prefix, self.prefix)- self.peer_prefix = bytes(peer_prefix)-- def seal(self, msg: dict) -> bytes:- body = json.dumps(msg).encode("utf-8")- with self.send_lock:- if self._send_key is None:- raise ProtocolError("nothing is sealed before the peer's preamble")- if self._send_counter >= MAX_COUNTER:- raise ProtocolError("frame counter exhausted; reconnect")- self._send_counter += 1- counter = struct.pack(">I", self._send_counter)- ciphertext = crypto_aead_chacha20poly1305_ietf_encrypt(body, None, self.prefix + counter, self._send_key)- return struct.pack(">I", COUNTER_SIZE + len(ciphertext)) + counter + ciphertext-- def open(self, body: bytes) -> dict:- if self._recv_key is None:- raise ProtocolError("frame received before the peer's preamble")- if len(body) <= COUNTER_SIZE:- raise ProtocolError("frame too short")- # PyNaCl takes bytes only; any other buffer is copied, and a non-buffer is a TypeError as it- # always was, never a tag failure.- body = bytes(memoryview(body))- (counter,) = struct.unpack(">I", body[:COUNTER_SIZE])- if counter != self._recv_counter + 1:- raise ProtocolError("frame counter did not advance; replay rejected")- sealed = body[COUNTER_SIZE:]- # Shorter than a tag cannot authenticate, and PyNaCl would fail to size its output- # buffer with a ValueError rather than refuse it, so it is refused here first.- if len(sealed) < crypto_aead_chacha20poly1305_ietf_ABYTES:- raise AuthenticationError() from None- try:- plain = crypto_aead_chacha20poly1305_ietf_decrypt(sealed, None, self.peer_prefix + body[:COUNTER_SIZE], self._recv_key)- except CryptoError:- raise AuthenticationError() from None- self._recv_counter = counter- try:- message = json.loads(plain.decode("utf-8"))- except (UnicodeDecodeError, json.JSONDecodeError) as exc:- raise ProtocolError(f"malformed message body: {exc}") from exc- if not isinstance(message, dict):- raise ProtocolError("message body must be a JSON object")- return message--def send_msg(sock: socket.socket, session, msg: dict) -> None:with session.send_lock:sock.sendall(session.seal(msg))@@ -275,50 +184,22 @@ def _recv_exact(sock: socket.socket, n: int, deadline: float = None) -> bytes:return b"".join(chunks)-def recv_preamble(sock: socket.socket, session, deadline: float = None) -> None:- session.accept_preamble(_recv_exact(sock, PREAMBLE_SIZE, deadline))--def recv_msg(sock: socket.socket, session, limit: int = MAX_FRAME_BYTES, deadline: float = None) -> dict:"""`limit` is the most a frame may claim before it is read. The receiverpasses HELLO_MAX_BYTES for the first frame: until that frame's tag hasbeen checked the peer has proved nothing, so it must not be able to makethis side buffer a clipboard-sized frame per connection. `deadline`bounds the whole read the same way, for the same reason."""+ return session.open(recv_frame(sock, limit, deadline))+++def recv_frame(sock: socket.socket, limit: int = MAX_FRAME_BYTES, deadline: float = None) -> bytes:+ """One frame as it came, after its length (held to `limit`) and before it is opened."""header = _recv_exact(sock, HEADER_SIZE, deadline)(length,) = struct.unpack(">I", header)if length < 1 or length > limit:raise ProtocolError(f"invalid message length: {length}")- return session.open(_recv_exact(sock, length, deadline))---def hello_msg(return_edge: str = None, resistance_px: int = None) -> dict:- """The first encrypted frame. It carries no token: decrypting it is the- proof the sender holds the shared secret.-- `return_edge` and `resistance_px` are the same pair a focus message- carries, sent here as well so the receiver knows the way home before the- first crossing rather than after it -- which is what lets the receiver's- own machine push back across that same border unprompted. Both are- omitted when None and unknown keys are ignored, so this needs no version- bump. `settings` says this end keeps settings in step (settings_sync), so an end- holding the switch on can tell an older peer that never will."""- data = {"version": PROTOCOL_VERSION, "settings": 1}- if return_edge is not None:- data["return_edge"] = return_edge- if resistance_px is not None:- data["resistance_px"] = resistance_px- return {"type": MSG_HELLO, "data": data}---def welcome_msg(error: str = None) -> dict:- """Sent by the receiver to confirm authentication and protocol version.- `error` (e.g. "version_mismatch") is set when the sender's declared version- is not supported. `settings` is the hello's: this end keeps settings in step."""- data = {"version": PROTOCOL_VERSION, "settings": 1}- if error is not None:- data["error"] = error- return {"type": MSG_WELCOME, "data": data}+ return _recv_exact(sock, length, deadline)def ping_msg() -> dict:@@ -327,23 +208,6 @@ def ping_msg() -> dict:return {"type": MSG_PING, "data": {}}-def ack_msg(seq: int, locked: bool = False) -> dict:- """Sent by the receiver to acknowledge processed input up to `seq`.- The sender increments `seq` once per outbound input event; the receiver- echoes back the highest `seq` it has processed. Used as a watchdog- heartbeat — if the sender doesn't see an ACK for ~2s while redirecting,- it must force-revert to local input.-- `locked` is set only while Windows is clearing its lock screen, during- which input is being dropped rather than injected. It is omitted when- false, and unknown keys are ignored on both sides, so this stays- compatible in both directions and needs no protocol version bump."""- data = {"seq": seq}- if locked:- data["locked"] = True- return {"type": MSG_ACK, "data": data}--def scroll_msg(dy, dx=0.0, mode: str = "line") -> dict:"""Scroll event. `mode` is "pixel" for continuous trackpad deltas (floatpx) or "line" for discrete wheel clicks. `dx` and `mode` are optional on@@ -353,13 +217,8 @@ def scroll_msg(dy, dx=0.0, mode: str = "line") -> dict:def clipboard_msg(text: str = None, image: bytes = None) -> dict:- """Whatever was on the clipboard at the switch: `text` as before, and an- optional PNG under `image` (base64) with `image_format` naming it. Each- key is omitted when absent. A pre-image receiver ignores the two new keys- and an image-only message (no `text`) the same way it ignores any other- unknown data, so this needs no protocol version bump: SecureSession.open- only requires a JSON object, and neither app validates keys it does not- read."""+ """Whatever was on the clipboard at the switch: `text`, and an optional PNG under `image`+ (base64) with `image_format` naming it. Each key is omitted when absent (WIRE.md section 3)."""data = {}if text is not None:data["text"] = text@@ -390,104 +249,822 @@ def clipboard_image(data) -> bytes:return image-def focus_msg(- target: str,- edge: str = None,- offset: float = None,- return_edge: str = None,- resistance_px: int = None,-) -> dict:- """Sent by the sender to move input. `edge` is the receiver edge being- arrived at and `offset` the fraction along it, both absent when the switch- came from the shortcut rather than a crossing. `return_edge` and- `resistance_px` are sent on every switch to the receiver: they are how it- knows the way home, so nothing about crossing is configured on its side.- `target` names the machine input is moving to, which is the receiver's own- name on the way out and the sender's on the way back. All four are omitted when None, and unknown keys are ignored,- so this needs no protocol version bump."""- data = {"target": target}+def settings_msg(data: dict) -> dict:+ """Same on both machines: whether it is on, its stamp and, while on, the shared values, as+ settings_sync.message_data builds them. Sent on every change while on and announced on every+ new connection; an older Beamer ignores the type."""+ return {"type": MSG_SETTINGS, "data": dict(data)}+++def gesture_msg(name: str) -> dict:+ """One completed system gesture (a GESTURE_* name). Unknown message types are+ ignored by the receiver, so this needs no protocol version bump."""+ return {"type": MSG_GESTURE, "data": {"name": name}}+++LINK_SALT = b"beamer-link-v6"+KEY_ID_INFO = b"beamer-key-id"+KEY_ID_SIZE = 16+MACHINE_ID_SIZE = 16+SHARE_SIZE = 32+TOKEN_SIZE = 32+PREAMBLE_HEAD_SIZE = len(WIRE_MAGIC) + 1+LINK_PREAMBLE_SIZE = PREAMBLE_HEAD_SIZE + NONCE_PREFIX_SIZE + KEY_ID_SIZE + SHARE_SIZE+SHORT_REPLY_SIZE = PREAMBLE_HEAD_SIZE + NONCE_PREFIX_SIZE+# The smallest frame: a counter and a tag around an empty plaintext.+MIN_FRAME_BYTES = COUNTER_SIZE + 1 + crypto_aead_chacha20poly1305_ietf_ABYTES++ROLE_INITIATOR = "initiator"+ROLE_RESPONDER = "responder"+# The direction byte in `info`: whose frames the key seals.+_DIRECTION = {ROLE_INITIATOR: 1, ROLE_RESPONDER: 2}++MSG_ACCEPT = "accept"+MSG_REFUSE = "refuse"+MSG_ACCEPTS = "accepts"+MSG_PAIRED = "paired"+MSG_TEXT = "text"+INPUT_TYPES = frozenset({MSG_KEYDOWN, MSG_KEYUP, MSG_MOUSEMOVE, MSG_MOUSEDOWN, MSG_MOUSEUP, MSG_SCROLL, MSG_GESTURE, MSG_TEXT})++ERROR_INVALID_HELLO = "invalid_hello"+ERROR_WRONG_ID = "wrong_id"+WELCOME_ERRORS = (ERROR_INVALID_HELLO, ERROR_WRONG_ID)+REFUSE_REASONS = ("owned", "not_allowed", "busy", "sent_home", "malformed")++PLATFORMS = ("macos", "windows", "linux", "ios", "android")+EDGES = ("left", "right", "top", "bottom")+BUTTONS = ("left", "right", "middle", "back", "forward")+SCROLL_MODES = ("pixel", "line")++MAX_SAFE_INTEGER = 2**53 - 1+HELD_US_MAX = 2**31 - 1+SET_AT_MAX = 2**53 - 2+SET_AT_AHEAD = 86400+MAX_PEERS = 32+MAX_CAPS = 16+MAX_NAME_CHARS = 48+MAX_ASCII_FIELD = 32+MAX_KEY_CHARS = 32+MOVE_MAX = 65535+DEFAULT_RESISTANCE_PX = 120+MAX_RESISTANCE_PX = 1000+TEXT_MAX_BYTES = 4096++_PLATFORM_SHAPE = re.compile(r"[a-z0-9_]{1,16}")+_HW_SHAPE = re.compile(r"[0-9a-f]{2}(:[0-9a-f]{2}){5}")+_PRINTABLE_ASCII = re.compile(r"[\x20-\x7e]+")+# A lone surrogate can only reach a parsed string through a \u escape: UTF-8 cannot carry one.+_SURROGATE_ESCAPE = re.compile(r"\\u[dD][89a-fA-F]")+++class PreambleRefused(ProtocolError):+ """A version 6 preamble this side will not answer or go on from: another pair's key id, this+ side's own prefix back, or an ephemeral share that gives X25519's all-zero result."""+++class NotAnObject(ProtocolError):+ """A frame opened, its tag and counter checked, but its plaintext is not a JSON object. On a+ later frame it ends the link like any ProtocolError; as the first frame to a responder it is+ the one failure answered, with `invalid_hello_v6()`, since only a token holder sealed it."""+++class InvalidHello(ProtocolError):+ """The first frame opened but is not a valid `hello`: answered with `invalid_hello_v6()`."""+++class InvalidWelcome(ProtocolError):+ """The first frame back opened but is not a valid `welcome`."""+++class HelloRefused(ProtocolError):+ """The responder answered with an error `welcome`; `error` is `invalid_hello` or `wrong_id`."""++ def __init__(self, error):+ super().__init__(f"the peer refused this hello: {error}")+ self.error = error+++def id_text(ident: bytes) -> str:+ """A machine id, a token or a QR secret as PAIRING.md's `b64`."""+ return base64.urlsafe_b64encode(bytes(ident)).decode("ascii").rstrip("=")+++def _from_b64(text, size):+ """The bytes `text` spells, only when it is the one spelling `id_text` writes of `size` bytes."""+ if not isinstance(text, str) or not text.isascii():+ return None+ try:+ data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))+ except (binascii.Error, ValueError):+ return None+ if len(data) != size or id_text(data) != text:+ return None+ return data+++def read_id(text):+ """A machine id's 16 bytes from its `b64`, or None: another length, another spelling, or all+ zero."""+ ident = _from_b64(text, MACHINE_ID_SIZE)+ return None if ident is None or ident == bytes(MACHINE_ID_SIZE) else ident+++def is_paired_token(token) -> bool:+ """Whether `token` is one pairing made: the `b64` of 32 bytes, in its one spelling. Anything+ else is a typed token, which never links (WIRE.md section 1)."""+ return _from_b64(token, TOKEN_SIZE) is not None+++def key_id(token: str) -> bytes:+ """The pair's key id: the first 16 bytes of HKDF over the token's text. Refused for a typed+ token, because a key id is an offline test of its token."""+ if not is_paired_token(token):+ raise ValueError("a typed token has no key id")+ return hkdf_sha256(token.encode("ascii"), LINK_SALT, KEY_ID_INFO)[:KEY_ID_SIZE]+++def link_ikm(token: str, shared: bytes) -> bytes:+ """75 bytes for a token made by pairing: its 43 characters of text, then the X25519 result."""+ return token.encode("ascii") + bytes(shared)+++def link_info(key_id_: bytes, prefix_i: bytes, prefix_r: bytes, share_i: bytes, share_r: bytes, direction: int) -> bytes:+ """111 bytes: label, version, key id, both prefixes and both shares in role order, direction."""+ parts = ((key_id_, KEY_ID_SIZE), (prefix_i, NONCE_PREFIX_SIZE), (prefix_r, NONCE_PREFIX_SIZE), (share_i, SHARE_SIZE), (share_r, SHARE_SIZE))+ if any(len(part) != size for part, size in parts) or direction not in (1, 2):+ raise ValueError("link_info takes fixed-size parts and a direction of 1 or 2")+ return KEY_INFO + bytes([LINK_VERSION]) + b"".join(bytes(part) for part, _ in parts) + bytes([direction])+++def link_key(token, shared, key_id, prefix_i, prefix_r, share_i, share_r, direction) -> bytes:+ """The key for one direction of one link (WIRE.md section 2, the keys)."""+ return hkdf_sha256(link_ikm(token, shared), LINK_SALT, link_info(key_id, prefix_i, prefix_r, share_i, share_r, direction))+++def _x25519_shared(secret: bytes, share: bytes) -> bytes:+ # libsodium refuses a low-order share itself; the zero check stands for any X25519 that+ # does not, since every low-order share gives zeros and nothing else does.+ try:+ shared = crypto_scalarmult(secret, share)+ except CryptoError:+ raise PreambleRefused("the peer's ephemeral share is of low order") from None+ if shared == bytes(SHARE_SIZE):+ raise PreambleRefused("the peer's ephemeral share is of low order")+ return shared+++def split_preamble(data: bytes):+ """(prefix, key id, share) from a whole version 6 preamble."""+ data = bytes(data)+ if len(data) != LINK_PREAMBLE_SIZE or data[:PREAMBLE_HEAD_SIZE] != WIRE_MAGIC + bytes([LINK_VERSION]):+ raise ProtocolError("not a version 6 preamble")+ prefix_end = PREAMBLE_HEAD_SIZE + NONCE_PREFIX_SIZE+ key_id_end = prefix_end + KEY_ID_SIZE+ return data[PREAMBLE_HEAD_SIZE:prefix_end], data[prefix_end:key_id_end], data[key_id_end:]+++def short_reply(prefix: bytes = None) -> bytes:+ """What a version 6 responder answers an older or newer preamble with: 14 bytes, no key id,+ which a version 5 Beamer reads as a newer peer."""+ return WIRE_MAGIC + bytes([LINK_VERSION]) + (os.urandom(NONCE_PREFIX_SIZE) if prefix is None else bytes(prefix))+++def legacy_version_reply() -> bytes:+ """What a version 6 responder answers a Beamer from before version 4 with."""+ return legacy_frame({"type": MSG_WELCOME, "data": {"version": LINK_VERSION, "error": "version_mismatch"}})+++def recv_link_preamble(sock: socket.socket, deadline: float = None) -> bytes:+ """A peer's whole version 6 preamble. Reads 6 bytes first, and raises VersionMismatch naming+ the peer's version (None for a Beamer from before version 4, which sent no preamble) before+ reading anything a version 6 peer would not have sent: after an older version's 6 bytes it+ reads only the 8 left of its 14."""+ head = _recv_exact(sock, PREAMBLE_HEAD_SIZE, deadline)+ if head[: len(WIRE_MAGIC)] != WIRE_MAGIC:+ raise VersionMismatch(None, LINK_VERSION)+ version = head[len(WIRE_MAGIC)]+ if version < LINK_VERSION:+ try:+ _recv_exact(sock, NONCE_PREFIX_SIZE, deadline)+ except (ConnectionClosed, OSError):+ pass+ raise VersionMismatch(version, LINK_VERSION)+ if version > LINK_VERSION:+ raise VersionMismatch(version, LINK_VERSION)+ return head + _recv_exact(sock, LINK_PREAMBLE_SIZE - PREAMBLE_HEAD_SIZE, deadline)+++class Message(dict):+ """A parsed message. `malformed` is set when its text broke a rule JSON parsers disagree on+ (WIRE.md, Encodings): a byte order mark, NaN or an infinity, a repeated key, a lone surrogate.+ The offending value, where there is one, reads as MALFORMED, so a validator refuses the field;+ the flag makes the message as a whole malformed even where that field is one it ignores."""++ malformed = False+++class _Malformed:+ def __repr__(self):+ return "MALFORMED"+++MALFORMED = _Malformed()+++def parse_message(plain: bytes) -> Message:+ """A frame's plaintext as a Message. Raises NotAnObject when it is not a JSON object at all,+ which ends the link (and, for the first frame, is answered `invalid_hello`)."""+ flags = []+ while plain.startswith(b"\xef\xbb\xbf"):+ flags.append("byte order mark")+ plain = plain[3:]+ try:+ text = plain.decode("utf-8")+ except UnicodeDecodeError as exc:+ raise NotAnObject("message body is not UTF-8") from exc++ def constant(name):+ flags.append(name)+ return MALFORMED++ def number(text_):+ value = float(text_)+ if not math.isfinite(value):+ flags.append(text_)+ return MALFORMED+ return value++ def integer(text_):+ # Python refuses to parse an integer of thousands of digits; nothing here allows more than 16.+ return int(text_) if len(text_) <= 32 else MALFORMED++ def pairs(items):+ result = {}+ for key, value in items:+ if key in result:+ flags.append(key)+ value = MALFORMED+ result[key] = value+ return result++ try:+ value = json.loads(text, parse_constant=constant, parse_float=number, parse_int=integer, object_pairs_hook=pairs)+ except (json.JSONDecodeError, RecursionError, ValueError) as exc:+ raise NotAnObject(f"malformed message body: {exc}") from exc+ if not isinstance(value, dict):+ raise NotAnObject("message body must be a JSON object")+ if _SURROGATE_ESCAPE.search(text):+ try:+ json.dumps(value, ensure_ascii=False, default=repr).encode("utf-8")+ except UnicodeEncodeError:+ flags.append("lone surrogate")+ message = Message(value)+ message.malformed = bool(flags)+ return message+++def dumps_message(msg: dict) -> bytes:+ """A message as version 6 sends it: UTF-8, compact, never NaN, never a lone surrogate+ (either raises ValueError)."""+ return json.dumps(msg, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode("utf-8")+++class LinkSession:+ """One version 6 link's handshake and cipher state, for one role. Build a new one per link: it+ draws a fresh nonce prefix and ephemeral X25519 secret, and starts both counters at zero. The+ initiator sends `preamble()` first; the responder sends its own only after `accept_preamble`+ has taken the initiator's, because its prefix must differ from it and its share is useless+ before the other is checked. Neither key exists until then, and once they are made the+ ephemeral secret is dropped. `send_lock` serialises sealing, and send_msg holds it across the+ write too, so counters are never reused and frames reach the wire in counter order; `open` is+ expected to run on a single reader thread per link."""++ def __init__(self, token: str, role: str, prefix: bytes = None, secret: bytes = None):+ if role not in _DIRECTION:+ raise ValueError(f"role must be {ROLE_INITIATOR!r} or {ROLE_RESPONDER!r}")+ self._token = token+ self.prefix = os.urandom(NONCE_PREFIX_SIZE) if prefix is None else bytes(prefix)+ if len(self.prefix) != NONCE_PREFIX_SIZE:+ raise ValueError("nonce prefix must be 8 bytes")+ self.send_lock = threading.RLock()+ self._send_counter = 0+ self._send_key = None+ self.peer_prefix = None+ self._recv_key = None+ self._recv_counter = 0+ self.role = role+ self.key_id = key_id(token)+ self._secret = os.urandom(SHARE_SIZE) if secret is None else bytes(secret)+ if len(self._secret) != SHARE_SIZE:+ raise ValueError("an ephemeral secret is 32 bytes")+ self.share = crypto_scalarmult_base(self._secret)+ self.peer_share = None++ def preamble(self) -> bytes:+ if self.role == ROLE_RESPONDER and self.peer_prefix is None:+ raise ProtocolError("the responder answers the initiator's preamble, never goes first")+ return WIRE_MAGIC + bytes([LINK_VERSION]) + self.prefix + self.key_id + self.share++ def accept_preamble(self, data: bytes) -> None:+ if self.peer_prefix is not None:+ raise ProtocolError("second preamble on one connection")+ if self._secret is None:+ raise ProtocolError("this session refused a preamble; build a new one")+ try:+ peer_prefix, peer_key_id, peer_share = split_preamble(data)+ if not hmac.compare_digest(peer_key_id, self.key_id):+ raise PreambleRefused("the peer's preamble names another pair's key id")+ if self.role == ROLE_RESPONDER:+ while self.prefix == peer_prefix:+ self.prefix = os.urandom(NONCE_PREFIX_SIZE)+ elif peer_prefix == self.prefix:+ raise PreambleRefused("the peer sent this side's own nonce prefix back")+ shared = _x25519_shared(self._secret, peer_share)+ finally:+ self._secret = None+ if self.role == ROLE_INITIATOR:+ order = (self.prefix, peer_prefix, self.share, peer_share)+ else:+ order = (peer_prefix, self.prefix, peer_share, self.share)+ sending = _DIRECTION[self.role]+ with self.send_lock:+ self._send_key = link_key(self._token, shared, self.key_id, *order, sending)+ self._recv_key = link_key(self._token, shared, self.key_id, *order, 3 - sending)+ self.peer_share = peer_share+ self.peer_prefix = peer_prefix++ def seal(self, msg: dict) -> bytes:+ return self.seal_raw(dumps_message(msg))++ def seal_raw(self, body: bytes) -> bytes:+ with self.send_lock:+ if self._send_key is None:+ raise ProtocolError("nothing is sealed before the peer's preamble")+ if self._send_counter >= MAX_COUNTER:+ raise ProtocolError("frame counter exhausted; reconnect")+ self._send_counter += 1+ counter = struct.pack(">I", self._send_counter)+ ciphertext = crypto_aead_chacha20poly1305_ietf_encrypt(body, None, self.prefix + counter, self._send_key)+ return struct.pack(">I", COUNTER_SIZE + len(ciphertext)) + counter + ciphertext++ def open(self, body: bytes) -> Message:+ return parse_message(self.open_raw(body))++ def open_raw(self, body: bytes) -> bytes:+ """The frame's plaintext, once its counter and tag check out."""+ if self._recv_key is None:+ raise ProtocolError("frame received before the peer's preamble")+ if len(body) <= COUNTER_SIZE:+ raise ProtocolError("frame too short")+ # PyNaCl takes bytes only; any other buffer is copied, and a non-buffer is a TypeError as it+ # always was, never a tag failure.+ body = bytes(memoryview(body))+ (counter,) = struct.unpack(">I", body[:COUNTER_SIZE])+ if counter != self._recv_counter + 1:+ raise ProtocolError("frame counter did not advance; replay rejected")+ sealed = body[COUNTER_SIZE:]+ # Shorter than a tag cannot authenticate, and PyNaCl would fail to size its output+ # buffer with a ValueError rather than refuse it, so it is refused here first.+ if len(sealed) < crypto_aead_chacha20poly1305_ietf_ABYTES:+ raise AuthenticationError() from None+ try:+ plain = crypto_aead_chacha20poly1305_ietf_decrypt(sealed, None, self.peer_prefix + body[:COUNTER_SIZE], self._recv_key)+ except CryptoError:+ raise AuthenticationError() from None+ self._recv_counter = counter+ return plain+++def recv_first_msg(sock: socket.socket, session: LinkSession, deadline: float = None) -> Message:+ """The first frame each way: its length held to 21 to 4096 before it is read. A responder+ answers `invalid_hello` to NotAnObject and to InvalidHello from read_hello, and closes with+ nothing sent on any other ProtocolError (a length out of range, the counter, a failed tag)."""+ header = _recv_exact(sock, HEADER_SIZE, deadline)+ (length,) = struct.unpack(">I", header)+ if length < MIN_FRAME_BYTES or length > HELLO_MAX_BYTES:+ raise ProtocolError(f"invalid first frame length: {length}")+ return session.open(_recv_exact(sock, length, deadline))+++# Validators. Each takes a parsed message and returns its fields, checked and in Python types, or+# None when it is malformed, except read_hello, read_welcome and read_ack, which raise, because a+# malformed first frame or `ack` ends the link.++def _int(value, low, high) -> bool:+ return type(value) is int and low <= value <= high+++def _number(value, low, high) -> bool:+ # An int is never infinite, and math.isfinite overflows on one past a float's range.+ return type(value) in (int, float) and (type(value) is int or math.isfinite(value)) and low <= value <= high+++def _one_of(value, choices) -> bool:+ """Membership that a list or dict from the wire cannot make raise."""+ return isinstance(value, str) and value in choices+++def _utf8_size(value):+ """The UTF-8 length of a string, or None for one holding a lone surrogate."""+ try:+ return len(value.encode("utf-8"))+ except UnicodeEncodeError:+ return None+++def _text(value, low, high) -> bool:+ return isinstance(value, str) and low <= len(value) <= high+++def _ascii_field(value) -> bool:+ return _text(value, 1, MAX_ASCII_FIELD) and _PRINTABLE_ASCII.fullmatch(value) is not None+++def valid_name(value) -> bool:+ """1 to 48 code points of valid Unicode (PAIRING.md's rule)."""+ if not _text(value, 1, MAX_NAME_CHARS):+ return False+ try:+ value.encode("utf-8")+ except UnicodeEncodeError:+ return False+ return True+++def valid_platform(value) -> bool:+ """One of PLATFORMS, or any other 1 to 16 of a-z, 0-9 and _ (keyed as linux)."""+ return isinstance(value, str) and _PLATFORM_SHAPE.fullmatch(value) is not None+++def _ids(value, limit=MAX_PEERS, repeats=True):+ if not isinstance(value, list) or len(value) > limit:+ return None+ ids = [read_id(item) for item in value]+ if None in ids or (not repeats and len(set(ids)) != len(ids)):+ return None+ return ids+++def _clamp_offset(value) -> float:+ return float(min(1.0, max(0.0, value)))+++def read_message(message):+ """(type, data) when `message` has a string `type` and an object `data` and broke none of the+ strictness rules, else None."""+ if not isinstance(message, dict) or getattr(message, "malformed", False):+ return None+ kind, data = message.get("type"), message.get("data")+ if not isinstance(kind, str) or not isinstance(data, dict):+ return None+ return kind, data+++def _identity_fields(data, error):+ """The fields `hello` and `welcome` share, checked; raises `error` on any that is not valid."""+ ident = read_id(data.get("id"))+ caps = data.get("caps")+ hw = data.get("hw")+ if (+ not _int(data.get("version"), LINK_VERSION, LINK_VERSION)+ or ident is None+ or not valid_name(data.get("name"))+ or not valid_platform(data.get("platform"))+ or not _ascii_field(data.get("app"))+ or not isinstance(caps, list)+ or len(caps) > MAX_CAPS+ or not all(_ascii_field(cap) for cap in caps)+ or ("hw" in data and not (isinstance(hw, str) and _HW_SHAPE.fullmatch(hw)))+ ):+ raise error("malformed first frame")+ return {+ "version": LINK_VERSION,+ "id": ident,+ "name": data["name"],+ "platform": data["platform"],+ "app": data["app"],+ "caps": list(caps),+ "hw": hw if "hw" in data else None,+ }+++def read_hello(message) -> dict:+ """A valid `hello`'s fields, or InvalidHello. `id` comes back as 16 bytes and `hw` as None+ when it is absent."""+ parsed = read_message(message)+ if parsed is None or parsed[0] != MSG_HELLO:+ raise InvalidHello("the first frame is not a hello")+ data = parsed[1]+ fields = _identity_fields(data, InvalidHello)+ if not _int(data.get("port"), 0, 65535):+ raise InvalidHello("malformed first frame")+ fields["port"] = data["port"]+ return fields+++def read_welcome(message) -> dict:+ """A valid `welcome`'s fields, HelloRefused for an `invalid_hello` or `wrong_id` answer, or+ InvalidWelcome."""+ parsed = read_message(message)+ if parsed is None or parsed[0] != MSG_WELCOME:+ raise InvalidWelcome("the first frame back is not a welcome")+ data = parsed[1]+ if "error" in data:+ if _int(data.get("version"), LINK_VERSION, LINK_VERSION) and _one_of(data["error"], WELCOME_ERRORS):+ raise HelloRefused(data["error"])+ raise InvalidWelcome("a welcome with an unknown error")+ fields = _identity_fields(data, InvalidWelcome)+ if type(data.get("accepts")) is not bool:+ raise InvalidWelcome("malformed first frame")+ fields["accepts"] = data["accepts"]+ return fields+++def _identity(machine_id, name, platform, app, caps, hw):+ # The sender cuts its name, as PAIRING.md says: a hostname can be 63 characters.+ name = name[:MAX_NAME_CHARS]+ if not name:+ raise ValueError("a machine's name is never empty")+ data = {"version": LINK_VERSION, "id": id_text(machine_id), "name": name, "platform": platform, "app": app, "caps": list(caps)}+ if hw:+ data["hw"] = hw+ return data+++def hello_v6(machine_id: bytes, name: str, platform: str, app: str, caps, port: int, hw: str = None) -> dict:+ data = _identity(machine_id, name, platform, app, caps, hw)+ data["port"] = port+ return {"type": MSG_HELLO, "data": data}+++def welcome_v6(machine_id: bytes, name: str, platform: str, app: str, caps, accepts: bool, hw: str = None) -> dict:+ data = _identity(machine_id, name, platform, app, caps, hw)+ data["accepts"] = bool(accepts)+ return {"type": MSG_WELCOME, "data": data}+++def invalid_hello_v6() -> dict:+ return {"type": MSG_WELCOME, "data": {"version": LINK_VERSION, "error": ERROR_INVALID_HELLO}}+++def wrong_id_v6() -> dict:+ return {"type": MSG_WELCOME, "data": {"version": LINK_VERSION, "error": ERROR_WRONG_ID}}+++def focus_v6(route: int, target: bytes, edge: str = None, offset: float = None, resistance_px: int = None, reach=None, stay: bool = False) -> dict:+ """A `focus`. Leave everything but `route` and `target` out to let go; pass `reach` (and+ `resistance_px`) to take, with `edge` and `offset` for a zone, or with `stay` to re-arm."""+ data = {"route": route, "target": id_text(target)}+ if (edge is None) != (offset is None):+ raise ValueError("edge and offset go together")if edge is not None:data["edge"] = edge- if offset is not None:data["offset"] = offset- if return_edge is not None:- data["return_edge"] = return_edgeif resistance_px is not None:data["resistance_px"] = resistance_px+ if reach is not None:+ data["reach"] = [id_text(ident) for ident in reach]+ if stay:+ data["stay"] = Truereturn {"type": MSG_FOCUS, "data": data}-def switch_msg(target: str, edge: str = None, offset: float = None) -> dict:- """Sent by the receiver to ask the sender to move input, when the pointer- has been pushed through the receiver's return edge. `target` is the- sender's machine -- "mac" on the Mac-to-Windows link, "windows" on the- Windows-to-Mac one. `edge` is the edge to arrive at there and `offset`- the fraction along it; both are absent for a plain return with no- position to carry."""- data = {"target": target}+def read_focus(message, own_id: bytes):+ """A `focus` as the responder `own_id` reads it (WIRE.md sections 4 and 5), or None when its+ `route` or `target` is malformed, which cannot be answered and is ignored.++ `here` says it names this machine. A let-go (`here` false) carries only `route` and `target`,+ and any other field is ignored; a let-go that is malformed as a whole is None. A take or+ re-arm comes back with `malformed` set when any other field is, which the responder answers+ with `refuse {why: "malformed"}`. `reach` is kept as sent: the caller drops the owner and+ itself from it."""+ if not isinstance(message, dict) or message.get("type") != MSG_FOCUS or not isinstance(message.get("data"), dict):+ return None+ data = message["data"]+ route, target = data.get("route"), read_id(data.get("target"))+ if not _int(route, 1, MAX_SAFE_INTEGER) or target is None:+ return None+ here = target == bytes(own_id)+ focus = {"route": route, "target": target, "here": here, "malformed": False, "edge": None, "offset": None,+ "resistance_px": DEFAULT_RESISTANCE_PX, "reach": [], "stay": False}+ if not here:+ return None if getattr(message, "malformed", False) else focus+ malformed = getattr(message, "malformed", False)+ if "stay" in data:+ focus["stay"] = data["stay"] is True+ malformed = malformed or not focus["stay"]+ if not focus["stay"] and ("edge" in data or "offset" in data):+ if _one_of(data.get("edge"), EDGES) and _number(data.get("offset"), -math.inf, math.inf):+ focus["edge"], focus["offset"] = data["edge"], _clamp_offset(data["offset"])+ else:+ malformed = True+ if "resistance_px" in data:+ if _int(data["resistance_px"], 0, MAX_RESISTANCE_PX):+ focus["resistance_px"] = data["resistance_px"]+ else:+ malformed = True+ if "reach" in data:+ reach = _ids(data["reach"], repeats=False)+ if reach is None:+ malformed = True+ else:+ focus["reach"] = reach+ focus["malformed"] = malformed+ return focus+++def accept_msg(route: int) -> dict:+ return {"type": MSG_ACCEPT, "data": {"route": route}}+++def refuse_msg(route: int, why: str) -> dict:+ if why not in REFUSE_REASONS:+ raise ValueError(f"not a refusal: {why!r}")+ return {"type": MSG_REFUSE, "data": {"route": route, "why": why}}+++def accepts_msg(accepts: bool) -> dict:+ return {"type": MSG_ACCEPTS, "data": {"accepts": bool(accepts)}}+++def read_accept(message):+ parsed = read_message(message)+ if parsed is None or parsed[0] != MSG_ACCEPT or not _int(parsed[1].get("route"), 1, MAX_SAFE_INTEGER):+ return None+ return {"route": parsed[1]["route"]}+++def read_refuse(message):+ """`why` is kept as sent, and None when it is missing or not a string: an initiator treats+ either as a refusal it cannot name, rather than waiting out a take that was refused."""+ parsed = read_message(message)+ if parsed is None or parsed[0] != MSG_REFUSE:+ return None+ route, why = parsed[1].get("route"), parsed[1].get("why")+ if not _int(route, 1, MAX_SAFE_INTEGER):+ return None+ return {"route": route, "why": why if isinstance(why, str) else None}+++def read_accepts(message):+ parsed = read_message(message)+ if parsed is None or parsed[0] != MSG_ACCEPTS or type(parsed[1].get("accepts")) is not bool:+ return None+ return {"accepts": parsed[1]["accepts"]}+++def switch_v6(route: int, next_id: bytes, edge: str = None, offset: float = None) -> dict:+ data = {"route": route, "next": id_text(next_id)}+ if (edge is None) != (offset is None):+ raise ValueError("edge and offset go together")if edge is not None:data["edge"] = edge- if offset is not None:data["offset"] = offsetreturn {"type": MSG_SWITCH, "data": data}-def arrangement_msg(mac_edge: str, set_at: int) -> dict:- """Where the two machines are in relation to each other, as one value:- the edge of the MAC that leads to the PC. Everything else follows from it- -- the Mac crosses out by that edge, arrives at the opposite edge of the- PC, and comes home the same way -- so the two ends cannot describe a- border that does not exist.+def read_switch(message):+ parsed = read_message(message)+ if parsed is None or parsed[0] != MSG_SWITCH:+ return None+ data = parsed[1]+ route, next_id = data.get("route"), read_id(data.get("next"))+ if not _int(route, 1, MAX_SAFE_INTEGER) or next_id is None:+ return None+ edge = offset = None+ if "edge" in data or "offset" in data:+ if not _one_of(data.get("edge"), EDGES) or not _number(data.get("offset"), -math.inf, math.inf):+ return None+ edge, offset = data["edge"], _clamp_offset(data["offset"])+ return {"route": route, "next": next_id, "edge": edge, "offset": offset}+++def ack_v6(seq: int, held_us: int, locked: bool = False) -> dict:+ """An `ack`, with `held_us` clamped to what the wire allows."""+ data = {"seq": seq, "held_us": min(HELD_US_MAX, max(0, int(held_us)))}+ if locked:+ data["locked"] = True+ return {"type": MSG_ACK, "data": data}+++def read_ack(message) -> dict:+ """A valid `ack`'s fields; ProtocolError otherwise, which ends the link. Whether its `seq` goes+ backwards or ahead of what was sent is the link's to check."""+ parsed = read_message(message)+ if parsed is None or parsed[0] != MSG_ACK:+ raise ProtocolError("malformed ack")+ data = parsed[1]+ if not _int(data.get("seq"), 0, MAX_SAFE_INTEGER) or not _int(data.get("held_us"), 0, HELD_US_MAX):+ raise ProtocolError("malformed ack")+ if "locked" in data and data["locked"] is not True:+ raise ProtocolError("malformed ack")+ return {"seq": data["seq"], "held_us": data["held_us"], "locked": "locked" in data}+++def _with_seq(kind, data, seq):+ if seq is not None:+ data["seq"] = seq+ return {"type": kind, "data": data}+++def key_msg(kind: str, key: str, us: str = None, seq: int = None) -> dict:+ """`keydown` or `keyup`; the link adds `seq` when it is left out here."""+ data = {"key": key}+ if us is not None:+ data["us"] = us+ return _with_seq(kind, data, seq)+++def mousemove_msg(dx: int, dy: int, seq: int = None) -> dict:+ return _with_seq(MSG_MOUSEMOVE, {"dx": dx, "dy": dy}, seq)- Either machine may change it, and tells the other with this message.- `set_at` is unix seconds at the machine that made the change: when two- ends meet holding different arrangements, because one was changed while- the other was asleep, the newer one wins rather than whichever spoke- first. Unknown message types are ignored, so an older Beamer keeps- working with the arrangement it already has."""- return {"type": MSG_ARRANGEMENT, "data": {"mac_edge": mac_edge, "set_at": int(set_at)}}+def text_msg(text: str, seq: int = None) -> dict:+ return _with_seq(MSG_TEXT, {"text": text}, seq)-def read_arrangement(data):- """(mac_edge, set_at) from an arrangement message's data, or None when it- carries no edge worth acting on. Never raises: a malformed arrangement- must not take a working link down."""- if not isinstance(data, dict):++def read_input(message):+ """An input message's fields with `type` and `seq`, or None. A `text` over 4096 bytes comes+ back with `text` None: it is dropped whole but still acknowledged."""+ parsed = read_message(message)+ if parsed is None or parsed[0] not in INPUT_TYPES:return None- edge = data.get("mac_edge")- if edge not in ("left", "right", "top", "bottom"):+ kind, data = parsed+ seq = data.get("seq")+ if not _int(seq, 1, MAX_SAFE_INTEGER):return None- set_at = data.get("set_at")- if isinstance(set_at, bool) or not isinstance(set_at, (int, float)):- set_at = 0- return edge, int(set_at)-+ read = {"type": kind, "seq": seq}+ if kind in (MSG_KEYDOWN, MSG_KEYUP):+ us = data.get("us")+ if not _text(data.get("key"), 1, MAX_KEY_CHARS) or ("us" in data and not _text(us, 1, 1)):+ return None+ read.update(key=data["key"], us=us if "us" in data else None)+ elif kind == MSG_MOUSEMOVE:+ if not _int(data.get("dx"), -MOVE_MAX, MOVE_MAX) or not _int(data.get("dy"), -MOVE_MAX, MOVE_MAX):+ return None+ read.update(dx=data["dx"], dy=data["dy"])+ elif kind in (MSG_MOUSEDOWN, MSG_MOUSEUP):+ if not _one_of(data.get("button"), BUTTONS):+ return None+ read.update(button=data["button"])+ elif kind == MSG_SCROLL:+ dx, mode = data.get("dx", 0), data.get("mode", "line")+ if not _number(data.get("dy"), -MOVE_MAX, MOVE_MAX) or not _number(dx, -MOVE_MAX, MOVE_MAX) or not _one_of(mode, SCROLL_MODES):+ return None+ read.update(dy=data["dy"], dx=dx, mode=mode)+ elif kind == MSG_GESTURE:+ if not _one_of(data.get("name"), GESTURE_NAMES):+ return None+ read.update(name=data["name"])+ else:+ text = data.get("text")+ size = _utf8_size(text) if isinstance(text, str) else None+ if size is None:+ return None+ read.update(text=text if size <= TEXT_MAX_BYTES else None)+ return read+++def read_clipboard(message):+ """{text, image} from a `clipboard`, each None when absent or over its limit (that part is+ dropped and the rest stands), or None when the message is malformed."""+ parsed = read_message(message)+ if parsed is None or parsed[0] != MSG_CLIPBOARD:+ return None+ data = parsed[1]+ text = data.get("text")+ if ("text" in data and (not isinstance(text, str) or _utf8_size(text) is None)) or ("image" in data and not isinstance(data["image"], str)):+ return None+ if text is not None and _utf8_size(text) > CLIPBOARD_MAX_BYTES:+ text = None+ return {"text": text, "image": clipboard_image(data)}-def arrangement_wins(theirs: int, mine: int) -> bool:- """Whether an arrangement the peer sent should replace the one held here.- Both ends stamp their own change, so the newer stamp stands: without that,- an arrangement changed at one machine while the other was asleep would be- silently undone by the sleeper's hello on the next connection. A peer that- sends no stamp at all (an older Beamer, or a first connection) loses to any- stamp of ours, and two ends that have never changed it both hold zero and- agree anyway."""- return int(theirs or 0) > int(mine or 0)+def arrangement_v6(edge: str, set_at: int, by: bytes) -> dict:+ return {"type": MSG_ARRANGEMENT, "data": {"edge": edge, "set_at": int(set_at), "by": id_text(by)}}-def settings_msg(data: dict) -> dict:- """Same on both machines: whether it is on, its stamp and, while on, the shared values, as- settings_sync.message_data builds them. Sent on every change while on and announced on every- new connection; an older Beamer ignores the type."""- return {"type": MSG_SETTINGS, "data": dict(data)}+def read_arrangement_v6(message, now: float):+ """{edge, set_at, by} from an `arrangement`, or None: malformed, or stamped more than a day+ ahead of `now` or above 2^53 - 2, which the receiver ignores."""+ parsed = read_message(message)+ if parsed is None or parsed[0] != MSG_ARRANGEMENT:+ return None+ data = parsed[1]+ by = read_id(data.get("by"))+ set_at = data.get("set_at")+ if not _one_of(data.get("edge"), EDGES) or by is None or not _int(set_at, 0, SET_AT_MAX) or set_at > now + SET_AT_AHEAD:+ return None+ return {"edge": data["edge"], "set_at": set_at, "by": by}-def keeps_settings(data) -> bool:- """Whether a hello's or welcome's data says the peer keeps settings in step."""- return isinstance(data, dict) and data.get("settings") == 1+def paired_msg(ids) -> dict:+ return {"type": MSG_PAIRED, "data": {"ids": [id_text(ident) for ident in ids]}}-def gesture_msg(name: str) -> dict:- """One completed system gesture (a GESTURE_* name). Unknown message types are- ignored by the receiver, so this needs no protocol version bump."""- return {"type": MSG_GESTURE, "data": {"name": name}}+def read_paired(message):+ """The ids in a `paired`, as 16-byte ids, or None."""+ parsed = read_message(message)+ if parsed is None or parsed[0] != MSG_PAIRED:+ return None+ return _ids(parsed[1].get("ids"))diff --git a/core/receiver.py b/core/receiver.pyindex a59483f..cc8234f 100644--- a/core/receiver.py+++ b/core/receiver.py@@ -1,7 +1,13 @@-"""Threaded TCP receiver and ACK watchdog for the Windows tray app."""-+"""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 ipaddressimport logging-import mathimport socketimport sysimport threading@@ -10,15 +16,12 @@ from enum import Enumfrom typing import Callable, Optional, Tuplefrom . import return_edge as crossing+from . import peerlistfrom . import protocolLOGGER = logging.getLogger(__name__)-# `config` throughout is whichever settings object the app on this side keeps.-# Only `port` and `auth_token` are ever read from it, and the two apps' classes-# are unrelated types, so it is not annotated or imported here -- importing one-# app's config module would stop this file being the other app's as well.-# The longest an idle link goes without an ACK, so the Mac's watchdog keeps+# 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.@@ -27,15 +30,13 @@ ACK_IDLE_SECONDS = 0.4# which a 400ms timer did not -- every reading carried up to 400ms of waiting# that was never network latency.ACK_COALESCE_SECONDS = 0.015-HELLO_TIMEOUT_SECONDS = 5.0-SESSION_READ_TIMEOUT_SECONDS = 2.5LOCK_CHECK_SECONDS = 0.5INJECTION_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 HELLO_TIMEOUT_SECONDS as a whole,+# 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@@ -48,31 +49,6 @@ class ServerState(Enum):ERROR = "Error"-class ProcessedSequence:- def __init__(self) -> None:- self._lock = threading.Lock()- self._latest = 0- self._fallback = 0-- def record(self, message: dict) -> int:- data = message.get("data", {})- raw_sequence = message.get("seq")- if raw_sequence is None and isinstance(data, dict):- raw_sequence = data.get("seq")- with self._lock:- if isinstance(raw_sequence, int) and not isinstance(raw_sequence, bool) and raw_sequence >= 0:- self._latest = max(self._latest, raw_sequence)- self._fallback = max(self._fallback, self._latest)- else:- self._fallback = max(self._fallback, self._latest) + 1- self._latest = self._fallback- return self._latest-- def latest(self) -> int:- with self._lock:- return self._latest--class InputScale:"""This machine's own speed for the pointer and scroll arriving from the peer. The peer sendswhat its own acceleration made of the hand's movement, and this machine may accelerate it@@ -103,692 +79,1029 @@ class InputScale:return dy * self.scroll * sign, dx * self.scroll * sign-def handle_message(message: dict, injector=None, scale: Optional[InputScale] = None) -> bool:- """Inject one input event. `injector` defaults to the real input_injector- module, imported lazily here (not at module load) so receiver.py stays- importable — and its non-injection logic testable — on a machine without- ctypes.windll. The Mac copy of this file is handed its own injector at- construction and never reaches that import. Tests can pass a fake- injector directly."""- if injector is None:- import input_injector as injector- if not isinstance(message, dict):- raise protocol.ProtocolError("message body must be a JSON object")- message_type = message.get("type")- data = message.get("data", {})- if not isinstance(data, dict):- raise protocol.ProtocolError("message data must be a JSON object")- if message_type == protocol.MSG_KEYDOWN:- injector.inject_key(data["key"], down=True, us=data.get("us"))- elif message_type == protocol.MSG_KEYUP:- injector.inject_key(data["key"], down=False, us=data.get("us"))- elif message_type == protocol.MSG_MOUSEMOVE:- dx, dy = int(data["dx"]), int(data["dy"])- if scale is not None and (dx or dy):- dx, dy = scale.move(dx, dy)- if not (dx or dy):- return True- injector.inject_mouse_move(dx, dy)- elif message_type == protocol.MSG_MOUSEDOWN:- injector.inject_mouse_button(data["button"], down=True)- elif message_type == protocol.MSG_MOUSEUP:- injector.inject_mouse_button(data["button"], down=False)- elif message_type == protocol.MSG_SCROLL:- dy, dx = data["dy"], data.get("dx", 0)- if scale is not None:- dy, dx = scale.wheel(dy, dx)- injector.inject_scroll(dy, dx, data.get("mode", "line"))- elif message_type == protocol.MSG_GESTURE:- injector.inject_gesture(data["name"])- else:- LOGGER.warning("Unknown message type ignored: %r", message_type)+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"+FIRST_LINK = "first_link"+FOLDED = "folded"+WRONG_ID = "wrong_id"+GONE = "gone"++_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- return True+ 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:+ 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:+ 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) -> Optional[bytes]:+ # Only for a token made by pairing: a key id is an offline test of its token (section 2).+ return protocol.key_id(token) if protocol.is_paired_token(token) else None+++def _entry_key_id(entry) -> Optional[bytes]:+ token = entry.get("token") if isinstance(entry, dict) else None+ return _key_id_of(token) if isinstance(token, str) 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; FIRST_LINK when the entry migrated from 1.4.x (id "") learnt its id+ here (its zones are rewritten to name it); FOLDED when the migrated entry's link named+ another entry's id, so that machine was paired again since the upgrade: the migrated entry+ is dropped into that one (`fold`) and `entry` is that one; 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+ text = protocol.id_text(peer_id)+ first = not entry.get("id")+ if peer_id == own_id:+ return WRONG_ID, None+ if not first and entry.get("id") != text:+ return WRONG_ID, None+ if first:+ other = next((p for p in peers if p is not entry and p.get("id") == text), None)+ if other is not None:+ # Only into a desktop of the platform 1.4.x paired: a phone never had a 1.4.x+ # pairing, and a machine of another platform is not the one it was.+ if not other.get("port") or other.get("platform") != entry.get("platform"):+ return WRONG_ID, None+ fold(settings, entry, other)+ self._save(settings)+ return FOLDED, dict(copy.deepcopy(other), folded=copy.deepcopy(entry))+ before = copy.deepcopy(entry)+ entry.update(changes)+ entry["linked"] = True+ if first:+ entry["id"] = text+ for zone in settings.get("zones") or ():+ if isinstance(zone, dict) and zone.get("peer") == "":+ zone["peer"] = text+ if entry != before:+ self._save(settings)+ return (FIRST_LINK if first else ADMITTED), copy.deepcopy(entry)+++def fold(settings: dict, migrated: dict, into: dict) -> None:+ """Drops the entry migrated from 1.4.x (`migrated`, id "") into `into`, the entry of the same+ machine paired again since: only that machine holds the 1.4.x token, so a link under it that+ names `into`'s id is that machine (section 2, step 8). The migrated entry goes; `into` takes+ its side when it has never had one (`side_set_at` 0); each of its zones moves to `into` unless+ `into` has one of that kind already, which wins; and one pass over the zones in use, other+ peers' first, then `into`'s own, then the moved ones, turns off any that would cover a stretch+ already covered (section 8), so the list stays one the apps will save. Changes `settings` in+ place."""+ text = into["id"]+ settings["peers"] = [peer for peer in settings.get("peers") or [] if peer is not migrated]+ if not into.get("side") and not into.get("side_set_at") and migrated.get("side") in crossing.EDGES:+ into.update(side=migrated["side"], side_set_at=migrated.get("side_set_at", 0), side_by=migrated.get("side_by", ""))+ kinds = {zone.get("kind") for zone in settings.get("zones") or [] if isinstance(zone, dict) and zone.get("peer") == text}+ zones, moved = [], []+ for zone in settings.get("zones") or []:+ if isinstance(zone, dict) and zone.get("peer") == "":+ if zone.get("kind") in kinds:+ continue+ zone["peer"] = text+ kinds.add(zone.get("kind"))+ moved.append(zone)+ zones.append(zone)+ settings["zones"] = zones+ sides = {peer.get("id"): peer.get("side", "") for peer in settings["peers"]}+ dicts = [zone for zone in zones if isinstance(zone, dict)]+ own = [zone for zone in dicts if zone.get("peer") == text and not any(zone is other for other in moved)]+ others = [zone for zone in dicts if zone.get("peer") != text]+ covered = set()+ for zone in others + own + moved:+ if zone.get("off") is True:+ continue+ stretch = zone_stretch(zone, sides)+ if stretch & covered:+ zone["off"] = True+ else:+ covered |= stretch+++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)`; `notice_callback(text)` for the+ one-time notice when a migrated pairing learns its peer; `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."""-class ReceiverServer:def __init__(self,+ book: PeerBook,+ identity: Callable[[], dict],+ *,status_callback: Callable[[ServerState, str], None],+ injector=None,+ desktop=None,clipboard=None,unlock=None,- desktop=None,- pressure_callback: Optional[Callable[[str, float, bool, Optional[str]], None]] = None,- injector=None,- focus_callback: Optional[Callable[[str], None]] = None,- peer_callback: Optional[Callable[[str, Optional[str], Optional[int]], None]] = None,- arrangement_callback: Optional[Callable[[str, int], None]] = None,- arrival_callback: Optional[Callable[[str, int, int], None]] = None,- self_name: str = "PC",- peer_name: str = "Mac",- self_target: str = "windows",- peer_target: str = "mac",+ 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,+ notice_callback=None,+ link_callback=None,+ announce=None,) -> None:- # One module serves both machines. Everything- # platform-shaped is handed in -- the injector, clipboard, desktop- # geometry and unlock modules, the two names that appear in status- # text, and the two wire target words -- so nothing below knows which- # side it is running on. `focus_callback(target)` fires on every focus- # message, which is how the app that owns this receiver knows input- # has arrived or gone home -- and once more with the peer's own target- # when the link that brought input here ends before the peer has- # taken it back, because the peer fails open on its side and the- # message saying so never reaches a dead socket.- self._injector = injector- # This machine's speed for the peer's pointer and scroll; the owner replaces it when its- # settings change. Read once per message on the session thread.- self.input_scale: Optional[InputScale] = None- # Whether this machine's edges are held (Pause crossing, a full-screen app). A hold is- # about this screen, so it stops the peer's pointer going home through it as well as this- # machine's own; the peer's shortcut still switches. Read on the session thread.- self.edges_held: Callable[[], bool] = lambda: False- # `return_model(edge, resistance)` builds the way home the peer named from this machine's- # own ways in: the whole edge, only its chosen thirds, its corner, or None for no way home- # by the pointer. The edges on a screen follow that machine's settings, whoever's pointer- # pushes; without an owner's answer the whole edge is armed.- self.return_model: Optional[Callable[[str, int], Optional[crossing.ReturnEdge]]] = None- self._focus_callback = focus_callback- self._peer_driving = False- # `peer_callback(host, return_edge, resistance_px)` fires once per- # authenticated connection, with the peer's address and the way home- # its hello carried. It is how the machine on this side learns which- # border to push out across without anyone configuring it twice --- # the way home from there is the way out from here.- self._peer_callback = peer_callback- # `arrangement_callback(mac_edge, set_at)` fires when the peer says- # where the two machines are in relation to each other. Either end may- # change it, so this is how the change arrives at the end that did not- # make it.- self._arrangement_callback = arrangement_callback- # Same on both machines (settings_sync). `settings_callback(data)` fires on the session- # thread for each settings message; `announce()` returns the messages this end sends the- # moment a peer has authenticated -- its stamped arrangement and its settings -- so a- # change made while nobody was connected still reaches the other end; `peer_settings` is- # whether the latest peer's hello said it keeps settings in step, None before any.- self.settings_callback: Optional[Callable[[dict], None]] = None- self.announce: Callable[[], list] = lambda: []- self.peer_settings: Optional[bool] = None- # `arrival_callback(edge, x, y)` fires on the session thread each time- # a crossing lands the pointer here, with the edge it came in by and- # where it was placed, in the desktop module's coordinates, and with- # edge None and wherever the pointer is when input comes here by a- # switch instead. It is how the owner plays its arrival effect; the- # owner marshals it.- self._arrival_callback = arrival_callback- self._self_name = self_name- self._peer_name = peer_name- self._self_target = self_target- self._peer_target = peer_target+ self._book = book+ self._identity = identityself._status_callback = status_callback- # `desktop` defaults to the real desktop_win module, imported lazily for- # the same reason as `clipboard` below. `pressure_callback(edge,- # pressure, crossed, part)` is called on the session thread as the- # pointer is pushed against the return edge, `part` the third or corner- # pushed when the way home is only those; the GUI marshals it to the glow.+ self._injector = injectorself._desktop = desktop- self._pressure_callback = pressure_callback- # The way home. Armed by every focus{target:"windows"} the Mac sends,- # which carries the return edge and resistance, and None until then.- self._return_edge: Optional[crossing.ReturnEdge] = None- # The edge and resistance that focus named, kept so a settings change can rebuild the way- # home (`rearm_return`) without waiting for the next focus.- self._named_return: Optional[tuple] = None- # Held while the session thread feeds the way home and while a settings change rebuilds it,- # so a rebuild never revives a way home that was just pushed through or handed back.- self._return_lock = threading.RLock()- # `unlock` defaults to the real unlock_win module, imported lazily for- # the same reason as `clipboard` below.+ self._clipboard = clipboardself._unlock = unlock- # Set while a lock-screen unlock is in flight. Input that arrives in- # that window is dropped rather than queued: an unlock takes several- # seconds, and replaying seconds of stale mouse moves and keystrokes- # onto the desktop the moment it appears is worse than losing them.+ 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,+ "notice": notice_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()- # When the console was last tested for the lock screen and first seen on it while the peer- # drives this PC, and whether its input has been sent home for that lock. See- # _home_if_locked.+ self._arriving_visit = None # the visit whose pointer is landing and unlock not yet askedself._lock_checked_at = float("-inf")self._locked_since = Noneself._sent_home_for_lock = False- # Set from the moment a focus brings the peer's input here until the unlock it may need- # has been asked for, so the lock check cannot act in between. See _handle_focus.- self._arriving = threading.Event()- # `clipboard` defaults to the real clipboard_win module, imported- # lazily (not at module load) so receiver.py stays importable -- and- # its non-clipboard logic testable -- on a machine without- # ctypes.windll, e.g. this Mac. Tests can pass a fake directly, the- # same way handle_message's `injector` argument works.- self._clipboard = clipboard- self._lock = threading.RLock()+ self._connections = set()self._thread: Optional[threading.Thread] = Noneself._stop_event: Optional[threading.Event] = Noneself._listener: Optional[socket.socket] = None- self._client: Optional[socket.socket] = None- # The live session per connection, so a message can be sent to the- # client from outside its own thread -- which is what an arrangement- # changed in the window needs.- self._sessions: dict = {}- self._connections: set = set()- self._pending = 0- self._session_generation = 0+ self._port = Noneself._requested_running = False+ # The listener+@propertydef listening(self) -> bool:with self._lock:return self._requested_running and self._thread is not None and self._thread.is_alive()@property- def return_edge(self) -> Optional[str]:- """The Windows edge the Mac last named as the way home, or None."""- model = self._return_edge- return model.edge if model is not None else None+ def owner(self) -> Optional[bytes]:+ link = self._owner+ return link.peer_id if link is not None else None@property- def return_resistance(self) -> Optional[int]:- """How many pixels of push the Mac last asked for at the return edge, or None."""- model = self._return_edge- return model.resistance_px if model is not None else None+ 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, config) -> None:+ def start(self, port: int) -> None:with self._lock:if self._thread is not None and self._thread.is_alive():returnstop_event = threading.Event()- thread = threading.Thread(- target=self._server_thread,- args=(config, stop_event),- name="Beamer-server",- daemon=True,- )- self._stop_event = stop_event- self._thread = thread+ 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, portself._requested_running = True- self._set_status(ServerState.WAITING, f"Starting on port {config.port}")- try:- thread.start()- except Exception:- with self._lock:- if self._thread is thread:- self._thread = None- self._stop_event = None- self._requested_running = False- raise+ 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 = self._stop_event- listener = self._listener+ stop_event, listener, thread = self._stop_event, self._listener, self._threadconnections = set(self._connections)- thread = self._thread+ 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:- self._close_socket(connection)- self._close_socket(listener)- # start() publishes the thread under the lock and starts it outside, so a- # stop() landing in that window would join a thread that never started,- # which raises rather than returning.+ _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)- if thread is not None and thread.is_alive():- LOGGER.error("Server thread did not stop within two seconds")- self._set_status(ServerState.ERROR, "Listener did not stop; see log")- returnwith self._lock:if self._thread is thread:- self._thread = None- self._stop_event = None- self._listener = None- self._client = None- self._hand_back("Listening stopped")+ self._thread = self._stop_event = self._listener = Noneself._set_status(ServerState.STOPPED, "Listening stopped")- def _server_thread(self, config, stop_event: threading.Event) -> None:- failed = False+ def _server_thread(self, port: int, stop_event: threading.Event) -> None:try:- self._serve(config, stop_event)+ 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+ LOGGER.info("Listening for version 6 links on 0.0.0.0:%s", 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():- failed = True- LOGGER.exception("Server thread failed")+ LOGGER.exception("The version 6 listener failed")self._set_status(ServerState.ERROR, f"Listener failed: {exc}")finally:with self._lock:listener = self._listener- connections = set(self._connections)self._listener = None- self._client = None- if self._thread is threading.current_thread():- self._thread = None- self._stop_event = None- if failed:- self._requested_running = False- for connection in connections:- self._close_socket(connection)- self._close_socket(listener)- if stop_event.is_set():- self._set_status(ServerState.STOPPED, "Listening stopped")-- def _bind(self, config, stop_event: threading.Event):- """Bind the listening socket, waiting for the port if something holds it."""- reported = ""+ _close_socket(listener)++ def _bind(self, port: int, stop_event: threading.Event):+ reported = Falsewhile not stop_event.is_set():listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- # On the Mac this is what lets the port be taken back straight- # after a restart, while the last session's connections sit in- # TIME_WAIT. On Windows the same option means something else: a- # second bind on a port another listener holds succeeds, and the- # two split the Mac's connections between them, so the held-port- # wait below never fired for a zombie Beamer. Windows does not- # need it for TIME_WAIT, so it does without.+ # 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", config.port))+ listener.bind(("0.0.0.0", port))+ return listenerexcept OSError as exc:- self._close_socket(listener)- # Said the way a user can act on it: the log carries the error, the- # status carries the one thing they can change.- detail = f"Another program is using port {config.port} — change the port on the Connection page"- # Only on a change: a retry every few seconds otherwise repeats- # the same line and the same status for as long as the port is held.- if detail != reported:- LOGGER.error("Cannot listen on port %s: %s", config.port, exc)- reported = detail- self._set_status(ServerState.ERROR, detail)+ _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)- continue- return listenerreturn None- def _serve(self, config, stop_event: threading.Event) -> None:- listener = self._bind(config, stop_event)- if listener is None:- return- # A stale, not-yet-torn-down session must never block a reconnect: a- # backlog of 2 lets a fresh Mac connection queue up while the previous- # session's thread is still winding down, instead of the OS refusing- # it outright.- listener.listen(2)- listener.settimeout(0.5)- with self._lock:- self._listener = listener- LOGGER.info("Listening on 0.0.0.0:%s", config.port)- self._set_status(ServerState.WAITING, f"Waiting on port {config.port}")- while not stop_event.is_set():- try:- connection, address = listener.accept()- except socket.timeout:- continue- except OSError:- if stop_event.is_set():- break- raise- # Hand the connection to its own thread immediately and go back- # to accept(): a slow or stuck peer must never stall the listener,- # which is what used to make a stale session block a reconnect.- # Bounded, because accept() happens before any proof of the token.- # Only handshakes count: an authenticated peer never blocks the- # next one, and a stranger's slot frees itself within seconds.+ 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:- crowded = self._pending >= MAX_PENDING_CONNECTIONS- if not crowded:- self._pending += 1- if crowded:- LOGGER.warning("Refusing %s:%s: %d handshakes already in progress", address[0], address[1], MAX_PENDING_CONNECTIONS)- self._close_socket(connection)- continue- thread = threading.Thread(- target=self._session_thread,- args=(connection, address, config, stop_event),- name="Beamer-session",- daemon=True,- )- thread.start()-- def _session_thread(- self,- connection: socket.socket,- address,- config,- server_stop: threading.Event,- ) -> None:- with self._lock:- self._connections.add(connection)+ self._slots.free(host, connection)+ self._handshaking -= 1try:- self._handle_client(connection, address, config, server_stop)+ if link is not None:+ self._serve(link)finally:with self._lock:self._connections.discard(connection)- self._close_socket(connection)+ _close_socket(connection)- def _handle_client(- self,- connection: socket.socket,- address,- config,- server_stop: threading.Event,- ) -> None:- peer = f"{address[0]}:{address[1]}"- LOGGER.info("Connection from %s", peer)+ # 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:- handshake = self._handshake(connection, peer, config, server_stop)- finally:- with self._lock:- self._pending -= 1- if handshake is None:- return- session, version, hello = handshake- self._clipboard_module().forget_sync()-- if version != protocol.PROTOCOL_VERSION:- LOGGER.warning(- "Rejecting %s: unsupported protocol version %r (expected %s)",- peer,- version,- protocol.PROTOCOL_VERSION,+ 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 == FOLDED:+ # Answered with the welcome, so the far side's own step 7 folds its 1.4.x entry+ # too, then closed: the pairing this link came under is gone.+ name = peerlist.label_for(self._settings_now()[0], token=entry.get("token")) or entry.get("name") or host+ LOGGER.info("%s linked under its 1.4.x pairing after pairing again; folded into the new one", name)+ self._callback("notice", f"{name} linked from {host} under its Beamer 1.4 pairing, {entry['folded'].get('name') or 'unnamed'}, which is now part of {name}.")+ welcome = protocol.welcome_v6(+ own_id, identity["name"], identity["platform"], identity["app"], identity["caps"], entry.get("allow_drive") is True, self._hardware_towards(host, identity)+ )+ self._answer(connection, host, session.seal(welcome))+ 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 == FIRST_LINK:+ # Said the moment the id is saved: a claimer that resets before its welcome still+ # holds the entry, and this notice is how the user learns who took it.+ self._callback("notice", f"Linked with {hello['name']} at {host} for the first time on Beamer 1.5.0.")+ 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))- self._send_message(connection, session, protocol.welcome_msg(error="version_mismatch"))- self._note_version_mismatch(f"{self._peer_name} app is an older Beamer version — update both apps")- return+ 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- # The Mac now pings at least once a second while idle, so a read- # timeout here means the peer is gone, not merely quiet.- connection.settimeout(SESSION_READ_TIMEOUT_SECONDS)- connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)- sequence = ProcessedSequence()- if not self._send_message(connection, session, protocol.welcome_msg()):- return+ 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:- previous_client = self._client- self._client = connection- self._sessions[connection] = session- self._session_generation += 1- my_generation = self._session_generation- if previous_client is not None and previous_client is not connection:- # Preempt: a reconnecting Mac instantly replaces a stale session- # instead of queueing behind it. Closing it here unblocks that- # thread's blocked recv so it can exit.- LOGGER.info("Superseding the previous session for %s", peer)- self._close_socket(previous_client)-- LOGGER.info("Authenticated %s (protocol v%s)", peer, version)- # A peer that has just connected has its input at home, whatever the- # session it replaced was in the middle of.- self._hand_back(f"{self._peer_name} reconnected")- self.peer_settings = protocol.keeps_settings(hello)- self._notify_peer(address[0], hello)- self._set_status(ServerState.CONNECTED, f"Connected to {address[0]}")+ self._slots.free(host, connection)+ draining = self._drains < MAX_DRAINS+ if draining:+ self._drains += 1try:- announcements = list(self.announce())- except Exception:- LOGGER.exception("Announce failed")- announcements = []- for announcement in announcements:- self._send_message(connection, session, announcement)-- client_stop = threading.Event()- ack_due = threading.Event()- ack_thread = threading.Thread(- target=self._ack_thread,- args=(connection, session, sequence, client_stop, server_stop, ack_due),- name="Beamer-ack",- daemon=True,- )- ack_thread.start()-- last_injection_status_at = 0.0+ 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:- while not server_stop.is_set() and not client_stop.is_set():+ 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:- message = protocol.recv_msg(connection, session)+ 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:- if self._is_current_session(my_generation):- LOGGER.warning("%s went quiet; treating the connection as dead", peer)- break- except protocol.ConnectionClosed:- if self._is_current_session(my_generation):- LOGGER.info("%s disconnected", peer)+ LOGGER.warning("%s went quiet; its link is over", link.name)break- except protocol.ProtocolError as exc:- if self._is_current_session(my_generation):- LOGGER.warning("Protocol error from %s: %s", peer, exc)+ 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- except OSError as exc:- if (- not server_stop.is_set()- and not client_stop.is_set()- and self._is_current_session(my_generation)- ):- LOGGER.warning("Receive failed for %s: %s", peer, exc)- break- message_type = message.get("type") if isinstance(message, dict) else None- if message_type == protocol.MSG_PING:- # Liveness only; never recorded or acked as an input event.- continue- if message_type == protocol.MSG_FOCUS:- # Never recorded or acked as an input event, like ping.- self._handle_focus(message, connection, session, peer, address[0])- continue- if message_type == protocol.MSG_CLIPBOARD:- # Never recorded or acked as an input event, like ping.- self._handle_inbound_clipboard(message, peer)- continue- if message_type == protocol.MSG_ARRANGEMENT:- # Never recorded or acked as an input event, like ping.- self._handle_arrangement(message)- continue- if message_type == protocol.MSG_SETTINGS:- # Never recorded or acked as an input event, like ping.- self._handle_settings(message)- continue- if self._unlocking.is_set():- # Dropped, not queued: see _begin_unlock. Still recorded so- # the ACK sequence stays continuous and the Mac's watchdog- # does not read the unlock as a dead link.- sequence.record(message)- continue- if message_type == protocol.MSG_MOUSEMOVE and self._return_trip(message, connection, session):- # Held at the edge or crossed: not injected, but still an- # input event for the ACK sequence.- sequence.record(message)- continue- try:- processed = handle_message(message, self._injector, self.input_scale)- except Exception:- LOGGER.exception("Input event from %s could not be injected", peer)- now = time.monotonic()- if now - last_injection_status_at >= INJECTION_ERROR_STATUS_INTERVAL_SECONDS:- last_injection_status_at = now- self._set_status(ServerState.CONNECTED, f"Input error from {address[0]}; see log")- continue- if not processed:- continue- sequence.record(message)- ack_due.set()+ self._dispatch(link, message)finally:- client_stop.set()- ack_thread.join(timeout=1.0)- if ack_thread.is_alive():- LOGGER.error("ACK thread did not stop within one second")- self._set_status(ServerState.ERROR, "ACK worker did not stop; see log")with self._lock:- self._sessions.pop(connection, None)- is_current = self._session_generation == my_generation- if is_current:- self._client = None- if is_current:- self._hand_back(f"{self._peer_name} went away")- # A preempted (superseded) session must exit silently: only the- # current-generation session may flip status to WAITING.- if is_current and not server_stop.is_set():- self._set_status(ServerState.WAITING, f"Waiting on port {config.port}")-- def _is_current_session(self, generation: int) -> bool:- with self._lock:- return self._session_generation == generation-- def _handshake(self, connection: socket.socket, peer: str, config, server_stop: threading.Event):- """Read the Mac's preamble, answer with ours, then open its hello.- Returns (session, declared version) or None once the failure has been- logged. The preamble is read before ours is sent so an older Mac, which- opens with a cleartext frame instead, gets a cleartext version_mismatch- it can display rather than bytes it reads as a bogus length."""- connection.settimeout(HELLO_TIMEOUT_SECONDS)- # One deadline for the whole handshake, not a timeout per read: a peer- # trickling a byte at a time would otherwise hold its slot for ever.- deadline = time.monotonic() + HELLO_TIMEOUT_SECONDS- session = protocol.SecureSession(config.auth_token)- try:+ 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:- protocol.recv_preamble(connection, session, deadline=deadline)- except protocol.VersionMismatch as exc:- if exc.peer_version is None:- LOGGER.warning("%s opened with the pre-v4 cleartext protocol", peer)- connection.sendall(protocol.legacy_frame(protocol.welcome_msg(error="version_mismatch")))- self._note_version_mismatch(f"{self._peer_name} app is an older Beamer version — update both apps")- else:- LOGGER.warning("%s speaks wire version %r, expected %s", peer, exc.peer_version, protocol.PROTOCOL_VERSION)- connection.sendall(session.preamble())- self._note_version_mismatch(- f"{self._peer_name} app is Beamer protocol v{exc.peer_version}, this {self._self_name} is v{protocol.PROTOCOL_VERSION} — update both apps"- )- return None- connection.sendall(session.preamble())- first = protocol.recv_msg(connection, session, limit=protocol.HELLO_MAX_BYTES, deadline=deadline)- except socket.timeout:- LOGGER.warning("Authentication timed out for %s", peer)- return None- except protocol.ConnectionClosed:- LOGGER.info("%s disconnected before authentication", peer)- return None- except protocol.AuthenticationError:- # The one signal that the Mac does not hold the shared token. Nothing is sent back:- # a reply would tell a guesser it had reached a Beamer.- LOGGER.warning("Authentication failed for %s: frame failed authentication", peer)- return None- except protocol.ProtocolError as exc:- LOGGER.warning("Protocol error during authentication from %s: %s", peer, exc)- return None- except OSError as exc:- if not server_stop.is_set():- LOGGER.warning("Authentication receive failed for %s: %s", peer, exc)- return None- if first.get("type") != protocol.MSG_HELLO:- LOGGER.warning("%s authenticated but did not say hello first", peer)- return None- data = first.get("data")- return session, self._hello_version(first), data if isinstance(data, dict) else {}-- def _note_version_mismatch(self, detail: str) -> None:- with self._lock:- has_active_client = self._client is not None- if not has_active_client:- self._set_status(ServerState.ERROR, detail)+ # 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 _ack_thread(- self,- connection: socket.socket,- session: protocol.SecureSession,- sequence: ProcessedSequence,- client_stop: threading.Event,- server_stop: threading.Event,- ack_due: threading.Event,- ) -> None:+ def _dispatch(self, link: _Link, message) -> None:+ kind = message.get("type") if isinstance(message, dict) else Nonetry:- while not server_stop.is_set():- woken = ack_due.wait(ACK_IDLE_SECONDS)- if client_stop.is_set():- return- if woken:- ack_due.clear()- # Coalesce on client_stop, not sleep, so a disconnect during- # the batching window still exits promptly.- if client_stop.wait(ACK_COALESCE_SECONDS):- return- ack = protocol.ack_msg(sequence.latest(), locked=self._unlocking.is_set())- if not self._send_message(connection, session, ack):- client_stop.set()- self._close_socket(connection)- return- self._home_if_locked()- except Exception as exc:- LOGGER.exception("ACK thread failed")- self._set_status(ServerState.ERROR, f"ACK worker failed: {exc}")- client_stop.set()- self._close_socket(connection)-- def _home_if_locked(self) -> None:- """Send the peer's input home when this PC is on its lock screen. Beamer can neither inject- into the secure desktop nor watch the return edge there, so a Mac left driving a locked PC- had no way back until someone unlocked it by hand (issue #5).-- Timed, not per tick: the ACK thread wakes on every injected event, and is_locked walks the- process list. Locked on two checks LOCK_CHECK_SECONDS apart, and never while an unlock is- in flight: a switch to a locked PC reaches _begin_unlock a moment after focus, and an- unlock provider that can clear the lock screen must be given the chance."""- if not self._peer_driving or self._unlocking.is_set() or self._arriving.is_set():- self._locked_since = None- return- now = time.monotonic()- if now - self._lock_checked_at < LOCK_CHECK_SECONDS:+ 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- self._lock_checked_at = now+ after = []try:- locked = self._unlock_module().is_locked() is True+ 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:- locked = False- if not locked:- self._locked_since = None- return- if self._locked_since is None:- self._locked_since = now- return- if self._sent_home_for_lock:+ 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- LOGGER.info("Windows is locked while the %s drives it; sending its input home", self._peer_name)- self._sent_home_for_lock = self.send_home()+ 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")- def _clipboard_module(self):- if self._clipboard is not None:- return self._clipboard- import clipboard_win- return clipboard_win+ @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 _unlock_module(self):- if self._unlock is not None:- return self._unlock- import unlock_win- return unlock_win+ 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 _desktop_module(self):- if self._desktop is not None:- return self._desktop- import desktop_win- return desktop_win+ 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 _return_trip(self, message: dict, connection: socket.socket, session: protocol.SecureSession) -> bool:- """The return path. Feeds every mouse move to the pressure model while- a return edge is armed; True means the move was consumed — the pointer- was held at the edge, or it broke through and the Mac has been asked- to take input back — and must not be injected."""- data = message.get("data")- if not isinstance(data, dict):- return False+ 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+ returntry:- with self._return_lock:- model = self._return_edge- if model is None or not model.armed or self.edges_held():- return False- desktop = self._desktop_module()- monitors, pointer = desktop.monitors(), desktop.cursor_position()- outcome = model.feed(monitors, pointer, float(data["dx"]), float(data["dy"]))- if outcome.action == crossing.CROSS:- self._named_return = None- # Which third or corner is being pushed, so the owner lights only that.+ 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:+ continuepart = Noneif isinstance(model, crossing.PartEdge):part = crossing.part_of(crossing.display_fraction(monitors, model.edge, pointer))@@ -796,397 +1109,433 @@ class ReceiverServer:part = model.cornerif outcome.action == crossing.HOLD:desktop.set_cursor_position(*outcome.position)- elif outcome.action == crossing.CROSS:- LOGGER.info("Pointer pushed through the %s edge; returning input to the %s", model.edge, self._peer_name)- self._send_message(connection, session, protocol.switch_msg(self._peer_target, outcome.edge, outcome.offset))- except Exception:- # Logged once, not at 100Hz: the return edge is dropped until the- # Mac's next switch re-arms it, and input keeps flowing normally.- LOGGER.exception("Return edge failed; crossing back is off until the next switch")- self._drop_return()- return False- if outcome.action == crossing.PASS:- return False- self._notify_pressure(model.edge, outcome.pressure, outcome.action == crossing.CROSS, part)- return True-- def send_arrangement(self, mac_edge: str, set_at: int) -> bool:- """Tell the peer where the machines are, over the connection it opened- to this one. Used when the change was made at this end: the outward- link may be down, or may not exist on this machine at all, and this- one is up by definition whenever there is anyone to tell."""- with self._lock:- connection = self._client- session = self._session_for(connection)- if connection is None or session is None:- return False- return self._send_message(connection, session, protocol.arrangement_msg(mac_edge, set_at))-- def send_settings(self, data: dict) -> bool:- """Tell the peer this end's settings state, over the connection it opened to this one."""- with self._lock:- connection = self._client- session = self._session_for(connection)- if connection is None or session is None:- return False- return self._send_message(connection, session, protocol.settings_msg(data))+ 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 a zone here; asking %s to move its input on", 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 send_home(self) -> bool:- """Send the peer's input back to it from this end, as its own return- edge would. The escape that does not depend on that edge: the owner- calls it when someone here asks to switch while the peer is driving.- Earlier versions refused this outright, and a push through the edge- that failed to fire could then leave the peer's pointer stuck here- with no way back. The send runs on its own thread, because the- callers are a hook and an event tap that must never block on a- socket."""+ 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:- connection = self._client- session = self._session_for(connection)- if not self._peer_driving or connection is None or session is None:- return False- self._drop_return()- LOGGER.info("Switch asked for here; sending input home to the %s", self._peer_name)- threading.Thread(- target=self._send_message,- args=(connection, session, protocol.switch_msg(self._peer_target)),- name="Beamer-send-home",- daemon=True,- ).start()- return True+ self._generation += 1+ self._rearm_fresh()- def _session_for(self, connection):- return self._sessions.get(connection) if connection is not None else None+ 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 _handle_arrangement(self, message: dict) -> None:- read = protocol.read_arrangement(message.get("data"))- if read is None or self._arrangement_callback is None:- return+ def _settings_now(self):+ """The peers and zones as the app holds them now, or none of either when it cannot say."""try:- self._arrangement_callback(*read)+ peers = self._book.peers()except Exception:- LOGGER.exception("Arrangement callback failed")-- def _handle_settings(self, message: dict) -> None:- if self.settings_callback is None or not isinstance(message.get("data"), dict):- return+ LOGGER.exception("Could not read the peers")+ peers = []try:- self.settings_callback(message["data"])+ zones = list(self._zones() or [])except Exception:- LOGGER.exception("Settings callback failed")+ LOGGER.exception("Could not read the zones")+ zones = []+ return peers, zones++ # Ownership (section 4)- def _notify_peer(self, host: str, hello: dict) -> None:- if self._peer_callback is None:+ def _on_focus(self, link: _Link, message) -> None:+ focus = protocol.read_focus(message, link.own_id)+ if focus is None:return- edge = hello.get("return_edge")- if edge not in crossing.EDGES:- edge = None- resistance = hello.get("resistance_px")- if isinstance(resistance, bool) or not isinstance(resistance, (int, float)):- resistance = None+ 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:+ link.post(protocol.refuse_msg(focus["route"], why))+ 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) -> Optional[str]:+ """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"+ if not link.allow_drive:+ return "not_allowed"+ self._claiming = linktry:- self._peer_callback(host, edge, None if resistance is None else int(resistance))+ busy = bool(self._away())except Exception:- LOGGER.exception("Peer callback failed")-- def _notify_focus(self, target) -> None:- if self._focus_callback is None or not isinstance(target, str):- return- if target == self._self_target:- self._peer_driving = True+ LOGGER.exception("Could not tell whether this machine's input is elsewhere")+ busy = False+ why = None+ sent_home_at = self._sent_home_at.get(link.peer_id)+ if busy:+ why = "busy"+ 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"+ elif focus["stay"] and self._owner is not link:+ why = "malformed"+ if why is not None:+ self._claiming = None+ return why++ 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- # A lock seen on the last visit says nothing about this one.self._locked_since = None- elif target == self._peer_target:- self._peer_driving = False- try:- self._focus_callback(target)- except Exception:- LOGGER.exception("Focus callback failed")-- def _hand_back(self, why: str) -> None:- """The peer's input was on this machine and the link that carried it- is over. The peer has already failed open on its own side; the focus- that would have said so died with the socket, so it is raised here.- Otherwise the owner of this receiver keeps treating the peer as- driving, and its own edge and shortcut stay dead until the peer next- crosses in and back."""- if not self._peer_driving:+ 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+ 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- self._drop_return()- LOGGER.info("%s while its input was here; input returned to this %s", why, self._self_name)- self._release_peer_keys()- self._notify_focus(self._peer_target)-- def _release_peer_keys(self) -> None:- """Let go of whatever the peer was holding here. A modifier or button- injected for the peer and never released -- a chord in flight when- input went home or the link died -- would otherwise stay down on this- machine, turning every later local keystroke into a shortcut."""- injector = self._injector- if injector is None:+ # 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:+ returntry:- import input_injector as injector+ if not self._clipboard_module().set_contents(text, image):+ LOGGER.warning("Could not set the clipboard %s sent", link.name)except Exception:- LOGGER.exception("Injector unavailable; keys the peer held may still be down")- return- release = getattr(injector, "release_all", None)- if release is None:- return+ 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 Nonetry:- release()+ return stamp()except Exception:- LOGGER.exception("Could not release the keys the %s was holding", self._peer_name)+ LOGGER.exception("Could not read the clipboard's change stamp")+ return None- def _notify_pressure(self, edge: str, pressure: float, crossed: bool, part: Optional[str] = None) -> None:- if self._pressure_callback is 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:returntry:- self._pressure_callback(edge, pressure, crossed, part)+ text, image = self._clipboard_module().get_contents()except Exception:- LOGGER.exception("Pressure callback failed")-- def rearm_return(self) -> None:- """Rebuilds the way home from this machine's Crossing settings as they are now, for the- edge and resistance the peer last named, so a change applies while the peer's input is- here rather than at its next crossing. Nothing happens once that input has gone home, or- after the way home has been pushed through."""- with self._return_lock:- named = self._named_return- model = self._return_edge- if not self._peer_driving or named is None or (model is not None and not model.armed):- return- self._arm_return({"return_edge": named[0], "resistance_px": named[1]})-- def _drop_return(self) -> None:- """The peer's visit is over, or its way home is spent: nothing may rebuild it."""- with self._return_lock:- self._return_edge = None- self._named_return = None-- def _arm_return(self, data: dict) -> None:- """Every switch to Windows says which edge leads home and how hard to- push; an older Mac that says neither gets no return edge, so nothing- it does not expect can fire."""- with self._return_lock:- self._build_return(data)-- def _build_return(self, data: dict) -> None:- edge = data.get("return_edge")- if edge not in crossing.EDGES:- self._return_edge = None- self._named_return = None+ LOGGER.exception("Could not read the clipboard for %s", link.name)return- resistance = data.get("resistance_px", crossing.DEFAULT_RESISTANCE_PX)- # json.loads accepts Infinity and NaN, and int() of either raises, which- # nothing above this catches: a bad number gets the default instead.- if isinstance(resistance, bool) or not isinstance(resistance, (int, float)) or not math.isfinite(resistance):- resistance = crossing.DEFAULT_RESISTANCE_PX- self._named_return = (edge, int(resistance))- if self.return_model is None:- self._return_edge = crossing.ReturnEdge(edge, int(resistance))+ 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 len(image) > protocol.CLIPBOARD_IMAGE_MAX_BYTES:+ 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:- self._return_edge = self.return_model(edge, int(resistance))- except Exception:- LOGGER.exception("Could not build the way home through the %s edge", edge)- self._return_edge = crossing.ReturnEdge(edge, int(resistance))-- def _place_pointer(self, data: dict) -> None:- """A crossing names the edge and the fraction along it, and the pointer is placed there. A- switch by the shortcut or a menu names neither and leaves the pointer where it was, which- the arrival callback gets as edge None, so the owner can show where that is."""- edge = data.get("edge")- offset = data.get("offset")- if edge not in crossing.EDGES or isinstance(offset, bool) or not isinstance(offset, (int, float)):- if self._arrival_callback is None:+ with self._lock:+ current = self._visit == visit and self._owner is link+ if not current:return- try:- x, y = self._desktop_module().cursor_position()- self._arrival_callback(None, x, y)- except Exception:- LOGGER.exception("Arrival callback for a switch failed")- return- try:desktop = self._desktop_module()- x, y = crossing.arrival_position(desktop.monitors(), edge, offset)- desktop.set_cursor_position(x, y)+ if focus["edge"] is not None:+ x, y = crossing.arrival_position(desktop.monitors(), focus["edge"], focus["offset"])+ desktop.set_cursor_position(x, y)+ 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 place the pointer at the %s edge on arrival", edge)- return- if self._arrival_callback is None:- return+ LOGGER.exception("Could not land %s's pointer", link.name)try:- self._arrival_callback(edge, x, y)- except Exception:- LOGGER.exception("Arrival callback failed")-- def _begin_unlock(self, peer: str, host: str) -> None:- """Take the console off the lock screen, if it is on one, so the input- about to arrive has somewhere to land. Beamer cannot type on the secure- desktop at all -- see unlock_win -- so without this, switching to a- locked PC silently injects into nothing.-- The lock test is a cheap in-process snapshot, so the common case (an- unlocked PC) stays inline and costs nothing. Only a real unlock goes to- a thread, because it takes seconds and this runs on the message loop- that has to keep draining pings."""+ 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():+ returntry:- unlock = self._unlock_module()+ if unlock.is_locked() is not True:+ returnexcept Exception:- LOGGER.exception("Unlock support unavailable")- return- if unlock.is_locked() is not True:- return- if self._unlocking.is_set():+ LOGGER.exception("Could not tell whether this machine is locked")returnself._unlocking.set()- LOGGER.info("%s switched to a locked PC; asking the provider to unlock", peer)+ LOGGER.info("%s's input arrived at a locked machine; asking the provider to unlock", link.name)self._set_status(ServerState.CONNECTED, "Unlocking Windows…")- with self._lock:- generation = self._session_generation- threading.Thread(- target=self._unlock_worker,- args=(unlock, peer, host, generation),- name="Beamer-unlock",- daemon=True,- ).start()-- def _unlock_worker(self, unlock, peer: str, host: str, generation: int) -> None:+ 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("Unlock failed for %s", peer)+ LOGGER.exception("The unlock failed")unlocked = Falsefinally:self._unlocking.clear()- # An unlock takes seconds, so the Mac may have gone in the meantime and- # the session's own exit already have set WAITING. Only the session- # that asked for this unlock may report its outcome.- if not self._is_current_session(generation):- return- if unlocked:- self._set_status(ServerState.CONNECTED, f"Connected to {host}")+ # 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"- )+ self._set_status(ServerState.CONNECTED, "Windows is locked — unlock it at the PC")- def _handle_focus(- self,- message: dict,- connection: socket.socket,- session: protocol.SecureSession,- peer: str,- host: str,- ) -> None:- """`focus{target:"mac"}` means the Mac just switched input back to- itself: reply with this Windows clipboard's text so the Mac's- pasteboard picks up whatever was last copied here.- `target:"windows"` means input is coming here: learn the way home- from it, land the pointer where a crossing says, and clear the lock- screen out of its way."""- data = message.get("data")- target = data.get("target") if isinstance(data, dict) else None- if target == self._peer_target:- # Released before the owner hears input is home: the Mac's tap- # comes back on at that notice, and a modifier still down would- # chord with the first local keystroke.- self._drop_return()- self._release_peer_keys()- if target == self._self_target:- # Raised before anyone hears the peer is driving, and held until the unlock has been- # asked for. Placing the pointer or an owner's callback can take a second, and in- # that second the lock check saw a locked PC with the peer driving and sent its- # input home before the provider that could have unlocked it was tried.- self._arriving.set()- try:- self._notify_focus(target)- self._arm_return(data)- self._place_pointer(data)- self._begin_unlock(peer, host)- finally:- self._arriving.clear()+ 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- self._notify_focus(target)- if target != self._peer_target:+ 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- clipboard = self._clipboard_module()+ self._lock_checked_at = nowtry:- text, image = clipboard.changed_contents()+ locked = self._unlock.is_locked() is Trueexcept Exception:- LOGGER.exception("Failed to read the local clipboard for %s", peer)+ locked = False+ if not locked:+ self._locked_since = Nonereturn- if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:- LOGGER.warning("Local clipboard text too large; skipping the text for %s", peer)- text = None- if image is not None and len(image) > protocol.CLIPBOARD_IMAGE_MAX_BYTES:- LOGGER.warning(- "Local clipboard image is %d bytes, over the %d cap; skipping the image for %s",- len(image),- protocol.CLIPBOARD_IMAGE_MAX_BYTES,- peer,- )- image = None- if not text and image is None:+ if self._locked_since is None:+ self._locked_since = nowreturn- self._send_message(connection, session, protocol.clipboard_msg(text or None, image))+ 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)- def _handle_inbound_clipboard(self, message: dict, peer: str) -> None:- data = message.get("data")- text = data.get("text") if isinstance(data, dict) else None- 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 %s", peer)- text = None- image = protocol.clipboard_image(data)- if text is None and image is None:+ # 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- clipboard = self._clipboard_module()try:- if not clipboard.set_contents(text, image):- LOGGER.warning("Failed to set the local clipboard for %s", peer)+ callback(*args)except Exception:- LOGGER.exception("Failed to set the local clipboard for %s", peer)+ LOGGER.exception("The %s callback failed", name)- @staticmethod- def _hello_version(message: dict):- data = message.get("data", {})- if not isinstance(data, dict):- return None- return data.get("version")+ 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)- @staticmethod- def _send_message(- connection: socket.socket,- session: protocol.SecureSession,- message: dict,- ) -> bool:- """The session's own lock serialises the seal and the write together,- so frames reach the wire in counter order from every thread."""- try:- protocol.send_msg(connection, session, message)- return True- except (OSError, protocol.ProtocolError) as exc:- LOGGER.warning("Send failed: %s", exc)- return False+ 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")-- @staticmethod- 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:- passdiff --git a/core/settings_sync.py b/core/settings_sync.pyindex 689821a..6ae49ee 100644--- a/core/settings_sync.py+++ b/core/settings_sync.py@@ -1,78 +1,71 @@-"""Same on both machines: the Crossing and Design settings the Mac and the PC keep in step.+"""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 either end is sent to the other;-on every new connection each end announces its own state and the newer `set_at` stands, as the-arrangement does. Turning it on at one end turns it on at the other and carries this end's values-across; turning it off turns it off at both and leaves each end with what it has.+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 onsome, 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. A corner names a place on the leaving-machine's screen, and the two machines face each other, so it crosses the wire in the Mac's frame-and the PC mirrors it across the border between them.+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: the Mac's notch way in and notch look, the haptics,-whether crossings animate on each screen, the arrangement (it has its own stamped message, which-also reaches an older Beamer), and anything outside the Crossing and Design pages.+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 . import return_edge+from .protocol import MACHINE_ID_SIZE-# The ways in both machines have; the notch is the Mac's alone, and a received set keeps the-# receiver's own notch.-WAYS = ("shortcut", "edge", "part", "corner")-CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")TRIGGER_STYLES = ("double_tap", "hold")GLOW_STYLES = ("glow", "beam") + effects.EFFECT_IDSGLOW_COLOURS = ("signal", "colourful", "ocean", "sunset", "mono") + effects.PACK_IDSLENGTHS = 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 = ("methods", "edge_parts", "corner", "resistance_px", "block_while_dragging",- "trigger_key", "trigger_style", "double_tap_ms")+CROSSING_KEYS = ("resistance_px", "block_while_dragging", "shortcut", "trigger_key", "trigger_style", "double_tap_ms")DESIGN_KEYS = ("glow_style", "glow_colour", "effect_length", "shortcut_arrival", "shortcut_arrival_style")-# The PC's field for each wire key; the PC's corner also needs mirroring (see pc_values).+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 = {- "methods": "crossing_methods", "edge_parts": "crossing_edge_parts", "corner": "crossing_corner","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","shortcut_arrival": "shortcut_arrival", "shortcut_arrival_style": "shortcut_arrival_style",}-# The Mac keeps the shortcut at the top of its settings and the rest in `crossing`.+# 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 mirror_corner(corner, edge):- """`corner` as the machine across `edge` names the same place: the two screens face each other,- so the corner flips across the border and keeps its place along it. Its own inverse."""- vertical, horizontal = corner.split("_")- if edge in ("top", "bottom"):- vertical = "bottom" if vertical == "top" else "top"- else:- horizontal = "right" if horizontal == "left" else "left"- return f"{vertical}_{horizontal}"--def _whole(value, low, high):return not isinstance(value, bool) and isinstance(value, int) and low <= value <= highdef _valid(key, value, trigger_keys):- if key == "methods":- return isinstance(value, list) and all(way in WAYS for way in value)- if key == "edge_parts":- return isinstance(value, list) and bool(value) and all(part in return_edge.PARTS for part in value)- if key == "corner":- return value in CORNERSif key == "resistance_px":return _whole(value, 0, 500)- if key in ("block_while_dragging", "shortcut_arrival"):+ 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+ return isinstance(value, str) and value in trigger_keys and value not in NOT_TRIGGERSif key == "trigger_style":return value in TRIGGER_STYLESif key == "double_tap_ms":@@ -88,10 +81,10 @@ def _valid(key, value, trigger_keys):return False-def message_data(on, set_at, values=None):+def message_data(on, set_at, values=None, by=""):"""What a `settings` message carries: whether it is on, when that or a shared value last- changed, and while on, the values."""- data = {"on": bool(on), "set_at": int(set_at)}+ 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}@@ -100,12 +93,12 @@ def message_data(on, set_at, values=None):def read(data, trigger_keys):"""(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 -- is left out- rather than failing the rest. Never raises: a malformed message must not take a link down."""+ 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 isinstance(data, dict) or not isinstance(data.get("on"), bool):return Noneset_at = data.get("set_at")- if isinstance(set_at, bool) or not isinstance(set_at, (int, float)):+ if type(set_at) is not int:return Nonevalues = {}for group, keys in (("crossing", CROSSING_KEYS), ("design", DESIGN_KEYS)):@@ -114,14 +107,27 @@ def read(data, trigger_keys):continuefor key in keys:if key in section and _valid(key, section[key], trigger_keys):- values[key] = list(section[key]) if isinstance(section[key], list) else section[key]- return data["on"], int(set_at), values+ values[key] = section[key]+ return data["on"], set_at, values-def wins(theirs, mine):- """Whether the peer's state replaces this end's: the newer stamp stands, and a tie changes- nothing, so the copy that arrives over the second link is a no-op."""- return int(theirs or 0) > int(mine or 0)+# 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 Nonedef next_stamp(held, now):@@ -131,72 +137,84 @@ def next_stamp(held, now):return max(int(now), int(held or 0) + 1)-def arrived(data, set_at_here, trigger_keys, held=None):+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, or no newer than what is held here.+ 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.- Two ends that each changed something in the same second while apart meet with equal stamps- and different values. The Mac's stands: the PC passes `held`, its own (on, values), and takes a- tie that differs from it; the Mac never takes a tie, so nothing goes back and forth."""+ 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)- if read_back is None:+ 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- on, set_at, values = read_back- if wins(set_at, set_at_here):+ 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- if held is not None and int(set_at) == int(set_at_here or 0) and set_at:- held_on, held_values = held- if on != held_on or (on and changed(held_values, {**held_values, **values})):- return read_backreturn 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 ways and thirds in one fixed order, as sets are: the windows build them in tile order,- and a saved list in another order is not a change."""- values["methods"] = [way for way in WAYS if way in (values.get("methods") or [])]- values["edge_parts"] = [part for part in return_edge.PARTS if part in (values.get("edge_parts") or [])]+ """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}+ for key in CROSSING_KEYS + DESIGN_KEYS if key != "shortcut"}+ 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 notch stays in `methods` if it- was there: it is this Mac's own way in."""+ """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 == "methods":- crossing[key] = list(value) + (["notch"] if "notch" in crossing.get("methods", []) else [])+ elif key == "shortcut":+ crossing["methods"] = _with_shortcut(crossing.get("methods", []), value)else:- crossing[key] = list(value) if isinstance(value, list) else value+ crossing[key] = valueraw["crossing"] = crossingreturn rawdef pc_values(config):- """The shared values in the PC's Config, the corner in the Mac's frame. A PC that has not- learned where the Mac is mirrors as if it were on the right, the PC's own default."""+ """The shared values in the PC's Config."""values = {key: getattr(config, field) for key, field in PC_FIELDS.items()}- values["corner"] = mirror_corner(values["corner"], config.mac_return_edge or "right")+ values["shortcut"] = "shortcut" in config.crossing_methodsreturn _in_order(values)def apply_pc(config, values):- """Sets `values` on the PC's Config in place; the corner arrives in the Mac's frame."""+ """Sets `values` on the PC's Config in place."""for key, value in values.items():- if key == "corner":- value = mirror_corner(value, config.mac_return_edge or "right")- setattr(config, PC_FIELDS[key], list(value) if isinstance(value, list) else value)+ if key == "shortcut":+ config.crossing_methods = _with_shortcut(config.crossing_methods, value)+ else:+ setattr(config, PC_FIELDS[key], value)def changed(before, after):@@ -208,19 +226,25 @@ def changed(before, after):SHARED_PAGES = ("crossing", "design")-def scope(page, peer, on, own):+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):"""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."""+ 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 your {peer}. Change it on either machine."+ return f"Kept the same as {who}. Change it on any machine."return own-def switch_note(peer, on, peer_too_old):+def switch_note(who, on, peer_too_old):"""The note under Overview's Same on both machines switch."""if peer_too_old:- return f"Your {peer}'s Beamer is too old to keep settings in step. Update it to turn this on."+ 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 your {peer}'s. A change on either machine reaches the other."- return (f"Off: the Crossing and Design pages are this machine's own. On, they match your {peer}'s, "- "and a change on either reaches the other.")+ 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.")diff --git a/core/tests/responder_harness.py b/core/tests/responder_harness.pynew file mode 100644index 0000000..156978e--- /dev/null+++ b/core/tests/responder_harness.py@@ -0,0 +1,369 @@+"""A version 6 responder on loopback, and a scripted initiator that speaks to it through+protocol.py's builders, so the responder's half of WIRE.md sections 2 to 5, 9 and 10 is tested+without either app's shell. Only the platform edges are faked: the injector, the desktop, the+clipboard and the settings the peer book reads."""++import base64+import copy+import queue+import socket+import threading+import time++from core import protocol, receiver+from core.return_edge import Rect+++def token(seed):+ return base64.urlsafe_b64encode(bytes((seed + i) % 256 for i in range(32))).decode("ascii").rstrip("=")+++def ident(seed):+ return bytes((seed + i) % 256 for i in range(1, 17))+++HERE = ident(10)+B, C, D = ident(40), ident(70), ident(100)+TOKENS = {B: token(1), C: token(2), D: token(3)}+MONITORS = [Rect(0, 0, 1920, 1080)]+++def entry(peer, name, **fields):+ """A peer entry as settings.json holds it (WIRE.md section 1)."""+ data = {+ "id": protocol.id_text(peer) if isinstance(peer, bytes) else peer,+ "name": name,+ "platform": "macos",+ "token": fields.pop("token", None) or TOKENS.get(peer),+ "host": "192.168.77.9",+ "port": 24820,+ "hw": "",+ "send": True,+ "allow_drive": True,+ "side": "",+ "side_set_at": 0,+ "side_by": "",+ "paired_with": [],+ "paired_at": 1790000000,+ "linked": True,+ "from_1_4": False,+ }+ data.update(fields)+ return data+++class Settings:+ """The app's settings as held in memory: `load` gives them, `save` replaces them."""++ def __init__(self, peers, zones=(), own=HERE):+ self.data = {"schema": 6, "machine_id": protocol.id_text(own), "peers": copy.deepcopy(list(peers)), "zones": copy.deepcopy(list(zones))}+ self.saves = 0++ def load(self):+ return self.data++ def save(self, data):+ self.data = copy.deepcopy(data)+ self.saves += 1++ def peer(self, key):+ for item in self.data["peers"]:+ if item["token"] == key or item["id"] == key:+ return item+ return None+++class FakeInjector:+ def __init__(self):+ self.calls = []+ self.keys_us = []+ self._lock = threading.Lock()++ def _add(self, *call):+ with self._lock:+ self.calls.append(call)++ def inject_key(self, key, down, us=None):+ with self._lock:+ self.keys_us.append(us)+ self._add("key", key, down)++ def inject_mouse_move(self, dx, dy):+ self._add("move", dx, dy)++ def inject_mouse_button(self, button, down):+ self._add("button", button, down)++ def inject_scroll(self, dy, dx=0.0, mode="line"):+ self._add("scroll", dy, dx, mode)++ def inject_gesture(self, name):+ self._add("gesture", name)++ def inject_text(self, text):+ self._add("text", text)++ def release_all(self):+ self._add("release_all")++ def seen(self):+ with self._lock:+ return list(self.calls)+++class FakeDesktop:+ def __init__(self, monitors=MONITORS, cursor=(960, 540), slow=0.0):+ self._monitors = list(monitors)+ self.cursor = cursor+ self.slow = slow+ self.placed = []++ def monitors(self):+ return list(self._monitors)++ def cursor_position(self):+ return self.cursor++ def set_cursor_position(self, x, y):+ if self.slow:+ time.sleep(self.slow)+ self.cursor = (x, y)+ self.placed.append((x, y))+++class FakeClipboard:+ """`stamp` rises on every change, as the Mac's change count and Windows' sequence number do."""++ def __init__(self, text="here", events=None):+ self.text = text+ self.image = None+ self.stamp = 1+ self.set_calls = []+ self.slow_get = 0.0+ self.slow_set = 0.0+ self.events = events if events is not None else []++ def change_stamp(self):+ return self.stamp++ def copy(self, text):+ self.text = text+ self.stamp += 1++ def get_contents(self):+ time.sleep(self.slow_get)+ return self.text, self.image++ def set_contents(self, text, image):+ time.sleep(self.slow_set)+ self.events.append(("set", text))+ self.set_calls.append((text, image))+ self.text, self.image = text, image+ self.stamp += 1+ return True+++CAPS = ["clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings"]+++def wait_for(predicate, timeout=3.0):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return True+ time.sleep(0.005)+ return bool(predicate())+++class Machine:+ """A responder listening on loopback, with fakes at every platform edge."""++ def __init__(self, peers, zones=(), caps=CAPS, away=False, desktop=None, notch_span=None, own=HERE, name="Here", unlock=None, hardware=None, hw=None):+ self.own = own+ self.settings = Settings(peers, zones, own)+ self.book = receiver.PeerBook(self.settings.load, self.settings.save)+ self.injector = FakeInjector()+ self.desktop = desktop or FakeDesktop()+ self.events = []+ self.clipboard = FakeClipboard(events=self.events)+ self.away = away+ self.statuses = []+ self.notices = []+ self.owners = []+ self.arrivals = []+ self.pressures = []+ self.arrangements = []+ self.settings_seen = []+ self.paired = []+ self.links = []+ self.announcements = {}+ self.responder = receiver.LinkResponder(+ self.book,+ lambda: {"id": own, "name": name, "platform": "windows", "app": "1.5.0", "caps": list(caps), **({"hw": hw} if hw else {})},+ status_callback=lambda state, detail: self.statuses.append((state, detail)),+ injector=self.injector,+ desktop=self.desktop,+ clipboard=self.clipboard,+ unlock=unlock,+ hardware=hardware,+ away=lambda: self.away() if callable(self.away) else self.away,+ zones=lambda: self.settings.data["zones"],+ notch_span=notch_span,+ owner_callback=lambda peer: (self.owners.append(peer), self.events.append(("owner", peer))),+ arrival_callback=lambda edge, x, y: self.arrivals.append((edge, x, y)),+ pressure_callback=lambda edge, pressure, crossed, part: self.pressures.append((edge, pressure, crossed, part)),+ arrangement_callback=lambda peer, read: self.arrangements.append((peer, read)),+ settings_callback=lambda peer, data: self.settings_seen.append((peer, data)),+ paired_callback=lambda peer, ids: self.paired.append((peer, ids)),+ notice_callback=self.notices.append,+ link_callback=lambda peer, up: self.links.append((peer, up)),+ announce=lambda peer: list(self.announcements.get(peer, [])),+ )+ self.port = None++ def start(self):+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ self.port = probe.getsockname()[1]+ self.responder.start(self.port)+ assert wait_for(lambda: self.responder.listening and self._accepting()), "the responder did not listen"+ return self++ def _accepting(self):+ try:+ with socket.create_connection(("127.0.0.1", self.port), timeout=0.2):+ return True+ except OSError:+ return False++ def stop(self):+ self.responder.stop()++ def injected(self):+ return [call for call in self.injector.seen() if call[0] != "release_all"]+++class Initiator:+ """A scripted version 6 initiator. Its reader thread queues every frame the responder sends."""++ def __init__(self, machine, peer=B, key=None, preamble=True):+ self.peer = peer+ self.token = key or TOKENS[peer]+ self.sock = socket.create_connection(("127.0.0.1", machine.port), timeout=5)+ self.session = protocol.LinkSession(self.token, protocol.ROLE_INITIATOR)+ self.inbox = queue.Queue()+ self.seen = []+ self.unclaimed = []+ self.closed = threading.Event()+ self.seq = 0+ self.route = 0+ if preamble:+ self.sock.sendall(self.session.preamble())++ def hello(self, **fields):+ data = {"id": self.peer, "name": "Peer", "platform": "macos", "app": "1.5.0", "caps": list(CAPS), "port": 24820}+ data.update(fields)+ return protocol.hello_v6(data.pop("id"), data.pop("name"), data.pop("platform"), data.pop("app"), data.pop("caps"), data.pop("port"), data.pop("hw", None))++ def handshake(self, hello=None, raw=None, reader=True):+ """The responder's `welcome` as read_welcome gives it; raises HelloRefused for its error+ answers and ConnectionClosed when it closes."""+ deadline = time.monotonic() + 5+ self.session.accept_preamble(protocol.recv_link_preamble(self.sock, deadline))+ if raw is not None:+ with self.session.send_lock:+ self.sock.sendall(self.session.seal_raw(raw))+ else:+ protocol.send_msg(self.sock, self.session, hello or self.hello())+ welcome = protocol.read_welcome(protocol.recv_first_msg(self.sock, self.session, deadline))+ if reader:+ threading.Thread(target=self._read, daemon=True).start()+ return welcome++ def _read(self):+ self.sock.settimeout(None)+ try:+ while True:+ self.inbox.put(protocol.recv_msg(self.sock, self.session))+ except Exception:+ self.closed.set()++ def send(self, message):+ protocol.send_msg(self.sock, self.session, message)++ def input(self, message):+ self.seq += 1+ message = copy.deepcopy(message)+ message["data"]["seq"] = self.seq+ self.send(message)+ return self.seq++ def key(self, kind, name):+ return self.input(protocol.key_msg(kind, name))++ def move(self, dx, dy):+ return self.input(protocol.mousemove_msg(dx, dy))++ def take(self, route=None, **fields):+ self.route = self.route + 1 if route is None else route+ self.send(protocol.focus_v6(self.route, HERE, **fields))+ return self.route++ def let_go(self, target=None, route=None):+ self.route = self.route + 1 if route is None else route+ self.send(protocol.focus_v6(self.route, target or self.peer))+ return self.route++ def _claim(self, match, timeout):+ """The first frame `match` accepts. Frames passed over are kept for a later call, except+ `ack`s, which are a stream: only one that arrives while it is waited for counts."""+ for message in self.unclaimed:+ if match(message):+ self.unclaimed.remove(message)+ return message+ deadline = time.monotonic() + timeout+ while True:+ left = deadline - time.monotonic()+ if left <= 0:+ return None+ try:+ message = self.inbox.get(timeout=left)+ except queue.Empty:+ return None+ self.seen.append(message)+ if match(message):+ return message+ if message.get("type") != protocol.MSG_ACK:+ self.unclaimed.append(message)++ def expect(self, kind, timeout=2.0, where=None):+ """The next frame of `kind` (and matching `where`); None when none comes."""+ found = self._claim(lambda m: m.get("type") == kind and (where is None or where(m["data"])), timeout)+ return None if found is None else found["data"]++ def answer(self, route, timeout=2.0):+ """The `accept` or `refuse` for `route`, as (type, data), or None."""+ found = self._claim(+ lambda m: m.get("type") in (protocol.MSG_ACCEPT, protocol.MSG_REFUSE) and m["data"].get("route") == route, timeout+ )+ return None if found is None else (found["type"], found["data"])++ def acked(self, seq, timeout=2.0):+ return self.expect(protocol.MSG_ACK, timeout, where=lambda data: data["seq"] >= seq)++ def close(self):+ try:+ self.sock.close()+ except OSError:+ pass+++def silent_close(sock, timeout=2.0):+ """True when the responder closed `sock` without sending a byte."""+ sock.settimeout(timeout)+ try:+ return sock.recv(1) == b""+ except ConnectionError:+ return True+ except socket.timeout:+ return Falsediff --git a/core/tests/test_input_scale.py b/core/tests/test_input_scale.pynew file mode 100644index 0000000..01f6e3d--- /dev/null+++ b/core/tests/test_input_scale.py@@ -0,0 +1,26 @@+import unittest++from core import receiver+++class InputScaleTests(unittest.TestCase):+ def test_a_slower_pointer_carries_its_fractions(self):+ scale = receiver.InputScale(pointer=0.5)+ moves = [scale.move(1, 1) for _ in range(4)]+ self.assertEqual(moves, [(0, 0), (1, 1), (0, 0), (1, 1)])++ def test_a_faster_pointer_multiplies(self):+ self.assertEqual(receiver.InputScale(pointer=2.0).move(3, -4), (6, -8))++ def test_speeds_are_held_to_their_range(self):+ scale = receiver.InputScale(pointer=99, scroll=0)+ self.assertEqual((scale.pointer, scale.scroll), (4.0, 0.25))++ def test_scroll_speed_and_reverse(self):+ self.assertEqual(receiver.InputScale(scroll=2.0).wheel(3, 1), (6.0, 2.0))+ self.assertEqual(receiver.InputScale(reverse=True).wheel(3, -1), (-3.0, 1.0))+ self.assertEqual(receiver.InputScale().wheel(3, 1), (3, 1))+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_keytable.py b/core/tests/test_keytable.pynew file mode 100644index 0000000..aa8eda0--- /dev/null+++ b/core/tests/test_keytable.py@@ -0,0 +1,140 @@+"""WIRE.md section 7's key table: which wire name each physical key sends to each kind of peer."""++import unittest++from core import keytable++MODS = ("ctrl", "ctrl_r", "cmd", "cmd_r", "alt", "alt_r")+MAC = ("macos", "ios")+PC = ("windows", "linux", "android", "plan9")++# Section 7, row by row: (physical key, same family, Semantic, Positional).+MAC_ROWS = [+ ("ctrl", "ctrl", "cmd", "ctrl"),+ ("ctrl_r", "ctrl_r", "cmd", "ctrl"),+ ("cmd", "cmd", "ctrl", "cmd"),+ ("cmd_r", "cmd_r", "ctrl", "cmd"),+ ("alt", "alt", "alt", "alt"),+ ("alt_r", "alt_r", "alt", "alt"),+]+PC_ROWS = [+ ("ctrl", "ctrl", "cmd", "ctrl"),+ ("ctrl_r", "ctrl_r", "cmd_r", "ctrl_r"),+ ("cmd", "cmd", "ctrl", "cmd"),+ ("cmd_r", "cmd_r", "ctrl_r", "cmd_r"),+ ("alt", "alt", "alt", "alt"),+ ("alt_r", "alt_r", "alt_r", "alt_r"),+]++# 1.4.x as it stands: the Mac's two key_map styles, and Windows' capture names (Ctrl is "cmd", the+# Windows key is "ctrl") with POSITIONAL_SWAP on top.+DEFAULT_KEY_MAP = {"alt": "alt", "alt_r": "alt", "ctrl": "cmd", "ctrl_r": "cmd", "cmd": "ctrl", "cmd_r": "ctrl"}+LEGACY_POSITIONAL_KEY_MAP = {"alt": "alt", "alt_r": "alt", "ctrl": "ctrl", "ctrl_r": "ctrl", "cmd": "cmd", "cmd_r": "cmd"}+POSITIONAL_SWAP = {"cmd": "ctrl", "cmd_r": "ctrl_r", "ctrl": "cmd", "ctrl_r": "cmd_r"}+WINDOWS_CAPTURE = {"ctrl": "cmd", "ctrl_r": "cmd_r", "cmd": "ctrl", "cmd_r": "ctrl_r", "alt": "alt", "alt_r": "alt_r"}+++class TableTests(unittest.TestCase):+ def test_every_row_for_a_mac_sender(self):+ for own in MAC:+ for physical, same, semantic, positional in MAC_ROWS:+ for peer in MAC:+ for style in ("semantic", "positional"):+ self.assertEqual(keytable.wire_name(physical, own, peer, style), same, (own, peer, physical))+ for peer in PC:+ self.assertEqual(keytable.wire_name(physical, own, peer, "semantic"), semantic, (own, peer, physical))+ self.assertEqual(keytable.wire_name(physical, own, peer, "positional"), positional, (own, peer, physical))++ def test_every_row_for_a_pc_sender(self):+ for own in PC:+ for physical, same, semantic, positional in PC_ROWS:+ for peer in PC:+ for style in ("semantic", "positional"):+ self.assertEqual(keytable.wire_name(physical, own, peer, style), same, (own, peer, physical))+ for peer in MAC:+ self.assertEqual(keytable.wire_name(physical, own, peer, "semantic"), semantic, (own, peer, physical))+ self.assertEqual(keytable.wire_name(physical, own, peer, "positional"), positional, (own, peer, physical))++ def test_an_unknown_platform_is_a_pc_on_both_sides(self):+ self.assertEqual(keytable.wire_name("cmd", "haiku", "macos", "semantic"), "ctrl")+ self.assertEqual(keytable.wire_name("cmd", "macos", "haiku", "semantic"), "ctrl")+ self.assertEqual(keytable.wire_name("cmd", "haiku", "beos", "semantic"), "cmd")++ def test_keys_that_are_not_those_six_go_out_as_themselves(self):+ for name in ("shift", "shift_r", "caps_lock", "a", "enter", "f13", "volume_up", "not_a_key"):+ for own, peer in (("macos", "windows"), ("windows", "macos"), ("linux", "linux"), ("macos", "ios")):+ for style in ("semantic", "positional"):+ self.assertEqual(keytable.wire_name(name, own, peer, style), name)+++class OldStylesTests(unittest.TestCase):+ def test_a_mac_with_a_saved_key_map_sends_what_1_4_x_sent(self):+ for saved, style in ((DEFAULT_KEY_MAP, "semantic"), (LEGACY_POSITIONAL_KEY_MAP, "positional")):+ for name in MODS + ("shift", "caps_lock", "f1"):+ expected = saved.get(name, name)+ self.assertEqual(keytable.wire_name(name, "macos", "windows", style), expected, (style, name))+ self.assertEqual(keytable.wire_name(name, "macos", "windows", dict(saved)), expected, (style, name))++ def test_windows_with_a_saved_modifier_style_sends_what_1_4_x_sent(self):+ for physical in MODS:+ capture = WINDOWS_CAPTURE[physical]+ self.assertEqual(keytable.wire_name(physical, "windows", "macos", "semantic"), capture)+ self.assertEqual(keytable.wire_name(physical, "windows", "macos", "positional"), POSITIONAL_SWAP.get(capture, capture))++ def test_a_hand_written_map_applies_across_families_only(self):+ mine = {"alt": "cmd", "cmd": "alt"}+ self.assertEqual(keytable.wire_name("alt", "macos", "windows", mine), "cmd")+ self.assertEqual(keytable.wire_name("ctrl", "macos", "windows", mine), "ctrl")+ self.assertEqual(keytable.wire_name("alt", "macos", "macos", mine), "alt")+ self.assertEqual(keytable.wire_name("alt", "windows", "windows", mine), "alt")++ def test_a_style_nobody_offers_is_refused(self):+ with self.assertRaises(ValueError):+ keytable.wire_name("ctrl", "macos", "windows", "sideways")+++class EvdevTests(unittest.TestCase):+ def test_the_modifier_codes_the_spec_names(self):+ self.assertEqual(keytable.evdev_physical(29), "ctrl")+ self.assertEqual(keytable.evdev_physical(97), "ctrl_r")+ self.assertEqual(keytable.evdev_physical(125), "cmd")+ self.assertEqual(keytable.evdev_physical(126), "cmd_r")+ self.assertEqual(keytable.evdev_physical(56), "alt")+ self.assertEqual(keytable.evdev_physical(100), "alt_r")+ self.assertEqual(keytable.evdev_physical(42), "shift")+ self.assertEqual(keytable.evdev_physical(54), "shift_r")+ self.assertEqual(keytable.evdev_physical(58), "caps_lock")++ def test_a_linux_sender_goes_through_the_same_table(self):+ cases = {29: "cmd", 97: "cmd_r", 125: "ctrl", 126: "ctrl_r", 56: "alt", 100: "alt_r"}+ for code, wire in cases.items():+ self.assertEqual(keytable.wire_name(keytable.evdev_physical(code), "linux", "macos", "semantic"), wire)+ self.assertEqual(keytable.wire_name(keytable.evdev_physical(125), "linux", "macos", "positional"), "cmd")+ self.assertEqual(keytable.wire_name(keytable.evdev_physical(125), "linux", "windows", "semantic"), "cmd")++ def test_named_keys_and_the_numpad_enter(self):+ self.assertEqual(keytable.evdev_physical(1), "esc")+ self.assertEqual(keytable.evdev_physical(28), "enter")+ self.assertEqual(keytable.evdev_physical(96), "enter")+ self.assertEqual(keytable.evdev_physical(59), "f1")+ self.assertEqual(keytable.evdev_physical(88), "f12")+ self.assertEqual(keytable.evdev_physical(183), "f13")+ self.assertEqual(keytable.evdev_physical(194), "f24")+ self.assertEqual(keytable.evdev_physical(111), "delete")+ self.assertEqual(keytable.evdev_physical(113), "volume_mute")++ def test_every_name_it_returns_is_in_the_spec_and_no_name_twice_but_enter(self):+ names = list(keytable.EVDEV_NAMES.values())+ self.assertLessEqual(set(names), keytable.SPEC_NAMES)+ self.assertEqual([n for n in set(names) if names.count(n) > 1], ["enter"])++ def test_a_character_key_or_an_unknown_code_is_none(self):+ self.assertIsNone(keytable.evdev_physical(30))+ self.assertIsNone(keytable.evdev_physical(99999))++ def test_the_stand_in_code_is_still_right_ctrl(self):+ self.assertEqual(keytable.evdev_physical(97), "ctrl_r")+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_link.py b/core/tests/test_link.pynew file mode 100644index 0000000..b07748c--- /dev/null+++ b/core/tests/test_link.py@@ -0,0 +1,1108 @@+"""core.link.OutboundLink, the initiator's side of WIRE.md sections 2, 3 and 9, against a real+LinkResponder on loopback (responder_harness.Machine) and a scripted responder where a test needs+a peer that misbehaves."""++import socket+import threading+import time+import unittest+from unittest import mock++from core import protocol, receiver+from core import link as link_module+from core.link import OutboundLink+from core.tests.responder_harness import B, C, CAPS, HERE, TOKENS, Machine, Settings, entry, wait_for++LOOPBACK = "127.0.0.1"+++class Side:+ """The initiator's own settings, with one peer entry for the machine it dials."""++ def __init__(self, machine=None, peer=HERE, own=B, token=None, **fields):+ port = machine.port if machine is not None else 24820+ data = entry(peer, "Far", token=token or TOKENS[B], host=LOOPBACK, port=port, send=True, **fields)+ self.settings = Settings([data])+ self.settings.data["machine_id"] = protocol.id_text(own)+ self.own = own+ self.book = receiver.PeerBook(self.settings.load, self.settings.save)+ self.states, self.ups, self.messages, self.notices = [], [], [], []++ def identity(self, **fields):+ data = {"id": self.own, "name": "Near", "platform": "macos", "app": "1.5.0", "caps": list(CAPS), "port": 24820}+ data.update(fields)+ return data++ def link(self, **kwargs):+ kwargs.setdefault("reconnect_seconds", 0.05)+ link = OutboundLink(+ self.settings.data["peers"][0]["token"], self.book, self.identity,+ state=lambda link, up, text: self.states.append((up, text)),+ up=lambda link, fields: self.ups.append(fields),+ message=lambda link, message: self.messages.append(message),+ notice=self.notices.append,+ **kwargs,+ )+ return link++ def peer(self):+ return self.settings.data["peers"][0]++ def last_text(self):+ return self.states[-1][1] if self.states else None+++def machine_with_peer(**kwargs):+ from core.tests.responder_harness import entry as make+ return Machine([make(B, "Peer")], **kwargs).start()+++class Scripted:+ """A listener that runs `script(connection)` for each connection."""++ def __init__(self, script):+ self.script = script+ self.listener = socket.socket()+ self.listener.bind((LOOPBACK, 0))+ self.listener.listen(4)+ self.port = self.listener.getsockname()[1]+ self.connections = 0+ self.stopped = False+ self.thread = threading.Thread(target=self._serve, daemon=True)+ self.thread.start()++ def _serve(self):+ while not self.stopped:+ try:+ connection, _ = self.listener.accept()+ except OSError:+ return+ self.connections += 1+ threading.Thread(target=self._one, args=(connection,), daemon=True).start()++ def _one(self, connection):+ try:+ self.script(connection)+ except Exception:+ pass+ finally:+ try:+ connection.close()+ except OSError:+ pass++ def stop(self):+ self.stopped = True+ self.listener.close()+++def scripted_session(connection, token):+ """The responder's half of the handshake up to its own preamble; the session and hello."""+ session = protocol.LinkSession(token, protocol.ROLE_RESPONDER)+ session.accept_preamble(protocol.recv_link_preamble(connection, time.monotonic() + 5))+ connection.sendall(session.preamble())+ hello = protocol.read_hello(protocol.recv_first_msg(connection, session, time.monotonic() + 5))+ return session, hello+++class LinkHandshakeTests(unittest.TestCase):+ def setUp(self):+ self.machine = machine_with_peer()+ self.addCleanup(self.machine.stop)++ def start(self, side, **kwargs):+ link = side.link(**kwargs)+ self.addCleanup(link.stop)+ link.start()+ return link++ def test_links_and_saves_what_the_welcome_taught(self):+ side = Side(self.machine)+ link = self.start(side)+ self.assertTrue(wait_for(lambda: side.ups), side.states)+ fields = side.ups[0]+ self.assertEqual(fields["id"], HERE)+ self.assertTrue(fields["accepts"])+ self.assertEqual(fields["platform"], "windows")+ self.assertIn("clipboard", fields["caps"])+ self.assertTrue(link.live())+ self.assertTrue(side.peer()["linked"])+ self.assertEqual(side.peer()["name"], "Here")+ self.assertEqual(link.peer_id, protocol.id_text(HERE))+ self.assertTrue(wait_for(lambda: self.machine.links))++ def test_a_migrated_entry_learns_the_peer_id(self):+ side = Side(self.machine, linked=False, from_1_4=True)+ side.peer()["id"] = ""+ self.start(side)+ self.assertTrue(wait_for(lambda: side.ups), side.states)+ self.assertEqual(side.peer()["id"], protocol.id_text(HERE))+ self.assertTrue(side.peer()["linked"])+ self.assertTrue(any("for the first time on Beamer 1.5.0" in text for text in side.notices), side.notices)++ def test_accepts_is_false_when_the_peer_does_not_let_this_machine_drive(self):+ self.machine.settings.peer(TOKENS[B])["allow_drive"] = False+ side = Side(self.machine)+ self.start(side)+ self.assertTrue(wait_for(lambda: side.ups), side.states)+ self.assertFalse(side.ups[0]["accepts"])++ def test_a_different_id_than_the_entry_has_is_refused_and_taught_nothing(self):+ side = Side(self.machine, peer=ident_other())+ self.start(side)+ self.assertTrue(wait_for(lambda: side.states and not side.states[-1][0]), side.states)+ self.assertEqual(side.ups, [])+ self.assertIn("different Beamer", side.last_text())++ def test_a_typed_token_is_never_dialled(self):+ side = Side(self.machine, token="hunter2")+ link = self.start(side)+ time.sleep(0.4)+ self.assertEqual(self.machine.links, [])+ self.assertFalse(link.live())++ def test_send_off_is_not_dialled(self):+ side = Side(self.machine)+ side.peer()["send"] = False+ self.start(side)+ time.sleep(0.3)+ self.assertEqual(self.machine.links, [])++ def test_a_peer_that_does_not_know_the_key_id_closes_and_the_text_follows_linked(self):+ for linked, expected in ((False, "Update Beamer on Far to 1.5.0"), (True, "closed the connection")):+ side = Side(self.machine, token=other_token(), linked=linked)+ link = self.start(side)+ self.assertTrue(wait_for(lambda: side.states and not side.states[-1][0]), side.states)+ self.assertIn(expected, side.last_text())+ link.stop()++ def test_an_entry_removed_stops_the_link(self):+ side = Side(self.machine)+ link = self.start(side)+ self.assertTrue(wait_for(lambda: side.ups))+ side.settings.data["peers"].clear()+ self.assertTrue(wait_for(lambda: not link.live() and not link.running, 5.0))++ def test_one_failed_read_of_the_settings_does_not_end_the_link(self):+ side = Side(self.machine)+ reads = []+ load = side.settings.load++ def flaky():+ reads.append(1)+ if len(reads) == 1:+ raise PermissionError("settings.json is locked")+ return load()++ side.book = receiver.PeerBook(flaky, side.settings.save)+ link = self.start(side)+ self.assertTrue(wait_for(lambda: side.ups, 5.0), side.states)+ self.assertTrue(link.running)+++def ident_other():+ return bytes((200 + i) % 256 for i in range(1, 17))+++def other_token():+ import base64+ return base64.urlsafe_b64encode(bytes((9 + i) % 256 for i in range(32))).decode("ascii").rstrip("=")+++class LinkRefusalTests(unittest.TestCase):+ def serve(self, script):+ server = Scripted(script)+ self.addCleanup(server.stop)+ return server++ def link(self, side, **kwargs):+ link = side.link(**kwargs)+ self.addCleanup(link.stop)+ link.start()+ return link++ def test_a_version_5_peer_is_named_as_older(self):+ def script(connection):+ connection.recv(62)+ connection.sendall(b"BEAMY\x05" + bytes(8))+ time.sleep(0.5)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states), side.states)+ self.assertIn("Update Beamer on Far: it is older than this one", side.last_text())++ def test_two_machines_of_one_name_are_told_apart_in_what_the_link_says(self):+ def script(connection):+ connection.recv(62)+ connection.sendall(b"BEAMY\x05" + bytes(8))+ time.sleep(0.5)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ side.peer()["name"] = "Studio"+ twin = entry(C, "studio", token=TOKENS[C], host="192.0.2.9", port=24820, send=True)+ side.settings.data["peers"].append(twin)+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states), side.states)+ self.assertIn(f"Update Beamer on Studio ({protocol.id_text(HERE)[-4:]}): it is older than this one", side.last_text())++ def test_a_newer_peer_says_this_machine_is_older(self):+ def script(connection):+ connection.recv(62)+ connection.sendall(b"BEAMY\x07" + bytes(8))+ time.sleep(0.5)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states))+ self.assertIn("newer Beamer", side.last_text())++ def test_a_peer_that_is_not_a_beamer_is_said_to_be_one_from_before_version_4(self):+ def script(connection):+ connection.recv(62)+ time.sleep(6)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states, 8.0), side.states)+ self.assertIn("before version 4", side.last_text())++ def test_a_peer_that_answers_with_something_else_is_said_not_to_be_a_beamer(self):+ def script(connection):+ connection.recv(62)+ connection.sendall(b"HTTP/1.1 400 Bad Request\r\n\r\n")+ time.sleep(0.5)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states), side.states)+ self.assertEqual(side.last_text(), "Far did not answer as a Beamer")++ def test_a_responder_that_names_another_key_id_is_a_different_beamer(self):+ def script(connection):+ connection.recv(62)+ connection.sendall(b"BEAMY\x06" + bytes(8) + bytes(16) + bytes(32))+ time.sleep(0.5)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states))+ self.assertIn("different Beamer", side.last_text())++ def test_wrong_id_stops_dialling_until_the_entry_changes(self):+ def script(connection):+ session, _ = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.wrong_id_v6())+ time.sleep(0.3)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ link = self.link(side)+ self.assertTrue(wait_for(lambda: side.states))+ self.assertIn("under another machine: remove it on both and pair again", side.last_text())+ seen = server.connections+ time.sleep(0.5)+ self.assertEqual(server.connections, seen)+ side.peer()["host"] = "localhost"+ self.assertTrue(wait_for(lambda: server.connections > seen, 3.0))+ link.stop()++ def test_invalid_hello_says_this_app_sent_something_unreadable(self):+ def script(connection):+ session, _ = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.invalid_hello_v6())+ time.sleep(0.3)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states))+ self.assertIn("could not read", side.last_text())++ def test_a_welcome_naming_this_machine_is_closed_with_nothing_taught(self):+ def script(connection):+ session, _ = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(B, "Me", "macos", "1.5.0", CAPS, True))+ time.sleep(0.3)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ side.peer()["id"] = ""+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states))+ self.assertIn("different Beamer", side.last_text())+ self.assertEqual(side.peer()["id"], "")+ self.assertEqual(side.ups, [])+++class LinkLiveTests(unittest.TestCase):+ def setUp(self):+ self.machine = machine_with_peer()+ self.addCleanup(self.machine.stop)+ self.side = Side(self.machine)+ self.link = self.side.link()+ self.addCleanup(self.link.stop)+ self.link.start()+ self.assertTrue(wait_for(lambda: self.side.ups), self.side.states)++ def take(self, route=1):+ self.assertTrue(self.link.post(protocol.focus_v6(route, HERE, resistance_px=120, reach=[])))+ self.assertTrue(wait_for(lambda: any(m["type"] == protocol.MSG_ACCEPT for m in self.side.messages)), self.side.messages)++ def test_send_input_numbers_from_one_and_the_responder_injects_for_its_owner(self):+ self.take()+ self.assertTrue(self.link.send_input(protocol.key_msg("keydown", "a")))+ self.assertTrue(self.link.send_input(protocol.mousemove_msg(3, 4)))+ self.assertTrue(wait_for(lambda: ("move", 3, 4) in self.machine.injected()))+ self.assertIn(("key", "a", True), self.machine.injected())+ self.assertEqual(self.link.last_sent_seq, 2)++ def test_acks_give_round_trip_samples_that_are_never_negative(self):+ self.take()+ for _ in range(5):+ self.link.send_input(protocol.mousemove_msg(1, 1))+ time.sleep(0.03)+ self.assertTrue(wait_for(lambda: self.link.round_trips()), "no round trip measured")+ self.assertTrue(all(sample >= 0 for sample in self.link.round_trips()))+ self.assertIsNotNone(self.link.last_ack_at)++ def test_inbound_messages_other_than_acks_reach_the_callback(self):+ self.link.post(protocol.focus_v6(1, HERE, resistance_px=120, reach=[]))+ self.assertTrue(wait_for(lambda: self.side.messages))+ self.assertEqual(self.side.messages[0]["type"], protocol.MSG_ACCEPT)+ self.assertNotIn(protocol.MSG_ACK, [m["type"] for m in self.side.messages])++ def test_a_clipboard_is_dropped_when_the_peer_lacks_the_capability(self):+ self.link._caps = frozenset()+ self.assertTrue(self.link.post(protocol.clipboard_msg("hello")))+ time.sleep(0.2)+ self.assertEqual(self.machine.clipboard.set_calls, [])++ def test_settings_are_not_sent_to_a_peer_without_the_capability(self):+ self.link._caps = frozenset()+ self.assertTrue(self.link.post(protocol.settings_msg({"a": 1})))+ time.sleep(0.2)+ self.assertEqual(self.machine.settings_seen, [])++ def test_the_link_reconnects_after_the_responder_closes_it(self):+ first = len(self.side.ups)+ self.machine.responder.peers_changed()+ self.side.peer()["linked"] = True+ for link in list(self.machine.responder._links.values()):+ link.close()+ self.assertTrue(wait_for(lambda: len(self.side.ups) > first, 5.0), self.side.states)++ def test_stop_ends_the_link_and_the_responder_sees_it_go(self):+ self.link.stop()+ self.assertTrue(wait_for(lambda: (protocol_id(B), False) in self.machine.links))+ self.assertFalse(self.link.live())++ def test_a_full_queue_reports_failure(self):+ self.link._stall.set()+ results = [self.link.send_input(protocol.mousemove_msg(1, 1)) for _ in range(2100)]+ self.link._stall.clear()+ self.assertIn(False, results)+ self.assertEqual(results.count(True), 2048)+++def protocol_id(ident):+ return ident+++class LinkLivenessTests(unittest.TestCase):+ def test_a_silent_peer_ends_the_link_after_two_seconds(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ time.sleep(6)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ began = time.monotonic()+ self.assertTrue(wait_for(lambda: "stopped responding" in (side.last_text() or ""), 5.0), side.states)+ self.assertGreaterEqual(time.monotonic() - began, 1.5)+ self.assertFalse(link.live())++ def test_an_idle_link_pings_each_second(self):+ pings = []++ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ connection.settimeout(3)+ started = time.monotonic()+ while time.monotonic() - started < 2.6:+ try:+ message = protocol.recv_msg(connection, session)+ except OSError:+ return+ if message["type"] == protocol.MSG_PING:+ pings.append(message)+ protocol.send_msg(connection, session, protocol.ack_v6(0, 0))++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link()+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: len(pings) >= 2, 4.0), pings)++ def test_an_ack_ahead_of_anything_sent_ends_the_link(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ protocol.send_msg(connection, session, protocol.ack_v6(5, 0))+ time.sleep(1)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ self.assertTrue(wait_for(lambda: not link.live(), 3.0))++ def test_an_ack_with_a_negative_held_us_ends_the_link(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ protocol.send_msg(connection, session, {"type": "ack", "data": {"seq": 0, "held_us": -1}})+ time.sleep(1)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ self.assertTrue(wait_for(lambda: not link.live(), 3.0))++ def test_an_ack_that_says_locked_sets_peer_locked_until_one_that_does_not(self):+ cleared = threading.Event()++ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ protocol.send_msg(connection, session, protocol.ack_v6(0, 0, locked=True))+ cleared.wait(5)+ protocol.send_msg(connection, session, protocol.ack_v6(0, 0))+ time.sleep(2)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ self.assertTrue(wait_for(lambda: link.peer_locked), side.states)+ cleared.set()+ self.assertTrue(wait_for(lambda: not link.peer_locked), side.states)+ self.assertTrue(link.live())+++class FakeClock:+ def __init__(self):+ self.now = 1000.0++ def __call__(self):+ return self.now+++class LinkFollowTests(unittest.TestCase):+ def link(self, clock, tried):+ side = Side(None)+ side.peer()["host"] = "192.168.77.7"++ def factory(address, timeout=None):+ tried.append(address)+ raise OSError("no route")++ link = side.link(socket_factory=factory, clock=clock, reconnect_seconds=0.02)+ self.addCleanup(link.stop)+ return side, link++ def test_a_beacon_with_the_exact_name_is_tried_once_the_link_has_been_down_ten_seconds(self):+ clock, tried = FakeClock(), []+ side, link = self.link(clock, tried)+ link.start()+ self.assertTrue(wait_for(lambda: tried))+ tried.clear()+ beacon = [{"name": "Far", "address": "192.168.77.9"}, {"name": "Other", "address": "192.168.77.10"}]+ link.follow(beacon)+ time.sleep(0.2)+ self.assertNotIn(("192.168.77.9", 24820), tried)+ clock.now += 11+ link.follow(beacon)+ self.assertTrue(wait_for(lambda: ("192.168.77.9", 24820) in tried), tried)+ self.assertNotIn(("192.168.77.10", 24820), tried)+ tried.clear()+ clock.now += 5+ link.follow(beacon)+ time.sleep(0.2)+ self.assertNotIn(("192.168.77.9", 24820), tried)+ clock.now += 30+ link.follow(beacon)+ self.assertTrue(wait_for(lambda: ("192.168.77.9", 24820) in tried), tried)++ def test_a_failed_try_shows_nothing_and_saves_nothing(self):+ clock, tried = FakeClock(), []+ side, link = self.link(clock, tried)+ link.start()+ self.assertTrue(wait_for(lambda: tried))+ clock.now += 11+ link.follow([{"name": "Far", "address": "192.168.77.9"}])+ self.assertTrue(wait_for(lambda: ("192.168.77.9", 24820) in tried))+ self.assertEqual(side.peer()["host"], "192.168.77.7")++ def test_the_address_is_saved_once_the_link_authenticates_there(self):+ machine = machine_with_peer()+ self.addCleanup(machine.stop)+ clock = FakeClock()+ side = Side(machine)+ side.peer()["host"] = "10.255.255.1"++ real = socket.create_connection++ def factory(address, timeout=None):+ if address[0] == "10.255.255.1":+ raise OSError("no route")+ return real(address, timeout=timeout)++ link = side.link(socket_factory=factory, clock=clock)+ self.addCleanup(link.stop)+ link.start()+ time.sleep(0.2)+ clock.now += 11+ link.follow([{"name": "Far", "address": LOOPBACK}])+ self.assertTrue(wait_for(lambda: side.ups), side.states)+ self.assertEqual(side.peer()["host"], LOOPBACK)+++class LinkTunnelTests(unittest.TestCase):+ def test_an_unreachable_host_falls_back_to_the_tunnel(self):+ import errno+ machine = machine_with_peer()+ self.addCleanup(machine.stop)+ side = Side(machine)++ def factory(address, timeout=None):+ raise OSError(errno.EHOSTUNREACH, "no route")++ link = side.link(socket_factory=factory, tunnel=lambda: socket.create_connection((LOOPBACK, machine.port), timeout=1))+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups), side.states)+ self.assertTrue(link.via_tunnel)+++class LinkFoldAndHeldTests(unittest.TestCase):+ def test_a_migrated_entry_whose_peer_is_already_paired_is_folded_and_the_link_ends(self):+ machine = machine_with_peer()+ self.addCleanup(machine.stop)+ side = Side(machine, linked=False, from_1_4=True)+ side.peer()["id"] = ""+ side.peer()["platform"] = "windows"+ other = entry(HERE, "Far again", token=other_token(), host="192.168.77.9", port=24820, platform="windows")+ side.settings.data["peers"].append(other)+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.notices), side.states)+ self.assertIn("which is now part of", side.notices[0])+ self.assertEqual([peer["name"] for peer in side.settings.data["peers"]], ["Far again"])+ self.assertEqual(side.ups, [])++ def test_held_us_is_taken_off_the_sample_and_never_goes_below_zero(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ message = protocol.recv_msg(connection, session)+ while message["type"] == protocol.MSG_PING:+ message = protocol.recv_msg(connection, session)+ time.sleep(0.05)+ protocol.send_msg(connection, session, protocol.ack_v6(message["data"]["seq"], 5_000_000))+ time.sleep(0.5)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link()+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ link.send_input(protocol.mousemove_msg(1, 1))+ self.assertTrue(wait_for(lambda: link.round_trips()))+ self.assertEqual(link.round_trips(), [0.0])+++class LinkReviewFindingsTests(unittest.TestCase):+ """What the cold review of the first version found, each shown failing before it was fixed."""++ def test_an_ack_that_beats_the_writers_bookkeeping_does_not_end_the_link(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ connection.settimeout(5)+ while True:+ message = protocol.recv_msg(connection, session)+ seq = message["data"].get("seq")+ if seq:+ protocol.send_msg(connection, session, protocol.ack_v6(seq, 0))++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port++ def slow_clock():+ time.sleep(0.003)+ return time.monotonic()++ link = side.link(clock=slow_clock)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ for _ in range(30):+ self.assertTrue(link.send_input(protocol.mousemove_msg(1, 1)))+ time.sleep(0.01)+ time.sleep(0.3)+ self.assertTrue(link.live(), side.states)++ def test_stop_during_a_handshake_ends_the_thread_and_start_runs_it_again(self):+ def script(connection):+ time.sleep(6)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=0.05)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: server.connections))+ began = time.monotonic()+ link.stop()+ self.assertLess(time.monotonic() - began, 1.0)+ self.assertFalse(link.running)+ before = server.connections+ link.start()+ self.assertTrue(wait_for(lambda: server.connections > before), "the link did not dial again")++ def test_stop_without_waiting_returns_at_once_reports_nothing_after_and_start_runs_it_again(self):+ # A window removing machines must not wait on a link thread that is in a handshake.+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ time.sleep(0.5)+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ time.sleep(1)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link()+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: server.connections))+ time.sleep(0.1)+ began = time.monotonic()+ link.stop(wait=False)+ self.assertLess(time.monotonic() - began, 0.05)+ states, ups = list(side.states), list(side.ups)+ time.sleep(1.2)+ self.assertEqual((side.states, side.ups, side.notices), (states, ups, []))+ self.assertFalse(link.running)+ before = server.connections+ link.start()+ self.assertTrue(wait_for(lambda: server.connections > before), "the link did not dial again")++ def test_nothing_is_reported_after_stop_returns(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ time.sleep(0.8)+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ time.sleep(1)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link()+ link.start()+ self.assertTrue(wait_for(lambda: server.connections))+ time.sleep(0.2)+ link.stop()+ states, ups, saved = list(side.states), list(side.ups), side.settings.saves+ time.sleep(1.5)+ self.assertEqual((side.states, side.ups, side.settings.saves), (states, ups, saved))++ def test_a_failed_try_at_a_beacons_address_shows_nothing_and_blocks_nothing(self):+ def script(connection):+ connection.close()++ server = Scripted(script)+ self.addCleanup(server.stop)+ clock = FakeClock()+ side = Side(None)+ side.peer()["host"] = "10.255.255.1"+ side.peer()["port"] = server.port+ real = socket.create_connection++ def factory(address, timeout=None):+ if address[0] == "10.255.255.1":+ raise OSError("no route")+ return real(address, timeout=timeout)++ link = side.link(socket_factory=factory, clock=clock)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.states))+ clock.now += 11+ shown = list(side.states)+ link.follow([{"name": "Far", "address": LOOPBACK}])+ self.assertTrue(wait_for(lambda: server.connections))+ time.sleep(0.3)+ self.assertEqual(side.states[: len(shown)], shown)+ self.assertFalse(any("closed the connection" in text for _, text in side.states[len(shown):]))++ def test_a_try_never_dials_a_peer_with_send_off(self):+ tried = []++ def factory(address, timeout=None):+ tried.append(address)+ raise OSError("no route")++ clock = FakeClock()+ side = Side(None)+ link = side.link(socket_factory=factory, clock=clock, reconnect_seconds=0.02)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: tried))+ clock.now += 11+ side.peer()["send"] = False+ link._try_host = "192.168.77.9"+ link._wake.set()+ tried.clear()+ time.sleep(0.4)+ self.assertEqual(tried, [])++ def test_a_peer_that_stops_reading_ends_the_link(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ for _ in range(60):+ protocol.send_msg(connection, session, protocol.ack_v6(0, 0))+ time.sleep(0.2)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ big = protocol.clipboard_msg("x" * 200_000)+ for _ in range(100):+ if not link.post(big):+ break+ self.assertTrue(wait_for(lambda: not link.live(), 8.0), "a wedged writer kept the link up")++ def test_only_one_ping_waits_in_the_queue(self):+ side = Side(None)+ link = side.link()+ link._live = True+ link._sock = object()+ for _ in range(20):+ link._tick_ping()+ self.assertEqual(sum(1 for m in link._outbox if m["type"] == protocol.MSG_PING), 1)++ def test_send_input_takes_only_input_and_filters_media_keys(self):+ side = Side(None)+ link = side.link()+ link._live = True+ link._sock = object()+ link._caps = frozenset()+ self.assertFalse(link.send_input(protocol.settings_msg({})))+ self.assertTrue(link.send_input(protocol.key_msg("keydown", "volume_up")))+ self.assertEqual(len(link._outbox), 0)+ link._caps = frozenset({"media_keys"})+ self.assertTrue(link.send_input(protocol.key_msg("keydown", "volume_up")))+ self.assertEqual(len(link._outbox), 1)++ def test_flush_waits_for_the_queue_to_be_written(self):+ machine = machine_with_peer()+ self.addCleanup(machine.stop)+ side = Side(machine)+ link = side.link()+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ link.post(protocol.focus_v6(1, HERE, resistance_px=120, reach=[]))+ link.flush(2.0)+ self.assertEqual(len(link._outbox), 0)+ self.assertTrue(wait_for(lambda: machine.responder.owner == B))++ def test_peer_locked_is_forgotten_on_a_new_link(self):+ side = Side(None)+ link = side.link()+ link._locked = True+ link._live = True+ self.assertTrue(link.peer_locked)+ link._reset_link_state()+ self.assertFalse(link.peer_locked)+++class LinkFramingTests(unittest.TestCase):+ def serve(self, after_welcome):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ after_welcome(connection, session)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ return side, link++ def test_a_frame_that_arrives_a_byte_at_a_time_is_one_message(self):+ def after(connection, session):+ frame = session.seal(protocol.accept_msg(3))+ for index in range(len(frame)):+ connection.sendall(frame[index:index + 1])+ time.sleep(0.002)+ time.sleep(1)++ side, link = self.serve(after)+ self.assertTrue(wait_for(lambda: side.messages), side.states)+ self.assertEqual(side.messages[0]["data"]["route"], 3)++ def test_two_frames_in_one_segment_are_two_messages(self):+ def after(connection, session):+ connection.sendall(session.seal(protocol.accept_msg(3)) + session.seal(protocol.accept_msg(4)))+ time.sleep(1)++ side, link = self.serve(after)+ self.assertTrue(wait_for(lambda: len(side.messages) == 2))++ def big(self, allowed):+ """A frame past SMALL_MESSAGE_BYTES, then a small one, to a link whose `large` hook says+ `allowed`; what the link hands on, once the small one is through."""+ parsed = []+ real_parse = protocol.parse_message+ filler = {"type": protocol.MSG_CLIPBOARD, "data": {"text": "x" * (protocol.SMALL_MESSAGE_BYTES + 10)}}++ def after(connection, session):+ connection.sendall(session.seal(filler) + session.seal(protocol.accept_msg(3)))+ time.sleep(1)++ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ after(connection, session)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ asked = []+ link = side.link(reconnect_seconds=30, large=lambda link_, began: asked.append((link_, began)) or allowed)+ self.addCleanup(link.stop)+ with mock.patch.object(protocol, "parse_message", side_effect=lambda plain: parsed.append(len(plain)) or real_parse(plain)):+ link.start()+ self.assertTrue(wait_for(lambda: any(m.get("type") == protocol.MSG_ACCEPT for m in side.messages)), side.states)+ self.assertEqual([who for who, _ in asked], [link])+ self.assertIsInstance(asked[0][1], float)+ self.assertTrue(link.live())+ return side, parsed++ def test_a_frame_too_large_for_anything_but_a_clipboard_is_never_parsed_unless_one_is_expected(self):+ side, parsed = self.big(False)+ self.assertEqual([m["type"] for m in side.messages], [protocol.MSG_ACCEPT])+ self.assertTrue(all(size <= protocol.SMALL_MESSAGE_BYTES for size in parsed), parsed)++ def test_an_expected_clipboard_of_any_size_is_handed_on(self):+ side, parsed = self.big(True)+ self.assertEqual([m["type"] for m in side.messages], [protocol.MSG_CLIPBOARD, protocol.MSG_ACCEPT])++ def test_a_frame_claiming_more_than_the_maximum_ends_the_link(self):+ def after(connection, session):+ connection.sendall((protocol.MAX_FRAME_BYTES + 1).to_bytes(4, "big"))+ time.sleep(1)++ side, link = self.serve(after)+ self.assertTrue(wait_for(lambda: not link.live(), 3.0))++ def test_a_replayed_frame_ends_the_link(self):+ def after(connection, session):+ frame = session.seal(protocol.accept_msg(3))+ connection.sendall(frame + frame)+ time.sleep(1)++ side, link = self.serve(after)+ self.assertTrue(wait_for(lambda: not link.live(), 3.0))+ self.assertEqual(len(side.messages), 1)+++class GeminiFindingsTests(unittest.TestCase):+ def test_a_link_that_is_down_refuses_what_its_capabilities_would_have_dropped(self):+ side = Side(None)+ link = side.link()+ self.assertFalse(link.post(protocol.clipboard_msg("x")))+ self.assertFalse(link.post(protocol.settings_msg({})))+ self.assertFalse(link.send_input(protocol.gesture_msg("pinch")))++ def test_a_drop_reason_is_forgotten_with_the_link(self):+ side = Side(None)+ link = side.link()+ link._drop_reason = "stale"+ link._reset_link_state()+ self.assertIsNone(link._drop_reason)++ def test_a_peer_that_never_acknowledges_cannot_grow_the_send_record_without_end(self):+ side = Side(None)+ link = side.link()+ link._live = True+ link._sock = object()+ for index in range(link_module.SENT_RECORD_LIMIT + 1):+ link._sent_at.append((index, 0.0))+ with self.assertRaises(protocol.ProtocolError):+ link._check_sent_record()+++class RoundTripLogTests(unittest.TestCase):+ """Section 9: every 60 seconds while input is on the link, the count, median, 95th percentile,+ largest and mean held_us of the round trips measured since the last line."""++ def setUp(self):+ self.now = [100.0]+ self.side = Side(None)+ self.link = self.side.link(clock=lambda: self.now[0])+ self.link.peer_name = "Far"+ self.link._logged_at = 100.0++ def acks(self, count, held_us=1000):+ self.link._written_seq = count+ for seq in range(1, count + 1):+ self.link._sent_at.append((seq, 100.0))+ self.now[0] = 100.2+ for seq in range(1, count + 1):+ self.link._ack({"seq": seq, "held_us": held_us * seq, "locked": False})++ def test_the_minute_gives_count_median_95th_percentile_largest_and_mean_held(self):+ self.acks(20)+ with self.assertLogs("Beamer", "INFO") as logged:+ self.now[0] = 160.1+ self.link._tick(160.1)+ text = logged.output[-1]+ self.assertIn("round trip to Far", text)+ self.assertIn("20 samples", text)+ for word in ("median", "95th percentile", "largest", "mean held_us 10500"):+ self.assertIn(word, text)++ def test_a_minute_without_input_logs_nothing(self):+ with self.assertNoLogs("Beamer", "INFO"):+ self.now[0] = 160.1+ self.link._tick(160.1)++ def test_what_was_logged_is_not_counted_again(self):+ self.acks(5)+ self.now[0] = 160.1+ self.link._tick(160.1)+ with self.assertNoLogs("Beamer", "INFO"):+ self.now[0] = 220.2+ self.link._tick(220.2)+++class LinkHardwareTests(unittest.TestCase):+ """`hw` in the hello is the address on the interface towards the host this link dials."""++ def hello_of(self, side, **kwargs):+ seen = []++ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ seen.append(hello)+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ time.sleep(1)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30, **kwargs)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: seen), side.states)+ return seen[0]++ def test_the_hook_is_asked_with_the_host_this_link_dials(self):+ asked = []+ side = Side(None)+ hello = self.hello_of(side, hardware=lambda host: asked.append(host) or "aa:bb:cc:dd:ee:01")+ self.assertEqual(asked, [LOOPBACK])+ self.assertEqual(hello["hw"], "aa:bb:cc:dd:ee:01")++ def test_the_hook_wins_over_the_identitys_own_hw(self):+ side = Side(None)+ side.identity = lambda: {"id": B, "name": "Near", "platform": "macos", "app": "1.5.0", "caps": list(CAPS),+ "port": 24820, "hw": "11:11:11:11:11:11"}+ hello = self.hello_of(side, hardware=lambda host: "aa:bb:cc:dd:ee:02")+ self.assertEqual(hello["hw"], "aa:bb:cc:dd:ee:02")++ def test_without_a_hook_the_identitys_hw_is_sent_as_before(self):+ side = Side(None)+ side.identity = lambda: {"id": B, "name": "Near", "platform": "macos", "app": "1.5.0", "caps": list(CAPS),+ "port": 24820, "hw": "11:11:11:11:11:11"}+ self.assertEqual(self.hello_of(side)["hw"], "11:11:11:11:11:11")++ def test_a_hook_that_raises_sends_no_hw_and_the_link_still_comes_up(self):+ def broken(host):+ raise OSError("no adapter table")++ side = Side(None)+ hello = self.hello_of(side, hardware=broken)+ self.assertIsNone(hello["hw"])+ self.assertTrue(wait_for(lambda: side.ups), side.states)++ def test_a_hook_that_knows_nothing_sends_no_hw(self):+ side = Side(None)+ self.assertIsNone(self.hello_of(side, hardware=lambda host: "")["hw"])+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_owner.py b/core/tests/test_owner.pynew file mode 100644index 0000000..b067dbc--- /dev/null+++ b/core/tests/test_owner.py@@ -0,0 +1,588 @@+"""The owner's state machine (WIRE.md sections 4 and 5), without sockets: the messages it sends, on+which link, and what it does with this machine's input, for every event. A scripted clock drives+the timers."""++import unittest++from core import owner+from core.owner import LOCAL, Moved, Send, SendClipboard, SetClipboard, Unreachable+++class Clock:+ def __init__(self, now=1000.0):+ self.now = now++ def __call__(self):+ return self.now+++def key(kind, name, us=None):+ data = {"key": name}+ if us is not None:+ data["us"] = us+ return {"type": kind, "data": data}+++def button(kind, name="left"):+ return {"type": kind, "data": {"button": name}}+++MOVE = {"type": "mousemove", "data": {"dx": 3, "dy": -1}}+++def focuses(actions, peer=None):+ return [a.message["data"] for a in actions+ if isinstance(a, Send) and a.message["type"] == "focus" and (peer is None or a.peer == peer)]+++def sent(actions, peer=None):+ return [(a.peer, a.message) for a in actions if isinstance(a, Send) and (peer is None or a.peer == peer)]+++def moved(actions):+ found = [a for a in actions if isinstance(a, Moved)]+ return found[-1] if found else None+++class ByteIds(unittest.TestCase):+ """The apps name machines by their 16-byte ids, not by strings."""++ def test_a_peer_that_refused_a_hand_over_stays_out_of_reach_for_three_seconds(self):+ clock = Clock()+ o = owner.Owner(b"A" * 16, clock)+ b, c = b"B" * 16, b"C" * 16+ for peer in (b, c):+ o.link_up(peer, True)+ o.go(b)+ o.accept(b, {"route": o.route})+ o.switch(b, {"route": o.route, "next": c})+ actions = o.refuse(c, {"route": o.route, "why": "owned"})+ stay = [a.message["data"] for a in actions if isinstance(a, Send) and a.message["data"].get("stay")]+ self.assertEqual(stay[0]["reach"], [])+ clock.now += owner.LEFT_OUT + 0.1+ self.assertEqual(o.reach_for(b), [c])+++class OwnerCase(unittest.TestCase):+ def setUp(self):+ self.clock = Clock()+ self.o = owner.Owner("A", self.clock)+ for peer in ("B", "C", "D"):+ self.assertEqual(self.o.link_up(peer, True), [])++ def take(self, peer, edge=None, offset=None):+ actions = self.o.go(peer, edge, offset)+ self.assertEqual(self.o.accept(peer, {"route": self.o.route}), [])+ return actions++ def switch(self, frm, nxt, route=None, **where):+ return self.o.switch(frm, {"route": self.o.route if route is None else route, "next": nxt, **where})+++class TakeFromHomeTests(OwnerCase):+ def test_a_take_by_a_zone_carries_the_route_the_landing_the_resistance_and_the_reach(self):+ actions = self.o.go("B", "left", 0.5)+ self.assertEqual(focuses(actions), [{"route": 1, "target": "B", "edge": "left", "offset": 0.5,+ "resistance_px": 120, "reach": ["C", "D"]}])+ self.assertEqual(moved(actions), Moved("B", None, "asked", "left", 0.5))+ self.assertEqual(self.o.on, "B")+ self.assertEqual(self.o.reach_sent, ["C", "D"])++ def test_a_take_by_the_shortcut_has_no_landing(self):+ self.assertEqual(focuses(self.o.go("B")), [{"route": 1, "target": "B", "resistance_px": 120, "reach": ["C", "D"]}])++ def test_a_phone_leaves_resistance_out(self):+ phone = owner.Owner("P", self.clock, resistance_px=None)+ phone.link_up("B", True)+ self.assertEqual(focuses(phone.go("B")), [{"route": 1, "target": "B", "reach": []}])++ def test_input_goes_at_once_without_waiting_for_the_answer(self):+ self.o.go("B")+ self.assertEqual(self.o.input(MOVE), [Send("B", MOVE)])++ def test_at_home_input_stays_here(self):+ self.assertEqual(self.o.input(MOVE), [LOCAL])+ self.assertEqual(self.o.input(key("keydown", "a", "a")), [LOCAL])++ def test_no_answer_within_a_second_brings_the_input_home(self):+ self.o.go("B")+ self.assertEqual(self.o.deadline(), 1001.0)+ self.clock.now = 1000.99+ self.assertEqual(self.o.tick(), [])+ self.clock.now = 1001.0+ actions = self.o.tick()+ self.assertEqual(focuses(actions, "B"), [{"route": 2, "target": "A"}])+ self.assertEqual(moved(actions), Moved(None, "B", "no_answer"))+ self.assertFalse(self.o.away)++ def test_an_accept_ends_the_wait(self):+ self.take("B")+ self.assertIsNone(self.o.deadline())+ self.clock.now += 5+ self.assertEqual(self.o.tick(), [])+ self.assertEqual(self.o.on, "B")++ def test_a_refusal_for_the_current_route_sends_the_input_home_saying_why(self):+ for why in ("owned", "not_allowed", "busy", "sent_home", "malformed", "something_new"):+ with self.subTest(why=why):+ self.o.go("B")+ actions = self.o.refuse("B", {"route": self.o.route, "why": why})+ self.assertEqual(moved(actions).to, None)+ self.assertEqual(moved(actions).why, why if why != "something_new" else "refused")+ self.assertFalse(self.o.away)++ def test_a_refusal_for_an_old_route_is_ignored(self):+ self.take("B")+ self.o.link_up("E", True) # a stay, route 2+ self.assertEqual(self.o.refuse("B", {"route": 1, "why": "owned"}), [])+ self.assertEqual(self.o.on, "B")+ self.assertEqual(moved(self.o.refuse("B", {"route": 2, "why": "owned"})).to, None)++ def test_a_refusal_from_a_machine_the_input_is_not_on_is_ignored(self):+ self.take("B")+ self.assertEqual(self.o.refuse("C", {"route": self.o.route, "why": "owned"}), [])++ def test_away_from_the_take_until_it_is_refused(self):+ self.assertFalse(self.o.away)+ self.o.go("B")+ self.assertTrue(self.o.away)+ self.o.refuse("B", {"route": 1, "why": "busy"})+ self.assertFalse(self.o.away)++ def test_two_desktops_taking_each_other_both_end_at_home_and_the_next_try_works(self):+ self.o.go("B")+ self.o.refuse("B", {"route": 1, "why": "busy"})+ self.assertIsNone(self.o.on)+ self.take("B")+ self.assertEqual(self.o.on, "B")++ def test_a_peer_without_a_link_or_that_does_not_accept_is_not_taken(self):+ self.o.link_up("E", False)+ for peer in ("E", "Z"):+ with self.subTest(peer=peer):+ self.assertEqual(self.o.go(peer), [Unreachable(peer, "unreachable")])+ self.assertFalse(self.o.away)+ self.assertEqual(self.o.route, 0)++ def test_going_where_the_input_already_is_does_nothing(self):+ self.take("B")+ self.assertEqual(self.o.go("B"), [])+ self.o.go(None)+ self.assertEqual(self.o.go(None), [])+ self.assertEqual(self.o.go("A"), [])+++class ReachTests(OwnerCase):+ def test_reach_leaves_out_the_owner_the_target_and_peers_that_do_not_accept(self):+ self.o.link_up("E", False)+ self.assertEqual(focuses(self.o.go("B"))[0]["reach"], ["C", "D"])++ def test_the_reach_is_kept_true_while_the_input_is_on_a_machine(self):+ self.take("B")+ self.assertEqual(focuses(self.o.link_up("E", True), "B"),+ [{"route": 2, "target": "B", "stay": True, "resistance_px": 120, "reach": ["C", "D", "E"]}])+ self.assertEqual(focuses(self.o.link_down("C"), "B")[0]["reach"], ["D", "E"])+ self.assertEqual(focuses(self.o.accepts("D", False), "B"), [{"route": 4, "target": "B", "stay": True,+ "resistance_px": 120, "reach": ["E"]}])+ self.assertEqual(self.o.accepts("D", False), [])+ self.assertEqual(self.o.reach_sent, ["E"])++ def test_at_home_a_link_changing_sends_nothing(self):+ self.assertEqual(self.o.link_up("E", True), [])+ self.assertEqual(self.o.link_down("E"), [])+ self.assertEqual(self.o.route, 0)++ def test_accepts_for_a_peer_with_no_link_is_ignored(self):+ self.take("B")+ self.assertEqual(self.o.accepts("E", True), [])+++class SwitchTests(OwnerCase):+ def test_a_switch_naming_the_owner_brings_the_input_home_landing_where_it_says(self):+ self.take("B")+ actions = self.switch("B", "A", edge="right", offset=0.25)+ self.assertEqual(focuses(actions, "B"), [{"route": 2, "target": "A"}])+ self.assertEqual(moved(actions), Moved(None, "B", "switch", "right", 0.25))++ def test_a_send_home_with_an_old_route_is_honoured_within_the_visit(self):+ self.take("B")+ self.o.link_up("E", True) # a re-arm crossing B's send-home+ self.assertEqual(moved(self.switch("B", "A", route=1)).to, None)++ def test_a_send_home_from_an_earlier_visit_or_another_machine_is_ignored(self):+ self.take("B") # route 1+ self.take("C") # route 2+ self.take("B") # route 3+ for route in (1, 2):+ self.assertEqual(self.switch("B", "A", route=route), [])+ self.assertEqual(self.switch("C", "A", route=3), [])+ self.assertEqual(self.o.on, "B")++ def test_a_stale_switch_is_ignored(self):+ self.take("B")+ for _ in range(2): # four re-arms, to route 5+ self.o.link_up("E", True)+ self.o.link_down("E")+ self.assertEqual(self.o.route, 5)+ self.o.go("C") # the shortcut, route 6+ self.assertEqual(self.switch("B", "D", route=5), [])+ self.assertEqual(self.o.on, "C")++ def test_a_switch_older_than_a_re_arm_is_ignored(self):+ self.take("B")+ self.o.link_up("E", True)+ self.assertEqual(self.switch("B", "C", route=1), [])+ self.assertEqual(self.o.on, "B")++ def test_a_switch_from_a_machine_the_input_is_not_on_is_ignored(self):+ self.take("B")+ self.assertEqual(self.switch("C", "D"), [])+ self.assertEqual(self.switch("C", "A"), [])++ def test_the_chain_hand_over_waits_for_the_accept_holding_the_input(self):+ self.take("B")+ self.assertEqual(self.o.input(key("keydown", "a", "a")), [Send("B", key("keydown", "a", "a"))])+ actions = self.switch("B", "C", edge="left", offset=0.5)+ self.assertEqual(sent(actions), [("C", {"type": "focus", "data": {+ "route": 2, "target": "C", "edge": "left", "offset": 0.5, "resistance_px": 120, "reach": ["B", "D"]}})])+ self.assertEqual(self.o.on, "B")+ self.assertTrue(self.o.away)+ self.assertEqual(self.o.input(MOVE), [])+ self.assertEqual(self.o.input(key("keyup", "a", "a")), [])++ actions = self.o.accept("C", {"route": 2})+ self.assertEqual(sent(actions), [+ ("B", key("keyup", "a", "a")),+ ("B", {"type": "focus", "data": {"route": 2, "target": "C"}}),+ ("C", MOVE),+ ])+ self.assertEqual([a for a in actions if isinstance(a, SendClipboard)], [SendClipboard("C")])+ clip_at = actions.index(SendClipboard("C"))+ self.assertLess(actions.index(Send("B", {"type": "focus", "data": {"route": 2, "target": "C"}})), clip_at)+ self.assertLess(clip_at, actions.index(Send("C", MOVE)))+ self.assertEqual(moved(actions), Moved("C", "B", "switch", "left", 0.5))+ self.assertEqual(self.o.on, "C")+ self.assertEqual(self.o.reach_sent, ["B", "D"])++ def test_a_refusal_from_the_next_machine_re_arms_the_one_left_leaving_it_out_for_three_seconds(self):+ self.take("B")+ self.switch("B", "C")+ self.o.input(MOVE)+ actions = self.o.refuse("C", {"route": 2, "why": "owned"})+ self.assertEqual(sent(actions), [+ ("B", {"type": "focus", "data": {"route": 3, "target": "B", "stay": True, "resistance_px": 120, "reach": ["D"]}}),+ ("B", MOVE),+ ])+ self.assertIn(Unreachable("C", "owned"), actions)+ self.assertIsNone(moved(actions))+ self.assertEqual(self.o.on, "B")+ self.assertEqual(self.o.deadline(), 1003.0)+ self.clock.now = 1003.0+ self.assertEqual(focuses(self.o.tick(), "B"), [{"route": 4, "target": "B", "stay": True, "resistance_px": 120,+ "reach": ["C", "D"]}])++ def test_no_answer_from_the_next_machine_re_arms_the_one_left(self):+ self.take("B")+ self.switch("B", "C")+ self.clock.now = 1000.99+ self.assertEqual(self.o.tick(), [])+ self.clock.now = 1001.0+ actions = self.o.tick()+ self.assertEqual(focuses(actions, "B")[0]["reach"], ["D"])+ self.assertIn(Unreachable("C", "no_answer"), actions)+ self.assertEqual(focuses(actions, "C"), [])++ def test_a_late_accept_is_let_go_naming_where_the_input_is_now(self):+ self.take("B")+ self.switch("B", "C")+ self.clock.now = 1001.0+ self.o.tick() # the stay is route 3+ self.assertEqual(sent(self.o.accept("C", {"route": 2})),+ [("C", {"type": "focus", "data": {"route": 3, "target": "B"}})])+ self.assertEqual(self.o.on, "B")++ def test_a_late_accept_after_coming_home_names_the_owner(self):+ self.o.go("C")+ self.clock.now = 1001.0+ self.o.tick() # home, route 2+ self.assertEqual(sent(self.o.accept("C", {"route": 1})),+ [("C", {"type": "focus", "data": {"route": 2, "target": "A"}})])++ def test_an_accept_for_a_route_never_taken_there_is_ignored(self):+ self.take("B")+ self.switch("B", "C")+ self.assertEqual(self.o.accept("C", {"route": 99}), [])+ self.assertEqual(self.o.accept("D", {"route": 2}), [])+ self.assertEqual(self.o.accept("C", {"route": 1}), [])+ self.assertEqual(self.o.on, "B")++ def test_a_send_home_while_waiting_ends_the_wait_and_no_stay_follows(self):+ self.take("B")+ self.switch("B", "C")+ self.assertEqual(moved(self.switch("B", "A", route=1)).to, None)+ self.clock.now += 5+ self.assertEqual(self.o.tick(), [])++ def test_losing_the_link_to_the_machine_left_while_waiting_brings_the_input_home(self):+ self.take("B")+ self.switch("B", "C")+ actions = self.o.link_down("B")+ self.assertEqual(sent(actions), [])+ self.assertEqual(moved(actions), Moved(None, "B", "link_lost"))+ self.clock.now += 5+ self.assertEqual(self.o.tick(), [])++ def test_the_shortcut_while_waiting_ends_the_wait(self):+ self.take("B")+ self.switch("B", "C")+ actions = self.o.go("D")+ self.assertEqual(focuses(actions), [{"route": 3, "target": "D"},+ {"route": 3, "target": "D", "resistance_px": 120, "reach": ["B", "C"]}])+ self.assertEqual(sent(actions)[0][0], "B")+ self.o.accept("D", {"route": 3})+ self.clock.now = 1001.0+ self.assertEqual(self.o.tick(), [])+ self.assertEqual(self.o.on, "D")++ def test_the_shortcut_to_the_machine_waited_on_from_re_arms_it(self):+ self.take("B")+ self.switch("B", "C")+ self.o.input(MOVE)+ actions = self.o.go("B")+ self.assertEqual(sent(actions), [+ ("B", {"type": "focus", "data": {"route": 3, "target": "B", "stay": True, "resistance_px": 120,+ "reach": ["C", "D"]}}),+ ("B", MOVE),+ ])+ self.clock.now = 1001.0+ self.assertEqual(self.o.tick(), [])++ def test_losing_the_link_to_the_next_machine_while_waiting_is_a_refusal(self):+ self.take("B")+ self.switch("B", "C")+ actions = self.o.link_down("C")+ self.assertEqual(focuses(actions, "B")[0]["stay"], True)+ self.assertIn(Unreachable("C", "link_lost"), actions)++ def test_a_switch_to_a_peer_outside_the_reach_last_sent_is_unreachable_even_with_a_link(self):+ self.take("B")+ self.switch("B", "C")+ self.o.refuse("C", {"route": 2, "why": "owned"}) # C left out; the stay is route 3+ self.assertNotIn("C", self.o.reach_sent)+ actions = self.switch("B", "C")+ self.assertEqual(focuses(actions, "C"), [])+ self.assertEqual(focuses(actions, "B")[0]["route"], 4)+ self.assertIn(Unreachable("C", "unreachable"), actions)++ def test_a_switch_to_a_peer_whose_link_dropped_is_unreachable_without_asking_it(self):+ self.take("B")+ self.assertEqual(focuses(self.o.link_down("C"), "B")[0]["reach"], ["D"])+ actions = self.switch("B", "C")+ self.assertEqual(sent(actions, "C"), [])+ self.assertTrue(focuses(actions, "B")[0]["stay"])+ self.assertIn(Unreachable("C", "unreachable"), actions)++ def test_a_switch_without_a_landing_takes_without_one(self):+ self.take("B")+ self.assertNotIn("edge", focuses(self.switch("B", "C"), "C")[0])+++class ComingHomeTests(OwnerCase):+ def test_every_trigger_brings_the_input_home_saying_why(self):+ triggers = {+ "asked": lambda: self.o.go(None),+ "switch": lambda: self.switch("B", "A"),+ "owned": lambda: self.o.refuse("B", {"route": self.o.route, "why": "owned"}),+ "link_lost": lambda: self.o.link_down("B"),+ }+ for why, trigger in triggers.items():+ with self.subTest(why=why):+ self.o.link_up("B", True)+ self.take("B")+ self.o.input(key("keydown", "shift"))+ actions = trigger()+ self.assertEqual(moved(actions), Moved(None, "B", why))+ if why == "link_lost":+ self.assertEqual(sent(actions), [])+ else:+ self.assertEqual(sent(actions), [("B", key("keyup", "shift")),+ ("B", {"type": "focus", "data": {"route": self.o.route, "target": "A"}})])+ self.assertEqual(self.o.input(key("keyup", "shift")), [])+ self.assertEqual(self.o.input(key("keyup", "shift")), [LOCAL])++ def test_the_owner_releases_what_it_pressed_there_before_letting_go(self):+ self.take("B")+ self.o.input(key("keydown", "shift"))+ self.o.input(button("mousedown", "left"))+ self.o.input(key("keydown", "A", "a"))+ self.o.input(key("keyup", "A", "a"))+ actions = self.o.go("C")+ self.assertEqual(sent(actions, "B"), [+ ("B", key("keyup", "shift")),+ ("B", button("mouseup", "left")),+ ("B", {"type": "focus", "data": {"route": 2, "target": "C"}}),+ ])+ self.assertEqual(self.o.input(key("keyup", "shift")), [])+ self.assertEqual(self.o.input(button("mouseup", "left")), [])+ self.assertEqual(self.o.input(key("keyup", "shift")), [Send("C", key("keyup", "shift"))])++ def test_a_key_still_held_from_the_machine_left_repeats_nowhere(self):+ self.take("B")+ self.o.input(key("keydown", "a", "a"))+ self.o.go(None)+ self.assertEqual(self.o.input(key("keydown", "a", "a")), [])+ self.assertEqual(self.o.input(key("keyup", "a", "a")), [])+ self.assertEqual(self.o.input(key("keydown", "a", "a")), [LOCAL])++ def test_input_held_for_a_hand_over_that_ends_at_home_goes_nowhere(self):+ self.take("B")+ self.switch("B", "C")+ self.o.input(key("keydown", "x", "x"))+ actions = self.switch("B", "A", route=1)+ self.assertEqual(sent(actions, "C"), [])+ self.assertEqual([m for p, m in sent(actions, "B") if m["type"] != "focus"], [])+ self.assertEqual(self.o.input(key("keyup", "x", "x")), [])+++class PressedHereTests(OwnerCase):+ def test_a_key_pressed_here_is_released_here_after_the_input_leaves(self):+ self.assertEqual(self.o.input(key("keydown", "ctrl")), [LOCAL])+ self.take("B")+ self.assertEqual(self.o.input(key("keydown", "ctrl")), [])+ self.assertEqual(self.o.input(key("keyup", "ctrl")), [LOCAL])+ self.assertEqual(self.o.input(key("keydown", "ctrl")), [Send("B", key("keydown", "ctrl"))])++ def test_a_key_pressed_here_is_released_here_during_a_hand_over(self):+ self.o.input(key("keydown", "ctrl"))+ self.take("B")+ self.switch("B", "C")+ self.assertEqual(self.o.input(key("keyup", "ctrl")), [LOCAL])++ def test_a_button_pressed_here_is_released_here(self):+ self.o.input(button("mousedown"))+ self.take("B")+ self.assertEqual(self.o.input(button("mouseup")), [LOCAL])+++class LinkTests(OwnerCase):+ def test_a_second_link_from_the_peer_the_input_is_on_ends_the_visit(self):+ self.take("B")+ self.assertEqual(moved(self.o.link_up("B", True)), Moved(None, "B", "link_lost"))+ self.assertIn("B", self.o.reach_for("C"))++ def test_a_refusal_of_the_take_counts_while_a_re_arm_is_crossing_it(self):+ self.o.go("C")+ self.o.link_up("E", True) # a stay, route 2, before C answers the take+ self.assertEqual(moved(self.o.refuse("C", {"route": 1, "why": "owned"})), Moved(None, "C", "owned"))++ def test_a_take_is_forgotten_after_a_while(self):+ self.o.go("B")+ self.clock.now = 1001.0+ self.o.tick()+ self.clock.now = 1040.0+ self.take("C")+ self.assertEqual(self.o.accept("B", {"route": 1}), [])+++class ClipboardTests(OwnerCase):+ def test_a_refused_take_does_not_count_as_having_the_clipboard(self):+ self.o.go("B")+ self.o.refuse("B", {"route": 1, "why": "owned"})+ self.assertIn(SendClipboard("B"), self.take("B"))++ def test_the_machine_left_keeps_its_clipboard_when_the_next_one_refuses_first(self):+ self.take("B")+ self.o.go("C")+ self.o.refuse("C", {"route": 2, "why": "owned"})+ message = {"type": "clipboard", "data": {"text": "copied on B"}}+ self.assertEqual(self.o.clipboard_arrived("B", 1000.25, message), [SetClipboard(message)])++ def test_the_clipboard_goes_after_the_taking_focus_and_before_any_input(self):+ actions = self.o.go("B")+ focus_at = next(i for i, a in enumerate(actions) if isinstance(a, Send))+ self.assertEqual(actions.index(SendClipboard("B")), focus_at + 1)++ def test_the_clipboard_goes_only_where_it_is_not_already(self):+ self.take("B")+ self.o.go(None)+ self.assertNotIn(SendClipboard("B"), self.take("B"))+ self.o.go(None)+ self.o.clipboard_changed()+ self.assertIn(SendClipboard("B"), self.take("B"))++ def test_the_machine_let_go_may_send_its_clipboard_once_within_ten_seconds(self):+ self.take("B")+ self.o.go(None)+ message = {"type": "clipboard", "data": {"text": "copied on B"}}+ self.assertEqual(self.o.clipboard_arrived("C", 1000.5, message), [])+ self.assertEqual(self.o.clipboard_arrived("B", 1010.0, message), [SetClipboard(message)])+ self.assertEqual(self.o.clipboard_arrived("B", 1010.0, message), [])++ def test_only_a_machine_just_let_go_is_expected_to_send_a_clipboard(self):+ # What a link asks before it reads a frame too large for anything but a clipboard.+ self.assertFalse(self.o.expects_clipboard("B", 1000.0))+ self.take("B")+ self.assertFalse(self.o.expects_clipboard("B", 1000.0))+ self.o.go(None)+ self.assertTrue(self.o.expects_clipboard("B", 1000.5))+ self.assertFalse(self.o.expects_clipboard("C", 1000.5))+ # By when the frame began, as clipboard_arrived judges it: a large one on a slow link that+ # began in time and finished a minute later is still the clipboard it would take.+ self.clock.now += 60+ self.assertTrue(self.o.expects_clipboard("B", 1010.0))+ self.assertFalse(self.o.expects_clipboard("B", 1010.01))++ def test_a_machine_whose_clipboard_came_is_not_expected_again(self):+ self.take("B")+ self.o.go(None)+ self.o.clipboard_arrived("B", 1000.5, {"type": "clipboard", "data": {"text": "x"}})+ self.assertFalse(self.o.expects_clipboard("B", 1000.6))++ def test_a_clipboard_beginning_more_than_ten_seconds_after_the_let_go_is_dropped(self):+ self.take("B")+ self.o.go(None)+ self.assertEqual(self.o.clipboard_arrived("B", 1010.01, {"type": "clipboard", "data": {"text": "x"}}), [])++ def test_in_a_chain_the_clipboard_of_the_machine_left_goes_on_to_the_next(self):+ self.take("B")+ self.switch("B", "C")+ self.o.accept("C", {"route": 2})+ message = {"type": "clipboard", "data": {"text": "copied on B"}}+ self.assertEqual(self.o.clipboard_arrived("B", 1000.1, message), [SetClipboard(message), Send("C", message)])++ def test_a_clipboard_brought_home_goes_to_the_next_machine_taken_and_not_back(self):+ self.take("B")+ self.take("C")+ self.o.go(None)+ self.o.clipboard_arrived("C", 1000.1, {"type": "clipboard", "data": {"text": "copied on C"}})+ self.assertIn(SendClipboard("B"), self.take("B"))+ self.o.go(None)+ self.assertNotIn(SendClipboard("C"), self.take("C"))+++class RouteTests(OwnerCase):+ def test_routes_only_rise_and_each_hand_over_shares_one(self):+ self.take("B")+ seen = [1]+ ring = ["B", "C", "D"]+ for n in range(1000):+ here, there = ring[n % 3], ring[(n + 1) % 3]+ if n % 2:+ actions = self.switch(here, there)+ taking = focuses(actions, there)+ actions = self.o.accept(there, {"route": taking[0]["route"]})+ letting_go = focuses(actions, here)+ else:+ actions = self.o.go(there)+ taking, letting_go = focuses(actions, there), focuses(actions, here)+ self.o.accept(there, {"route": taking[0]["route"]})+ self.assertEqual(letting_go[0]["target"], there)+ self.assertEqual(taking[0]["route"], letting_go[0]["route"])+ self.assertGreater(taking[0]["route"], seen[-1])+ seen.append(taking[0]["route"])+ self.assertEqual(self.o.on, there)+ self.assertEqual(self.o.route, seen[-1])+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_pairing_service.py b/core/tests/test_pairing_service.pynew file mode 100644index 0000000..6fa0bd3--- /dev/null+++ b/core/tests/test_pairing_service.py@@ -0,0 +1,565 @@+"""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.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)),+ )+ self.service.start()+ test.addCleanup(self.service.stop)++ def connect(self):+ sock = socket.create_connection(("127.0.0.1", self.tcp_port), timeout=3.0)+ sock.settimeout(3.0)+ return sock+++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)++ 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)+ 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)+ with self.assertRaises(socket.timeout):+ old.recvfrom(2048)+++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))+ 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)++ 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 --git a/core/tests/test_pairing_v3.py b/core/tests/test_pairing_v3.pynew file mode 100644index 0000000..6fffb43--- /dev/null+++ b/core/tests/test_pairing_v3.py@@ -0,0 +1,672 @@+"""Pairing version 3 (WIRE.md section 6): the exchange with 16-byte machine ids, platform and+port bound in, the `known` and `full` refusals, the peer entry written before `pair_done`, the+key id clash, and the QR's second secret. The QR text is here too.++Pure: no sockets, a fake clock for the code's life and a fake wall clock for `paired_at`.+"""++import hashlib+import hmac+import secrets+import unittest++from core import pairing+from core.pairing import AlreadyPaired, PairingClient, PairingError, PairingHost++REQUESTER_ID = bytes(range(1, 17))+HOST_ID = bytes(range(101, 117))+OTHER_ID = bytes(range(201, 217))+++class FakeClock:+ def __init__(self, value=1000.0):+ self.value = value++ def __call__(self):+ return self.value++ def advance(self, seconds):+ self.value += seconds+++def scripted(*values):+ queue = list(values)+ return lambda length: queue.pop(0)+++def other_code(code):+ return str((int(code) + 1) % 10**6).zfill(6)+++def hkdf_block(ikm, salt, info):+ """RFC 5869 for one 32-byte block, written here rather than borrowed from the code under test."""+ prk = hmac.new(salt, ikm, hashlib.sha256).digest()+ return hmac.new(prk, info + b"\x01", hashlib.sha256).digest()+++def b64(data):+ return pairing._b64(data)+++class Book:+ """One machine's peers list as the apps keep it, with the store callback pairing calls."""++ def __init__(self, entries=()):+ self.entries = [dict(entry) for entry in entries]+ self.stored = []+ self.fail = False++ def peers(self):+ return [dict(entry) for entry in self.entries]++ def store(self, entry, replaces):+ if self.fail:+ raise OSError("disk full")+ if replaces is not None:+ self.entries = [known for known in self.entries if known["id"] != replaces["id"]]+ self.entries.append(dict(entry))+ self.stored.append((dict(entry), replaces))+++def entry(identity, name="Somebody", platform="linux", linked=True, paired_at=1, token=None):+ return {+ "id": b64(identity), "name": name, "platform": platform, "linked": linked,+ "paired_at": paired_at, "token": token or b64(hashlib.sha256(identity).digest()),+ }+++class Rig:+ """A v3 host and requester with their own books, clocks and entropy."""++ def __init__(self, host_book=None, requester_book=None, wall=1_790_000_000, host_entropy=None):+ self.clock = FakeClock()+ self.wall = [wall]+ self.host_book = host_book or Book()+ self.requester_book = requester_book or Book()+ kwargs = {} if host_entropy is None else {"entropy": host_entropy}+ self.host = PairingHost(+ self.clock, name="Host PC", identity=HOST_ID, version=3, platform="windows", port=24820,+ peers=self.host_book.peers, store=self.host_book.store, wall=lambda: self.wall[0], **kwargs,+ )++ def begin(self):+ self.code = self.host.begin()+ return self.code++ def client(self, code=None, qr_secret=None, name="Requester Mac", identity=REQUESTER_ID, platform="macos", port=24820, **kwargs):+ return PairingClient(+ self.host.pair_id, code or self.code, name, identity, version=3, platform=platform, port=port,+ qr_secret=qr_secret, peers=self.requester_book.peers, wall=lambda: self.wall[0], **kwargs,+ )++ def exchange(self, client=None, address="192.168.77.5"):+ """One honest exchange: (client, start, answer, confirm, done, token)."""+ client = client or self.client()+ start = client.start()+ answer = self.host.handle(start, address)+ confirm = client.accept(answer)+ done = self.host.handle(confirm, address)+ return client, start, answer, confirm, done, client.finish(done)+++class ConstantTests(unittest.TestCase):+ def test_the_v3_labels_and_numbers(self):+ self.assertEqual(pairing.PAIRING_V3, 3)+ self.assertEqual(pairing.CHANNEL_V3, b"beamer-pair-v3")+ self.assertEqual(pairing.TOKEN_INFO_V3, b"beamer-pair-token-v3")+ self.assertEqual((pairing.ID_BYTES, pairing.QR_SECRET_BYTES, pairing.MAX_PEERS), (16, 16, 32))+ # Version 2 is untouched beside it until the apps' last call to it goes.+ self.assertEqual((pairing.PAIRING_VERSION, pairing.CHANNEL, pairing.TOKEN_INFO), (2, b"beamer-pair-v2", b"beamer-pair-token-v2"))++ def test_beacon_and_start_say_version_3(self):+ rig = Rig()+ rig.begin()+ self.assertEqual(rig.host.beacon(24820)["pairing"], 3)+ self.assertEqual(rig.client().start()["v"], 3)++ def test_the_exchange_matches_the_specification_computed_by_hand(self):+ """Every v3 input, built here from WIRE.md section 6 and PAIRING.md, gives the token both+ sides agree: CI, the token's info, ADa and ADb with platform and port, and the QR's+ 22-byte password with its 95 bytes of padding."""+ for qr in (False, True):+ with self.subTest(qr=qr):+ secret = bytes(range(50, 66))+ rig = Rig(host_entropy=scripted(bytes(range(16)), secret, bytes([7]) * 32))+ code = rig.begin()+ nonce, scalar_a = bytes(range(30, 46)), bytes([9]) * 32+ client = rig.client(qr_secret=secret if qr else None, entropy=scripted(nonce, scalar_a))+ _client, start, answer, _confirm, _done, token = rig.exchange(client)+ self.assertEqual(start.get("qr"), 1 if qr else None)++ prs = code.encode() + (secret if qr else b"")+ self.assertEqual(len(prs), 22 if qr else 6)+ sid = pairing._lv_cat(start["pair"].encode(), nonce)+ padding = bytes(95 if qr else 111)+ generator_string = pairing._lv_cat(b"CPace255", prs, padding, b"beamer-pair-v3", sid)+ r = int.from_bytes(hashlib.sha512(generator_string).digest()[:32], "little") & ((1 << 255) - 1)+ generator = pairing._elligator2(r).to_bytes(32, "little")+ ya = pairing._x25519(scalar_a, generator)+ self.assertEqual(b64(ya), start["share"])+ yb = pairing._unb64(answer["share"])+ k = pairing._x25519(scalar_a, yb)+ ada = pairing._lv_cat(b"requester", REQUESTER_ID, b"Requester Mac", b"macos", (24820).to_bytes(2, "big"))+ adb = pairing._lv_cat(b"host", HOST_ID, b"Host PC", b"windows", (24820).to_bytes(2, "big"))+ isk = hashlib.sha512(pairing._lv_cat(b"CPace255_ISK", sid, k) + pairing._lv_cat(ya, ada) + pairing._lv_cat(yb, adb)).digest()+ self.assertEqual(token, b64(hkdf_block(isk, sid, b"beamer-pair-token-v3")))+++class BindingTests(unittest.TestCase):+ def test_platform_or_port_changed_on_the_way_to_the_requester_fails_tb(self):+ for field, value in (("port", 24830), ("platform", "linux")):+ with self.subTest(field=field):+ rig = Rig()+ rig.begin()+ client = rig.client()+ answer = rig.host.handle(client.start(), "192.168.77.5")+ with self.assertRaises(PairingError) as caught:+ client.accept(dict(answer, **{field: value}))+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)++ def test_platform_or_port_changed_on_the_way_to_the_host_fails_and_nothing_is_stored(self):+ for field, value in (("port", 24830), ("platform", "linux")):+ with self.subTest(field=field):+ rig = Rig()+ rig.begin()+ client = rig.client()+ start = dict(client.start(), **{field: value})+ answer = rig.host.handle(start, "192.168.77.5")+ self.assertTrue(answer["ok"])+ # The requester computed ADa with what it sent, so the host's Tb, over the same+ # transcript, fails first: either way nothing is stored.+ with self.assertRaises(PairingError):+ client.accept(answer)+ done = rig.host.handle(client.abort(), "192.168.77.5")+ self.assertEqual(done["error"], pairing.ERROR_REFUSED)+ self.assertEqual(rig.host_book.stored, [])++ def test_identities_platforms_and_ports_out_of_shape_are_refused_in_pair_start(self):+ bad = [("id", b64(b"")), ("id", b64(bytes(range(15)))), ("id", b64(bytes(range(17)))),+ ("id", b64(bytes(range(32)))), ("id", b64(bytes(16))), ("id", None),+ ("platform", "MacOS"), ("platform", ""), ("platform", "a" * 17), ("platform", "mac-os"), ("platform", 5), ("platform", None),+ ("port", 70000), ("port", -1), ("port", "24820"), ("port", True), ("port", 1.0), ("port", None),+ ("name", ""), ("name", "x" * 49)]+ for field, value in bad:+ with self.subTest(field=field, value=value):+ rig = Rig()+ rig.begin()+ start = dict(rig.client().start(), **{field: value})+ if value is None:+ del start[field]+ reply = rig.host.handle(start, "192.168.77.5")+ self.assertEqual(reply, {"type": "pair_answer", "pair": start["pair"], "ok": False, "error": "refused"})+ self.assertFalse(rig.host.active)++ def test_identities_platforms_and_ports_out_of_shape_are_refused_in_pair_answer(self):+ bad = [("id", b64(b"")), ("id", b64(bytes(range(15)))), ("id", b64(bytes(range(17)))),+ ("id", b64(bytes(range(32)))), ("id", b64(bytes(16))),+ ("platform", "Windows"), ("platform", "a" * 17), ("platform", 3),+ ("port", 65536), ("port", False), ("port", 24820.0), ("name", "")]+ for field, value in bad:+ with self.subTest(field=field, value=value):+ rig = Rig()+ rig.begin()+ client = rig.client()+ answer = rig.host.handle(client.start(), "192.168.77.5")+ with self.assertRaises(PairingError) as caught:+ client.accept(dict(answer, **{field: value}))+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)++ def test_an_unknown_platform_of_the_allowed_shape_pairs(self):+ rig = Rig()+ rig.begin()+ rig.exchange(rig.client(platform="haiku_os2"))+ self.assertEqual(rig.host_book.entries[0]["platform"], "haiku_os2")++ def test_a_v3_side_needs_an_id_of_its_own(self):+ with self.assertRaises(ValueError):+ PairingHost(name="x", identity=b"", version=3, platform="macos", port=1, peers=list, store=lambda e, r: None)+ with self.assertRaises(ValueError):+ PairingClient("00" * 16, "123456", "x", bytes(16), version=3, platform="macos", port=1, peers=list)+++class KnownTests(unittest.TestCase):+ def test_the_requester_refuses_a_host_it_already_has_and_tells_the_host(self):+ known = entry(HOST_ID, name="Old PC", paired_at=1_700_000_000)+ rig = Rig(requester_book=Book([known]))+ rig.begin()+ client = rig.client()+ answer = rig.host.handle(client.start(), "192.168.77.5")+ with self.assertRaises(AlreadyPaired) as caught:+ client.accept(answer)+ self.assertEqual(str(caught.exception), pairing.ERROR_KNOWN)+ self.assertEqual((caught.exception.entry["name"], caught.exception.entry["paired_at"]), ("Old PC", 1_700_000_000))+ abort = client.abort()+ self.assertEqual(abort, {"type": "pair_confirm", "pair": rig.host.pair_id, "tag": "", "error": "known"})+ done = rig.host.handle(abort, "192.168.77.5")+ self.assertEqual(done, {"type": "pair_done", "pair": abort["pair"], "ok": False, "error": "refused"})+ self.assertEqual(rig.host.outcome, "known_there")+ self.assertEqual((rig.host_book.stored, rig.requester_book.stored), ([], []))++ def test_the_requester_refuses_its_own_id(self):+ rig = Rig()+ rig.begin()+ client = rig.client(identity=HOST_ID)+ # The host refuses too, but only after Ta; the requester checks Tb first and stops there.+ answer = rig.host.handle(client.start(), "192.168.77.5")+ with self.assertRaises(AlreadyPaired):+ client.accept(answer)++ def test_the_host_refuses_a_requester_it_already_has_after_ta(self):+ known = entry(REQUESTER_ID, name="Old Mac", paired_at=1_700_000_000)+ rig = Rig(host_book=Book([known]))+ rig.begin()+ client = rig.client()+ answer = rig.host.handle(client.start(), "192.168.77.5")+ self.assertTrue(answer["ok"], "the id is proved only by Ta, so it is not judged before")+ done = rig.host.handle(client.accept(answer), "192.168.77.5")+ self.assertEqual(done, {"type": "pair_done", "pair": answer["pair"], "ok": False, "error": "known"})+ self.assertIsNone(rig.host.code)+ self.assertEqual(rig.host.outcome, "known")+ self.assertEqual(rig.host.known["name"], "Old Mac")+ self.assertEqual(rig.host_book.stored, [])+ with self.assertRaises(PairingError) as caught:+ client.finish(done)+ self.assertEqual(str(caught.exception), pairing.ERROR_KNOWN)++ def test_the_host_refuses_its_own_id(self):+ rig = Rig()+ rig.begin()+ client = rig.client(identity=HOST_ID)+ # A requester that skipped its own check still meets the host's.+ client._check_host = lambda identity, name, platform: None+ answer = rig.host.handle(client.start(), "192.168.77.5")+ done = rig.host.handle(client.accept(answer), "192.168.77.5")+ self.assertEqual(done["error"], "known")++ def test_a_lost_pair_done_can_be_paired_again_within_ten_minutes(self):+ rig = Rig()+ rig.begin()+ client = rig.client()+ start = client.start()+ answer = rig.host.handle(start, "192.168.77.5")+ rig.host.handle(client.accept(answer), "192.168.77.5") # pair_done lost+ self.assertEqual(len(rig.host_book.entries), 1)+ rig.wall[0] += 599+ rig.begin()+ _client, *_rest, token = rig.exchange()+ self.assertEqual(len(rig.host_book.entries), 1)+ self.assertEqual(rig.host_book.entries[0]["token"], token)+ self.assertEqual(rig.host_book.stored[-1][1]["id"], b64(REQUESTER_ID))++ def test_an_unlinked_entry_is_known_after_ten_minutes_or_under_another_name_or_platform(self):+ cases = [+ ("ten minutes", entry(REQUESTER_ID, name="Requester Mac", platform="macos", linked=False, paired_at=1_790_000_000 - 600)),+ ("another name", entry(REQUESTER_ID, name="Other Mac", platform="macos", linked=False, paired_at=1_790_000_000 - 5)),+ ("another platform", entry(REQUESTER_ID, name="Requester Mac", platform="linux", linked=False, paired_at=1_790_000_000 - 5)),+ ("linked", entry(REQUESTER_ID, name="Requester Mac", platform="macos", linked=True, paired_at=1_790_000_000 - 5)),+ ("migrated", entry(REQUESTER_ID, name="Requester Mac", platform="macos", linked=False, paired_at=0)),+ ]+ for label, known in cases:+ with self.subTest(label):+ rig = Rig(host_book=Book([known]))+ rig.begin()+ client = rig.client()+ answer = rig.host.handle(client.start(), "192.168.77.5")+ done = rig.host.handle(client.accept(answer), "192.168.77.5")+ self.assertEqual(done["error"], "known")++ def test_the_requester_replaces_its_own_unlinked_entry_the_same_way(self):+ stale = entry(HOST_ID, name="Host PC", platform="windows", linked=False, paired_at=1_790_000_000 - 30)+ rig = Rig(requester_book=Book([stale]))+ rig.begin()+ client, *_rest, token = rig.exchange()+ self.assertEqual(client.replaces["id"], b64(HOST_ID))+ self.assertEqual(client.entry("192.168.77.4")["token"], token)+++class FullTests(unittest.TestCase):+ def test_a_host_with_32_peers_shows_no_code(self):+ rig = Rig(host_book=Book([entry(bytes([n]) * 16) for n in range(1, 33)]))+ with self.assertRaises(PairingError) as caught:+ rig.begin()+ self.assertEqual(str(caught.exception), pairing.ERROR_FULL)+ self.assertIsNone(rig.host.code)++ def test_a_host_that_reaches_32_while_its_code_is_up_answers_full_and_drops_the_code(self):+ book = Book([entry(bytes([n]) * 16) for n in range(1, 32)])+ rig = Rig(host_book=book)+ rig.begin()+ book.entries.append(entry(bytes([40]) * 16))+ start = rig.client().start()+ reply = rig.host.handle(start, "192.168.77.5")+ self.assertEqual(reply, {"type": "pair_answer", "pair": start["pair"], "ok": False, "error": "full"})+ self.assertIsNone(rig.host.code)+ self.assertEqual(rig.host.outcome, "full")++ def test_a_host_filled_between_the_start_and_the_confirmation_stores_nothing(self):+ book = Book([entry(bytes([n]) * 16) for n in range(1, 32)])+ rig = Rig(host_book=book)+ rig.begin()+ client = rig.client()+ answer = rig.host.handle(client.start(), "192.168.77.5")+ self.assertTrue(answer["ok"])+ book.entries.append(entry(bytes([40]) * 16))+ done = rig.host.handle(client.accept(answer), "192.168.77.5")+ self.assertEqual(done["error"], "refused")+ self.assertEqual((rig.host.outcome, rig.host_book.stored), ("full", []))++ def test_a_requester_with_32_peers_does_not_start(self):+ rig = Rig(requester_book=Book([entry(bytes([n]) * 16) for n in range(1, 33)]))+ rig.begin()+ with self.assertRaises(PairingError) as caught:+ rig.client()+ self.assertEqual(str(caught.exception), pairing.ERROR_FULL)+++class StrangerTests(unittest.TestCase):+ def test_a_confirmation_from_another_address_is_not_answered_and_ends_nothing(self):+ rig = Rig()+ rig.begin()+ client = rig.client()+ answer = rig.host.handle(client.start(), "192.168.77.5")+ junk = {"type": "pair_confirm", "pair": answer["pair"], "tag": b64(bytes(64))}+ self.assertIsNone(rig.host.handle(junk, "192.168.77.66"))+ self.assertIsNone(rig.host.handle(dict(junk, tag="", error="known"), "192.168.77.66"))+ self.assertTrue(rig.host.active)+ done = rig.host.handle(client.accept(answer), "192.168.77.5")+ self.assertTrue(done["ok"])++ def test_a_confirmation_from_the_same_address_on_another_channel_ends_nothing(self):+ # WIRE.md section 6: over TCP only on its own connection. A forged-source datagram, or a+ # second connection from that address, cannot end the exchange with a bad tag.+ rig = Rig()+ rig.begin()+ client = rig.client()+ answer = rig.host.handle(client.start(), "192.168.77.5", ("tcp", 1))+ junk = {"type": "pair_confirm", "pair": answer["pair"], "tag": b64(bytes(64))}+ for channel in ("udp", ("tcp", 2)):+ self.assertIsNone(rig.host.handle(junk, "192.168.77.5", channel))+ self.assertTrue(rig.host.active)+ done = rig.host.handle(client.accept(answer), "192.168.77.5", ("tcp", 1))+ self.assertTrue(done["ok"])++ def test_a_replayed_start_on_another_channel_is_answered_but_not_fresh(self):+ rig = Rig()+ rig.begin()+ start = rig.client().start()+ first = rig.host.handle(start, "192.168.77.5", ("tcp", 1))+ self.assertTrue(rig.host.fresh_answer)+ rig.host.fresh_answer = False+ self.assertEqual(rig.host.handle(start, "192.168.77.5", ("tcp", 2)), first)+ self.assertFalse(rig.host.fresh_answer)+++class VersionTests(unittest.TestCase):+ def test_a_v2_start_to_a_v3_host_is_told_version_and_drops_the_code(self):+ rig = Rig()+ rig.begin()+ start = dict(rig.client().start(), v=2)+ self.assertEqual(rig.host.handle(start, "192.168.77.5")["error"], "version")+ self.assertIsNone(rig.host.code)+ self.assertEqual(rig.host.outcome, "version")++ def test_a_v3_start_to_a_v2_host_is_told_version(self):+ host = PairingHost(FakeClock(), name="Old PC")+ host.begin()+ client = PairingClient(host.pair_id, host.code, "New Mac", REQUESTER_ID, version=3, platform="macos", port=24820, peers=list)+ self.assertEqual(host.handle(client.start())["error"], "version")+++def migrated(host="192.168.77.5", name="Old Name"):+ """The entry 1.4.x's one pairing migrated to: no id until its first link, a typed or old token."""+ return {"id": "", "name": name, "platform": "macos", "token": "typed-in-1.4", "host": host, "port": 24820,+ "linked": False, "paired_at": 0, "from_1_4": True}+++class MigratedEntryTests(unittest.TestCase):+ """Pairing afresh with the machine held as the 1.4.x entry replaces that entry, so it does not+ linger beside the new one to be answered wrong_id on its first link."""++ def test_the_host_replaces_it_when_the_requester_comes_from_its_address(self):+ rig = Rig(host_book=Book([migrated(host="192.168.77.5")]))+ rig.begin()+ rig.exchange(address="192.168.77.5")+ self.assertEqual([e["id"] for e in rig.host_book.entries], [b64(REQUESTER_ID)])+ self.assertEqual(rig.host_book.stored[-1][1]["from_1_4"], True)++ def test_a_machine_elsewhere_leaves_it_alone_whatever_its_name(self):+ # A name is the pairing machine's own claim: anyone who saw the code could take the old+ # peer's and evict a 1.4.x pair that still links.+ rig = Rig(host_book=Book([migrated(host="192.168.77.99", name="Requester Mac")]))+ rig.begin()+ rig.exchange(address="192.168.77.5")+ self.assertEqual(sorted(e["id"] for e in rig.host_book.entries), ["", b64(REQUESTER_ID)])+ self.assertIsNone(rig.host_book.stored[-1][1])++ def test_replacing_it_is_not_refused_by_a_count_reached_during_the_exchange(self):+ book = Book([entry(bytes([n]) * 16) for n in range(1, 31)] + [migrated(host="192.168.77.5")])+ rig = Rig(host_book=book)+ rig.begin()+ client = rig.client()+ answer = rig.host.handle(client.start(), "192.168.77.5")+ book.entries.append(entry(bytes([50]) * 16))+ done = rig.host.handle(client.accept(answer), "192.168.77.5")+ self.assertTrue(done["ok"])+ self.assertEqual(len(book.entries), 32)+++class StoreTests(unittest.TestCase):+ def test_the_host_writes_the_entry_before_pair_done_and_both_entries_agree(self):+ rig = Rig()+ rig.begin()+ seen_before_reply = []+ store = rig.host_book.store+ rig.host.store = lambda new, replaces: (seen_before_reply.append(rig.host.code is not None), store(new, replaces))+ client, *_rest, token = rig.exchange(address="192.168.77.5")+ self.assertEqual(seen_before_reply, [True], "stored while the code was still up, before pair_done went")+ host_entry = rig.host_book.entries[0]+ self.assertEqual(host_entry, {+ "id": b64(REQUESTER_ID), "name": "Requester Mac", "platform": "macos", "token": token,+ "host": "192.168.77.5", "port": 24820, "hw": "", "send": True, "allow_drive": True,+ "side": "", "side_set_at": 0, "side_by": "", "paired_with": [], "paired_at": 1_790_000_000,+ "linked": False, "from_1_4": False,+ })+ requester_entry = client.entry("192.168.77.4")+ self.assertEqual(+ {k: requester_entry[k] for k in ("id", "name", "platform", "token", "host", "port", "send", "allow_drive", "linked")},+ {"id": b64(HOST_ID), "name": "Host PC", "platform": "windows", "token": token, "host": "192.168.77.4",+ "port": 24820, "send": True, "allow_drive": True, "linked": False},+ )+ self.assertEqual(rig.host.paired["token"], token)++ def test_a_phone_requester_is_saved_undialled(self):+ rig = Rig()+ rig.begin()+ rig.exchange(rig.client(name="Alex's iPhone", platform="ios", port=0), address="192.168.77.9")+ saved = rig.host_book.entries[0]+ self.assertEqual((saved["host"], saved["port"], saved["send"], saved["allow_drive"]), ("", 0, False, True))++ def test_a_write_that_fails_is_refused_and_nothing_is_kept(self):+ rig = Rig()+ rig.host_book.fail = True+ rig.begin()+ client = rig.client()+ answer = rig.host.handle(client.start(), "192.168.77.5")+ done = rig.host.handle(client.accept(answer), "192.168.77.5")+ self.assertEqual(done, {"type": "pair_done", "pair": answer["pair"], "ok": False, "error": "refused"})+ self.assertEqual(rig.host_book.entries, [])+ self.assertEqual(rig.host.outcome, "not_saved")+ self.assertIsNone(rig.host.paired)+ with self.assertRaises(PairingError):+ client.finish(done)+++class KeyIdTests(unittest.TestCase):+ def test_the_key_id_is_the_link_s_and_a_typed_token_has_none(self):+ token = b64(bytes(range(32)))+ expected = hkdf_block(token.encode("ascii"), b"beamer-link-v6", b"beamer-key-id")[:16]+ self.assertEqual(pairing._key_id(token), expected)+ for typed in ("hunter2", b64(bytes(31)), b64(bytes(33)), b64(bytes(32)) + "=", "", None):+ with self.subTest(typed=typed):+ self.assertIsNone(pairing._key_id(typed))++ def test_an_entry_with_a_typed_token_never_clashes(self):+ rig = Rig(host_book=Book([entry(OTHER_ID, token="hunter2")]))+ rig.begin()+ rig.exchange()+ self.assertEqual(len(rig.host_book.stored), 1)++ def _token_of_a_fixed_exchange(self):+ rig = Rig(host_entropy=scripted(bytes(16), bytes([3]) * 16, bytes([7]) * 32))+ rig.begin()+ client = rig.client(entropy=scripted(bytes([4]) * 16, bytes([9]) * 32))+ return rig.code, rig.exchange(client)[-1]++ def _fixed_rig(self, code, host_book=None, requester_book=None):+ rig = Rig(host_book=host_book, requester_book=requester_book, host_entropy=scripted(bytes(16), bytes([3]) * 16, bytes([7]) * 32))+ rig.begin()+ rig.host.code = rig.code = code+ return rig, rig.client(entropy=scripted(bytes([4]) * 16, bytes([9]) * 32))++ def test_the_host_refuses_a_token_whose_key_id_is_already_an_entry_s(self):+ code, token = self._token_of_a_fixed_exchange()+ rig, client = self._fixed_rig(code, host_book=Book([entry(OTHER_ID, token=token)]))+ answer = rig.host.handle(client.start(), "192.168.77.5")+ done = rig.host.handle(client.accept(answer), "192.168.77.5")+ self.assertEqual(done["error"], "refused")+ self.assertEqual(rig.host_book.stored, [])++ def test_the_requester_finds_the_clash_after_td_and_the_host_s_entry_is_replaced_next_time(self):+ code, token = self._token_of_a_fixed_exchange()+ rig, client = self._fixed_rig(code, requester_book=Book([entry(OTHER_ID, token=token)]))+ answer = rig.host.handle(client.start(), "192.168.77.5")+ done = rig.host.handle(client.accept(answer), "192.168.77.5")+ self.assertTrue(done["ok"])+ with self.assertRaises(PairingError) as caught:+ client.finish(done)+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ self.assertEqual(len(rig.host_book.entries), 1)+ # Pairing again at once replaces the host's entry that never linked.+ rig.requester_book.entries = []+ rig.host._entropy = secrets.token_bytes+ rig.begin()+ rig.exchange()+ self.assertEqual(len(rig.host_book.entries), 1)+ self.assertIsNotNone(rig.host_book.stored[-1][1])+++class QrSecretTests(unittest.TestCase):+ def test_a_qr_exchange_and_a_typed_one_each_agree_a_token(self):+ for qr in (True, False):+ with self.subTest(qr=qr):+ rig = Rig()+ rig.begin()+ client, start, *_rest, token = rig.exchange(rig.client(qr_secret=rig.host.qr_secret if qr else None))+ self.assertEqual("qr" in start, qr)+ self.assertEqual(rig.host.paired["token"], token)++ def test_qr_stripped_or_added_on_the_path_fails_and_drops_the_code(self):+ for strip in (True, False):+ with self.subTest(strip=strip):+ rig = Rig()+ rig.begin()+ client = rig.client(qr_secret=rig.host.qr_secret if strip else None)+ start = client.start()+ start = {k: v for k, v in start.items() if k != "qr"} if strip else dict(start, qr=1)+ answer = rig.host.handle(start, "192.168.77.5")+ with self.assertRaises(PairingError):+ client.accept(answer)+ rig.host.handle(client.abort(), "192.168.77.5")+ self.assertIsNone(rig.host.code)+ self.assertEqual(rig.host_book.stored, [])++ def test_qr_of_any_value_but_the_integer_1_is_malformed(self):+ for value in (True, "1", 1.0, 2, 0, None):+ with self.subTest(value=value):+ rig = Rig()+ rig.begin()+ start = dict(rig.client(qr_secret=rig.host.qr_secret).start(), qr=value)+ self.assertEqual(rig.host.handle(start, "192.168.77.5")["error"], "refused")+ self.assertIsNone(rig.host.code)++ def test_every_code_has_a_new_secret_dropped_with_it(self):+ rig = Rig()+ rig.begin()+ first = rig.host.qr_secret+ rig.begin()+ second = rig.host.qr_secret+ self.assertEqual((len(first), len(second)), (16, 16))+ self.assertNotEqual(first, second)+ rig.host.cancel()+ self.assertIsNone(rig.host.qr_secret)++ def test_a_qr_secret_of_the_wrong_length_is_a_programming_error(self):+ rig = Rig()+ rig.begin()+ with self.assertRaises(ValueError):+ rig.client(qr_secret=bytes(15))+++class BeaconTests(unittest.TestCase):+ def test_the_id_and_pairing_id_travel_only_while_a_code_is_up(self):+ rig = Rig()+ idle = rig.host.beacon(24820)+ self.assertEqual(idle, {"type": "beacon", "name": "Host PC", "port": 24820, "pairing": 3, "platform": "windows"})+ rig.begin()+ live = rig.host.beacon(24820)+ self.assertEqual((live["pair"], live["id"]), (rig.host.pair_id, b64(HOST_ID)))+ rig.clock.advance(pairing.CODE_LIFETIME_SECONDS)+ self.assertNotIn("id", rig.host.beacon(24820))+++class QrTextTests(unittest.TestCase):+ SECRET = bytes(range(16))+ K = b64(bytes(range(16)))++ def test_the_text_is_built_and_read_back(self):+ text = pairing.qr_text("192.168.1.20", 24821, "048213", self.SECRET)+ self.assertEqual(text, f"beamer://pair?host=192.168.1.20&port=24821&code=048213&k={self.K}")+ self.assertEqual(pairing.read_qr(text), {"host": "192.168.1.20", "port": 24821, "code": "048213", "secret": self.SECRET})++ def test_anything_else_is_refused(self):+ k = self.K+ bad = [+ f"beamer://pair?host=192.168.77.4&port=24821&code=048213",+ f"beamer://pair?host=192.168.77.4&port=24821&k={k}",+ f"beamer://pair?host=192.168.77.4&host=192.168.77.4&port=24821&code=048213&k={k}",+ f"beamer://pair?port=24821&host=192.168.77.4&code=048213&k={k}",+ f"beamer://pair?host=192.168.77.4&port=24821&k={k}&code=048213",+ f"BEAMER://pair?host=192.168.77.4&port=24821&code=048213&k={k}",+ f"beamer://pair?HOST=192.168.77.4&port=24821&code=048213&k={k}",+ f"beamer://pair?host=192.168.77.4&port=024821&code=048213&k={k}",+ f"beamer://pair?host=192.168.77.4&port=65536&code=048213&k={k}",+ f"beamer://pair?host=192.168.77.4&port=0&code=048213&k={k}",+ f"beamer://pair?host=192.168.77.4&port=24821&code=48213&k={k}",+ f"beamer://pair?host=192.168.77.4&port=24821&code=0482133&k={k}",+ f"beamer://pair?host=::1&port=24821&code=048213&k={k}",+ f"beamer://pair?host=[::1]&port=24821&code=048213&k={k}",+ f"beamer://pair?host=10.0.0&port=24821&code=048213&k={k}",+ f"beamer://pair?host=192.168.77.256&port=24821&code=048213&k={k}",+ f"beamer://pair?host=192.168.77.04&port=24821&code=048213&k={k}",+ f"beamer://pair?host=beamer.local&port=24821&code=048213&k={k}",+ f"beamer://pair?host=192.168.77.4&port=24821&code=048213&k={k[:21]}",+ f"beamer://pair?host=192.168.77.4&port=24821&code=048213&k={k}A",+ f"beamer://pair?host=192.168.77.4&port=24821&code=048213&k={k[:21]}B",+ f"beamer://pair?host=192.168.77.4&port=24821&code=048213&k={k}&x=1",+ f"beamer://pair?host=192.168.77.4&port=24821&code=048213&k={k}&",+ f"beamer://pair?host=192.168.77.4&port=24821&code=04821%33&k={k}",+ f"beamer://pair?host=192.168.77.4&port=24821&code=048213&k={k}",+ f" beamer://pair?host=192.168.77.4&port=24821&code=048213&k={k}",+ f"beamer://pair/?host=192.168.77.4&port=24821&code=048213&k={k}",+ "",+ None,+ ]+ for text in bad:+ with self.subTest(text=text):+ with self.assertRaises(PairingError) as caught:+ pairing.read_qr(text)+ self.assertEqual(str(caught.exception), pairing.ERROR_BAD_QR)+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_peerlist.py b/core/tests/test_peerlist.pynew file mode 100644index 0000000..af5931a--- /dev/null+++ b/core/tests/test_peerlist.py@@ -0,0 +1,174 @@+"""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")+++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_the_replaced_entrys_zones_go_with_it(self):+ held = settings(peer("", token="legacy", from_1_4=True), zones=[{"peer": "", "kind": "edge"}])+ peerlist.add_peer(held, peer(A), replaced=copy.deepcopy(held["peers"][0]))+ self.assertEqual(held["zones"], [])++ 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"}])++ 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_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"), "")+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_protocol_v6.py b/core/tests/test_protocol_v6.pynew file mode 100644index 0000000..00d68e8--- /dev/null+++ b/core/tests/test_protocol_v6.py@@ -0,0 +1,877 @@+"""Wire version 6 in protocol.py: the pure half of WIRE.md sections 2 to 5 and 9.++The key id, the preamble, the keys and X25519 are checked against HKDF and a Montgomery ladder+written here, never through protocol.py's own helpers, so a mistake in the module and a mistake in+the test cannot cancel out. The version 5 names protocol.py still carries are covered by+test_wire_vectors.py and the apps' suites; nothing here touches them.+"""++import base64+import hashlib+import hmac+import json+import os+import socket+import struct+import threading+import time+import unittest++from nacl.bindings import crypto_aead_chacha20poly1305_ietf_decrypt++from core import protocol++TOKEN = base64.urlsafe_b64encode(bytes(range(32))).decode("ascii").rstrip("=")+OTHER_TOKEN = base64.urlsafe_b64encode(bytes(range(1, 33))).decode("ascii").rstrip("=")+ID_A = bytes(range(16, 32))+ID_B = bytes(range(32, 48))+ID_C = bytes(range(48, 64))++_P = 2**255 - 19++# X25519's low-order points (and the same with bit 255 set, which RFC 7748 ignores): every one+# gives the all-zero result.+LOW_ORDER = [+ bytes(32),+ b"\x01" + bytes(31),+ bytes.fromhex("e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800"),+ bytes.fromhex("5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157"),+ (_P - 1).to_bytes(32, "little"),+ _P.to_bytes(32, "little"),+ (_P + 1).to_bytes(32, "little"),+]+LOW_ORDER += [point[:31] + bytes([point[31] | 0x80]) for point in LOW_ORDER]+++def _b64(data):+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")+++def _hkdf(ikm, salt, info, length):+ prk = hmac.new(salt, ikm, hashlib.sha256).digest()+ return hmac.new(prk, info + b"\x01", hashlib.sha256).digest()[:length]+++def _x25519(scalar, u_bytes):+ """RFC 7748 section 5, written out: the clamped scalar, bit 255 of u ignored."""+ k = bytearray(scalar)+ k[0] &= 248+ k[31] &= 127+ k[31] |= 64+ k = int.from_bytes(k, "little")+ u = int.from_bytes(u_bytes, "little") & ((1 << 255) - 1)+ x1, x2, z2, x3, z3, swap = u, 1, 0, u, 1, 0+ for t in reversed(range(255)):+ 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")+++def _key_id(token):+ return _hkdf(token.encode("ascii"), b"beamer-link-v6", b"beamer-key-id", 16)+++def _key(token, shared, key_id, prefix_i, prefix_r, share_i, share_r, direction):+ info = b"beamer-frames" + b"\x06" + key_id + prefix_i + prefix_r + share_i + share_r + bytes([direction])+ return _hkdf(token.encode("ascii") + shared, b"beamer-link-v6", info, 32)+++def _pair(token=TOKEN, prefix_i=b"I" * 8, prefix_r=b"R" * 8, secret_i=b"\x11" * 32, secret_r=b"\x22" * 32):+ initiator = protocol.LinkSession(token, protocol.ROLE_INITIATOR, prefix=prefix_i, secret=secret_i)+ responder = protocol.LinkSession(token, protocol.ROLE_RESPONDER, prefix=prefix_r, secret=secret_r)+ first = initiator.preamble()+ responder.accept_preamble(first)+ second = responder.preamble()+ initiator.accept_preamble(second)+ return initiator, responder, first, second+++def _open_frame(session, frame):+ return session.open(frame[protocol.HEADER_SIZE:])+++class Tokens(unittest.TestCase):+ def test_a_paired_token_is_43_characters_of_one_spelling(self):+ self.assertTrue(protocol.is_paired_token(TOKEN))+ # The last character carries four spare bits: a second spelling of the same 32 bytes.+ spare = TOKEN[:-1] + ("B" if TOKEN[-1] == "A" else chr(ord(TOKEN[-1]) + 1))+ self.assertEqual(base64.urlsafe_b64decode(spare + "="), base64.urlsafe_b64decode(TOKEN + "="))+ for typed in ("", "hunter2", TOKEN[:-1], TOKEN + "A", TOKEN + "=", TOKEN[:5] + "+" + TOKEN[6:], spare, 12, None):+ with self.subTest(typed=typed):+ self.assertFalse(protocol.is_paired_token(typed))++ def test_the_key_id_is_hkdf_over_the_tokens_text(self):+ for token in (TOKEN, OTHER_TOKEN, _b64(os.urandom(32))):+ with self.subTest(token=token):+ self.assertEqual(protocol.key_id(token), _key_id(token))+ self.assertNotEqual(protocol.key_id(TOKEN), protocol.key_id(OTHER_TOKEN))++ def test_a_typed_token_has_no_key_id_and_no_session(self):+ with self.assertRaises(ValueError):+ protocol.key_id("hunter2")+ with self.assertRaises(ValueError):+ protocol.LinkSession("hunter2", protocol.ROLE_INITIATOR)+ with self.assertRaises(ValueError):+ protocol.LinkSession(TOKEN, "server")+++class Ids(unittest.TestCase):+ def test_round_trip(self):+ for ident in (ID_A, b"\xff" * 16, b"\x00" * 15 + b"\x01"):+ text = protocol.id_text(ident)+ self.assertEqual(len(text), 22)+ self.assertEqual(protocol.read_id(text), ident)++ def test_refused(self):+ good = protocol.id_text(ID_A)+ spare = good[:-1] + ("B" if good[-1] == "A" else chr(ord(good[-1]) + 1))+ for bad in (protocol.id_text(bytes(16)), _b64(bytes(15)), _b64(bytes(17)), good + "=", spare, good[:5] + "/" + good[6:], "", 5, None, ["x"]):+ with self.subTest(bad=bad):+ self.assertIsNone(protocol.read_id(bad))+++class Preamble(unittest.TestCase):+ def test_layout(self):+ secret = b"\x33" * 32+ session = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR, prefix=b"P" * 8, secret=secret)+ data = session.preamble()+ self.assertEqual(len(data), 62)+ self.assertEqual(protocol.LINK_PREAMBLE_SIZE, 62)+ self.assertEqual(data[:5], b"BEAMY")+ self.assertEqual(data[5], 6)+ self.assertEqual(data[6:14], b"P" * 8)+ self.assertEqual(data[14:30], _key_id(TOKEN))+ self.assertEqual(data[30:62], _x25519(secret, b"\x09" + bytes(31)))+ self.assertEqual(session.key_id, _key_id(TOKEN))++ def test_the_responder_carries_the_same_key_id_back(self):+ _, _, first, second = _pair()+ self.assertEqual(first[14:30], second[14:30])++ def test_fresh_prefix_and_share_per_session(self):+ one = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR).preamble()+ two = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR).preamble()+ self.assertNotEqual(one[6:14], two[6:14])+ self.assertNotEqual(one[30:], two[30:])++ def test_the_responder_sends_nothing_before_the_initiators_preamble(self):+ responder = protocol.LinkSession(TOKEN, protocol.ROLE_RESPONDER)+ with self.assertRaises(protocol.ProtocolError):+ responder.preamble()++ def test_short_reply(self):+ reply = protocol.short_reply(prefix=b"Q" * 8)+ self.assertEqual(reply, b"BEAMY\x06" + b"Q" * 8)+ self.assertEqual(len(protocol.short_reply()), 14)++ def test_legacy_reply(self):+ reply = protocol.legacy_version_reply()+ (length,) = struct.unpack(">I", reply[:4])+ self.assertEqual(length, len(reply) - 4)+ self.assertEqual(json.loads(reply[4:]), {"type": "welcome", "data": {"version": 6, "error": "version_mismatch"}})++ def test_split(self):+ _, _, first, _ = _pair()+ prefix, key_id, share = protocol.split_preamble(first)+ self.assertEqual((prefix, key_id, share), (first[6:14], first[14:30], first[30:]))+ for bad in (first[:61], first + b"\x00", b"BEAMX" + first[5:], first[:5] + b"\x05" + first[6:]):+ with self.assertRaises(protocol.ProtocolError):+ protocol.split_preamble(bad)+++class ReadingThePreamble(unittest.TestCase):+ """recv_link_preamble reads 6 bytes, then the rest only for version 6, and names what it met."""++ def _read(self, sent, close=True):+ left, right = socket.socketpair()+ try:+ left.sendall(sent)+ if close:+ left.shutdown(socket.SHUT_WR)+ return protocol.recv_link_preamble(right, time.monotonic() + 1)+ finally:+ left.close()+ right.close()++ def test_version_6(self):+ _, _, first, _ = _pair()+ self.assertEqual(self._read(first), first)++ def test_version_5_reads_its_whole_preamble(self):+ with self.assertRaises(protocol.VersionMismatch) as caught:+ self._read(b"BEAMY\x05" + b"x" * 8)+ self.assertEqual(caught.exception.peer_version, 5)++ def test_older_and_newer_versions(self):+ for version in (0, 1, 4, 7, 255):+ with self.subTest(version=version), self.assertRaises(protocol.VersionMismatch) as caught:+ self._read(b"BEAMY" + bytes([version]) + b"x" * 8)+ self.assertEqual(caught.exception.peer_version, version)++ def test_not_a_beamer_preamble(self):+ with self.assertRaises(protocol.VersionMismatch) as caught:+ self._read(protocol.legacy_frame({"type": "hello", "data": {}}))+ self.assertIsNone(caught.exception.peer_version)++ def test_eof_before_a_byte(self):+ with self.assertRaises(protocol.ConnectionClosed):+ self._read(b"")++ def test_the_deadline_bounds_the_whole_preamble(self):+ _, _, first, _ = _pair()+ started = time.monotonic()+ with self.assertRaises(socket.timeout):+ self._read(first[:61], close=False)+ self.assertLess(time.monotonic() - started, 2.0)+++class Keys(unittest.TestCase):+ def test_both_keys_match_hkdf_and_x25519_written_here(self):+ secret_i, secret_r = b"\x11" * 32, b"\x22" * 32+ initiator, responder, first, second = _pair(secret_i=secret_i, secret_r=secret_r)+ share_i, share_r = first[30:], second[30:]+ shared = _x25519(secret_i, share_r)+ self.assertEqual(shared, _x25519(secret_r, share_i))+ key_id = _key_id(TOKEN)+ for direction, sealer, opener in ((1, initiator, responder), (2, responder, initiator)):+ key = _key(TOKEN, shared, key_id, first[6:14], second[6:14], share_i, share_r, direction)+ frame = sealer.seal({"type": "ping", "data": {}})+ body = frame[4:]+ nonce = sealer.prefix + body[:4]+ plain = crypto_aead_chacha20poly1305_ietf_decrypt(body[4:], None, nonce, key)+ self.assertEqual(json.loads(plain), {"type": "ping", "data": {}})+ self.assertEqual(_open_frame(opener, frame), {"type": "ping", "data": {}})++ def test_the_sizes(self):+ key_id = _key_id(TOKEN)+ info = protocol.link_info(key_id, b"I" * 8, b"R" * 8, b"a" * 32, b"b" * 32, 1)+ self.assertEqual(len(info), 111)+ self.assertEqual(info, b"beamer-frames\x06" + key_id + b"I" * 8 + b"R" * 8 + b"a" * 32 + b"b" * 32 + b"\x01")+ self.assertEqual(len(protocol.link_ikm(TOKEN, b"s" * 32)), 75)+ self.assertEqual(protocol.link_ikm(TOKEN, b"s" * 32), TOKEN.encode("ascii") + b"s" * 32)++ def test_every_input_is_bound(self):+ key_id = _key_id(TOKEN)+ base = dict(token=TOKEN, shared=b"s" * 32, key_id=key_id, prefix_i=b"I" * 8, prefix_r=b"R" * 8,+ share_i=b"a" * 32, share_r=b"b" * 32, direction=1)+ reference = protocol.link_key(**base)+ self.assertEqual(reference, _key(**base))+ changes = {+ "token": OTHER_TOKEN,+ "shared": b"t" * 32,+ "key_id": _key_id(OTHER_TOKEN),+ "prefix_i": b"J" * 8,+ "prefix_r": b"S" * 8,+ "share_i": b"c" * 32,+ "share_r": b"d" * 32,+ "direction": 2,+ }+ for field, value in changes.items():+ with self.subTest(field=field):+ self.assertNotEqual(protocol.link_key(**dict(base, **{field: value})), reference)+ swapped = dict(base, prefix_i=b"R" * 8, prefix_r=b"I" * 8, share_i=b"b" * 32, share_r=b"a" * 32)+ self.assertNotEqual(protocol.link_key(**swapped), reference)++ def test_reflection_fails_the_tag(self):+ initiator, _, _, _ = _pair()+ frame = initiator.seal({"type": "ping", "data": {}})+ with self.assertRaises(protocol.AuthenticationError):+ _open_frame(initiator, frame)++ def test_a_rewritten_preamble_fails_the_first_tag(self):+ initiator = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR)+ responder = protocol.LinkSession(TOKEN, protocol.ROLE_RESPONDER)+ first = bytearray(initiator.preamble())+ first[10] ^= 1 # the initiator's prefix, as the responder sees it+ responder.accept_preamble(bytes(first))+ initiator.accept_preamble(responder.preamble())+ with self.assertRaises(protocol.AuthenticationError):+ _open_frame(responder, initiator.seal({"type": "ping", "data": {}}))++ def test_a_recorded_link_does_not_open_in_a_new_one(self):+ initiator, _, first, _ = _pair()+ recorded = initiator.seal({"type": "ping", "data": {}})+ responder = protocol.LinkSession(TOKEN, protocol.ROLE_RESPONDER)+ responder.accept_preamble(first)+ with self.assertRaises(protocol.AuthenticationError):+ _open_frame(responder, recorded)++ def test_forward_secrecy_the_token_alone_opens_nothing(self):+ initiator, _, first, second = _pair()+ frame = initiator.seal({"type": "ping", "data": {}})+ key_id = _key_id(TOKEN)+ # Everything in the clear plus the token, with the one thing an eavesdropper lacks guessed+ # as the obvious candidates: no shared secret, and each share used as if it were one.+ for shared in (bytes(32), first[30:], second[30:], _x25519(b"\x00" * 32, first[30:])):+ key = _key(TOKEN, shared, key_id, first[6:14], second[6:14], first[30:], second[30:], 1)+ with self.assertRaises(Exception):+ crypto_aead_chacha20poly1305_ietf_decrypt(frame[8:], None, first[6:14] + frame[4:8], key)+ self.assertIsNone(initiator._secret)++ def test_counters(self):+ initiator, responder, _, _ = _pair()+ one = initiator.seal({"type": "ping", "data": {}})+ two = initiator.seal({"type": "ping", "data": {}})+ with self.assertRaises(protocol.ProtocolError):+ _open_frame(responder, two)+ _open_frame(responder, one)+ with self.assertRaises(protocol.ProtocolError):+ _open_frame(responder, one)+ _open_frame(responder, two)++ def test_nothing_is_sealed_before_the_keys(self):+ with self.assertRaises(protocol.ProtocolError):+ protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR).seal({"type": "ping", "data": {}})+++class PreambleRefusals(unittest.TestCase):+ def test_low_order_share_from_the_initiator(self):+ for point in LOW_ORDER:+ with self.subTest(point=point.hex()):+ self.assertEqual(_x25519(b"\x22" * 32, point), bytes(32))+ initiator = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR)+ forged = initiator.preamble()[:30] + point+ responder = protocol.LinkSession(TOKEN, protocol.ROLE_RESPONDER)+ with self.assertRaises(protocol.PreambleRefused):+ responder.accept_preamble(forged)+ with self.assertRaises(protocol.ProtocolError):+ responder.preamble()++ def test_low_order_share_from_the_responder(self):+ for point in LOW_ORDER:+ with self.subTest(point=point.hex()):+ initiator = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR)+ first = initiator.preamble()+ responder = protocol.LinkSession(TOKEN, protocol.ROLE_RESPONDER)+ responder.accept_preamble(first)+ forged = responder.preamble()[:30] + point+ with self.assertRaises(protocol.PreambleRefused):+ initiator.accept_preamble(forged)+ with self.assertRaises(protocol.ProtocolError):+ initiator.seal({"type": "ping", "data": {}})++ def test_equal_prefixes(self):+ initiator = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR, prefix=b"S" * 8)+ first = initiator.preamble()+ responder = protocol.LinkSession(TOKEN, protocol.ROLE_RESPONDER, prefix=b"S" * 8)+ responder.accept_preamble(first)+ self.assertNotEqual(responder.prefix, b"S" * 8)+ second = responder.preamble()+ self.assertEqual(second[6:14], responder.prefix)+ initiator.accept_preamble(second)+ # An initiator given its own prefix back closes.+ again = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR, prefix=b"S" * 8)+ again.preamble()+ echo = second[:6] + b"S" * 8 + second[14:]+ with self.assertRaises(protocol.PreambleRefused):+ again.accept_preamble(echo)++ def test_a_reflected_preamble(self):+ initiator = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR)+ first = initiator.preamble()+ with self.assertRaises(protocol.PreambleRefused):+ initiator.accept_preamble(first)++ def test_the_initiator_requires_its_own_key_id_back(self):+ initiator = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR)+ first = initiator.preamble()+ responder = protocol.LinkSession(TOKEN, protocol.ROLE_RESPONDER)+ responder.accept_preamble(first)+ second = responder.preamble()+ forged = second[:14] + _key_id(OTHER_TOKEN) + second[30:]+ with self.assertRaises(protocol.PreambleRefused):+ initiator.accept_preamble(forged)++ def test_the_responder_requires_its_tokens_key_id(self):+ initiator = protocol.LinkSession(OTHER_TOKEN, protocol.ROLE_INITIATOR)+ responder = protocol.LinkSession(TOKEN, protocol.ROLE_RESPONDER)+ with self.assertRaises(protocol.PreambleRefused):+ responder.accept_preamble(initiator.preamble())++ def test_a_second_preamble(self):+ initiator, responder, first, second = _pair()+ with self.assertRaises(protocol.ProtocolError):+ responder.accept_preamble(first)+ with self.assertRaises(protocol.ProtocolError):+ initiator.accept_preamble(second)+++class StrictJson(unittest.TestCase):+ def _open(self, plain):+ initiator, responder, _, _ = _pair()+ frame = initiator.seal_raw(plain)+ return _open_frame(responder, frame)++ def test_a_clean_message(self):+ message = self._open(b'{"type":"ping","data":{}}')+ self.assertEqual(message, {"type": "ping", "data": {}})+ self.assertFalse(message.malformed)++ def test_malformed_but_an_object(self):+ for plain in (+ b'{"type":"ping","data":{"x":NaN}}',+ b'{"type":"ping","data":{"x":Infinity}}',+ b'{"type":"ping","data":{"x":-Infinity}}',+ b'{"type":"ping","data":{"x":1e400}}',+ b'{"type":"ping","data":{},"data":{}}',+ b'{"type":"ping","data":{"x":1,"x":2}}',+ b'{"type":"ping","data":{"x":"\\ud800"}}',+ b'{"type":"ping","data":{"\\udc00":1}}',+ b'\xef\xbb\xbf{"type":"ping","data":{}}',+ ):+ with self.subTest(plain=plain):+ message = self._open(plain)+ self.assertTrue(message.malformed)+ self.assertIsNone(protocol.read_message(message))++ def test_not_an_object_ends_the_link(self):+ for plain in (b"[]", b"1", b'"x"', b"{", b"\xff", b"", b"[" * 100000):+ with self.subTest(plain=plain[:10]), self.assertRaises(protocol.ProtocolError):+ self._open(plain)++ def test_envelope(self):+ for message in ({"type": 1, "data": {}}, {"data": {}}, {"type": "ping"}, {"type": "ping", "data": []}):+ with self.subTest(message=message):+ self.assertIsNone(protocol.read_message(message))+ self.assertEqual(protocol.read_message({"type": "ping", "data": {}, "extra": 1}), ("ping", {}))++ def test_integers_by_their_text(self):+ for plain, ok in ((b'{"type":"accept","data":{"route":1}}', True),+ (b'{"type":"accept","data":{"route":1.0}}', False),+ (b'{"type":"accept","data":{"route":1e0}}', False),+ (b'{"type":"accept","data":{"route":true}}', False)):+ with self.subTest(plain=plain):+ self.assertEqual(protocol.read_accept(self._open(plain)) is not None, ok)++ def test_seal_writes_strict_json(self):+ initiator, responder, _, _ = _pair()+ with self.assertRaises(ValueError):+ initiator.seal({"type": "ping", "data": {"x": float("nan")}})+ message = _open_frame(responder, initiator.seal({"type": "text", "data": {"text": "é\U0001F600", "seq": 1}}))+ self.assertEqual(message["data"]["text"], "é\U0001F600")+++def _hello(**changes):+ data = {"version": 6, "id": protocol.id_text(ID_A), "name": "Studio Mac", "platform": "macos",+ "app": "1.5.0", "caps": ["clipboard", "settings"], "port": 24820}+ data.update(changes)+ return {"type": "hello", "data": {k: v for k, v in data.items() if v is not _DROP}}+++_DROP = object()+++class HelloAndWelcome(unittest.TestCase):+ def test_builders_read_back(self):+ hello = protocol.hello_v6(ID_A, "Studio Mac", "macos", "1.5.0", ["clipboard"], 24820, hw="aa:bb:cc:dd:ee:ff")+ read = protocol.read_hello(hello)+ self.assertEqual(read["id"], ID_A)+ self.assertEqual(read["name"], "Studio Mac")+ self.assertEqual(read["port"], 24820)+ self.assertEqual(read["hw"], "aa:bb:cc:dd:ee:ff")+ self.assertEqual(hello["data"]["version"], 6)+ welcome = protocol.welcome_v6(ID_B, "PC", "windows", "1.5.0", ["text"], accepts=True)+ read = protocol.read_welcome(welcome)+ self.assertEqual(read["id"], ID_B)+ self.assertIs(read["accepts"], True)+ self.assertIsNone(read["hw"])+ self.assertNotIn("port", welcome["data"])++ def test_invalid_hellos(self):+ cases = {+ "version 5": _hello(version=5),+ "version 6.0": _hello(version=6.0),+ "no id": _hello(id=_DROP),+ "15-byte id": _hello(id=_b64(bytes(range(15)))),+ "zero id": _hello(id=_b64(bytes(16))),+ "empty name": _hello(name=""),+ "49 code points": _hello(name="é" * 49),+ "port 70000": _hello(port=70000),+ "port true": _hello(port=True),+ "17 caps": _hello(caps=["c%d" % n for n in range(17)]),+ "a cap of 33": _hello(caps=["c" * 33]),+ "a non-ASCII cap": _hello(caps=["cé"]),+ "capital platform": _hello(platform="MacOS"),+ "long platform": _hello(platform="a" * 17),+ "empty app": _hello(app=""),+ "app of 33": _hello(app="1" * 33),+ "upper-case hw": _hello(hw="AA:BB:CC:DD:EE:FF"),+ "not a hello": {"type": "ping", "data": {}},+ }+ for label, message in cases.items():+ with self.subTest(label), self.assertRaises(protocol.InvalidHello):+ protocol.read_hello(message)+ self.assertEqual(protocol.read_hello(_hello(name="é" * 48))["name"], "é" * 48)+ self.assertEqual(protocol.read_hello(_hello(platform="haiku_os"))["platform"], "haiku_os")+ self.assertEqual(protocol.read_hello(_hello(port=0))["port"], 0)+ self.assertEqual(protocol.read_hello(_hello(extra="ignored"))["name"], "Studio Mac")++ def test_the_error_answers(self):+ for answer, error in ((protocol.invalid_hello_v6(), "invalid_hello"), (protocol.wrong_id_v6(), "wrong_id")):+ self.assertEqual(answer, {"type": "welcome", "data": {"version": 6, "error": error}})+ with self.assertRaises(protocol.HelloRefused) as caught:+ protocol.read_welcome(answer)+ self.assertEqual(caught.exception.error, error)+ for data in ({"version": 6, "error": "other"}, {"version": 6, "error": 1}, {"version": 5, "error": "wrong_id"}):+ with self.subTest(data=data), self.assertRaises(protocol.InvalidWelcome):+ protocol.read_welcome({"type": "welcome", "data": data})++ def test_invalid_welcomes(self):+ good = protocol.welcome_v6(ID_B, "PC", "windows", "1.5.0", [], accepts=False)+ self.assertIs(protocol.read_welcome(good)["accepts"], False)+ for change in ({"accepts": 1}, {"accepts": None}, {"id": "x"}, {"version": 5}):+ bad = {"type": "welcome", "data": dict(good["data"], **change)}+ with self.subTest(change=change), self.assertRaises(protocol.InvalidWelcome):+ protocol.read_welcome(bad)+ with self.assertRaises(protocol.InvalidWelcome):+ protocol.read_welcome({"type": "hello", "data": good["data"]})+++class Focus(unittest.TestCase):+ def test_take_by_a_zone(self):+ message = protocol.focus_v6(7, ID_B, edge="left", offset=0.25, resistance_px=90, reach=[ID_C])+ read = protocol.read_focus(message, ID_B)+ self.assertEqual(read["route"], 7)+ self.assertEqual(read["target"], ID_B)+ self.assertTrue(read["here"])+ self.assertFalse(read["malformed"])+ self.assertEqual((read["edge"], read["offset"], read["resistance_px"], read["reach"], read["stay"]),+ ("left", 0.25, 90, [ID_C], False))++ def test_defaults_and_clamping(self):+ read = protocol.read_focus({"type": "focus", "data": {"route": 1, "target": protocol.id_text(ID_B),+ "edge": "top", "offset": 1.5}}, ID_B)+ self.assertEqual((read["offset"], read["resistance_px"], read["reach"]), (1.0, 120, []))+ read = protocol.read_focus({"type": "focus", "data": {"route": 1, "target": protocol.id_text(ID_B),+ "edge": "top", "offset": -2}}, ID_B)+ self.assertEqual(read["offset"], 0.0)++ def test_stay(self):+ read = protocol.read_focus(protocol.focus_v6(3, ID_B, resistance_px=120, reach=[], stay=True), ID_B)+ self.assertTrue(read["stay"])+ self.assertFalse(read["malformed"])++ def test_let_go_ignores_the_fields_it_does_not_have(self):+ message = protocol.focus_v6(9, ID_C)+ self.assertEqual(message["data"], {"route": 9, "target": protocol.id_text(ID_C)})+ extra = {"type": "focus", "data": dict(message["data"], reach="junk", resistance_px=-4, stay=5, edge="up")}+ read = protocol.read_focus(extra, ID_B)+ self.assertFalse(read["here"])+ self.assertFalse(read["malformed"])+ self.assertEqual(read["target"], ID_C)++ def test_route_or_target_malformed_is_ignored(self):+ for data in ({"route": 0, "target": protocol.id_text(ID_B)},+ {"route": 2**53, "target": protocol.id_text(ID_B)},+ {"route": 1.0, "target": protocol.id_text(ID_B)},+ {"route": True, "target": protocol.id_text(ID_B)},+ {"target": protocol.id_text(ID_B)},+ {"route": 1, "target": "nope"},+ {"route": 1}):+ with self.subTest(data=data):+ self.assertIsNone(protocol.read_focus({"type": "focus", "data": data}, ID_B))++ def test_other_fields_malformed_are_flagged_for_refuse(self):+ target = protocol.id_text(ID_B)+ for extra in ({"edge": "left"}, {"offset": 0.5}, {"edge": "middle", "offset": 0.5},+ {"edge": "left", "offset": True}, {"resistance_px": 1001}, {"resistance_px": -1},+ {"resistance_px": 12.5}, {"reach": [protocol.id_text(ID_C)] * 2},+ {"reach": [protocol.id_text(bytes([n]) * 16) for n in range(1, 34)]},+ {"reach": ["bad"]}, {"reach": "x"}, {"stay": False}, {"stay": 1}):+ with self.subTest(extra=extra):+ read = protocol.read_focus({"type": "focus", "data": dict({"route": 4, "target": target}, **extra)}, ID_B)+ self.assertEqual(read["route"], 4)+ self.assertTrue(read["malformed"])++ def test_strictness_marks_a_take_malformed(self):+ initiator, responder, _, _ = _pair()+ plain = ('{"type":"focus","data":{"route":4,"target":"%s","offset":NaN,"edge":"left"}}' % protocol.id_text(ID_B)).encode()+ read = protocol.read_focus(_open_frame(responder, initiator.seal_raw(plain)), ID_B)+ self.assertEqual(read["route"], 4)+ self.assertTrue(read["malformed"])++ def test_a_reach_naming_the_owner_or_responder_is_kept_for_the_caller(self):+ read = protocol.read_focus(protocol.focus_v6(1, ID_B, reach=[ID_A, ID_B, ID_C]), ID_B)+ self.assertEqual(read["reach"], [ID_A, ID_B, ID_C])+++class Answers(unittest.TestCase):+ def test_accept_refuse_accepts(self):+ self.assertEqual(protocol.read_accept(protocol.accept_msg(5)), {"route": 5})+ self.assertEqual(protocol.read_refuse(protocol.refuse_msg(5, "owned")), {"route": 5, "why": "owned"})+ self.assertEqual(protocol.read_refuse({"type": "refuse", "data": {"route": 5, "why": "new_reason"}})["why"], "new_reason")+ self.assertIsNone(protocol.read_accept({"type": "accept", "data": {"route": 0}}))+ self.assertEqual(protocol.read_accepts(protocol.accepts_msg(False)), {"accepts": False})+ self.assertIsNone(protocol.read_accepts({"type": "accepts", "data": {"accepts": 0}}))+ with self.assertRaises(ValueError):+ protocol.refuse_msg(5, "because")++ def test_switch(self):+ read = protocol.read_switch(protocol.switch_v6(3, ID_A, edge="right", offset=0.5))+ self.assertEqual(read, {"route": 3, "next": ID_A, "edge": "right", "offset": 0.5})+ read = protocol.read_switch(protocol.switch_v6(3, ID_A))+ self.assertEqual(read, {"route": 3, "next": ID_A, "edge": None, "offset": None})+ for data in ({"route": 3, "next": protocol.id_text(ID_A), "edge": "right"},+ {"route": 3, "next": protocol.id_text(ID_A), "offset": 0.5},+ {"route": 3, "next": "x"}, {"route": 0, "next": protocol.id_text(ID_A)}):+ with self.subTest(data=data):+ self.assertIsNone(protocol.read_switch({"type": "switch", "data": data}))++ def test_ack(self):+ self.assertEqual(protocol.read_ack(protocol.ack_v6(4, 250)), {"seq": 4, "held_us": 250, "locked": False})+ self.assertEqual(protocol.ack_v6(4, -3)["data"]["held_us"], 0)+ self.assertEqual(protocol.ack_v6(4, 2**40)["data"]["held_us"], 2**31 - 1)+ self.assertEqual(protocol.read_ack(protocol.ack_v6(0, 0, locked=True))["locked"], True)+ for data in ({"seq": 1}, {"seq": 1, "held_us": -1}, {"seq": 1, "held_us": 2**31}, {"seq": -1, "held_us": 0},+ {"seq": 1.0, "held_us": 0}, {"seq": 1, "held_us": 0, "locked": False}, {"held_us": 0}):+ with self.subTest(data=data), self.assertRaises(protocol.ProtocolError):+ protocol.read_ack({"type": "ack", "data": data})+++class Input(unittest.TestCase):+ def test_each_kind(self):+ good = [+ ({"type": "keydown", "data": {"key": "a", "us": "a", "seq": 1}}, {"key": "a", "us": "a"}),+ ({"type": "keyup", "data": {"key": "shift_r", "seq": 2}}, {"key": "shift_r", "us": None}),+ ({"type": "mousemove", "data": {"dx": -65535, "dy": 65535, "seq": 3}}, {"dx": -65535, "dy": 65535}),+ ({"type": "mousedown", "data": {"button": "forward", "seq": 4}}, {"button": "forward"}),+ ({"type": "scroll", "data": {"dy": -1.5, "dx": 2, "mode": "pixel", "seq": 5}}, {"dy": -1.5, "dx": 2, "mode": "pixel"}),+ ({"type": "scroll", "data": {"dy": 3, "seq": 6}}, {"dy": 3, "dx": 0, "mode": "line"}),+ ({"type": "gesture", "data": {"name": "pinch", "seq": 7}}, {"name": "pinch"}),+ ({"type": "text", "data": {"text": "a\n\U0001F600", "seq": 8}}, {"text": "a\n\U0001F600"}),+ ]+ for message, expected in good:+ with self.subTest(message=message):+ read = protocol.read_input(message)+ self.assertEqual(read["seq"], message["data"]["seq"])+ self.assertEqual(read["type"], message["type"])+ for key, value in expected.items():+ self.assertEqual(read[key], value)++ def test_builders(self):+ self.assertEqual(protocol.read_input(protocol.key_msg("keydown", "c", us="c", seq=1))["key"], "c")+ self.assertEqual(protocol.read_input(protocol.text_msg("hé", seq=2))["text"], "hé")+ self.assertEqual(protocol.read_input(protocol.mousemove_msg(3, -4, seq=3))["dx"], 3)++ def test_malformed(self):+ for message in (+ {"type": "keydown", "data": {"key": "", "seq": 1}},+ {"type": "keydown", "data": {"key": "a", "us": "ab", "seq": 1}},+ {"type": "keydown", "data": {"key": 5, "seq": 1}},+ {"type": "keydown", "data": {"key": "a"}},+ {"type": "keydown", "data": {"key": "a", "seq": 0}},+ {"type": "mousemove", "data": {"dx": 1.5, "dy": 0, "seq": 1}},+ {"type": "mousemove", "data": {"dx": 65536, "dy": 0, "seq": 1}},+ {"type": "mousemove", "data": {"dx": 0, "seq": 1}},+ {"type": "mousedown", "data": {"button": "fourth", "seq": 1}},+ {"type": "scroll", "data": {"dy": 70000, "seq": 1}},+ {"type": "scroll", "data": {"dy": 1, "mode": "page", "seq": 1}},+ {"type": "scroll", "data": {"dy": True, "seq": 1}},+ {"type": "gesture", "data": {"name": "rotate", "seq": 1}},+ {"type": "text", "data": {"text": 5, "seq": 1}},+ {"type": "ping", "data": {}},+ ):+ with self.subTest(message=message):+ self.assertIsNone(protocol.read_input(message))++ def test_text_over_4096_bytes_is_dropped_but_keeps_its_seq(self):+ read = protocol.read_input({"type": "text", "data": {"text": "é" * 2049, "seq": 9}})+ self.assertEqual(read["seq"], 9)+ self.assertIsNone(read["text"])+ self.assertEqual(protocol.read_input({"type": "text", "data": {"text": "é" * 2048, "seq": 9}})["text"], "é" * 2048)+++class Others(unittest.TestCase):+ def test_clipboard(self):+ png = protocol.PNG_SIGNATURE + b"x"+ read = protocol.read_clipboard(protocol.clipboard_msg(text="hi", image=png))+ self.assertEqual(read, {"text": "hi", "image": png})+ read = protocol.read_clipboard({"type": "clipboard", "data": {"text": "x" * (256 * 1024 + 1)}})+ self.assertEqual(read, {"text": None, "image": None})+ self.assertIsNone(protocol.read_clipboard({"type": "clipboard", "data": {"text": "hi", "image": 5}}))+ self.assertIsNone(protocol.read_clipboard({"type": "clipboard", "data": {"text": 5}}))+ self.assertEqual(protocol.read_clipboard({"type": "clipboard", "data": {"text": "é" * (128 * 1024)}})["text"], "é" * (128 * 1024))++ def test_arrangement(self):+ now = 1_790_000_000+ read = protocol.read_arrangement_v6(protocol.arrangement_v6("left", now, ID_A), now)+ self.assertEqual(read, {"edge": "left", "set_at": now, "by": ID_A})+ for data in ({"edge": "middle", "set_at": now, "by": protocol.id_text(ID_A)},+ {"edge": "left", "set_at": now + 86401, "by": protocol.id_text(ID_A)},+ {"edge": "left", "set_at": 2**53 - 1, "by": protocol.id_text(ID_A)},+ {"edge": "left", "set_at": -1, "by": protocol.id_text(ID_A)},+ {"edge": "left", "set_at": now, "by": ""},+ {"edge": "left", "set_at": float(now), "by": protocol.id_text(ID_A)}):+ with self.subTest(data=data):+ self.assertIsNone(protocol.read_arrangement_v6({"type": "arrangement", "data": data}, now))+ self.assertIsNotNone(protocol.read_arrangement_v6(+ {"type": "arrangement", "data": {"edge": "top", "set_at": now + 86400, "by": protocol.id_text(ID_A)}}, now))++ def test_paired(self):+ self.assertEqual(protocol.read_paired(protocol.paired_msg([ID_A, ID_C])), [ID_A, ID_C])+ self.assertEqual(protocol.read_paired(protocol.paired_msg([])), [])+ for ids in (["x"], [protocol.id_text(bytes([n]) * 16) for n in range(1, 34)], "x"):+ with self.subTest(ids=ids):+ self.assertIsNone(protocol.read_paired({"type": "paired", "data": {"ids": ids}}))++ def test_platforms_and_names(self):+ for platform in ("macos", "windows", "linux", "ios", "android", "haiku", "a_1"):+ self.assertTrue(protocol.valid_platform(platform))+ for platform in ("", "MacOS", "a" * 17, "mac-os", "é", 5):+ self.assertFalse(protocol.valid_platform(platform))+++class OverASocket(unittest.TestCase):+ """The helpers the links use, end to end over a socket pair: preambles each way, then the+ first frames, as the handshake steps order them."""++ def test_a_whole_handshake(self):+ left, right = socket.socketpair()+ results = {}++ def responder():+ deadline = time.monotonic() + 5+ first = protocol.recv_link_preamble(right, deadline)+ _, key_id, _ = protocol.split_preamble(first)+ results["key_id"] = key_id+ session = protocol.LinkSession(TOKEN, protocol.ROLE_RESPONDER)+ session.accept_preamble(first)+ right.sendall(session.preamble())+ results["hello"] = protocol.read_hello(protocol.recv_msg(right, session, protocol.HELLO_MAX_BYTES, deadline))+ protocol.send_msg(right, session, protocol.welcome_v6(ID_B, "PC", "windows", "1.5.0", [], accepts=True))++ thread = threading.Thread(target=responder)+ thread.start()+ try:+ deadline = time.monotonic() + 5+ session = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR)+ left.sendall(session.preamble())+ session.accept_preamble(protocol.recv_link_preamble(left, deadline))+ protocol.send_msg(left, session, protocol.hello_v6(ID_A, "Mac", "macos", "1.5.0", [], 24820))+ welcome = protocol.read_welcome(protocol.recv_msg(left, session, protocol.HELLO_MAX_BYTES, deadline))+ thread.join(5)+ self.assertEqual(welcome["id"], ID_B)+ self.assertEqual(results["hello"]["id"], ID_A)+ self.assertEqual(results["key_id"], _key_id(TOKEN))+ finally:+ left.close()+ right.close()+++class HostileInput(unittest.TestCase):+ """What the Part B review found: nothing a peer sends may raise anything but ProtocolError."""++ def test_unhashable_values_where_a_name_is_due(self):+ for value in (["x"], {"x": 1}):+ with self.subTest(value=value):+ self.assertIsNone(protocol.read_input({"type": "gesture", "data": {"seq": 1, "name": value}}))+ self.assertIsNone(protocol.read_input({"type": "mousedown", "data": {"seq": 1, "button": value}}))+ self.assertIsNone(protocol.read_input({"type": "scroll", "data": {"seq": 1, "dy": 1, "mode": value}}))+ self.assertIsNone(protocol.read_switch({"type": "switch", "data": {"route": 1, "next": protocol.id_text(ID_A), "edge": value, "offset": 0}}))+ self.assertIsNone(protocol.read_arrangement_v6({"type": "arrangement", "data": {"edge": value, "set_at": 1, "by": protocol.id_text(ID_A)}}, 10))+ read = protocol.read_focus({"type": "focus", "data": {"route": 1, "target": protocol.id_text(ID_B), "edge": value, "offset": 0}}, ID_B)+ self.assertTrue(read["malformed"])+ with self.assertRaises(protocol.InvalidWelcome):+ protocol.read_welcome({"type": "welcome", "data": {"version": 6, "error": value}})++ def test_plain_dicts_with_what_a_parser_would_flag(self):+ self.assertIsNone(protocol.read_input({"type": "text", "data": {"seq": 1, "text": "\ud800"}}))+ self.assertIsNone(protocol.read_clipboard({"type": "clipboard", "data": {"text": "\ud800"}}))+ self.assertIsNone(protocol.read_input({"type": "scroll", "data": {"seq": 1, "dy": 10**400}}))++ def test_a_refused_session_stays_refused(self):+ initiator = protocol.LinkSession(TOKEN, protocol.ROLE_INITIATOR)+ responder = protocol.LinkSession(TOKEN, protocol.ROLE_RESPONDER)+ first = initiator.preamble()+ with self.assertRaises(protocol.PreambleRefused):+ responder.accept_preamble(first[:30] + bytes(32))+ with self.assertRaises(protocol.ProtocolError):+ responder.accept_preamble(first)++ def test_repeated_byte_order_marks_are_malformed_not_fatal(self):+ message = protocol.parse_message(b"\xef\xbb\xbf\xef\xbb\xbf" + b'{"type":"ping","data":{}}')+ self.assertTrue(message.malformed)++ def test_a_refuse_without_a_why_is_still_a_refusal(self):+ self.assertEqual(protocol.read_refuse({"type": "refuse", "data": {"route": 5}}), {"route": 5, "why": None})+ self.assertEqual(protocol.read_refuse({"type": "refuse", "data": {"route": 5, "why": 3}}), {"route": 5, "why": None})+ self.assertIsNone(protocol.read_refuse({"type": "refuse", "data": {"route": 0, "why": "owned"}}))+++class Builders(unittest.TestCase):+ def test_names_are_cut_to_48_code_points(self):+ hello = protocol.hello_v6(ID_A, "é" * 60, "macos", "1.5.0", [], 24820)+ self.assertEqual(protocol.read_hello(hello)["name"], "é" * 48)+ welcome = protocol.welcome_v6(ID_B, "x" * 63, "windows", "1.5.0", [], accepts=True)+ self.assertEqual(protocol.read_welcome(welcome)["name"], "x" * 48)+ with self.assertRaises(ValueError):+ protocol.hello_v6(ID_A, "", "macos", "1.5.0", [], 24820)++ def test_edge_and_offset_go_together(self):+ for build in (lambda **kw: protocol.focus_v6(1, ID_B, **kw), lambda **kw: protocol.switch_v6(1, ID_A, **kw)):+ with self.assertRaises(ValueError):+ build(edge="left")+ with self.assertRaises(ValueError):+ build(offset=0.5)+++class FirstFrames(unittest.TestCase):+ """recv_first_msg, and telling apart the one failure the responder answers (a frame that opened+ but is not a JSON object: invalid_hello) from those it closes on without a word."""++ def _first(self, frame):+ initiator, responder, _, _ = _pair()+ left, right = socket.socketpair()+ try:+ left.sendall(frame(initiator))+ left.shutdown(socket.SHUT_WR)+ return protocol.recv_first_msg(right, responder, time.monotonic() + 1)+ finally:+ left.close()+ right.close()++ def test_a_good_first_frame(self):+ self.assertEqual(self._first(lambda s: s.seal({"type": "ping", "data": {}})), {"type": "ping", "data": {}})++ def test_not_an_object_is_its_own_error(self):+ for plain in (b"[]", b"{", b"\xff", b"1"):+ with self.subTest(plain=plain), self.assertRaises(protocol.NotAnObject):+ self._first(lambda s: s.seal_raw(plain))++ def test_the_length_bounds_are_refused_before_reading(self):+ for length in (0, 20, 4097, 2**31):+ with self.subTest(length=length), self.assertRaises(protocol.ProtocolError) as caught:+ self._first(lambda s: struct.pack(">I", length))+ self.assertNotIsInstance(caught.exception, protocol.NotAnObject)+ self.assertEqual(self._first(lambda s: s.seal_raw(b"{}")), {})++ def test_a_bad_tag_or_counter_is_not_answered(self):+ def flipped(session):+ frame = bytearray(session.seal({"type": "ping", "data": {}}))+ frame[-1] ^= 1+ return bytes(frame)++ def skipped(session):+ session.seal({"type": "ping", "data": {}})+ return session.seal({"type": "ping", "data": {}})++ for frame in (flipped, skipped):+ with self.subTest(frame=frame.__name__), self.assertRaises(protocol.ProtocolError) as caught:+ self._first(frame)+ self.assertNotIsInstance(caught.exception, protocol.NotAnObject)+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_responder_accessors.py b/core/tests/test_responder_accessors.pynew file mode 100644index 0000000..2e20dc1--- /dev/null+++ b/core/tests/test_responder_accessors.py@@ -0,0 +1,40 @@+"""Two small readers the apps need from the responder and its book: the zones as the book holds+them, and the capabilities a linked peer announced."""++import unittest++from core import protocol+from core.tests.responder_harness import B, Initiator, Machine, entry, wait_for+++class AccessorTests(unittest.TestCase):+ def test_the_book_gives_the_zones_it_holds(self):+ machine = Machine([entry(B, "Peer")], zones=[{"peer": protocol.id_text(B), "kind": "edge"}])+ self.assertEqual(machine.book.zones(), [{"peer": protocol.id_text(B), "kind": "edge"}])+ machine.book.zones().append({"peer": "x"})+ self.assertEqual(len(machine.book.zones()), 1)++ def test_the_book_stores_a_peers_paired_list_with_its_entry_and_only_when_it_changed(self):+ machine = Machine([entry(B, "Peer")])+ ids = [protocol.id_text(bytes(range(1, 17)))]+ machine.book.store_paired(protocol.id_text(B), ids)+ self.assertEqual(machine.settings.peer(protocol.id_text(B))["paired_with"], ids)+ saves = machine.settings.saves+ machine.book.store_paired(protocol.id_text(B), ids)+ self.assertEqual(machine.settings.saves, saves)+ machine.book.store_paired("nobody", ids)+ self.assertEqual(machine.settings.saves, saves)++ def test_the_responder_gives_a_linked_peers_capabilities(self):+ machine = Machine([entry(B, "Peer")]).start()+ self.addCleanup(machine.stop)+ self.assertIsNone(machine.responder.caps_of(B))+ initiator = Initiator(machine)+ self.addCleanup(initiator.close)+ initiator.handshake(initiator.hello(caps=["settings", "text"]))+ self.assertTrue(wait_for(lambda: machine.responder.caps_of(B) is not None))+ self.assertEqual(machine.responder.caps_of(B), frozenset({"settings", "text"}))+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_responder_handshake.py b/core/tests/test_responder_handshake.pynew file mode 100644index 0000000..4930647--- /dev/null+++ b/core/tests/test_responder_handshake.py@@ -0,0 +1,584 @@+"""The responder's half of the version 6 handshake (WIRE.md section 2, the handshake+and older peers), over real sockets on loopback against LinkResponder."""++import hashlib+import hmac+import json+import os+import select+import socket+import struct+import threading+import time+import unittest+from unittest import mock++from core import protocol, receiver+from core.tests import v5_link+from core.tests.responder_harness import (+ B, C, D, HERE, TOKENS, Initiator, Machine, entry, ident, silent_close, token, wait_for,+)+++def raw_preamble(key_id, share=None, prefix=None):+ return protocol.WIRE_MAGIC + bytes([protocol.LINK_VERSION]) + (prefix or os.urandom(8)) + key_id + (share or os.urandom(32))+++class Case(unittest.TestCase):+ peers = None+ zones = ()++ def setUp(self):+ self.machine = Machine(self.peers or [entry(B, "Bee"), entry(C, "Sea")], self.zones).start()+ self.addCleanup(self.machine.stop)+ self.opened = []++ def initiator(self, *args, **kwargs):+ link = Initiator(self.machine, *args, **kwargs)+ self.opened.append(link)+ self.addCleanup(link.close)+ return link++ def raw(self):+ sock = socket.create_connection(("127.0.0.1", self.machine.port), timeout=5)+ self.addCleanup(sock.close)+ return sock+++class TheWelcomesHardwareAddress(unittest.TestCase):+ """`hw` in the welcome is this machine's address on the interface the link came in by."""++ def welcome_of(self, **machine):+ machine = Machine([entry(B, "Bee")], **machine).start()+ self.addCleanup(machine.stop)+ link = Initiator(machine)+ self.addCleanup(link.close)+ return link.handshake()++ def test_the_hook_is_asked_with_the_address_the_link_came_from_and_its_answer_is_sent(self):+ asked = []+ welcome = self.welcome_of(hardware=lambda host: asked.append(host) or "aa:bb:cc:dd:ee:01", hw="11:11:11:11:11:11")+ self.assertEqual(asked, ["127.0.0.1"])+ self.assertEqual(welcome["hw"], "aa:bb:cc:dd:ee:01")++ def test_without_a_hook_the_identitys_hw_is_sent_as_before(self):+ self.assertEqual(self.welcome_of(hw="11:11:11:11:11:11")["hw"], "11:11:11:11:11:11")++ def test_a_hook_that_raises_sends_no_hw_and_the_link_still_comes_up(self):+ def broken(host):+ raise OSError("no adapter table")++ self.assertIsNone(self.welcome_of(hardware=broken, hw="11:11:11:11:11:11")["hw"])++ def test_a_hook_that_knows_nothing_sends_no_hw(self):+ self.assertIsNone(self.welcome_of(hardware=lambda host: "")["hw"])+++class TheLookup(Case):+ def test_an_unknown_key_id_is_closed_with_nothing_sent(self):+ link = self.initiator(key=token(200))+ self.assertTrue(silent_close(link.sock))++ def test_a_known_key_id_is_welcomed(self):+ welcome = self.initiator().handshake()+ self.assertEqual(welcome["id"], HERE)+ self.assertEqual(welcome["name"], "Here")+ self.assertTrue(welcome["accepts"])+ self.assertIn("text", welcome["caps"])+ self.assertTrue(wait_for(lambda: self.machine.responder.links() == {B}))++ def test_welcome_accepts_is_false_without_allow_drive(self):+ self.machine.settings.peer(TOKENS[B])["allow_drive"] = False+ self.assertFalse(self.initiator().handshake()["accepts"])++ def test_a_typed_token_is_never_matched_or_given_a_key_id(self):+ typed = "hunter2"+ self.machine.settings.data["peers"].append(entry("", "Typed", token=typed, from_1_4=True, linked=False))+ typed_key_id = hmac.new(+ hmac.new(protocol.LINK_SALT, typed.encode(), hashlib.sha256).digest(), protocol.KEY_ID_INFO + b"\x01", hashlib.sha256+ ).digest()[:16]+ with mock.patch.object(protocol, "key_id", wraps=protocol.key_id) as computed:+ sock = self.raw()+ sock.sendall(raw_preamble(typed_key_id))+ self.assertTrue(silent_close(sock))+ self.assertNotIn(typed, [call.args[0] for call in computed.call_args_list])++ def test_low_order_shares_are_closed_with_nothing_sent_not_even_a_preamble(self):+ for share in (bytes(32), b"\x01" + bytes(31), (2**255 - 19).to_bytes(32, "little")):+ sock = self.raw()+ sock.sendall(raw_preamble(protocol.key_id(TOKENS[B]), share))+ self.assertTrue(silent_close(sock), share.hex())++ def test_the_hello_updates_the_entry_and_is_saved(self):+ link = self.initiator()+ link.handshake(link.hello(name="Bee Two", platform="linux", hw="aa:bb:cc:dd:ee:ff", port=24830))+ saved = self.machine.settings.peer(TOKENS[B])+ self.assertEqual((saved["name"], saved["platform"], saved["hw"], saved["port"]), ("Bee Two", "linux", "aa:bb:cc:dd:ee:ff", 24830))+ # Loopback never changes a saved host.+ self.assertEqual(saved["host"], "192.168.77.9")++ def test_an_absent_hw_keeps_the_saved_one(self):+ self.machine.settings.peer(TOKENS[B])["hw"] = "11:22:33:44:55:66"+ self.initiator().handshake()+ self.assertEqual(self.machine.settings.peer(TOKENS[B])["hw"], "11:22:33:44:55:66")++ def test_which_addresses_teach_a_host(self):+ self.assertTrue(receiver.learnable_host("192.168.77.5", 24820))+ self.assertTrue(receiver.learnable_host("192.168.1.20", 1))+ self.assertFalse(receiver.learnable_host("192.168.77.5", 0))+ self.assertFalse(receiver.learnable_host("127.0.0.1", 24820))+ self.assertFalse(receiver.learnable_host("127.4.5.6", 24820))+ self.assertFalse(receiver.learnable_host("169.254.10.1", 24820))+ self.assertFalse(receiver.learnable_host("not an address", 24820))++ def test_a_first_link_marks_the_entry_linked(self):+ self.machine.settings.peer(TOKENS[B])["linked"] = False+ self.initiator().handshake()+ self.assertTrue(self.machine.settings.peer(TOKENS[B])["linked"])++ def test_a_peer_removed_during_its_handshake_is_closed(self):+ admit = self.machine.book.admit++ def admit_then_remove(*args):+ outcome = admit(*args)+ self.machine.settings.data["peers"] = [p for p in self.machine.settings.data["peers"] if p["token"] != TOKENS[B]]+ return outcome++ self.machine.book.admit = admit_then_remove+ link = self.initiator()+ link.handshake()+ self.assertTrue(link.closed.wait(2))+ self.assertTrue(wait_for(lambda: self.machine.responder.links() == set()))++ def test_an_unknown_platform_of_the_allowed_shape_is_accepted(self):+ link = self.initiator()+ link.handshake(link.hello(platform="freebsd_14"))+ self.assertEqual(self.machine.settings.peer(TOKENS[B])["platform"], "freebsd_14")+++class TheMigratedEntry(Case):+ peers = [entry("", "Old PC", token=token(50), from_1_4=True, linked=False, paired_at=0), entry(C, "Sea")]+ zones = [{"peer": "", "kind": "edge"}, {"peer": protocol.id_text(C), "kind": "edge"}]++ def migrated(self):+ return self.machine.settings.peer(token(50))++ def test_its_first_link_learns_the_id_and_rewrites_its_zones(self):+ link = self.initiator(peer=B, key=token(50))+ link.handshake(link.hello(name="Bee"))+ self.assertEqual(self.migrated()["id"], protocol.id_text(B))+ self.assertTrue(self.migrated()["linked"])+ self.assertEqual([zone["peer"] for zone in self.machine.settings.data["zones"]], [protocol.id_text(B), protocol.id_text(C)])+ self.assertEqual(self.machine.notices, ["Linked with Bee at 127.0.0.1 for the first time on Beamer 1.5.0."])++ def test_a_later_link_naming_another_id_is_answered_wrong_id(self):+ self.initiator(peer=B, key=token(50)).handshake()+ with self.assertRaises(protocol.HelloRefused) as refused:+ self.initiator(peer=D, key=token(50)).handshake()+ self.assertEqual(refused.exception.error, protocol.ERROR_WRONG_ID)+ self.assertEqual(self.migrated()["id"], protocol.id_text(B))++ def fold(self, **hello):+ link = self.initiator(peer=C, key=token(50))+ welcome = link.handshake(link.hello(**hello))+ self.assertTrue(link.closed.wait(2))+ return welcome++ def test_a_hello_naming_another_entrys_id_folds_the_migrated_entry_into_it(self):+ # The machine was paired again since the upgrade, somewhere its saved host did not match,+ # and still dials under the 1.4.x token: only it holds that token (the campaign's call,+ # after step 4c's review). It gets the welcome, so its own step 7 folds its side too.+ self.migrated().update(side="left", side_set_at=1790000000, side_by=protocol.id_text(B))+ self.machine.settings.data["zones"] = [{"peer": "", "kind": "edge"}, {"peer": "", "kind": "corner", "corner": "top_left", "edge": "left"}]+ welcome = self.fold(name="Sea")+ self.assertEqual(welcome["id"], HERE)+ self.assertIsNone(self.migrated())+ self.assertEqual(self.machine.settings.data["zones"], [+ {"peer": protocol.id_text(C), "kind": "edge"},+ {"peer": protocol.id_text(C), "kind": "corner", "corner": "top_left", "edge": "left"},+ ])+ sea = self.machine.settings.peer(protocol.id_text(C))+ self.assertEqual((sea["side"], sea["side_set_at"], sea["side_by"]), ("left", 1790000000, protocol.id_text(B)))+ self.assertEqual(sea["token"], TOKENS[C])+ self.assertEqual(self.machine.notices, ["Sea linked from 127.0.0.1 under its Beamer 1.4 pairing, Old PC, which is now part of Sea."])+ self.assertEqual(self.machine.responder.links(), set())++ def test_a_folded_zone_of_a_kind_the_entry_has_is_dropped(self):+ self.machine.settings.data["zones"].append({"peer": "", "kind": "corner", "corner": "top_right", "edge": "right"})+ self.fold()+ self.assertEqual(self.machine.settings.data["zones"], [+ {"peer": protocol.id_text(C), "kind": "edge"},+ {"peer": protocol.id_text(C), "kind": "corner", "corner": "top_right", "edge": "right"},+ ])++ def test_a_side_taken_by_the_fold_turns_off_what_would_then_overlap(self):+ # Case A: the entry's own edge and thirds, both on while it had no side.+ self.migrated().update(side="left")+ self.machine.settings.data["zones"] = [+ {"peer": protocol.id_text(C), "kind": "edge"},+ {"peer": protocol.id_text(C), "kind": "part", "parts": ["start"]},+ ]+ self.fold()+ self.assertEqual(self.machine.settings.data["zones"], [+ {"peer": protocol.id_text(C), "kind": "edge"},+ {"peer": protocol.id_text(C), "kind": "part", "parts": ["start"], "off": True},+ ])++ def test_a_side_taken_by_the_fold_gives_way_to_another_peers_zone(self):+ # Case B: another peer's edge already on that side.+ self.machine.settings.data["peers"].append(entry(D, "Dee", side="right"))+ self.migrated().update(side="right")+ self.machine.settings.data["zones"] = [+ {"peer": protocol.id_text(C), "kind": "edge"},+ {"peer": protocol.id_text(D), "kind": "edge"},+ ]+ self.fold()+ self.assertEqual(self.machine.settings.data["zones"], [+ {"peer": protocol.id_text(C), "kind": "edge", "off": True},+ {"peer": protocol.id_text(D), "kind": "edge"},+ ])++ def test_no_fold_into_a_phone_or_a_machine_of_another_platform(self):+ for change in ({"port": 0, "host": ""}, {"platform": "windows"}):+ with self.subTest(change=change):+ self.machine.settings.data["peers"] = [+ entry("", "Old PC", token=token(50), from_1_4=True, linked=False, paired_at=0), entry(C, "Sea", **change)+ ]+ with self.assertRaises(protocol.HelloRefused) as refused:+ self.initiator(peer=C, key=token(50)).handshake()+ self.assertEqual(refused.exception.error, protocol.ERROR_WRONG_ID)+ self.assertEqual(self.migrated()["id"], "")++ def test_this_machines_own_id_under_the_migrated_token_is_still_wrong_id(self):+ with self.assertRaises(protocol.HelloRefused) as refused:+ self.initiator(peer=HERE, key=token(50)).handshake()+ self.assertEqual(refused.exception.error, protocol.ERROR_WRONG_ID)+ self.assertEqual(self.migrated()["id"], "")++ def test_two_links_racing_to_claim_it_one_wins(self):+ one, two = ident(130), ident(160)+ results = {}+ # Two addresses in the handshake at once: loopback has one, so the slots are keyed by+ # connection here, and the save is slow so the second reaches the claim while the first saves.+ self.machine.responder._slots = SlotPerConnection()+ save = self.machine.settings.save+ self.machine.book._save = lambda data: (time.sleep(0.1), save(data))+ first = self.initiator(peer=one, key=token(50))+ second = self.initiator(peer=two, key=token(50))+ barrier = threading.Barrier(2)++ def run(name, link):+ barrier.wait()+ try:+ link.handshake(link.hello(name=name))+ results[name] = "welcome"+ except protocol.HelloRefused as refused:+ results[name] = refused.error++ threads = [threading.Thread(target=run, args=("One", first)), threading.Thread(target=run, args=("Two", second))]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(5)+ self.assertEqual(sorted(results.values()), ["welcome", protocol.ERROR_WRONG_ID])+ winner = next(name for name, result in results.items() if result == "welcome")+ self.assertEqual(self.migrated()["id"], protocol.id_text(one if winner == "One" else two))+ self.assertEqual(self.machine.notices, [f"Linked with {winner} at 127.0.0.1 for the first time on Beamer 1.5.0."])+++ def test_the_claim_is_one_step_under_the_lock(self):+ book = self.machine.book+ save = self.machine.settings.save+ book._save = lambda data: (time.sleep(0.1), save(data))+ key_id = protocol.key_id(token(50))+ outcomes = []+ barrier = threading.Barrier(2)++ def claim(peer):+ barrier.wait()+ outcomes.append(book.admit(key_id, HERE, peer, {})[0])++ threads = [threading.Thread(target=claim, args=(peer,)) for peer in (ident(130), ident(160))]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(5)+ self.assertEqual(sorted(outcomes), [receiver.FIRST_LINK, receiver.WRONG_ID])+++class SlotPerConnection(receiver.HandshakeSlots):+ def take(self, host, connection):+ return super().take((host, id(connection)), connection)++ def free(self, host, connection):+ super().free((host, id(connection)), connection)+++class TheIdsInHello(Case):+ def test_this_machines_own_id_is_answered_wrong_id(self):+ with self.assertRaises(protocol.HelloRefused) as refused:+ self.initiator(peer=HERE, key=TOKENS[B]).handshake()+ self.assertEqual(refused.exception.error, protocol.ERROR_WRONG_ID)++ def test_another_id_than_the_entrys_is_answered_wrong_id(self):+ with self.assertRaises(protocol.HelloRefused) as refused:+ self.initiator(peer=D, key=TOKENS[B]).handshake()+ self.assertEqual(refused.exception.error, protocol.ERROR_WRONG_ID)+ self.assertEqual(self.machine.settings.peer(TOKENS[B])["id"], protocol.id_text(B))++ def test_the_answer_is_followed_by_a_close(self):+ link = self.initiator(peer=D, key=TOKENS[B])+ with self.assertRaises(protocol.HelloRefused):+ link.handshake()+ self.assertTrue(silent_close(link.sock))+++def _hello_text(**changes):+ data = {"version": 6, "id": protocol.id_text(B), "name": "Peer", "platform": "macos", "app": "1.5.0", "caps": [], "port": 24820}+ data.update(changes)+ return {"type": "hello", "data": data}+++class TheFirstFrame(Case):+ def refused_with_invalid_hello(self, raw):+ link = self.initiator()+ with self.assertRaises(protocol.HelloRefused) as refused:+ link.handshake(raw=raw)+ self.assertEqual(refused.exception.error, protocol.ERROR_INVALID_HELLO)+ self.assertTrue(silent_close(link.sock))++ def test_not_json_not_an_object_or_another_type(self):+ for raw in (b"not json", b"[1, 2]", b'"hello"', json.dumps({"type": "focus", "data": {"route": 1}}).encode()):+ with self.subTest(raw=raw):+ self.refused_with_invalid_hello(raw)++ def test_hellos_that_are_not_valid(self):+ bad = [+ {"version": 5},+ {"id": None},+ {"id": protocol.id_text(bytes(range(15)))},+ {"id": protocol.id_text(B)[:-1] + chr(ord(protocol.id_text(B)[-1]) + 1)},+ {"id": protocol.id_text(bytes(16))},+ {"name": ""},+ {"name": "x" * 49},+ {"port": 70000},+ {"caps": ["c"] * 17},+ {"platform": "MacOS"},+ ]+ for changes in bad:+ with self.subTest(changes=changes):+ message = _hello_text(**changes)+ if changes.get("id", "") is None:+ del message["data"]["id"]+ self.refused_with_invalid_hello(json.dumps(message).encode())++ def test_strict_json(self):+ good = json.dumps(_hello_text())+ texts = [+ good.replace('"port": 24820', '"port": 24820.0'),+ good.replace('"port": 24820', '"port": true'),+ good.replace('"caps": []', '"caps": [NaN]'),+ "" + good,+ json.dumps({"type": "hello"}),+ good.replace('"port": 24820', '"port": 24820, "port": 24820'),+ ]+ for text in texts:+ with self.subTest(text=text):+ self.refused_with_invalid_hello(text.encode("utf-8"))++ def test_a_length_out_of_bounds_is_refused_before_it_is_read(self):+ for length in (4097, 20, 0):+ with self.subTest(length=length):+ link = self.initiator()+ link.session.accept_preamble(protocol.recv_link_preamble(link.sock, time.monotonic() + 5))+ link.sock.sendall(struct.pack(">I", length))+ self.assertTrue(silent_close(link.sock))++ def test_a_first_frame_that_fails_its_tag_is_not_answered(self):+ link = self.initiator()+ link.session.accept_preamble(protocol.recv_link_preamble(link.sock, time.monotonic() + 5))+ frame = bytearray(link.session.seal(link.hello()))+ frame[-1] ^= 1+ link.sock.sendall(bytes(frame))+ self.assertTrue(silent_close(link.sock))+++class TheDeadlines(Case):+ def test_the_real_figures(self):+ self.assertEqual(receiver.PREAMBLE_SECONDS, 1.0)+ self.assertEqual(receiver.HANDSHAKE_SECONDS, 5.0)++ def closed_after(self, sock):+ started = time.monotonic()+ self.assertTrue(silent_close(sock, timeout=5))+ return time.monotonic() - started++ def test_61_bytes_then_nothing_is_dropped_at_the_preamble_deadline(self):+ with mock.patch.object(receiver, "PREAMBLE_SECONDS", 0.4):+ sock = self.raw()+ sock.sendall(raw_preamble(protocol.key_id(TOKENS[B]))[:61])+ self.assertLess(self.closed_after(sock), 0.9)++ def test_a_trickle_after_the_preamble_is_dropped_at_the_handshake_deadline(self):+ with mock.patch.object(receiver, "HANDSHAKE_SECONDS", 1.0):+ link = self.initiator()+ link.session.accept_preamble(protocol.recv_link_preamble(link.sock, time.monotonic() + 5))+ started = time.monotonic()+ frame = link.session.seal(link.hello())+ for byte in frame:+ readable, _, _ = select.select([link.sock], [], [], 0.1)+ if readable or time.monotonic() - started > 3:+ break+ try:+ link.sock.send(bytes([byte]))+ except OSError:+ break+ self.assertTrue(silent_close(link.sock))+ elapsed = time.monotonic() - started+ self.assertLess(elapsed, 2.0)+ self.assertGreater(elapsed, 0.8)+++class TheSlots(unittest.TestCase):+ def test_a_second_connection_from_an_address_replaces_the_first(self):+ slots = receiver.HandshakeSlots()+ self.assertIsNone(slots.take("192.168.77.2", "one"))+ self.assertEqual(slots.take("192.168.77.2", "two"), "one")+ self.assertEqual(len(slots), 1)++ def test_a_fifth_address_replaces_the_oldest(self):+ slots = receiver.HandshakeSlots()+ for n in range(4):+ self.assertIsNone(slots.take(f"192.168.77.{n}", n))+ self.assertEqual(slots.take("192.168.77.9", 9), 0)+ self.assertEqual(len(slots), 4)++ def test_freeing_is_only_for_the_connection_holding_the_slot(self):+ slots = receiver.HandshakeSlots()+ slots.take("192.168.77.2", "one")+ slots.take("192.168.77.2", "two")+ slots.free("192.168.77.2", "one")+ self.assertEqual(len(slots), 1)+ slots.free("192.168.77.2", "two")+ self.assertEqual(len(slots), 0)+++class TheSlotsLive(Case):+ def test_a_second_connection_from_the_same_address_closes_the_first(self):+ first = self.raw()+ first.sendall(raw_preamble(protocol.key_id(TOKENS[B]))[:10])+ self.assertTrue(wait_for(lambda: len(self.machine.responder._slots) == 1))+ second = self.raw()+ self.assertTrue(silent_close(first))+ second.close()++ def test_an_authenticated_link_never_counts(self):+ link = self.initiator()+ link.handshake()+ for _ in range(6):+ self.raw().sendall(b"BE")+ self.assertIsNotNone(link.expect(protocol.MSG_ACK, timeout=1.0))+ self.assertFalse(link.closed.is_set())+ self.assertEqual(self.machine.responder.links(), {B})+++class TwoOfOneName(Case):+ peers = [entry(B, "Studio"), entry(C, "Studio")]++ def test_the_status_tells_two_machines_of_one_name_apart(self):+ first = self.initiator(B)+ first.handshake(first.hello(name="Studio"))+ second = self.initiator(C)+ second.handshake(second.hello(name="Studio"))+ self.assertTrue(wait_for(lambda: self.machine.responder.links() == {B, C}))+ expected = "Connected to " + ", ".join(sorted(f"Studio ({protocol.id_text(peer)[-4:]})" for peer in (B, C)))+ self.assertTrue(wait_for(lambda: any(detail == expected for _, detail in self.machine.statuses)), self.machine.statuses)+++class OlderPeers(Case):+ def test_a_version_5_initiator_gets_the_short_reply_and_is_named(self):+ self.machine.settings.peer(TOKENS[B])["host"] = "127.0.0.1"+ sock = self.raw()+ session = v5_link.SecureSession("old-token")+ sock.sendall(session.preamble())+ with self.assertRaises(protocol.VersionMismatch) as mismatch:+ v5_link.recv_preamble(sock, session, deadline=time.monotonic() + 3)+ self.assertEqual(mismatch.exception.peer_version, 6)+ self.assertTrue(wait_for(lambda: any("Bee" in detail for _, detail in self.machine.statuses)))++ def test_the_reply_survives_bytes_the_peer_sent_after_its_preamble(self):+ sock = self.raw()+ sock.sendall(v5_link.SecureSession("old-token").preamble() + os.urandom(3000))+ time.sleep(0.2)+ reply = protocol._recv_exact(sock, protocol.SHORT_REPLY_SIZE, time.monotonic() + 3)+ self.assertEqual(reply[:6], b"BEAMY\x06")++ def test_a_beamer_from_before_version_4_gets_the_legacy_welcome(self):+ sock = self.raw()+ sock.sendall(protocol.legacy_frame({"type": "hello", "data": {"version": 3}}))+ (length,) = struct.unpack(">I", protocol._recv_exact(sock, 4, time.monotonic() + 3))+ body = json.loads(protocol._recv_exact(sock, length, time.monotonic() + 3))+ self.assertEqual(body, {"type": "welcome", "data": {"version": 6, "error": "version_mismatch"}})++ def test_a_newer_version_gets_the_short_reply(self):+ sock = self.raw()+ sock.sendall(b"BEAMY\x07" + os.urandom(56))+ reply = protocol._recv_exact(sock, protocol.SHORT_REPLY_SIZE, time.monotonic() + 3)+ self.assertEqual(reply[:6], b"BEAMY\x06")+ self.assertTrue(silent_close(sock))++ def test_the_drain_does_not_hold_a_slot(self):+ sock = self.raw()+ sock.sendall(v5_link.SecureSession("old-token").preamble())+ protocol._recv_exact(sock, protocol.SHORT_REPLY_SIZE, time.monotonic() + 3)+ self.assertEqual(len(self.machine.responder._slots), 0)++ def test_past_the_drain_cap_the_reply_still_survives_what_was_already_sent(self):+ # Gemini's review: with every drain busy the socket was closed over unread bytes, and the+ # reset threw the reply away.+ with mock.patch.object(receiver, "MAX_DRAINS", 0):+ sock = self.raw()+ sock.sendall(v5_link.SecureSession("old-token").preamble() + os.urandom(3000))+ time.sleep(0.2)+ reply = protocol._recv_exact(sock, protocol.SHORT_REPLY_SIZE, time.monotonic() + 3)+ self.assertEqual(reply[:6], b"BEAMY\x06")+++class TheThreadCap(Case):+ def test_connections_past_the_cap_are_closed_without_a_thread_or_a_slot(self):+ # Gemini's review: every accepted connection had a thread, however fast they came.+ with mock.patch.object(receiver, "MAX_HANDSHAKE_THREADS", 1):+ first = self.raw()+ first.sendall(b"BEA")+ self.assertTrue(wait_for(lambda: len(self.machine.responder._slots) == 1))+ second = self.raw()+ self.assertTrue(silent_close(second))+ first.sendall(b"MY\x07" + os.urandom(56))+ self.assertEqual(protocol._recv_exact(first, protocol.SHORT_REPLY_SIZE, time.monotonic() + 3)[:6], b"BEAMY\x06")+++class ASecondLinkFromOnePeer(Case):+ def test_it_replaces_the_first_and_releases_the_owners_keys_before_serving(self):+ first = self.initiator()+ first.handshake()+ other = self.initiator(peer=C)+ other.handshake()+ route = first.take()+ self.assertEqual(first.answer(route)[0], protocol.MSG_ACCEPT)+ first.key("keydown", "shift")+ self.assertTrue(wait_for(lambda: ("key", "shift", True) in self.machine.injected()))+ second = self.initiator()+ second.handshake()+ self.assertTrue(first.closed.wait(2))+ route = second.take(route=1)+ self.assertEqual(second.answer(route)[0], protocol.MSG_ACCEPT)+ second.key("keydown", "a")+ self.assertTrue(wait_for(lambda: ("key", "a", True) in self.machine.injected()))+ calls = self.machine.injected()+ self.assertLess(calls.index(("key", "shift", False)), calls.index(("key", "a", True)))+ self.assertFalse(other.closed.is_set())+ self.assertEqual(self.machine.responder.links(), {B, C})+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_responder_input.py b/core/tests/test_responder_input.pynew file mode 100644index 0000000..2a2b47c--- /dev/null+++ b/core/tests/test_responder_input.py@@ -0,0 +1,211 @@+"""What the responder does with its owner's input: `ack` and `held_us` (WIRE.md section 9),+`text` (section 10), liveness, and the lock screen, over real sockets on loopback against+LinkResponder."""++import threading+import time+import unittest+from unittest import mock++from core import protocol, receiver+from core.tests.responder_harness import B, C, TOKENS, Initiator, Machine, entry, wait_for+++class Case(unittest.TestCase):+ caps = None++ def setUp(self):+ kwargs = {} if self.caps is None else {"caps": self.caps}+ self.machine = Machine([entry(B, "Bee"), entry(C, "Sea")], **kwargs).start()+ self.addCleanup(self.machine.stop)++ def owner(self, peer=B):+ link = Initiator(self.machine, peer)+ self.addCleanup(link.close)+ link.handshake()+ route = link.take()+ self.assertEqual(link.answer(route)[0], protocol.MSG_ACCEPT)+ return link+++class Acks(Case):+ def test_held_us_is_in_every_ack_and_zero_before_any_input(self):+ link = Initiator(self.machine, B)+ self.addCleanup(link.close)+ link.handshake()+ first = link.expect(protocol.MSG_ACK, timeout=1.0)+ self.assertEqual(first, {"seq": 0, "held_us": 0})++ def test_a_heartbeat_that_repeats_a_seq_carries_held_us_zero(self):+ link = self.owner()+ seq = link.key("keydown", "a")+ self.assertIsNotNone(link.acked(seq))+ repeat = link.expect(protocol.MSG_ACK, timeout=1.0)+ self.assertEqual(repeat, {"seq": seq, "held_us": 0})++ def test_a_lone_event_is_acknowledged_at_once(self):+ # The responder's own measure of how long it held the ack says "at once": a coalesced ack+ # holds it ACK_COALESCE_SECONDS. A wall-clock bound on the round trip failed under a build.+ link = self.owner()+ link.expect(protocol.MSG_ACK, timeout=1.0)+ time.sleep(0.05)+ sent = time.monotonic()+ seq = link.key("keydown", "a")+ ack = link.acked(seq)+ self.assertLess(time.monotonic() - sent, 0.5)+ self.assertLess(ack["held_us"], receiver.ACK_COALESCE_SECONDS * 1_000_000)++ def test_a_burst_is_one_ack_at_the_end_of_15_ms(self):+ link = self.owner()+ link.expect(protocol.MSG_ACK, timeout=1.0)+ time.sleep(0.05)+ first = link.key("keydown", "a")+ self.assertIsNotNone(link.acked(first))+ acked_at = time.monotonic()+ for name in "bcd":+ last = link.key("keydown", name)+ last_sent = time.monotonic()+ ack = link.acked(last)+ arrived = time.monotonic()+ self.assertGreater(arrived - acked_at, 0.010)+ # Held for its highest seq, never longer than it was in flight (Windows' timer oversleeps 15 ms).+ self.assertLess(ack["held_us"], (arrived - last_sent) * 1_000_000 + 2000)+ self.assertGreater(ack["held_us"], 5000)+ between = [m["data"]["seq"] for m in link.seen if m["type"] == protocol.MSG_ACK and first < m["data"]["seq"] < last]+ self.assertEqual(between, [])++ def test_the_ack_timing_rule(self):+ # Timed from the last ack: at once when 15 ms have passed, else 15 ms after it; a heartbeat 0.4 s after.+ self.assertEqual(receiver.ack_due(last_ack_at=10.0, pending_since=10.020), 10.020)+ self.assertEqual(receiver.ack_due(last_ack_at=10.0, pending_since=10.005), 10.015)+ self.assertEqual(receiver.ack_due(last_ack_at=10.0, pending_since=None), 10.4)+++class Liveness(Case):+ def test_a_large_frame_arriving_slowly_keeps_the_link(self):+ with mock.patch.object(receiver, "LINK_READ_TIMEOUT_SECONDS", 0.5):+ link = self.owner()+ frame = link.session.seal(protocol.clipboard_msg("x" * 200000))+ chunk = len(frame) // 8 + 1+ for start in range(0, len(frame), chunk):+ with link.session.send_lock:+ link.sock.sendall(frame[start:start + chunk])+ time.sleep(0.2)+ self.assertTrue(wait_for(lambda: self.machine.clipboard.set_calls))+ self.assertFalse(link.closed.is_set())++ def test_silence_ends_the_link(self):+ with mock.patch.object(receiver, "LINK_READ_TIMEOUT_SECONDS", 0.3):+ link = self.owner()+ self.assertTrue(link.closed.wait(2))+++class Text(Case):+ def test_text_is_typed_as_characters_with_return_and_tab(self):+ link = self.owner()+ link.input(protocol.text_msg("é😀\na\tb\x01c\x85d\x7f"))+ expected = [("text", "é😀"), ("key", "enter", True), ("key", "enter", False), ("text", "a"),+ ("key", "tab", True), ("key", "tab", False), ("text", "bcd")]+ self.assertTrue(wait_for(lambda: self.machine.injected() == expected), self.machine.injected())++ def test_text_over_4096_bytes_is_dropped_and_acknowledged(self):+ link = self.owner()+ seq = link.input(protocol.text_msg("é" * 2049))+ self.assertIsNotNone(link.acked(seq))+ self.assertEqual(self.machine.injected(), [])++ def test_the_pure_split(self):+ self.assertEqual(receiver.text_runs("a\r\nb\x00\x9f\x80"), ["a", "\n", "b"])+ self.assertEqual(receiver.text_runs("\t\t"), ["\t", "\t"])+ self.assertEqual(receiver.text_runs(""), [])+++class WithoutCapabilities(Case):+ caps = ["clipboard"]++ def test_text_and_gestures_are_dropped_and_acknowledged(self):+ link = self.owner()+ link.input(protocol.text_msg("hello"))+ seq = link.input(protocol.gesture_msg("pinch"))+ self.assertIsNotNone(link.acked(seq))+ self.assertEqual(self.machine.injected(), [])++ def test_an_image_is_dropped_and_the_text_kept(self):+ link = self.owner()+ link.send(protocol.clipboard_msg("words", protocol.PNG_SIGNATURE + b"\x00" * 16))+ self.assertTrue(wait_for(lambda: self.machine.clipboard.set_calls == [("words", None)]))+++class Injecting(Case):+ def test_each_kind_reaches_the_injector(self):+ link = self.owner()+ link.key("keydown", "a")+ link.key("keyup", "a")+ link.move(3, -4)+ link.input({"type": "mousedown", "data": {"button": "right"}})+ link.input({"type": "mouseup", "data": {"button": "right"}})+ link.input(protocol.scroll_msg(2.5, -1, "pixel"))+ seq = link.input(protocol.gesture_msg("swipe_left"))+ self.assertIsNotNone(link.acked(seq))+ self.assertEqual(self.machine.injected(), [+ ("key", "a", True), ("key", "a", False), ("move", 3, -4), ("button", "right", True),+ ("button", "right", False), ("scroll", 2.5, -1, "pixel"), ("gesture", "swipe_left"),+ ])++ def test_a_malformed_input_is_ignored_and_the_link_stays(self):+ link = self.owner()+ link.input({"type": "mousemove", "data": {"dx": 1.5, "dy": 0}})+ seq = link.key("keydown", "b")+ self.assertIsNotNone(link.acked(seq))+ self.assertEqual(self.machine.injected(), [("key", "b", True)])++ def test_the_input_scale_applies(self):+ self.machine.responder.input_scale = receiver.InputScale(pointer=2.0)+ link = self.owner()+ seq = link.move(3, 1)+ self.assertIsNotNone(link.acked(seq))+ self.assertEqual(self.machine.injected(), [("move", 6, 2)])+++class LockScreen(Case):+ class Unlock:+ def __init__(self, locked=True, unlocks=True, takes=0.6):+ self.locked, self.unlocks, self.takes = locked, unlocks, takes++ def is_locked(self):+ return self.locked++ def ensure_unlocked(self):+ time.sleep(self.takes)+ if self.unlocks:+ self.locked = False+ return self.unlocks++ def test_a_locked_machine_answers_at_once_and_drops_input_while_it_unlocks(self):+ self.machine.responder._unlock = self.Unlock()+ link = Initiator(self.machine, B)+ self.addCleanup(link.close)+ link.handshake()+ started = time.monotonic()+ route = link.take()+ self.assertEqual(link.answer(route)[0], protocol.MSG_ACCEPT)+ self.assertLess(time.monotonic() - started, 0.3)+ seq = link.key("keydown", "a")+ ack = link.acked(seq)+ self.assertEqual(ack.get("locked"), True)+ self.assertEqual(self.machine.injected(), [])+ time.sleep(0.7)+ seq = link.key("keydown", "b")+ self.assertIsNotNone(link.acked(seq))+ self.assertTrue(wait_for(lambda: self.machine.injected() == [("key", "b", True)]))++ def test_a_machine_that_stays_locked_sends_its_owner_home(self):+ self.machine.responder._unlock = self.Unlock(unlocks=False, takes=0.0)+ link = self.owner()+ switch = link.expect(protocol.MSG_SWITCH, timeout=3.0)+ self.assertEqual(switch["next"], protocol.id_text(B))+ self.assertNotIn("edge", switch)+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_responder_ownership.py b/core/tests/test_responder_ownership.pynew file mode 100644index 0000000..4e7b20a--- /dev/null+++ b/core/tests/test_responder_ownership.py@@ -0,0 +1,530 @@+"""Input ownership and the responder's half of routing (WIRE.md sections 4 and+5), over real sockets on loopback against+LinkResponder, with scripted owners."""++import time+import unittest+from unittest import mock++from core import protocol, receiver+from core.return_edge import CornerPush, PartEdge, ReturnEdge, SpanEdge+from core.tests.responder_harness import B, C, D, HERE, TOKENS, Initiator, Machine, entry, wait_for++ACCEPT, REFUSE = protocol.MSG_ACCEPT, protocol.MSG_REFUSE+++def ids(*peers):+ return [protocol.id_text(peer) for peer in peers]+++class Case(unittest.TestCase):+ zones = ()+ sides = {}++ def setUp(self):+ peers = [entry(peer, name, side=self.sides.get(peer, "")) for peer, name in ((B, "Bee"), (C, "Sea"), (D, "Dee"))]+ self.machine = Machine(peers, self.zones).start()+ self.addCleanup(self.machine.stop)++ def link(self, peer=B, **hello):+ link = Initiator(self.machine, peer)+ self.addCleanup(link.close)+ link.handshake(link.hello(**hello) if hello else None)+ self.assertTrue(wait_for(lambda: peer in self.machine.responder.links()))+ return link++ def own(self, link, **fields):+ route = link.take(**fields)+ self.assertEqual(link.answer(route), (ACCEPT, {"route": route}))+ self.assertTrue(wait_for(lambda: self.machine.responder.owner == link.peer))+ return route++ def refused(self, link, why, **fields):+ route = link.take(**fields)+ self.assertEqual(link.answer(route), (REFUSE, {"route": route, "why": why}))++ def injected_from(self, count=None):+ return self.machine.injected()++ def peer_entry(self, peer):+ return self.machine.settings.peer(TOKENS[peer])+++class Taking(Case):+ def test_two_peers_compete_and_the_second_gets_in_after_the_first_lets_go(self):+ b, c = self.link(B), self.link(C)+ self.own(b)+ self.refused(c, "owned")+ b.let_go()+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ self.own(c)+ self.assertEqual(self.machine.owners, [B, None, C])++ def test_a_route_not_higher_than_the_last_accepted_gets_no_answer(self):+ b = self.link(B)+ self.own(b, route=5)+ for route in (5, 4):+ b.take(route=route)+ self.assertIsNone(b.answer(route, timeout=0.3))++ def test_the_decision_order(self):+ b, c = self.link(B), self.link(C)+ self.peer_entry(C)["allow_drive"] = False+ self.machine.responder.peers_changed()+ self.machine.away = True+ # Malformed before everything.+ self.refused(c, "malformed", resistance_px=5000)+ # Then not allowed before busy.+ self.refused(c, "not_allowed")+ self.peer_entry(C)["allow_drive"] = True+ self.machine.responder.peers_changed()+ self.refused(c, "busy")+ self.machine.away = False+ with mock.patch.object(receiver, "SENT_HOME_SECONDS", 0.6):+ self.own(b)+ self.assertTrue(self.machine.responder.send_home())+ b.let_go()+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ self.own(c)+ # Sent home before owned.+ self.refused(b, "sent_home")+ time.sleep(0.7)+ self.refused(b, "owned")++ def test_a_stay_from_a_machine_that_is_not_the_owner_is_never_accepted(self):+ b, c = self.link(B), self.link(C)+ self.refused(c, "malformed", stay=True, resistance_px=120, reach=[])+ self.own(b)+ route = c.take(stay=True, resistance_px=120, reach=[])+ self.assertEqual(c.answer(route)[0], REFUSE)+ self.assertEqual(self.machine.responder.owner, B)++ def test_a_driven_desktop_is_busy(self):+ self.machine.away = True+ self.refused(self.link(B), "busy")+ self.assertIsNone(self.machine.responder.owner)++ def test_the_answer_comes_before_the_pointer_is_placed(self):+ self.machine.desktop.slow = 1.0+ b = self.link(B)+ started = time.monotonic()+ route = b.take(edge="left", offset=0.5, resistance_px=120, reach=[])+ self.assertEqual(b.answer(route)[0], ACCEPT)+ self.assertLess(time.monotonic() - started, 0.5)+ self.assertTrue(wait_for(lambda: self.machine.desktop.placed == [(0, 540)]))+ self.assertEqual(self.machine.arrivals, [("left", 0, 540)])++ def test_a_take_by_the_shortcut_lands_nothing_and_says_where_the_pointer_is(self):+ self.own(self.link(B))+ self.assertTrue(wait_for(lambda: self.machine.arrivals == [(None, 960, 540)]))+ self.assertEqual(self.machine.desktop.placed, [])++ def test_the_owners_own_take_moves_the_pointer_in_place(self):+ b = self.link(B)+ self.own(b)+ self.own(b, edge="top", offset=0.25)+ self.assertTrue(wait_for(lambda: self.machine.desktop.placed == [(480, 0)]))+ self.assertEqual(self.machine.owners, [B])++ def test_a_focus_whose_route_or_target_is_malformed_is_ignored(self):+ b = self.link(B)+ b.send({"type": "focus", "data": {"route": 1.0, "target": protocol.id_text(HERE)}})+ b.send({"type": "focus", "data": {"route": 2, "target": "nope"}})+ self.assertIsNone(b.expect(ACCEPT, timeout=0.3))+ self.assertIsNone(b.expect(REFUSE, timeout=0.1))++ def test_strict_json_on_a_later_focus_is_malformed(self):+ b = self.link(B)+ text = '{"type":"focus","data":{"route":1,"target":"%s","resistance_px":%s}}'+ for value in ("120.0", "true", "NaN"):+ with self.subTest(value=value):+ route = b.route + 1+ b.route = route+ raw = (text % (protocol.id_text(HERE), value)).replace('"route":1', '"route":%d' % route).encode()+ with b.session.send_lock:+ b.sock.sendall(b.session.seal_raw(raw))+ self.assertEqual(b.answer(route), (REFUSE, {"route": route, "why": "malformed"}))+++class NonOwners(Case):+ def test_a_non_owners_input_is_dropped_and_acknowledged(self):+ b, c = self.link(B), self.link(C)+ self.own(b)+ seq = c.key("keydown", "x")+ self.assertIsNotNone(c.acked(seq))+ self.assertEqual(self.machine.injected(), [])++ def test_a_non_owners_clipboard_is_dropped_and_the_owners_is_set(self):+ b, c = self.link(B), self.link(C)+ self.own(b)+ c.send(protocol.clipboard_msg("from c"))+ b.send(protocol.clipboard_msg("from b"))+ self.assertTrue(wait_for(lambda: self.machine.clipboard.set_calls == [("from b", None)]))+ time.sleep(0.1)+ self.assertEqual(self.machine.clipboard.set_calls, [("from b", None)])++ def send_big(self, link, filler, size=protocol.SMALL_MESSAGE_BYTES + 1000):+ """A frame whose plaintext is `size` bytes, sealed for real so its counter advances."""+ body = ('{"type":"%s","data":{},"z":"' % filler).encode() + b"a" * size + b'"}'+ with link.session.send_lock:+ frame = link.session.seal_raw(body)+ link.sock.sendall(frame)++ def test_a_non_owners_large_frame_is_authenticated_and_dropped_without_being_parsed(self):+ b, c = self.link(B), self.link(C)+ self.own(b)+ parsed = []+ real = protocol.parse_message++ def watching(plain):+ parsed.append(len(plain))+ return real(plain)++ with mock.patch.object(protocol, "parse_message", watching):+ self.send_big(c, "x")+ self.send_big(c, "clipboard")+ c.send(protocol.paired_msg([D]))+ self.assertTrue(wait_for(lambda: self.machine.paired == [(C, [D])]), "the link did not survive")+ self.assertTrue(all(size < protocol.SMALL_MESSAGE_BYTES for size in parsed), parsed)++ def test_a_take_refused_as_owned_then_a_clipboard_does_not_end_the_link(self):+ b, c = self.link(B), self.link(C)+ self.own(b)+ self.refused(c, "owned")+ c.send(protocol.clipboard_msg("c" * 200_000))+ seq = c.key("keydown", "x")+ self.assertIsNotNone(c.acked(seq))+ self.assertEqual(self.machine.clipboard.set_calls, [])++ def test_the_owners_large_clipboard_still_arrives(self):+ b = self.link(B)+ self.own(b)+ text = "b" * 200_000+ b.send(protocol.clipboard_msg(text))+ self.assertTrue(wait_for(lambda: self.machine.clipboard.set_calls == [(text, None)]))++ def test_a_non_owners_arrangement_settings_and_paired_are_handled(self):+ self.own(self.link(B))+ c = self.link(C)+ c.send(protocol.arrangement_v6("left", 1790000000, C))+ c.send(protocol.settings_msg({"on": True, "set_at": 1790000000, "by": protocol.id_text(C)}))+ c.send(protocol.paired_msg([D]))+ self.assertTrue(wait_for(lambda: self.machine.paired == [(C, [D])]))+ self.assertEqual(self.machine.arrangements, [(C, {"edge": "left", "set_at": 1790000000, "by": C})])+ self.assertEqual([peer for peer, _ in self.machine.settings_seen], [C])++ def test_settings_from_a_peer_without_the_capability_are_ignored(self):+ d = self.link(D, caps=["clipboard"])+ d.send(protocol.settings_msg({"on": False, "set_at": 1790000000, "by": protocol.id_text(D)}))+ d.send(protocol.paired_msg([B]))+ self.assertTrue(wait_for(lambda: self.machine.paired == [(D, [B])]))+ self.assertEqual(self.machine.settings_seen, [])++ def test_a_non_owners_let_go_is_ignored(self):+ b, c = self.link(B), self.link(C)+ self.own(b)+ c.let_go(target=D)+ time.sleep(0.1)+ self.assertEqual(self.machine.responder.owner, B)+ b.key("keydown", "q")+ self.assertTrue(wait_for(lambda: ("key", "q", True) in self.machine.injected()))++ def test_not_allowed_keeps_the_link_for_arrangement(self):+ self.peer_entry(B)["allow_drive"] = False+ b = self.link(B)+ self.refused(b, "not_allowed")+ b.send(protocol.arrangement_v6("top", 1790000001, B))+ self.assertTrue(wait_for(lambda: len(self.machine.arrangements) == 1))+ self.assertFalse(b.closed.is_set())+++class Ending(Case):+ def hold(self, link):+ link.key("keydown", "shift")+ link.input({"type": "mousedown", "data": {"button": "left"}})+ self.assertTrue(wait_for(lambda: ("button", "left", True) in self.machine.injected()))++ def released(self):+ calls = self.machine.injected()+ return ("key", "shift", False) in calls and ("button", "left", False) in calls++ def test_a_let_go_releases_what_the_owner_held(self):+ b = self.link(B)+ self.own(b)+ self.hold(b)+ b.let_go(target=C)+ self.assertTrue(wait_for(self.released))+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ self.assertEqual(self.machine.owners, [B, None])++ def test_the_link_closing_releases(self):+ b = self.link(B)+ self.own(b)+ self.hold(b)+ b.close()+ self.assertTrue(wait_for(self.released))+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None and B not in self.machine.responder.links()))++ def test_the_link_timing_out_releases(self):+ with mock.patch.object(receiver, "LINK_READ_TIMEOUT_SECONDS", 0.4):+ b = self.link(B)+ self.own(b)+ self.hold(b)+ self.assertTrue(wait_for(self.released, timeout=2))+ self.assertTrue(b.closed.wait(2))++ def test_removing_the_owner_releases_and_closes_its_links(self):+ b, c = self.link(B), self.link(C)+ self.own(b)+ self.hold(b)+ self.machine.settings.data["peers"] = [p for p in self.machine.settings.data["peers"] if p["token"] != TOKENS[B]]+ self.machine.responder.peers_changed()+ self.assertTrue(wait_for(self.released))+ self.assertTrue(b.closed.wait(2))+ self.assertIsNone(self.machine.responder.owner)+ self.assertFalse(c.closed.is_set())++ def test_turning_allow_drive_off_and_on(self):+ b = self.link(B)+ route = self.own(b)+ self.hold(b)+ self.peer_entry(B)["allow_drive"] = False+ self.machine.responder.peers_changed()+ self.assertEqual(b.expect(REFUSE), {"route": route, "why": "not_allowed"})+ self.assertEqual(b.expect(protocol.MSG_ACCEPTS), {"accepts": False})+ self.assertTrue(self.released())+ before = len(self.machine.injected())+ seq = b.key("keydown", "z")+ self.assertIsNotNone(b.acked(seq))+ self.assertEqual(len(self.machine.injected()), before)+ self.peer_entry(B)["allow_drive"] = True+ self.machine.responder.peers_changed()+ self.assertEqual(b.expect(protocol.MSG_ACCEPTS), {"accepts": True})+ self.own(b)++ def test_the_forced_end_after_a_send_home(self):+ with mock.patch.object(receiver, "FORCED_END_SECONDS", 0.3), mock.patch.object(receiver, "SENT_HOME_SECONDS", 1.0):+ b = self.link(B)+ route = self.own(b)+ self.hold(b)+ self.assertTrue(self.machine.responder.send_home())+ self.assertEqual(b.expect(protocol.MSG_SWITCH), {"route": route, "next": protocol.id_text(B)})+ self.assertEqual(b.expect(REFUSE, timeout=1.0), {"route": route, "why": "sent_home"})+ self.assertTrue(self.released())+ self.assertIsNone(self.machine.responder.owner)+ before = len(self.machine.injected())+ seq = b.key("keydown", "z")+ self.assertIsNotNone(b.acked(seq))+ self.assertEqual(len(self.machine.injected()), before)+ self.refused(b, "sent_home")+ time.sleep(1.0)+ self.own(b)++ def test_an_owner_that_obeys_a_send_home_is_refused_for_a_while_too(self):+ with mock.patch.object(receiver, "SENT_HOME_SECONDS", 0.5):+ b = self.link(B)+ self.own(b)+ self.machine.responder.send_home()+ b.expect(protocol.MSG_SWITCH)+ b.let_go()+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ self.refused(b, "sent_home")+ time.sleep(0.6)+ self.own(b)++ def test_nothing_to_send_home(self):+ self.assertFalse(self.machine.responder.send_home())++ def test_each_link_keeps_its_own_seq(self):+ b, c = self.link(B), self.link(C)+ self.own(b)+ for name in "abc":+ b.key("keydown", name)+ self.assertIsNotNone(b.acked(3))+ b.let_go()+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ self.own(c)+ c.key("keydown", "d")+ self.assertIsNotNone(c.acked(1))+ time.sleep(0.5)+ c.expect("nothing", timeout=0.1)+ self.assertEqual(max(m["data"]["seq"] for m in c.seen if m["type"] == protocol.MSG_ACK), 1)+++class TheClipboardOnLettingGo(Case):+ def test_an_unchanged_clipboard_is_not_sent(self):+ self.machine.clipboard.copy("copied before anyone drove")+ b = self.link(B)+ self.own(b)+ b.let_go(target=C)+ self.assertIsNone(b.expect(protocol.MSG_CLIPBOARD, timeout=0.4))++ def test_a_change_made_here_is_sent(self):+ b = self.link(B)+ self.own(b)+ self.machine.clipboard.copy("copied here")+ b.let_go(target=C)+ self.assertEqual(b.expect(protocol.MSG_CLIPBOARD), {"text": "copied here"})++ def test_what_the_owner_brought_is_not_echoed(self):+ b = self.link(B)+ self.own(b)+ b.send(protocol.clipboard_msg("brought"))+ self.assertTrue(wait_for(lambda: self.machine.clipboard.set_calls))+ b.let_go(target=C)+ self.assertIsNone(b.expect(protocol.MSG_CLIPBOARD, timeout=0.4))++ def test_nothing_is_sent_when_ownership_ends_any_other_way(self):+ with mock.patch.object(receiver, "FORCED_END_SECONDS", 0.2):+ b = self.link(B)+ self.own(b)+ self.machine.clipboard.copy("copied here")+ self.machine.responder.send_home()+ self.assertIsNotNone(b.expect(REFUSE))+ self.assertIsNone(b.expect(protocol.MSG_CLIPBOARD, timeout=0.3))+++class Zones(Case):+ sides = {B: "left", C: "right", D: "top"}+ zones = [{"peer": protocol.id_text(B), "kind": "edge"},+ {"peer": protocol.id_text(C), "kind": "edge"},+ {"peer": protocol.id_text(D), "kind": "edge"}]++ def push(self, link, cursor, dx, dy):+ self.machine.desktop.cursor = cursor+ seq = link.move(dx, dy)+ self.assertIsNotNone(link.acked(seq))++ def test_reach_limits_the_zones_armed(self):+ b = self.link(B)+ route = self.own(b, resistance_px=120, reach=[C])+ self.push(b, (960, 0), 0, -200)+ self.assertIn(("move", 0, -200), self.machine.injected())+ self.push(b, (1919, 500), 200, 0)+ switch = b.expect(protocol.MSG_SWITCH)+ self.assertEqual((switch["route"], switch["next"], switch["edge"]), (route, protocol.id_text(C), "left"))+ self.assertAlmostEqual(switch["offset"], 500 / 1080, places=2)++ def test_a_take_without_reach_arms_only_the_way_home(self):+ b = self.link(B)+ self.own(b)+ self.push(b, (1919, 500), 200, 0)+ self.assertIn(("move", 200, 0), self.machine.injected())+ self.push(b, (0, 500), -200, 0)+ self.assertEqual(b.expect(protocol.MSG_SWITCH)["next"], protocol.id_text(B))++ def test_the_owners_resistance_is_used(self):+ b = self.link(B)+ self.own(b, resistance_px=500, reach=[])+ self.push(b, (0, 500), -200, 0)+ self.assertIsNone(b.expect(protocol.MSG_SWITCH, timeout=0.2))+ self.assertEqual(self.machine.desktop.placed[-1], (0, 500))+ self.assertNotIn(("move", -200, 0), self.machine.injected())++ def test_resistance_out_of_range_is_malformed(self):+ self.refused(self.link(B), "malformed", resistance_px=1001)++ def test_after_a_switch_the_zones_are_disarmed_until_a_stay(self):+ b = self.link(B)+ self.own(b, reach=[C])+ self.push(b, (1919, 500), 200, 0)+ self.assertIsNotNone(b.expect(protocol.MSG_SWITCH))+ self.push(b, (1919, 500), 200, 0)+ self.assertIsNone(b.expect(protocol.MSG_SWITCH, timeout=0.2))+ self.assertIn(("move", 200, 0), self.machine.injected())+ self.own(b, stay=True, resistance_px=120, reach=[C])+ self.push(b, (1919, 500), 200, 0)+ self.assertIsNotNone(b.expect(protocol.MSG_SWITCH))+ self.assertEqual(self.machine.arrivals, [(None, 960, 540)])++ def test_held_edges_do_not_cross(self):+ b = self.link(B)+ self.own(b, reach=[C])+ self.machine.responder.edges_held = lambda: True+ self.push(b, (1919, 500), 200, 0)+ self.assertIsNone(b.expect(protocol.MSG_SWITCH, timeout=0.2))++ def test_the_send_home_names_no_position(self):+ b = self.link(B)+ route = self.own(b, reach=[C])+ self.machine.responder.send_home()+ self.assertEqual(b.expect(protocol.MSG_SWITCH), {"route": route, "next": protocol.id_text(B)})+ # Its zones are disarmed with it.+ self.push(b, (1919, 500), 200, 0)+ self.assertIsNone(b.expect(protocol.MSG_SWITCH, timeout=0.2))++ def test_a_zone_change_rearms_while_driven(self):+ b = self.link(B)+ self.own(b, reach=[C])+ self.machine.settings.data["zones"][1]["off"] = True+ self.machine.responder.rearm()+ self.push(b, (1919, 500), 200, 0)+ self.assertIsNone(b.expect(protocol.MSG_SWITCH, timeout=0.2))+++class ZoneModels(unittest.TestCase):+ peers = [entry(B, "Bee", side="left"), entry(C, "Sea", side="top"), entry(D, "Dee", side="")]++ def models(self, zones, allowed=(B, C, D), resistance=150, notch=None):+ return receiver.zone_models(zones, self.peers, set(allowed), resistance, notch)++ def test_each_kind(self):+ zones = [+ {"peer": protocol.id_text(B), "kind": "edge"},+ {"peer": protocol.id_text(C), "kind": "part", "parts": ["start", "end"]},+ {"peer": protocol.id_text(B), "kind": "corner", "corner": "top_right", "edge": "right"},+ {"peer": protocol.id_text(C), "kind": "notch"},+ ]+ found = self.models(zones, notch=lambda: (100, 200))+ kinds = [(peer, type(model)) for peer, model in found]+ # Corners first, then edges, then parts, then the notch.+ self.assertEqual(kinds, [(B, CornerPush), (B, ReturnEdge), (C, PartEdge), (C, SpanEdge)])+ self.assertEqual([model.edge for _, model in found], ["right", "left", "top", "top"])+ self.assertEqual({model.resistance_px for _, model in found}, {150})+ self.assertEqual(found[2][1].parts, frozenset({"start", "end"}))++ def test_what_is_left_out(self):+ zones = [+ {"peer": protocol.id_text(B), "kind": "edge", "off": True},+ {"peer": "", "kind": "edge"},+ {"peer": protocol.id_text(D), "kind": "edge"},+ {"peer": protocol.id_text(C), "kind": "notch"},+ {"peer": protocol.id_text(C), "kind": "edge"},+ {"peer": "junk", "kind": "edge"},+ {"peer": protocol.id_text(B), "kind": "sideways"},+ ]+ self.assertEqual([peer for peer, _ in self.models(zones, allowed=(B, D))], [])+ self.assertEqual([peer for peer, _ in self.models(zones)], [C])++ def test_a_corner_lands_at_the_end_nearest_it(self):+ self.assertEqual(receiver.corner_offset("top_right", "right"), 0.0)+ self.assertEqual(receiver.corner_offset("top_right", "top"), 1.0)+ self.assertEqual(receiver.corner_offset("bottom_left", "left"), 1.0)+ self.assertEqual(receiver.corner_offset("bottom_left", "bottom"), 0.0)+++if __name__ == "__main__":+ unittest.main()+++class DrivenNeverWaits(unittest.TestCase):+ def test_driven_is_answered_while_the_responders_lock_is_held_by_another_thread(self):+ import threading++ machine = Machine([entry(B, "Bee")]).start()+ self.addCleanup(machine.stop)+ held, release, answered = threading.Event(), threading.Event(), []++ def hold():+ with machine.responder._lock:+ held.set()+ release.wait(3)++ holder = threading.Thread(target=hold, daemon=True)+ holder.start()+ held.wait(3)+ asker = threading.Thread(target=lambda: answered.append(machine.responder.driven), daemon=True)+ asker.start()+ asker.join(0.5)+ release.set()+ self.assertEqual(answered, [False], "driven waited for the lock")diff --git a/core/tests/test_responder_ported.py b/core/tests/test_responder_ported.pynew file mode 100644index 0000000..f5b0b99--- /dev/null+++ b/core/tests/test_responder_ported.py@@ -0,0 +1,608 @@+"""What version 5's ReceiverServer tests pinned and no version 6 test did, ported to LinkResponder+over real sockets on loopback (step 8's port brief, groups A to M). Each class is one group. A+check that something did NOT happen waits on the link's own ordering (an `ack` for the next input+arrives after anything that input queued) rather than on a sleep, wherever the wire allows it."""++import os+import socket+import struct+import threading+import time+import unittest+from unittest import mock++from core import protocol, receiver+from core.receiver import ServerState+from core.tests.responder_harness import (+ B, C, HERE, TOKENS, Initiator, Machine, entry, ident, silent_close, wait_for,+)+from core.tests.test_responder_handshake import SlotPerConnection++ACCEPT, ACK, SWITCH, CLIPBOARD = protocol.MSG_ACCEPT, protocol.MSG_ACK, protocol.MSG_SWITCH, protocol.MSG_CLIPBOARD+PNG = protocol.PNG_SIGNATURE + b"\x00" * 64+++class Case(unittest.TestCase):+ zones = ()+ sides = {}+ caps = None++ def setUp(self):+ self.machine = self.start()++ def start(self, unlock=None):+ kwargs = {} if self.caps is None else {"caps": self.caps}+ peers = [entry(B, "Bee", side=self.sides.get(B, "")), entry(C, "Sea", side=self.sides.get(C, ""))]+ machine = Machine(peers, self.zones, unlock=unlock, **kwargs).start()+ self.addCleanup(machine.stop)+ return machine++ def link(self, peer=B, machine=None, **hello):+ # The hello teaches the entry its name, so a link says the one the test reads back.+ hello.setdefault("name", {B: "Bee", C: "Sea"}[peer])+ link = Initiator(machine or self.machine, peer)+ self.addCleanup(link.close)+ link.handshake(link.hello(**hello))+ return link++ def owner(self, peer=B, machine=None, **fields):+ link = self.link(peer, machine)+ route = link.take(**fields)+ self.assertEqual(link.answer(route)[0], ACCEPT)+ return link++ def raw(self):+ sock = socket.create_connection(("127.0.0.1", self.machine.port), timeout=5)+ self.addCleanup(sock.close)+ return sock++ def last_status(self):+ return self.machine.statuses[-1] if self.machine.statuses else None++ def waiting(self):+ return (ServerState.WAITING, f"Waiting on port {self.machine.port}")+++def acks(link):+ return [m["data"] for m in link.seen if m["type"] == ACK]+++class StatusText(Case):+ """A: what the status line says."""++ def test_after_start_it_waits_on_the_port(self):+ self.assertTrue(wait_for(lambda: self.waiting() in self.machine.statuses), self.machine.statuses)++ def test_a_handshake_reports_connected_by_label(self):+ self.link()+ self.assertTrue(wait_for(lambda: self.last_status() == (ServerState.CONNECTED, "Connected to Bee")), self.machine.statuses)++ def test_a_second_link_from_the_same_peer_never_shows_waiting_between(self):+ first = self.link()+ self.assertTrue(wait_for(lambda: self.last_status() == (ServerState.CONNECTED, "Connected to Bee")))+ mark = len(self.machine.statuses)+ second = self.link()+ self.assertTrue(first.closed.wait(2))+ self.assertTrue(wait_for(lambda: ServerState.CONNECTED in [state for state, _ in self.machine.statuses[mark:]]))+ second.close()+ # The one WAITING after the handover is the second link's own end; a stale first link's+ # exit would have made two.+ self.assertTrue(wait_for(lambda: self.last_status() == self.waiting()))+ self.assertEqual([state for state, _ in self.machine.statuses[mark:]].count(ServerState.WAITING), 1)++ def test_closing_the_link_ends_in_waiting(self):+ link = self.link()+ self.assertTrue(wait_for(lambda: self.last_status() == (ServerState.CONNECTED, "Connected to Bee")))+ link.close()+ self.assertTrue(wait_for(lambda: self.last_status() == self.waiting()), self.machine.statuses)++ def test_silence_ends_in_waiting(self):+ with mock.patch.object(receiver, "LINK_READ_TIMEOUT_SECONDS", 0.3):+ self.link()+ self.assertTrue(wait_for(lambda: (ServerState.CONNECTED, "Connected to Bee") in self.machine.statuses))+ self.assertTrue(wait_for(lambda: self.last_status() == self.waiting(), 3.0), self.machine.statuses)++ def test_a_version_5_preamble_names_the_peer_as_older(self):+ self.machine.settings.peer(TOKENS[B])["host"] = "127.0.0.1"+ self.raw().sendall(b"BEAMY\x05" + os.urandom(8))+ expected = (ServerState.ERROR, "Update Beamer on Bee: it is older than this one")+ self.assertTrue(wait_for(lambda: expected in self.machine.statuses), self.machine.statuses)++ def test_a_version_7_preamble_names_the_peer_as_newer(self):+ self.machine.settings.peer(TOKENS[B])["host"] = "127.0.0.1"+ self.raw().sendall(b"BEAMY\x07" + os.urandom(8))+ expected = (ServerState.ERROR, "Bee runs a newer Beamer: update Beamer on this machine")+ self.assertTrue(wait_for(lambda: expected in self.machine.statuses), self.machine.statuses)++ def test_a_cleartext_frame_from_before_version_4_names_the_peer(self):+ self.machine.settings.peer(TOKENS[B])["host"] = "127.0.0.1"+ self.raw().sendall(protocol.legacy_frame({"type": "hello", "data": {"token": "x", "version": 3}}))+ expected = (ServerState.ERROR, "Update Beamer on Bee: it is older than this one")+ self.assertTrue(wait_for(lambda: expected in self.machine.statuses), self.machine.statuses)++ def test_an_address_no_peer_has_is_named_as_it_is(self):+ self.raw().sendall(b"BEAMY\x05" + os.urandom(8))+ expected = (ServerState.ERROR, "Update Beamer on 127.0.0.1: it is older than this one")+ self.assertTrue(wait_for(lambda: expected in self.machine.statuses), self.machine.statuses)+++class NothingThatMovesTheSeq(Case):+ """B: messages that are not input are never acknowledged as input."""++ def test_ping_unknown_let_go_and_clipboard_leave_the_ack_at_seq_zero(self):+ link = self.owner()+ link.send(protocol.ping_msg())+ link.send({"type": "bogus", "data": {}})+ link.send(protocol.clipboard_msg("from the owner"))+ self.assertTrue(wait_for(lambda: self.machine.clipboard.set_calls))+ link.let_go()+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ for _ in range(2):+ self.assertIsNotNone(link.expect(ACK, timeout=2.0))+ self.assertTrue(all(ack == {"seq": 0, "held_us": 0} for ack in acks(link)), acks(link))+ self.assertEqual(self.machine.injected(), [])+ self.assertFalse(link.closed.is_set())+ self.assertEqual(self.machine.responder.links(), {B})+++class TheKeysPlace(Case):+ """C: GitHub issue 3, `us` reaches the injector."""++ def test_the_press_hands_its_place_on_and_a_release_without_one_hands_none(self):+ link = self.owner()+ link.input(protocol.key_msg("keydown", "с", us="c"))+ seq = link.input(protocol.key_msg("keyup", "с"))+ self.assertIsNotNone(link.acked(seq))+ self.assertEqual(self.machine.injector.keys_us, ["c", None])+ self.assertEqual(self.machine.injected(), [("key", "с", True), ("key", "с", False)])++ def test_a_let_go_releases_a_held_key_with_the_presss_place(self):+ link = self.owner()+ seq = link.input(protocol.key_msg("keydown", "с", us="c"))+ self.assertIsNotNone(link.acked(seq))+ link.let_go()+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ self.assertTrue(wait_for(lambda: len(self.machine.injector.keys_us) == 2))+ self.assertEqual(self.machine.injector.keys_us, ["c", "c"])+ self.assertEqual(self.machine.injected(), [("key", "с", True), ("key", "с", False)])+++class TheClipboardOnLettingGo(Case):+ """D: what a let-go owner is sent back, and what it brings."""++ def visit(self, link, text, image=None):+ route = link.take()+ self.assertEqual(link.answer(route)[0], ACCEPT)+ self.assertTrue(wait_for(lambda: self.machine.responder.owner == B))+ self.machine.clipboard.image = image+ self.machine.clipboard.copy(text)+ link.let_go()+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))++ def nothing_was_sent(self, link):+ # Frames reach the link in the order they were queued, so the marker is the first clipboard+ # it hears if the visit before it sent none.+ self.visit(link, "marker")+ self.assertEqual(link.expect(CLIPBOARD), {"text": "marker"})++ def test_empty_text_sends_nothing(self):+ link = self.link()+ self.visit(link, "")+ self.nothing_was_sent(link)++ def test_text_over_the_limit_is_not_sent(self):+ link = self.link()+ self.visit(link, "z" * (protocol.CLIPBOARD_MAX_BYTES + 1))+ self.nothing_was_sent(link)++ def test_text_and_a_png_are_both_sent(self):+ link = self.link()+ self.visit(link, "shot.png", PNG)+ self.assertEqual(link.expect(CLIPBOARD), protocol.clipboard_msg("shot.png", PNG)["data"])++ def test_an_oversized_image_is_dropped_and_the_text_kept(self):+ link = self.link()+ self.visit(link, "shot.png", protocol.PNG_SIGNATURE + b"\x00" * protocol.CLIPBOARD_IMAGE_MAX_BYTES)+ self.assertEqual(link.expect(CLIPBOARD), {"text": "shot.png"})++ def test_inbound_text_and_a_png_set_both(self):+ link = self.owner()+ link.send(protocol.clipboard_msg("shot.png", PNG))+ self.assertTrue(wait_for(lambda: self.machine.clipboard.set_calls == [("shot.png", PNG)]), self.machine.clipboard.set_calls)++ def test_inbound_a_malformed_image_keeps_the_text(self):+ link = self.owner()+ link.send({"type": CLIPBOARD, "data": {"text": "bad", "image": "not base64!", "image_format": "png"}})+ link.send(protocol.clipboard_msg("shot.png", PNG))+ self.assertTrue(wait_for(lambda: self.machine.clipboard.set_calls == [("bad", None), ("shot.png", PNG)]), self.machine.clipboard.set_calls)++ def test_inbound_oversized_text_is_ignored_and_a_later_good_one_is_set(self):+ link = self.owner()+ link.send(protocol.clipboard_msg("y" * (protocol.CLIPBOARD_MAX_BYTES + 1)))+ link.send(protocol.clipboard_msg("ok"))+ self.assertTrue(wait_for(lambda: self.machine.clipboard.set_calls == [("ok", None)]), self.machine.clipboard.set_calls)+++class Unlock:+ """The Windows unlock provider as the responder uses it. `gate`, when given, holds+ ensure_unlocked until the test releases it."""++ def __init__(self, locked=True, unlocks=True, gate=None):+ self.locked, self.unlocks, self.gate = locked, unlocks, gate+ self.asked = 0++ def is_locked(self):+ return self.locked++ def ensure_unlocked(self):+ self.asked += 1+ if self.gate is not None:+ self.gate.wait(10)+ if self.unlocks:+ self.locked = False+ return self.unlocks+++def finish_unlock():+ for thread in threading.enumerate():+ if thread.name == "Beamer-v6-unlock":+ thread.join(3)+++class LockScreen(Case):+ """E: Windows' lock screen, with the unlock provider faked."""++ def setUp(self):+ # These wait seconds on a link that says nothing, which the responder's 2.5 s silence limit+ # would otherwise end.+ patch = mock.patch.object(receiver, "LINK_READ_TIMEOUT_SECONDS", 60.0)+ patch.start()+ self.addCleanup(patch.stop)++ def switches(self, link):+ return [m["data"] for m in link.seen if m["type"] == SWITCH]++ def test_a_machine_that_locks_mid_drive_sends_its_owner_home_once(self):+ # Issue 5, 30-09-2026: the owner's pointer was left stuck on the lock screen.+ lock = Unlock(locked=False)+ self.machine = self.start(lock)+ with mock.patch.object(receiver, "FORCED_END_SECONDS", 2.0):+ link = self.owner()+ # Heartbeats are the lock checks' clock: three of them are two checks, and it is unlocked.+ for _ in range(3):+ self.assertIsNotNone(link.expect(ACK, timeout=3.0))+ self.assertEqual(self.switches(link), [])+ lock.locked = True+ switch = link.expect(SWITCH, timeout=5.0)+ self.assertEqual(switch["next"], protocol.id_text(B))+ self.assertNotIn("edge", switch)+ # The owner stays until the forced end's `refuse`, two seconds of heartbeats in which a+ # second send-home could have been made; any would be on the wire before it.+ self.assertIsNotNone(link.expect(protocol.MSG_REFUSE, timeout=6.0))+ self.assertEqual(len(self.switches(link)), 1)+ self.assertEqual(lock.asked, 0)++ def test_a_slow_arrival_on_a_locked_machine_still_gets_its_unlock_and_is_not_sent_home(self):+ # The lock check runs on the ack thread: an arrival that itself took 1.4 s saw a locked machine+ # with its owner driving and sent the owner home before the unlock was asked for.+ lock = Unlock(locked=True)+ self.machine = self.start(lock)+ self.machine.desktop.slow = 1.4+ link = self.link()+ route = link.take(edge="left", offset=0.5, resistance_px=120, reach=[])+ self.assertEqual(link.answer(route)[0], ACCEPT)+ self.assertIsNone(link.expect(SWITCH, timeout=3.0))+ self.assertTrue(wait_for(lambda: lock.asked == 1))+ self.assertEqual(lock.asked, 1)+ self.assertEqual(self.machine.responder.owner, B)+ self.assertEqual(self.machine.arrivals, [("left", 0, 540)])++ def test_an_unlocked_machine_makes_no_unlock_attempt(self):+ lock = Unlock(locked=False)+ self.machine = self.start(lock)+ link = self.owner(edge="left", offset=0.5, resistance_px=120, reach=[])+ # The landing runs on this link's reader thread, so an acknowledged input is after it.+ self.assertIsNotNone(link.acked(link.key("keydown", "a")))+ self.assertEqual(lock.asked, 0)+ self.assertFalse(self.machine.responder._unlocking.is_set())++ def test_the_statuses_run_unlocking_then_connected(self):+ lock = Unlock(locked=True)+ self.machine = self.start(lock)+ self.owner()+ self.assertTrue(wait_for(lambda: (ServerState.CONNECTED, "Unlocking Windows…") in self.machine.statuses))+ finish_unlock()+ self.assertEqual(lock.asked, 1)+ self.assertTrue(wait_for(lambda: self.last_status() == (ServerState.CONNECTED, "Connected to Bee")), self.machine.statuses)++ def test_a_failed_unlock_says_so_rather_than_claiming_a_connection(self):+ lock = Unlock(locked=True, unlocks=False)+ self.machine = self.start(lock)+ self.owner()+ self.assertTrue(wait_for(lambda: self.last_status() == (ServerState.CONNECTED, "Windows is locked — unlock it at the PC")), self.machine.statuses)++ def test_a_link_closed_mid_unlock_does_not_report_a_connection(self):+ # An unlock outlives an owner that disconnects during it; the link's own end has already said+ # WAITING and the unlock finishing must not overwrite it, whether it worked or not.+ for unlocks in (True, False):+ with self.subTest(unlocks=unlocks):+ gate = threading.Event()+ lock = Unlock(locked=True, unlocks=unlocks, gate=gate)+ machine = self.start(lock)+ link = self.owner(machine=machine)+ self.assertTrue(wait_for(lambda: (ServerState.CONNECTED, "Unlocking Windows…") in machine.statuses))+ link.close()+ waiting = (ServerState.WAITING, f"Waiting on port {machine.port}")+ self.assertTrue(wait_for(lambda: machine.statuses[-1] == waiting), machine.statuses)+ mark = len(machine.statuses)+ gate.set()+ finish_unlock()+ self.assertNotIn(ServerState.CONNECTED, [state for state, _ in machine.statuses[mark:]])+ self.assertEqual(machine.statuses[-1], waiting)++ def test_the_ack_says_locked_only_while_the_unlock_runs(self):+ gate = threading.Event()+ self.machine = self.start(Unlock(locked=True, gate=gate))+ link = self.owner()+ self.assertIsNotNone(link.expect(ACK, timeout=3.0, where=lambda data: data.get("locked") is True))+ gate.set()+ self.assertIsNotNone(link.expect(ACK, timeout=3.0, where=lambda data: "locked" not in data))+++class TheHandBack(Case):+ """F: the injector's keys are let go of however ownership ends."""++ def test_release_all_follows_a_let_go(self):+ link = self.owner()+ link.let_go()+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ self.assertIn(("release_all",), self.machine.injector.seen())++ def test_release_all_follows_a_link_that_closes(self):+ link = self.owner()+ link.close()+ self.assertTrue(wait_for(lambda: ("release_all",) in self.machine.injector.seen()))+ self.assertTrue(wait_for(lambda: self.machine.owners == [B, None]))++ def test_stopping_the_responder_while_driven_ends_the_ownership_and_says_stopped(self):+ self.owner()+ self.machine.responder.stop()+ self.assertEqual(self.machine.owners, [B, None])+ self.assertIn(("release_all",), self.machine.injector.seen())+ self.assertEqual(self.last_status()[0], ServerState.STOPPED)++ def test_a_let_go_then_a_close_reports_no_second_end(self):+ link = self.owner()+ link.let_go()+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ link.close()+ self.assertTrue(wait_for(lambda: (B, False) in self.machine.links))+ self.assertEqual(self.machine.owners, [B, None])+++class Pressure(Case):+ """G: the pressure callback the crossing effects are fed from."""++ sides = {B: "left"}+ zones = [{"peer": protocol.id_text(B), "kind": "edge"}]++ def test_a_push_short_of_the_resistance_holds_and_breaking_through_crosses(self):+ link = self.owner(resistance_px=100, reach=[])+ self.machine.desktop.cursor = (0, 540)+ link.move(-60, 0)+ self.assertTrue(wait_for(lambda: len(self.machine.pressures) == 1), self.machine.pressures)+ edge, pressure, crossed, part = self.machine.pressures[0]+ self.assertEqual((edge, crossed, part), ("left", False, None))+ self.assertAlmostEqual(pressure, 0.6)+ self.assertLess(pressure, 1)+ self.assertEqual(self.machine.desktop.placed[-1], (0, 540))+ self.assertEqual(self.machine.responder.owner, B)+ link.move(-60, 0)+ self.assertEqual(link.expect(SWITCH)["next"], protocol.id_text(B))+ self.assertTrue(wait_for(lambda: len(self.machine.pressures) == 2), self.machine.pressures)+ self.assertEqual(self.machine.pressures[1], ("left", 1.0, True, None))+ self.assertNotIn(("move", -60, 0), self.machine.injected())+++class RearmNeverRevives(Case):+ """H: a settings change re-arms only zones that are live; and a replayed frame ends the link."""++ sides = {B: "left", C: "right"}+ zones = [{"peer": protocol.id_text(B), "kind": "edge"}, {"peer": protocol.id_text(C), "kind": "edge"}]++ def switches(self, link):+ return [m["data"] for m in link.seen if m["type"] == SWITCH]++ def push(self, link, cursor, dx):+ self.machine.desktop.cursor = cursor+ self.assertIsNotNone(link.acked(link.move(dx, 0)))++ def test_after_a_switch(self):+ link = self.owner(reach=[C])+ self.push(link, (1919, 500), 200)+ self.assertIsNotNone(link.expect(SWITCH))+ self.machine.responder.rearm()+ self.push(link, (1919, 500), 200)+ self.assertEqual(len(self.switches(link)), 1)+ self.assertIn(("move", 200, 0), self.machine.injected())++ def test_after_send_home(self):+ with mock.patch.object(receiver, "FORCED_END_SECONDS", 30.0):+ link = self.owner(reach=[C])+ self.assertTrue(self.machine.responder.send_home())+ self.assertIsNotNone(link.expect(SWITCH))+ self.machine.responder.rearm()+ self.push(link, (0, 500), -200)+ self.push(link, (1919, 500), 200)+ self.assertEqual(len(self.switches(link)), 1)++ def test_with_no_owner(self):+ link = self.owner(reach=[C])+ link.let_go()+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ self.machine.responder.rearm()+ self.assertEqual(self.machine.responder._armed, [])+ self.assertFalse(self.machine.responder._zones_live)++ def test_a_frame_replayed_whole_ends_the_link(self):+ link = self.owner()+ frame = link.session.seal(protocol.key_msg("keydown", "a", seq=1))+ with link.session.send_lock:+ link.sock.sendall(frame + frame)+ self.assertTrue(link.closed.wait(3))+ self.assertTrue(wait_for(lambda: self.machine.responder.links() == set()))+ # The owner's key went down once, and its ending released it; the replay was not injected twice.+ self.assertEqual(self.machine.injected(), [("key", "a", True), ("key", "a", False)])+++class Binding(unittest.TestCase):+ """I: a port something else holds is waited out rather than ending the listener."""++ def hold(self, reuse):+ holder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ if reuse:+ holder.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ # The responder listens on 0.0.0.0, and SO_REUSEADDR only collides with a holder on the same+ # address, so 127.0.0.1 here would bind happily.+ holder.bind(("0.0.0.0", 0))+ holder.listen(1)+ self.addCleanup(holder.close)+ return holder, holder.getsockname()[1]++ def test_a_held_port_is_an_error_naming_it_then_waiting_once_it_is_free(self):+ holder, port = self.hold(reuse=False)+ machine = Machine([entry(B, "Bee")])+ self.addCleanup(machine.stop)+ with mock.patch.object(receiver, "BIND_RETRY_SECONDS", 0.05):+ machine.responder.start(port)+ self.assertTrue(wait_for(lambda: any(state == ServerState.ERROR for state, _ in machine.statuses), 3.0), machine.statuses)+ detail = next(detail for state, detail in machine.statuses if state == ServerState.ERROR)+ self.assertIn(f"port {port}", detail)+ self.assertIn("Connection page", detail)+ holder.close()+ self.assertTrue(wait_for(lambda: (ServerState.WAITING, f"Waiting on port {port}") in machine.statuses, 3.0), machine.statuses)++ def test_a_listener_that_set_reuseaddr_still_blocks_the_bind(self):+ # A zombie copy of Beamer itself opened its listener with SO_REUSEADDR too.+ holder, port = self.hold(reuse=True)+ machine = Machine([entry(B, "Bee")])+ self.addCleanup(machine.stop)+ with mock.patch.object(receiver, "BIND_RETRY_SECONDS", 0.05):+ machine.responder.start(port)+ self.assertTrue(wait_for(lambda: any(state == ServerState.ERROR for state, _ in machine.statuses), 3.0), machine.statuses)+ self.assertTrue(any(f"port {port}" in detail for state, detail in machine.statuses if state == ServerState.ERROR))+++class InputScale(Case):+ """J: this machine's pointer and scroll speed, as the apps set it on the responder."""++ def test_a_slower_pointer_carries_its_fractions_into_the_injector(self):+ self.machine.responder.input_scale = receiver.InputScale(pointer=0.5)+ link = self.owner()+ link.move(1, 0)+ seq = link.move(1, 0)+ self.assertIsNotNone(link.acked(seq))+ self.assertEqual(self.machine.injected(), [("move", 1, 0)])++ def test_reverse_scroll_turns_a_scroll_round(self):+ self.machine.responder.input_scale = receiver.InputScale(reverse=True)+ link = self.owner()+ seq = link.input(protocol.scroll_msg(2, 0))+ self.assertIsNotNone(link.acked(seq))+ self.assertEqual(self.machine.injected(), [("scroll", -2.0, -0.0, "line")])+++class StrangersAndTheSlots(Case):+ """K: four connections that say a byte and stall do not keep the real peer out."""++ def test_the_peer_gets_in_and_the_strangers_are_closed_silently(self):+ self.machine.responder._slots = SlotPerConnection()+ strangers = []+ for _ in range(receiver.MAX_PENDING_CONNECTIONS):+ sock = self.raw()+ sock.sendall(b"B")+ strangers.append(sock)+ self.assertTrue(wait_for(lambda: len(self.machine.responder._slots) == receiver.MAX_PENDING_CONNECTIONS))+ self.link()+ self.assertTrue(wait_for(lambda: self.machine.responder.links() == {B}))+ for sock in strangers:+ self.assertTrue(silent_close(sock, timeout=5.0))+ self.assertTrue(wait_for(lambda: len(self.machine.responder._slots) == 0, 5.0), len(self.machine.responder._slots))+++class HelloAtItsLargest(unittest.TestCase):+ """L: the largest valid `hello` and `welcome` fit the first frame's limit."""++ def pair(self):+ token = TOKENS[B]+ initiator = protocol.LinkSession(token, protocol.ROLE_INITIATOR)+ responder = protocol.LinkSession(token, protocol.ROLE_RESPONDER)+ responder.accept_preamble(initiator.preamble())+ initiator.accept_preamble(responder.preamble())+ return initiator, responder++ def largest(self):+ return dict(+ machine_id=ident(10), name="😀" * protocol.MAX_NAME_CHARS, platform="p" * 16, app="a" * protocol.MAX_ASCII_FIELD,+ caps=[f"{index:02d}".ljust(protocol.MAX_ASCII_FIELD, "c") for index in range(protocol.MAX_CAPS)],+ )++ def test_a_hello_at_every_maximum_fits_and_reads_back(self):+ initiator, responder = self.pair()+ hello = protocol.hello_v6(port=65535, hw="aa:bb:cc:dd:ee:ff", **self.largest())+ frame = initiator.seal(hello)+ self.assertLessEqual(len(frame) - protocol.HEADER_SIZE, protocol.HELLO_MAX_BYTES)+ near, far = socket.socketpair()+ self.addCleanup(near.close)+ self.addCleanup(far.close)+ near.sendall(frame)+ read = protocol.read_hello(protocol.recv_first_msg(far, responder, time.monotonic() + 3))+ self.assertEqual((len(read["name"]), len(read["caps"]), read["port"]), (protocol.MAX_NAME_CHARS, protocol.MAX_CAPS, 65535))++ def test_a_welcome_at_every_maximum_fits_and_reads_back(self):+ initiator, responder = self.pair()+ welcome = protocol.welcome_v6(accepts=True, hw="aa:bb:cc:dd:ee:ff", **self.largest())+ frame = responder.seal(welcome)+ self.assertLessEqual(len(frame) - protocol.HEADER_SIZE, protocol.HELLO_MAX_BYTES)+ near, far = socket.socketpair()+ self.addCleanup(near.close)+ self.addCleanup(far.close)+ near.sendall(frame)+ read = protocol.read_welcome(protocol.recv_first_msg(far, initiator, time.monotonic() + 3))+ self.assertTrue(read["accepts"])+++class InjectionErrors(Case):+ """M: an injector that raises says so in the status, once per interval, naming the peer."""++ def fail(self, error=RuntimeError("the desktop refused the key")):+ def inject(*args, **kwargs):+ raise error+ self.machine.injector.inject_key = inject++ def said(self):+ return [s for s in self.machine.statuses if s == (ServerState.CONNECTED, "Input error from Bee; see log")]++ def test_a_failing_injection_sets_the_status_by_label_and_the_link_stays(self):+ self.fail()+ link = self.owner()+ seq = link.key("keydown", "a")+ self.assertIsNotNone(link.acked(seq))+ self.assertTrue(wait_for(lambda: len(self.said()) == 1), self.machine.statuses)+ self.assertFalse(link.closed.is_set())++ def test_it_is_said_once_per_interval(self):+ self.fail()+ link = self.owner()+ with mock.patch.object(receiver, "INJECTION_ERROR_STATUS_INTERVAL_SECONDS", 3600.0):+ for name in "abc":+ self.assertIsNotNone(link.acked(link.key("keydown", name)))+ self.assertTrue(wait_for(lambda: len(self.said()) == 1))+ self.assertEqual(len(self.said()), 1)+ with mock.patch.object(receiver, "INJECTION_ERROR_STATUS_INTERVAL_SECONDS", 0.0):+ self.assertIsNotNone(link.acked(link.key("keydown", "d")))+ self.assertTrue(wait_for(lambda: len(self.said()) == 2), self.machine.statuses)+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_responder_races.py b/core/tests/test_responder_races.pynew file mode 100644index 0000000..8a0125c--- /dev/null+++ b/core/tests/test_responder_races.py@@ -0,0 +1,251 @@+"""The responder's races and resource bounds, each found by the cold reviews of step 4a (a fresh+Opus as an attacker, and Gemini 3.1 Pro on the handshake), written before its fix."""++import os+import socket+import threading+import time+import unittest+from unittest import mock++from core import protocol, receiver+from core.tests.responder_harness import B, C, TOKENS, Initiator, Machine, entry, token, wait_for++ACCEPT, REFUSE = protocol.MSG_ACCEPT, protocol.MSG_REFUSE+++class Case(unittest.TestCase):+ peers = None+ zones = ()++ def setUp(self):+ self.machine = Machine(self.peers or [entry(B, "Bee"), entry(C, "Sea")], self.zones).start()+ self.addCleanup(self.machine.stop)++ def link(self, peer=B, **kwargs):+ link = Initiator(self.machine, peer)+ self.addCleanup(link.close)+ link.handshake(**kwargs)+ return link++ def own(self, link, **fields):+ route = link.take(**fields)+ self.assertEqual(link.answer(route), (ACCEPT, {"route": route}))+ return route+++class TheClipboardAndTheOwnerCallbacks(Case):+ def test_a_let_go_never_sends_the_next_owners_clipboard_and_the_callbacks_keep_their_order(self):+ clipboard = self.machine.clipboard+ b, c = self.link(B), self.link(C)+ self.own(b)+ clipboard.copy("copied here")+ clipboard.slow_get = 0.4+ b.let_go(target=C)+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ self.own(c)+ c.send(protocol.clipboard_msg("C's secret"))+ self.assertTrue(wait_for(lambda: ("set", "C's secret") in self.machine.events))+ sent = b.expect(protocol.MSG_CLIPBOARD, timeout=1.0)+ self.assertNotEqual(sent, {"text": "C's secret"})+ self.assertTrue(wait_for(lambda: len(self.machine.owners) == 3))+ self.assertEqual(self.machine.owners, [B, None, C])++ def test_a_clipboard_is_never_set_after_its_senders_ownership_ended(self):+ b = self.link(B)+ self.own(b)+ self.machine.clipboard.slow_set = 0.4+ b.send(protocol.clipboard_msg("from b"))+ time.sleep(0.1)+ self.machine.settings.peer(TOKENS[B])["allow_drive"] = False+ self.machine.responder.peers_changed()+ self.assertTrue(wait_for(lambda: ("owner", None) in self.machine.events))+ events = [e for e in self.machine.events if e in (("set", "from b"), ("owner", None))]+ self.assertEqual(events, [("set", "from b"), ("owner", None)])+++class TheNotice(Case):+ peers = [entry("", "Old PC", token=token(50), from_1_4=True, linked=False, paired_at=0)]++ def test_the_notice_shows_even_when_the_welcome_cannot_be_sent(self):+ real = protocol.send_msg++ def refuse_welcome(sock, session, message):+ if message.get("type") == protocol.MSG_WELCOME:+ raise ConnectionResetError("the claimer reset the connection")+ return real(sock, session, message)++ with mock.patch.object(protocol, "send_msg", refuse_welcome):+ link = Initiator(self.machine, B, key=token(50))+ self.addCleanup(link.close)+ with self.assertRaises((protocol.ConnectionClosed, OSError)):+ link.handshake(link.hello(name="Claimer"))+ self.assertEqual(self.machine.settings.peer(token(50))["id"], protocol.id_text(B))+ self.assertEqual(self.machine.notices, ["Linked with Claimer at 127.0.0.1 for the first time on Beamer 1.5.0."])+++class ALargeFrameToASlowReader(Case):+ def test_a_slow_but_working_reader_keeps_the_link(self):+ with mock.patch.object(receiver, "LINK_READ_TIMEOUT_SECONDS", 0.5):+ b = Initiator(self.machine, B)+ self.addCleanup(b.close)+ b.handshake(reader=False)+ b.send(protocol.focus_v6(1, receiver_id(self.machine)))+ deadline = time.monotonic() + 3+ while time.monotonic() < deadline:+ if protocol.recv_msg(b.sock, b.session).get("type") == ACCEPT:+ break+ self.machine.clipboard.image = protocol.PNG_SIGNATURE + os.urandom(3_000_000)+ self.machine.clipboard.stamp += 1+ b.send(protocol.focus_v6(2, B))+ received, started = 0, time.monotonic()+ b.sock.settimeout(0.05)+ while received < 4_000_000 and time.monotonic() - started < 10:+ try:+ chunk = b.sock.recv(65536)+ except socket.timeout:+ chunk = None+ if chunk == b"":+ break+ received += len(chunk or b"")+ b.send(protocol.ping_msg())+ time.sleep(0.03)+ self.assertGreaterEqual(received, 4_000_000)+ self.assertIn(B, self.machine.responder.links())+++def receiver_id(machine):+ return machine.responder._identity()["id"]+++class BusyIsDecidedAfterTheClaimIsVisible(Case):+ def test_the_take_is_visible_to_the_app_before_away_is_read(self):+ seen = []++ def away():+ seen.append(self.machine.responder.driven)+ return False++ self.machine.responder._away = away+ b = self.link(B)+ self.own(b)+ self.assertEqual(seen, [True])+ self.assertTrue(self.machine.responder.driven)++ def test_a_busy_refusal_leaves_nothing_claimed(self):+ self.machine.away = True+ b = self.link(B)+ route = b.take()+ self.assertEqual(b.answer(route), (REFUSE, {"route": route, "why": "busy"}))+ self.assertFalse(self.machine.responder.driven)+ self.assertIsNone(self.machine.responder.owner)+++class AnAppCallbackThatRaises(Case):+ def test_a_zones_callback_that_raises_leaves_the_link_working(self):+ def broken():+ raise RuntimeError("the settings are being rewritten")++ self.machine.responder._zones = broken+ b = self.link(B)+ self.own(b)+ self.assertEqual(self.machine.responder.links(), {B})+++class Unlocking(Case):+ class Unlock:+ def __init__(self):+ self.locked = False++ def is_locked(self):+ return self.locked++ def ensure_unlocked(self):+ time.sleep(0.8)+ self.locked = False+ return True++ def test_releases_still_reach_the_injector_while_it_unlocks(self):+ unlock = self.Unlock()+ self.machine.responder._unlock = unlock+ b = self.link(B)+ self.own(b)+ b.key("keydown", "shift")+ self.assertTrue(wait_for(lambda: ("key", "shift", True) in self.machine.injected()))+ unlock.locked = True+ self.own(b, edge="left", offset=0.5)+ self.assertTrue(wait_for(lambda: self.machine.responder._unlocking.is_set()))+ b.key("keyup", "shift")+ b.key("keydown", "x")+ self.assertTrue(wait_for(lambda: ("key", "shift", False) in self.machine.injected(), timeout=0.5))+ self.assertNotIn(("key", "x", True), self.machine.injected())+ self.assertEqual(self.machine.responder.owner, B)++ def test_only_the_owner_hears_that_the_machine_is_locked(self):+ unlock = self.Unlock()+ unlock.locked = True+ self.machine.responder._unlock = unlock+ b, c = self.link(B), self.link(C)+ self.own(b, edge="left", offset=0.5)+ self.assertTrue(wait_for(lambda: self.machine.responder._unlocking.is_set()))+ self.assertTrue(b.expect(protocol.MSG_ACK, timeout=1.0).get("locked"))+ ack = c.expect(protocol.MSG_ACK, timeout=1.0)+ self.assertNotIn("locked", ack)+++class TheLinkReplaced(Case):+ def test_a_take_on_a_replaced_link_is_never_accepted(self):+ first = self.link(B)+ old = self.machine.responder._links[B]+ real_close = receiver._Link.close++ def slow_close(link):+ time.sleep(0.4)+ real_close(link)++ with mock.patch.object(receiver._Link, "close", slow_close):+ second = Initiator(self.machine, B)+ self.addCleanup(second.close)+ done = threading.Thread(target=second.handshake)+ done.start()+ self.assertTrue(wait_for(lambda: self.machine.responder._links.get(B) not in (None, old)))+ route = first.take()+ self.assertIsNone(first.answer(route, timeout=1.0))+ done.join(3)+ self.assertNotIn(B, self.machine.owners)+++class ZonesArmedFromFreshSettings(Case):+ zones = [{"peer": protocol.id_text(C), "kind": "edge", "off": True}]++ def setUp(self):+ super().setUp()+ for item in self.machine.settings.data["peers"]:+ item["side"] = "right" if item["token"] == TOKENS[C] else "left"++ def test_a_zone_change_during_a_take_is_not_lost(self):+ stale = [dict(zone) for zone in self.machine.settings.data["zones"]]+ calls = []++ def zones():+ calls.append(1)+ if len(calls) == 1:+ self.machine.settings.data["zones"][0]["off"] = False+ changer = threading.Thread(target=self.machine.responder.rearm)+ changer.start()+ changer.join(2)+ return stale+ return self.machine.settings.data["zones"]++ b = self.link(B)+ self.machine.responder._zones = zones+ route = self.own(b, reach=[C])+ self.machine.desktop.cursor = (1919, 500)+ b.move(200, 0)+ switch = b.expect(protocol.MSG_SWITCH, timeout=1.0)+ self.assertIsNotNone(switch)+ self.assertEqual((switch["route"], switch["next"]), (route, protocol.id_text(C)))+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_settings_sync.py b/core/tests/test_settings_sync.pyindex 16c2018..4178e4c 100644--- a/core/tests/test_settings_sync.py+++ b/core/tests/test_settings_sync.py@@ -1,11 +1,17 @@"""Same on both machines, without AppKit or Qt: the message, the merge and the window's words."""+import base64import unittestfrom types import SimpleNamespacefrom core import settings_syncKEYS = {"alt_r", "cmd_r", "f13"}+NOW = 1790000000+++def b64(raw):+ return base64.b64encode(raw).decode()def mac_raw(**crossing):@@ -33,30 +39,19 @@ def pc_config(**fields):return SimpleNamespace(**base)-class CornerTests(unittest.TestCase):- def test_a_corner_flips_across_the_border_and_keeps_its_place_along_it(self):- self.assertEqual(settings_sync.mirror_corner("top_right", "right"), "top_left")- self.assertEqual(settings_sync.mirror_corner("bottom_left", "left"), "bottom_right")- self.assertEqual(settings_sync.mirror_corner("top_right", "top"), "bottom_right")-- def test_mirroring_is_its_own_inverse(self):- for corner in settings_sync.CORNERS:- for edge in ("left", "right", "top", "bottom"):- self.assertEqual(settings_sync.mirror_corner(settings_sync.mirror_corner(corner, edge), edge), corner)--class MessageTests(unittest.TestCase):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})+ 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["crossing"]["methods"], ["shortcut", "edge"])+ 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"):+ 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_a_round_trip_reads_back_what_was_sent(self):@@ -70,11 +65,23 @@ class MessageTests(unittest.TestCase):data["crossing"]["trigger_key"] = "hyper"data["crossing"]["resistance_px"] = 9000data["design"]["glow_style"] = "from-the-future"- data["crossing"]["methods"] = ["edge", "notch"]+ 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", "methods"):+ for dropped in ("trigger_key", "resistance_px", "glow_style", "shortcut", "methods"):self.assertNotIn(dropped, values)- self.assertEqual(values["corner"], "top_right")+ 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}):@@ -86,72 +93,181 @@ class MessageTests(unittest.TestCase):# 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_mac_and_only_when_it_differs(self):- mac = settings_sync.message_data(True, 100, settings_sync.mac_values(mac_raw(glow_style="beam")))- pc_same = (True, settings_sync.mac_values(mac_raw(glow_style="beam")))- pc_other = (True, settings_sync.mac_values(mac_raw(glow_style="glow")))- self.assertIsNone(settings_sync.arrived(mac, 100, KEYS))- self.assertIsNone(settings_sync.arrived(mac, 100, KEYS, pc_same))- self.assertEqual(settings_sync.arrived(mac, 100, KEYS, pc_other)[2]["glow_style"], "beam")- self.assertIsNone(settings_sync.arrived(settings_sync.message_data(False, 0), 0, KEYS, (True, {})))+ 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_only_a_newer_stamp_wins(self):- self.assertTrue(settings_sync.wins(2, 1))- self.assertFalse(settings_sync.wins(1, 1))- self.assertFalse(settings_sync.wins(0, 0))+ 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_the_mac_keeps_its_notch_and_its_own_rows(self):+ def test_the_mac_keeps_its_notch_its_zones_and_its_own_rows(self):raw = mac_raw()- values = settings_sync.mac_values(mac_raw(methods=["corner"], glow_style="beam", resistance_px=40))+ values = settings_sync.mac_values(mac_raw(glow_style="beam", resistance_px=40))values["trigger_key"] = "f13"+ values["shortcut"] = Falseapplied = settings_sync.apply_mac(raw, values)- self.assertEqual(applied["crossing"]["methods"], ["corner", "notch"])+ 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"):+ 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_a_mac_without_the_notch_gains_none(self):- applied = settings_sync.apply_mac(mac_raw(methods=["edge"]), {"methods": ["corner"]})- self.assertEqual(applied["crossing"]["methods"], ["corner"])+ 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_pc_sends_its_corner_in_the_macs_frame_and_takes_one_back_in_its_own(self):- config = pc_config(crossing_corner="top_left", mac_return_edge="left")- self.assertEqual(settings_sync.pc_values(config)["corner"], "top_right")- settings_sync.apply_pc(config, {"corner": "bottom_right"})- self.assertEqual(config.crossing_corner, "bottom_left")+ 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_values_from_the_mac_land_on_the_pcs_fields_and_leave_its_own(self):+ 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", edge_parts=["start", "end"]))+ values = settings_sync.mac_values(mac_raw(glow_colour="ocean", methods=["edge"]))settings_sync.apply_pc(config, values)- self.assertEqual(config.crossing_methods, ["shortcut", "edge"])- self.assertEqual(config.crossing_edge_parts, ["start", "end"])+ 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))))+ 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 PC keeps its own."- self.assertEqual(settings_sync.scope("crossing", "PC", False, own), own)- self.assertEqual(settings_sync.scope("design", "PC", True, own),- "Kept the same as your PC. Change it on either machine.")- self.assertEqual(settings_sync.scope("keyboard", "Mac", True, own), 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.")+ 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("Mac", True, False))- self.assertIn("Crossing and Design", settings_sync.switch_note("Mac", False, False))- self.assertIn("too old", settings_sync.switch_note("PC", True, True))+ 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.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))if __name__ == "__main__":diff --git a/core/tests/test_three_machines.py b/core/tests/test_three_machines.pynew file mode 100644index 0000000..559fa3d--- /dev/null+++ b/core/tests/test_three_machines.py@@ -0,0 +1,311 @@+"""Three machines and more over real sockets on loopback (WIRE.md sections 4 and+5, routing and input ownership): LinkResponders driven by scripted owners whose every+decision is core/owner.py's, so the owner's state machine and the responder are held to each other+with nothing faked but the platform edges. The links are the harness's scripted initiators."""++import time+import unittest++from core import owner as owner_module+from core import protocol+from core.tests.responder_harness import Initiator, Machine, entry, ident, token, wait_for++O, O2 = ident(130), ident(160)+A, B, C = ident(190), ident(220), ident(250)+NAMES = {A: "Ay", B: "Bee", C: "Sea", O: "Owner", O2: "Other"}+++def key(one, other):+ """The token one pair shares, the same whichever end asks."""+ low, high = sorted((one, other))+ return token(low[0] * 3 + high[0])+++def text(peer):+ return protocol.id_text(peer)+++class ScriptedOwner:+ """A machine's input, routed by core/owner.Owner over one scripted link per responder. `pump`+ reads what the responders sent and carries out the owner's actions; `sent` keeps every+ `focus` the owner sent, by peer."""++ def __init__(self, test, own, machines):+ self.test = test+ self.own = own+ self.owner = owner_module.Owner(text(own), time.monotonic)+ self.links = {}+ self.sent = []+ self.moved = []+ self.clipboard = "owner's"+ self.clipboards = []+ for machine in machines:+ link = Initiator(machine, own, key(own, machine.own))+ test.addCleanup(link.close)+ welcome = link.handshake()+ self.links[text(machine.own)] = link+ self.carry_out(self.owner.link_up(text(machine.own), welcome["accepts"]))++ def carry_out(self, actions):+ for action in actions:+ if isinstance(action, owner_module.Send):+ message = action.message+ if message["type"] == protocol.MSG_FOCUS:+ self.sent.append((action.peer, dict(message["data"])))+ if message["type"] in protocol.INPUT_TYPES:+ self.links[action.peer].input(message)+ else:+ self.links[action.peer].send(message)+ elif isinstance(action, owner_module.SendClipboard):+ self.links[action.peer].send(protocol.clipboard_msg(text=self.clipboard))+ elif isinstance(action, owner_module.SetClipboard):+ self.clipboard = action.message["data"].get("text")+ self.clipboards.append(self.clipboard)+ elif isinstance(action, owner_module.Moved):+ self.moved.append(action)++ def pump(self):+ for peer, link in self.links.items():+ while not link.inbox.empty():+ message = link.inbox.get_nowait()+ kind, data = message.get("type"), message.get("data") or {}+ if kind == protocol.MSG_SWITCH:+ self.carry_out(self.owner.switch(peer, data))+ elif kind == protocol.MSG_ACCEPT:+ self.carry_out(self.owner.accept(peer, data))+ elif kind == protocol.MSG_REFUSE:+ self.carry_out(self.owner.refuse(peer, data))+ elif kind == protocol.MSG_ACCEPTS:+ self.carry_out(self.owner.accepts(peer, data.get("accepts")))+ elif kind == protocol.MSG_CLIPBOARD:+ self.carry_out(self.owner.clipboard_arrived(peer, time.monotonic(), message))+ self.carry_out(self.owner.tick())++ def until(self, predicate, timeout=3.0):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ self.pump()+ if predicate():+ return True+ time.sleep(0.005)+ return False++ def go(self, machine):+ self.carry_out(self.owner.go(None if machine is None else text(machine.own)))++ def move(self, dx, dy):+ self.carry_out(self.owner.input(protocol.mousemove_msg(dx, dy)))++ @property+ def on(self):+ return self.owner.on+++def responder(test, own, peers, zones=(), away=False):+ """A machine `own` whose peers are (id, side) pairs and whose zones lead to `zones`."""+ entries = [entry(peer, NAMES[peer], token=key(own, peer), side=side) for peer, side in peers]+ machine = Machine(entries, [{"peer": text(peer), "kind": "edge"} for peer in zones], away=away, own=own, name=NAMES[own]).start()+ test.addCleanup(machine.stop)+ return machine+++def moves(machine):+ return [call for call in machine.injected() if call[0] == "move"]+++class Chain(unittest.TestCase):+ """Owner to A, A's zone to B, B's zone to C, C's zone back to A, over four real links."""++ def setUp(self):+ self.a = responder(self, A, [(O, "bottom"), (B, "right"), (C, "left")], zones=(O, B))+ self.b = responder(self, B, [(O, "bottom"), (A, "left"), (C, "right")], zones=(O, C))+ self.c = responder(self, C, [(O, "bottom"), (B, "left"), (A, "right")], zones=(O, A))+ self.machines = {A: self.a, B: self.b, C: self.c}+ self.o = ScriptedOwner(self, O, [self.a, self.b, self.c])+ self.o.go(self.a)+ self.assertTrue(self.o.until(lambda: self.a.responder.owner == O))++ def push_right(self, machine):+ """The pointer at `machine`'s right edge, pushed on through it."""+ machine.desktop.cursor = (1919, 500)+ self.o.move(200, 0)++ def push_left(self, machine):+ machine.desktop.cursor = (0, 500)+ self.o.move(-200, 0)++ def hand_over(self, push, here, there):+ before = len(self.o.sent)+ push(self.machines[here])+ self.assertTrue(self.o.until(lambda: self.o.on == text(there) and self.machines[there].responder.owner == O))+ self.assertTrue(wait_for(lambda: self.machines[here].responder.owner is None))+ return self.o.sent[before:]+++class AChain(Chain):+ def test_every_hand_over_has_one_route_and_every_machine_left_is_let_go(self):+ routes = []+ for push, here, there in ((self.push_right, A, B), (self.push_right, B, C), (self.push_right, C, A)):+ sent = self.hand_over(push, here, there)+ take = [data for peer, data in sent if peer == text(there) and data["target"] == text(there)]+ let_go = [data for peer, data in sent if peer == text(here) and data["target"] != text(here)]+ self.assertEqual(len(take), 1, sent)+ self.assertEqual(len(let_go), 1, sent)+ self.assertEqual(take[0]["route"], let_go[0]["route"])+ self.assertEqual(let_go[0]["target"], text(there))+ routes.append(take[0]["route"])+ self.assertEqual(routes, sorted(set(routes)))+ self.assertEqual([self.machines[peer].responder.owner for peer in (A, B, C)], [O, None, None])++ def test_no_machine_but_the_current_one_injects(self):+ for push, here, there in ((self.push_right, A, B), (self.push_right, B, C), (self.push_right, C, A), (self.push_right, A, B)):+ self.hand_over(push, here, there)+ counts = {peer: len(moves(machine)) for peer, machine in self.machines.items()}+ self.machines[there].desktop.cursor = (960, 540)+ self.o.move(3, 4)+ self.assertTrue(self.o.until(lambda: len(moves(self.machines[there])) == counts[there] + 1))+ time.sleep(0.05)+ self.o.pump()+ self.assertEqual({peer: len(moves(machine)) for peer, machine in self.machines.items()},+ {**counts, there: counts[there] + 1})+ self.assertEqual(moves(self.machines[there])[-1], ("move", 3, 4))++ def test_the_way_home_from_the_far_end_of_the_chain(self):+ self.hand_over(self.push_right, A, B)+ self.hand_over(self.push_right, B, C)+ self.c.desktop.cursor = (960, 1079)+ self.o.move(0, 200)+ self.assertTrue(self.o.until(lambda: self.o.on is None))+ self.assertTrue(wait_for(lambda: self.c.responder.owner is None))+ self.assertEqual(self.o.moved[-1].why, "switch")+ self.assertEqual([machine.responder.owner for machine in self.machines.values()], [None, None, None])++ def test_a_clipboard_copied_on_b_reaches_c_through_the_owner_when_b_is_left(self):+ self.hand_over(self.push_right, A, B)+ # The owner's clipboard follows its take; a copy made before it lands is overwritten by it.+ self.assertTrue(wait_for(lambda: ("owner's", None) in self.b.clipboard.set_calls))+ self.b.clipboard.copy("copied on Bee")+ self.hand_over(self.push_right, B, C)+ self.assertTrue(self.o.until(lambda: ("copied on Bee", None) in self.c.clipboard.set_calls))+ self.assertEqual(self.o.clipboard, "copied on Bee")+ # A machine left with its clipboard untouched sends none back.+ self.assertTrue(self.o.until(lambda: self.o.on == text(C)))+ self.hand_over(self.push_right, C, A)+ time.sleep(0.2)+ self.o.pump()+ self.assertEqual(self.o.clipboards, ["copied on Bee"])++ def test_a_late_switch_from_the_machine_left_is_ignored(self):+ # A's zone asks for B, but the owner's shortcut takes the input home before it reads that.+ self.push_right(self.a)+ late = self.o.links[text(A)].expect(protocol.MSG_SWITCH)+ self.assertEqual(late["next"], text(B))+ self.o.go(None)+ self.assertIsNone(self.o.on)+ self.o.carry_out(self.o.owner.switch(text(A), late))+ self.assertFalse(self.o.until(lambda: self.o.on is not None, timeout=0.5))+ self.assertEqual([peer for peer, data in self.o.sent if peer == text(B)], [])+ self.assertIsNone(self.b.responder.owner)+ self.assertTrue(wait_for(lambda: self.a.responder.owner is None))+++class WhereTheRoutesMustAgree(Chain):+ """The cases the milestone's review found untested over real links: a hand-over refused, a+ machine that sends its owner home, and a machine that stops letting the owner drive."""++ def test_a_refused_hand_over_leaves_the_input_where_it_was_and_the_refuser_out_of_reach(self):+ self.b.away = True+ self.push_right(self.a)+ self.assertTrue(self.o.until(lambda: any(data.get("stay") for peer, data in self.o.sent if peer == text(A))))+ stay = [data for peer, data in self.o.sent if peer == text(A) and data.get("stay")][-1]+ self.assertNotIn(text(B), stay["reach"])+ self.assertEqual(self.o.on, text(A))+ self.assertTrue(wait_for(lambda: self.a.responder.owner == O))+ self.assertIsNone(self.b.responder.owner)+ # Still driving A: the stay was accepted on its own route.+ self.a.desktop.cursor = (960, 540)+ before = len(moves(self.a))+ self.o.move(5, 0)+ self.assertTrue(self.o.until(lambda: len(moves(self.a)) == before + 1))++ def test_a_machine_that_sends_its_owner_home_refuses_it_for_a_while(self):+ self.assertTrue(self.a.responder.send_home())+ self.assertTrue(self.o.until(lambda: self.o.on is None))+ self.assertTrue(wait_for(lambda: self.a.responder.owner is None))+ self.o.go(self.a)+ self.assertTrue(self.o.until(lambda: self.o.moved[-1].why == "sent_home"))+ self.assertIsNone(self.o.on)+ self.assertIsNone(self.a.responder.owner)++ def test_turning_allow_drive_off_sends_the_input_home_and_takes_the_machine_out_of_reach(self):+ self.a.settings.peer(key(A, O))["allow_drive"] = False+ self.a.responder.peers_changed()+ self.assertTrue(self.o.until(lambda: self.o.on is None))+ self.assertTrue(wait_for(lambda: self.a.responder.owner is None))+ self.assertEqual(self.o.owner.go(text(A)), [owner_module.Unreachable(text(A), "unreachable")])+ self.o.go(self.b)+ self.assertTrue(self.o.until(lambda: self.b.responder.owner == O))+ self.assertNotIn(text(A), [data for peer, data in self.o.sent if peer == text(B)][-1]["reach"])+++class Competing(unittest.TestCase):+ def setUp(self):+ self.a = responder(self, A, [(O, "left"), (O2, "right")], zones=(O, O2))+ self.first = ScriptedOwner(self, O, [self.a])+ self.second = ScriptedOwner(self, O2, [self.a])++ def test_two_owners_compete_and_the_second_gets_in_once_the_first_lets_go(self):+ self.first.go(self.a)+ self.assertTrue(self.first.until(lambda: self.a.responder.owner == O))+ self.second.go(self.a)+ self.assertTrue(self.second.until(lambda: self.second.on is None))+ self.assertEqual(self.second.moved[-1].why, "owned")+ self.assertEqual(self.a.responder.owner, O)+ self.first.go(None)+ self.assertTrue(wait_for(lambda: self.a.responder.owner is None))+ self.second.go(self.a)+ self.assertTrue(self.second.until(lambda: self.a.responder.owner == O2))+ self.assertEqual(self.second.on, text(A))+ self.assertIsNone(self.first.on)++ def test_only_the_owner_injects(self):+ self.first.go(self.a)+ self.assertTrue(self.first.until(lambda: self.a.responder.owner == O))+ self.second.go(self.a)+ self.assertTrue(self.second.until(lambda: self.second.on is None))+ # The second's input stays at home, so nothing it moves reaches A.+ self.assertEqual(self.second.owner.input(protocol.mousemove_msg(9, 9)), [owner_module.LOCAL])+ self.first.move(1, 2)+ self.assertTrue(wait_for(lambda: moves(self.a) == [("move", 1, 2)]))+++class TwoDesktopsTakeEachOther(unittest.TestCase):+ """Each runs a responder and an owner, and its responder's `busy` reads its own owner."""++ def test_both_end_at_home_and_neither_is_driven(self):+ owners = {}+ x = responder(self, A, [(B, "right")], zones=(B,), away=lambda: owners[A].owner.away)+ y = responder(self, B, [(A, "left")], zones=(A,), away=lambda: owners[B].owner.away)+ owners[A] = ScriptedOwner(self, A, [y])+ owners[B] = ScriptedOwner(self, B, [x])+ # Both decide before either take is on the wire: the same instant.+ takes = [owners[A].owner.go(text(B)), owners[B].owner.go(text(A))]+ owners[A].carry_out(takes[0])+ owners[B].carry_out(takes[1])+ # Both answers are in before either owner reads one: an owner that took its refusal first+ # would be home, no longer busy, and the other take could rightly get in.+ refusals = {here: owners[here].links[text(there)].expect(protocol.MSG_REFUSE) for here, there in ((A, B), (B, A))}+ for here, there in ((A, B), (B, A)):+ self.assertEqual(refusals[here]["why"], "busy")+ owners[here].carry_out(owners[here].owner.refuse(text(there), refusals[here]))+ self.assertIsNone(owners[here].on)+ self.assertEqual(owners[here].moved[-1].why, "busy")+ self.assertIsNone(x.responder.owner)+ self.assertIsNone(y.responder.owner)+ # Neither is stuck: one take now gets in.+ owners[A].go(y)+ self.assertTrue(owners[A].until(lambda: y.responder.owner == A))+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_v6_vectors.py b/core/tests/test_v6_vectors.pynew file mode 100644index 0000000..b1d4f53--- /dev/null+++ b/core/tests/test_v6_vectors.py@@ -0,0 +1,784 @@+"""The version 6 and pairing version 3 vectors (WIRE.md, The vectors).++`core/tests/v6_vectors.json` holds the `v6` and `pairing_v3` sections of the vector file the phone+apps are built against, copied beside the tests, which run without it. Every replay test reads+that copy and checks the shipped code against it, byte for byte, and again against HKDF, X25519+and ChaCha20-Poly1305 written here without protocol.py in the way. The last class needs that file+and its generator, which are not part of the public source: it regenerates the whole file and+compares it, and holds the version 5 and pairing version 2 sections to the bytes they had when+version 6 was added.+"""++import hashlib+import hmac+import importlib.util+import json+import os+import re+import struct+import unittest++from nacl.bindings import (+ crypto_aead_chacha20poly1305_ietf_decrypt,+ crypto_scalarmult,+ crypto_scalarmult_base,+)+from nacl.exceptions import CryptoError++from core import keytable, pairing, protocol++_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))+_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))+_TOOLS = os.path.join(_REPO_ROOT, "tools")++with open(os.path.join(_TESTS_DIR, "v6_vectors.json"), encoding="utf-8") as _handle:+ FILE = json.load(_handle)+V6 = FILE["v6"]+P3 = FILE["pairing_v3"]++INITIATOR_TO_RESPONDER = "initiator_to_responder"+RESPONDER_TO_INITIATOR = "responder_to_initiator"+++def hkdf(ikm, salt, info):+ """RFC 5869 for one 32-byte block, written here rather than borrowed from the code under test."""+ return hmac.new(hmac.new(salt, ikm, hashlib.sha256).digest(), info + b"\x01", hashlib.sha256).digest()+++def unhex(text):+ return bytes.fromhex(text)+++def sessions(link):+ """(initiator, responder) for one scripted link, preambles exchanged."""+ 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+++class ConstantsAndKeyIdTests(unittest.TestCase):+ def test_the_constants_are_the_modules(self):+ constants = V6["constants"]+ self.assertEqual(constants["version"], protocol.LINK_VERSION)+ self.assertEqual(constants["salt_ascii"].encode("ascii"), protocol.LINK_SALT)+ self.assertEqual(constants["key_id_info_ascii"].encode("ascii"), protocol.KEY_ID_INFO)+ self.assertEqual(constants["frame_info_label_ascii"].encode("ascii"), protocol.KEY_INFO)+ self.assertEqual(constants["key_id_bytes"], protocol.KEY_ID_SIZE)+ self.assertEqual(constants["preamble_bytes"], protocol.LINK_PREAMBLE_SIZE)+ self.assertEqual(constants["short_reply_bytes"], protocol.SHORT_REPLY_SIZE)+ self.assertEqual(constants["min_frame_bytes"], protocol.MIN_FRAME_BYTES)+ self.assertEqual(constants["first_frame_max_bytes"], protocol.HELLO_MAX_BYTES)++ def test_every_token_has_the_committed_key_id_by_the_module_and_by_hand(self):+ self.assertGreaterEqual(len(V6["key_id"]["cases"]), 3)+ for case in V6["key_id"]["cases"]:+ with self.subTest(token=case["token"]):+ self.assertTrue(protocol.is_paired_token(case["token"]))+ self.assertEqual(protocol.key_id(case["token"]).hex(), case["key_id_hex"])+ self.assertEqual(hkdf(case["token"].encode("ascii"), b"beamer-link-v6", b"beamer-key-id")[:16].hex(), case["key_id_hex"])++ def test_a_typed_token_has_no_key_id(self):+ self.assertGreaterEqual(len(V6["key_id"]["typed_tokens"]), 2)+ for token in V6["key_id"]["typed_tokens"]:+ with self.subTest(token=token):+ self.assertFalse(protocol.is_paired_token(token))+ with self.assertRaises(ValueError):+ protocol.key_id(token)+++class PreambleTests(unittest.TestCase):+ def test_the_preamble_is_the_committed_62_bytes(self):+ vector = V6["preamble"]+ session = protocol.LinkSession(vector["token"], protocol.ROLE_INITIATOR, unhex(vector["prefix_hex"]), unhex(vector["secret_hex"]))+ self.assertEqual(session.key_id.hex(), vector["key_id_hex"])+ self.assertEqual(session.share.hex(), vector["share_hex"])+ self.assertEqual(session.preamble().hex(), vector["preamble_hex"])+ self.assertEqual(len(unhex(vector["preamble_hex"])), 62)++ def test_the_share_is_x25519_of_the_secret_and_the_base_point(self):+ vector = V6["preamble"]+ self.assertEqual(crypto_scalarmult_base(unhex(vector["secret_hex"])).hex(), vector["share_hex"])+ self.assertEqual(crypto_scalarmult(unhex(vector["secret_hex"]), bytes([9]) + bytes(31)).hex(), vector["share_hex"])++ def test_the_layout_is_magic_version_prefix_key_id_share(self):+ vector = V6["preamble"]+ data = unhex(vector["preamble_hex"])+ self.assertEqual(data[:5], b"BEAMY")+ self.assertEqual(data[5], 6)+ self.assertEqual(data[6:14].hex(), vector["prefix_hex"])+ self.assertEqual(data[14:30].hex(), vector["key_id_hex"])+ self.assertEqual(data[30:].hex(), vector["share_hex"])+ self.assertEqual(tuple(part.hex() for part in protocol.split_preamble(data)), (vector["prefix_hex"], vector["key_id_hex"], vector["share_hex"]))++ def test_the_short_reply_is_14_bytes(self):+ vector = V6["short_reply"]+ reply = protocol.short_reply(unhex(vector["prefix_hex"]))+ self.assertEqual(reply.hex(), vector["reply_hex"])+ self.assertEqual(len(reply), 14)+ self.assertEqual(unhex(vector["reply_hex"])[:6], b"BEAMY\x06")+++class DeriveKeyTests(unittest.TestCase):+ def test_there_is_a_second_case_with_the_roles_swapped(self):+ first, second = V6["derive_key"]["cases"]+ self.assertEqual((first["prefix_i_hex"], first["secret_i_hex"]), (second["prefix_r_hex"], second["secret_r_hex"]))+ self.assertEqual((first["prefix_r_hex"], first["secret_r_hex"]), (second["prefix_i_hex"], second["secret_i_hex"]))+ self.assertEqual(first["shared_hex"], second["shared_hex"])+ self.assertNotEqual(first["key_i_hex"], second["key_i_hex"])+ self.assertNotEqual(first["key_r_hex"], second["key_r_hex"])++ def test_every_value_by_the_module(self):+ for case in V6["derive_key"]["cases"]:+ with self.subTest(case=case["comment"]):+ token, key_id = case["token"], unhex(case["key_id_hex"])+ self.assertEqual(protocol.key_id(token), key_id)+ parts = [unhex(case[name]) for name in ("prefix_i_hex", "prefix_r_hex", "share_i_hex", "share_r_hex")]+ self.assertEqual(crypto_scalarmult_base(unhex(case["secret_i_hex"])).hex(), case["share_i_hex"])+ self.assertEqual(crypto_scalarmult_base(unhex(case["secret_r_hex"])).hex(), case["share_r_hex"])+ self.assertEqual(protocol.link_ikm(token, unhex(case["shared_hex"])).hex(), case["ikm_hex"])+ self.assertEqual(len(unhex(case["ikm_hex"])), 75)+ for direction, info, key in ((1, "info_i_hex", "key_i_hex"), (2, "info_r_hex", "key_r_hex")):+ self.assertEqual(protocol.link_info(key_id, *parts, direction).hex(), case[info])+ self.assertEqual(len(unhex(case[info])), 111)+ self.assertEqual(protocol.link_key(token, unhex(case["shared_hex"]), key_id, *parts, direction).hex(), case[key])++ def test_every_value_by_hand(self):+ for case in V6["derive_key"]["cases"]:+ with self.subTest(case=case["comment"]):+ shared_i = crypto_scalarmult(unhex(case["secret_i_hex"]), unhex(case["share_r_hex"]))+ shared_r = crypto_scalarmult(unhex(case["secret_r_hex"]), unhex(case["share_i_hex"]))+ self.assertEqual(shared_i, shared_r)+ self.assertEqual(shared_i.hex(), case["shared_hex"])+ ikm = case["token"].encode("ascii") + shared_i+ self.assertEqual(ikm.hex(), case["ikm_hex"])+ for direction, info, key in ((b"\x01", "info_i_hex", "key_i_hex"), (b"\x02", "info_r_hex", "key_r_hex")):+ expected = (+ b"beamer-frames" + b"\x06" + unhex(case["key_id_hex"])+ + unhex(case["prefix_i_hex"]) + unhex(case["prefix_r_hex"])+ + unhex(case["share_i_hex"]) + unhex(case["share_r_hex"]) + direction+ )+ self.assertEqual(expected.hex(), case[info])+ self.assertEqual(hkdf(ikm, b"beamer-link-v6", expected).hex(), case[key])++ def test_a_handshake_of_the_sessions_makes_the_committed_keys(self):+ for case in V6["derive_key"]["cases"]:+ with self.subTest(case=case["comment"]):+ link = {+ "token": case["token"],+ "initiator": {"prefix_hex": case["prefix_i_hex"], "secret_hex": case["secret_i_hex"]},+ "responder": {"prefix_hex": case["prefix_r_hex"], "secret_hex": case["secret_r_hex"]},+ }+ initiator, responder = sessions(link)+ self.assertEqual(initiator._send_key.hex(), case["key_i_hex"])+ self.assertEqual(responder._recv_key.hex(), case["key_i_hex"])+ self.assertEqual(responder._send_key.hex(), case["key_r_hex"])+ self.assertEqual(initiator._recv_key.hex(), case["key_r_hex"])+++class LowOrderTests(unittest.TestCase):+ def test_every_share_ends_the_handshake(self):+ vector = V6["low_order"]+ secret = unhex(vector["secret_hex"])+ self.assertGreaterEqual(len(vector["shares"]), 14)+ for case in vector["shares"]:+ with self.subTest(share=case["share_hex"]):+ self.assertEqual(case["result_hex"], "00" * 32)+ with self.assertRaises(protocol.PreambleRefused):+ protocol._x25519_shared(secret, unhex(case["share_hex"]))+ token = V6["preamble"]["token"]+ key_id = protocol.key_id(token)+ preamble = b"BEAMY\x06" + bytes(range(1, 9)) + key_id + unhex(case["share_hex"])+ for role in (protocol.ROLE_INITIATOR, protocol.ROLE_RESPONDER):+ session = protocol.LinkSession(token, role, bytes(range(11, 19)), secret)+ with self.assertRaises(protocol.PreambleRefused):+ session.accept_preamble(preamble)++ def test_the_non_canonical_shares_are_there(self):+ shares = {case["share_hex"] for case in V6["low_order"]["shares"]}+ p = 2**255 - 19+ for value in (p, p + 1):+ low = value.to_bytes(32, "little")+ high = bytes(low[:31]) + bytes([low[31] | 0x80])+ self.assertIn(low.hex(), shares)+ self.assertIn(high.hex(), shares)+ self.assertIn("00" * 32, shares)+ self.assertIn("01" + "00" * 31, shares)++ def test_an_ordinary_share_is_not_refused(self):+ share = unhex(V6["preamble"]["share_hex"])+ self.assertNotEqual(protocol._x25519_shared(unhex(V6["low_order"]["secret_hex"]), share), bytes(32))+++class FrameTests(unittest.TestCase):+ def test_the_script_covers_every_message_the_spec_lists(self):+ seen = set()+ for link in V6["frames"]["links"]:+ for frame in link["frames"]:+ seen.add(frame["message"]["type"])+ self.assertTrue(+ {"hello", "welcome", "paired", "arrangement", "focus", "clipboard", "mousemove", "keydown", "keyup",+ "text", "mousedown", "mouseup", "scroll", "gesture", "ping", "accepts", "ack", "accept", "switch", "refuse"} <= seen,+ seen,+ )++ def test_the_scripted_links_seal_and_open_to_the_committed_bytes(self):+ for link in V6["frames"]["links"]:+ with self.subTest(link=link["name"]):+ initiator, responder = sessions(link)+ self.assertEqual(initiator.preamble().hex(), link["preamble_i_hex"])+ self.assertEqual(responder.preamble().hex(), link["preamble_r_hex"])+ counters = {INITIATOR_TO_RESPONDER: 0, RESPONDER_TO_INITIATOR: 0}+ for frame in link["frames"]:+ sender, receiver = (initiator, responder) if frame["direction"] == INITIATOR_TO_RESPONDER else (responder, initiator)+ counters[frame["direction"]] += 1+ self.assertEqual(frame["counter"], counters[frame["direction"]])+ self.assertEqual(protocol.dumps_message(frame["message"]).decode("utf-8"), frame["plaintext_json"])+ sealed = sender.seal(frame["message"])+ self.assertEqual(sealed.hex(), frame["frame_hex"])+ opened = receiver.open(sealed[protocol.HEADER_SIZE:])+ self.assertEqual(dict(opened), frame["message"])+ self.assertFalse(opened.malformed)++ def test_libsodium_by_hand_opens_every_committed_frame(self):+ for link in V6["frames"]["links"]:+ with self.subTest(link=link["name"]):+ token = link["token"]+ key_id = protocol.key_id(token)+ pre_i, pre_r = unhex(link["preamble_i_hex"]), unhex(link["preamble_r_hex"])+ prefix_i, prefix_r = pre_i[6:14], pre_r[6:14]+ share_i, share_r = pre_i[30:], pre_r[30:]+ shared = crypto_scalarmult(unhex(link["initiator"]["secret_hex"]), share_r)+ ikm = token.encode("ascii") + shared+ keys = {}+ for direction, byte in ((INITIATOR_TO_RESPONDER, b"\x01"), (RESPONDER_TO_INITIATOR, b"\x02")):+ info = b"beamer-frames\x06" + key_id + prefix_i + prefix_r + share_i + share_r + byte+ keys[direction] = hkdf(ikm, b"beamer-link-v6", info)+ prefixes = {INITIATOR_TO_RESPONDER: prefix_i, RESPONDER_TO_INITIATOR: prefix_r}+ for frame in link["frames"]:+ data = unhex(frame["frame_hex"])+ (length,) = struct.unpack(">I", data[:4])+ self.assertEqual(length, len(data) - 4)+ counter = data[4:8]+ self.assertEqual(struct.unpack(">I", counter)[0], frame["counter"])+ plain = crypto_aead_chacha20poly1305_ietf_decrypt(data[8:], None, prefixes[frame["direction"]] + counter, keys[frame["direction"]])+ self.assertEqual(plain.decode("utf-8"), frame["plaintext_json"])++ def test_the_text_frame_carries_a_character_outside_the_bmp(self):+ texts = [f["message"]["data"]["text"] for link in V6["frames"]["links"] for f in link["frames"] if f["message"]["type"] == "text"]+ self.assertTrue(any(ord(char) > 0xFFFF for text in texts for char in text))++ def test_the_responder_first_frames_read_as_the_spec_says(self):+ links = {link["name"]: link for link in V6["frames"]["links"]}+ for name, error in (("invalid_hello", protocol.ERROR_INVALID_HELLO), ("wrong_id", protocol.ERROR_WRONG_ID)):+ with self.subTest(link=name):+ link = links[name]+ initiator, responder = sessions(link)+ first = link["frames"][0]+ self.assertEqual(first["direction"], INITIATOR_TO_RESPONDER)+ received = responder.open(unhex(first["frame_hex"])[protocol.HEADER_SIZE:])+ if name == "invalid_hello":+ with self.assertRaises(protocol.InvalidHello):+ protocol.read_hello(received)+ else:+ self.assertEqual(protocol.read_hello(received)["id"].hex(), link["wrong_id_hello_id_hex"])+ answer = link["frames"][1]+ self.assertEqual(answer["direction"], RESPONDER_TO_INITIATOR)+ self.assertEqual(answer["message"], {"type": "welcome", "data": {"version": 6, "error": error}})+ with self.assertRaises(protocol.HelloRefused) as raised:+ protocol.read_welcome(initiator.open(unhex(answer["frame_hex"])[protocol.HEADER_SIZE:]))+ self.assertEqual(raised.exception.error, error)+ self.assertEqual(len(link["frames"]), 2)++ def test_the_main_link_messages_pass_their_validators(self):+ link = next(link for link in V6["frames"]["links"] if link["name"] == "main")+ responder_id = unhex(link["responder"]["id_hex"])+ readers = {+ "hello": protocol.read_hello,+ "welcome": protocol.read_welcome,+ "paired": protocol.read_paired,+ "accept": protocol.read_accept,+ "switch": protocol.read_switch,+ "ack": protocol.read_ack,+ "clipboard": protocol.read_clipboard,+ "keydown": protocol.read_input,+ "keyup": protocol.read_input,+ "mousemove": protocol.read_input,+ "mousedown": protocol.read_input,+ "mouseup": protocol.read_input,+ "scroll": protocol.read_input,+ "gesture": protocol.read_input,+ "text": protocol.read_input,+ "ping": protocol.read_message,+ "accepts": protocol.read_accepts,+ "focus": lambda message: protocol.read_focus(message, responder_id),+ "arrangement": lambda message: protocol.read_arrangement_v6(message, now=1_790_000_000),+ }+ for frame in link["frames"]:+ kind = frame["message"]["type"]+ with self.subTest(type=kind, counter=frame["counter"], direction=frame["direction"]):+ message = protocol.parse_message(frame["plaintext_json"].encode("utf-8"))+ result = readers[kind](message)+ self.assertIsNotNone(result)+++class BadFrameTests(unittest.TestCase):+ def test_each_bad_frame_ends_the_link(self):+ bad = V6["bad_frames"]+ self.assertGreaterEqual(len(bad["cases"]), 3)+ for case in bad["cases"]:+ with self.subTest(case=case["comment"]):+ initiator, responder = sessions(bad["link"])+ receiver = responder if case["receiver"] == "responder" else initiator+ self.assertEqual(case["must"], "close_without_reply")+ with self.assertRaises(protocol.ProtocolError):+ receiver.open(unhex(case["frame_hex"])[protocol.HEADER_SIZE:])++ def test_the_three_kinds_the_spec_lists_are_there(self):+ kinds = " ".join(case["comment"] for case in V6["bad_frames"]["cases"]).lower()+ for word in ("tag", "counter", "direction"):+ self.assertIn(word, kinds)++ def test_the_untouched_frame_the_cases_are_made_from_opens(self):+ bad = V6["bad_frames"]+ initiator, responder = sessions(bad["link"])+ self.assertEqual(dict(responder.open(unhex(bad["good_frame_hex"])[protocol.HEADER_SIZE:])), bad["good_message"])+++class IdTests(unittest.TestCase):+ def test_ids_spell_one_way(self):+ for case in V6["ids"]["cases"]:+ with self.subTest(b64=case["b64"]):+ self.assertEqual(len(case["b64"]), 22)+ self.assertEqual(protocol.id_text(unhex(case["id_hex"])), case["b64"])+ self.assertEqual(protocol.read_id(case["b64"]), unhex(case["id_hex"]))++ def test_the_refused_texts_are_refused(self):+ refused = V6["ids"]["refused"]+ self.assertGreaterEqual(len([case for case in refused if case["kind"] == "non_canonical"]), 3)+ for case in refused:+ with self.subTest(kind=case["kind"], text=case["text"]):+ self.assertIsNone(protocol.read_id(case["text"]))++ def test_a_non_canonical_spelling_decodes_to_the_same_bytes_in_a_lenient_decoder(self):+ import base64++ for case in V6["ids"]["refused"]:+ if case["kind"] != "non_canonical":+ continue+ with self.subTest(text=case["text"]):+ text = case["text"]+ self.assertEqual(base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)).hex(), case["id_hex"])+++class MalformedTests(unittest.TestCase):+ def action(self, hex_text, reader):+ """What the shipped code does with a body: end_link, ignore, answer_invalid_hello or accepted."""+ try:+ message = protocol.parse_message(unhex(hex_text))+ 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 reader in ("welcome", "ack"):+ try:+ {"welcome": protocol.read_welcome, "ack": protocol.read_ack}[reader](message)+ except protocol.ProtocolError:+ return "end_link"+ return "accepted"+ if message.malformed:+ return "ignore"+ result = {+ "message": protocol.read_message,+ "input": protocol.read_input,+ "accept": protocol.read_accept,+ "refuse": protocol.read_refuse,+ "switch": protocol.read_switch,+ "focus": lambda m: protocol.read_focus(m, bytes(range(1, 17))),+ }[reader](message)+ return "ignore" if result is None else "accepted"++ def test_every_case_is_what_the_desktops_do(self):+ cases = V6["malformed"]["cases"]+ self.assertGreaterEqual(len(cases), 40)+ for case in cases:+ with self.subTest(case=case["comment"]):+ self.assertIn(case["action"], ("end_link", "ignore", "answer_invalid_hello"))+ self.assertEqual(self.action(case["hex"], case["reader"]), case["action"])+ try:+ decoded = unhex(case["hex"]).decode("utf-8")+ except UnicodeDecodeError:+ decoded = None+ self.assertEqual(case["text"], decoded)++ def test_a_text_a_parser_may_refuse_outright_says_so(self):+ flagged = [case for case in V6["malformed"]["cases"] if "also_acceptable" in case]+ self.assertEqual(len(flagged), 4)+ for case in flagged:+ with self.subTest(case=case["comment"]):+ self.assertEqual(case["also_acceptable"], "end_link")+ self.assertEqual(case["action"], "ignore")+ self.assertTrue(protocol.parse_message(unhex(case["hex"])).malformed)++ def test_implementation_defined_cases_are_what_the_desktops_do(self):+ for case in V6["malformed"]["implementation_defined"]:+ with self.subTest(case=case["comment"]):+ self.assertTrue(protocol.parse_message(unhex(case["hex"])).malformed)+ self.assertEqual(self.action(case["hex"], case["reader"]), case["desktop_action"])++ def test_the_shapes_the_spec_names_are_there(self):+ comments = " ".join(case["comment"] for case in V6["malformed"]["cases"]).lower()+ for word in ("1.0", "boolean", "nan", "byte order mark", "hw", "app", "caps", "platform", "name", "welcome", "ack", "accept", "refuse", "switch"):+ self.assertIn(word, comments)++ def test_a_well_formed_hello_is_accepted_so_the_refusals_mean_something(self):+ good = V6["malformed"]["well_formed_hello"]+ self.assertEqual(self.action(good["hex"], "hello"), "accepted")+++class QrTests(unittest.TestCase):+ def test_good_texts_read_to_their_fields(self):+ self.assertGreaterEqual(len(V6["qr"]["good"]), 2)+ for case in V6["qr"]["good"]:+ with self.subTest(text=case["text"]):+ read = pairing.read_qr(case["text"])+ self.assertEqual((read["host"], read["port"], read["code"], read["secret"].hex()), (case["host"], case["port"], case["code"], case["secret_hex"]))+ self.assertEqual(pairing.qr_text(case["host"], case["port"], case["code"], unhex(case["secret_hex"])), case["text"])+ self.assertEqual(len(case["text"].split("k=")[1]), 22)++ def test_bad_texts_are_refused(self):+ self.assertGreaterEqual(len(V6["qr"]["bad"]), 12)+ for case in V6["qr"]["bad"]:+ with self.subTest(case=case["comment"]):+ self.assertEqual(case["error"], "bad_qr")+ with self.assertRaises(pairing.PairingError) as raised:+ pairing.read_qr(case["text"])+ self.assertEqual(str(raised.exception), "bad_qr")+++def _wire_md_rows():+ with open(os.path.join(_REPO_ROOT, "WIRE.md"), encoding="utf-8") as handle:+ text = handle.read()+ section = text.split("### Which physical key sends which name", 1)[1].split("\n- Semantic", 1)[0]+ rows = {}+ for line in section.splitlines():+ cells = [cell.strip().strip("`") for cell in line.strip().strip("|").split("|")]+ if len(cells) == 4 and cells[0] not in ("Physical key on the sender", "---"):+ rows[cells[0]] = tuple(cells[1:])+ return rows+++class KeyTableTests(unittest.TestCase):+ def test_every_row_is_what_keytable_gives(self):+ platforms = {"mac": ("macos", "windows"), "pc": ("windows", "macos")}+ for row in V6["key_table"]["rows"]:+ with self.subTest(key=row["key"]):+ own, peer = platforms[row["sender"]]+ self.assertEqual(keytable.wire_name(row["physical"], own, own, "semantic"), row["same_family"])+ self.assertEqual(keytable.wire_name(row["physical"], own, peer, "semantic"), row["across_semantic"])+ self.assertEqual(keytable.wire_name(row["physical"], own, peer, "positional"), row["across_positional"])++ def test_the_rows_are_section_7s_table(self):+ table = _wire_md_rows()+ self.assertEqual(len(table), 12)+ self.assertEqual({row["key"] for row in V6["key_table"]["rows"]}, set(table))+ for row in V6["key_table"]["rows"]:+ with self.subTest(key=row["key"]):+ self.assertEqual((row["same_family"], row["across_semantic"], row["across_positional"]), table[row["key"]])++ def test_the_families_names_and_evdev_codes(self):+ data = V6["key_table"]+ self.assertEqual(set(data["mac_platforms"]), keytable.MAC_PLATFORMS)+ self.assertEqual(data["names"], sorted(keytable.SPEC_NAMES))+ self.assertEqual({int(code): name for code, name in data["evdev"].items()}, keytable.EVDEV_NAMES)+ self.assertEqual(data["unknown_platform_is"], "pc")+++class AckTests(unittest.TestCase):+ def test_every_case_is_the_formula_and_the_module_s_message(self):+ cases = V6["ack"]["cases"]+ self.assertTrue(any(case["sample_us"] == 0 and case["arrived_at_us"] - case["sent_at_us"] < case["held_us_on_wire"] for case in cases))+ self.assertTrue(any(case["held_us_asked"] != case["held_us_on_wire"] for case in cases))+ for case in cases:+ with self.subTest(case=case["comment"]):+ message = protocol.ack_v6(case["seq"], case["held_us_asked"])+ self.assertEqual(message, case["message"])+ self.assertEqual(message["data"]["held_us"], case["held_us_on_wire"])+ self.assertEqual(protocol.read_ack(protocol.parse_message(protocol.dumps_message(message)))["held_us"], case["held_us_on_wire"])+ self.assertEqual(max(0, case["arrived_at_us"] - case["sent_at_us"] - case["held_us_on_wire"]), case["sample_us"])+++def lv_cat(*parts):+ """The CPace draft's lv_cat with its own LEB128, not pairing.py's."""+ out = b""+ for part in parts:+ length, prefix = len(part), b""+ while True:+ prefix += bytes([(length & 0x7F) | (0x80 if length > 0x7F else 0)])+ length >>= 7+ if not length:+ break+ out += prefix + part+ return out+++def _scripted(*values):+ queue = list(values)+ return lambda length: queue.pop(0)+++class PairingV3ConstantsTests(unittest.TestCase):+ def test_the_constants_are_the_modules(self):+ constants = P3["constants"]+ self.assertEqual(constants["pairing_version"], pairing.PAIRING_V3)+ self.assertEqual(constants["pair_start_v"], pairing.PAIRING_V3)+ self.assertEqual(constants["channel_ascii"].encode("ascii"), pairing.CHANNEL_V3)+ self.assertEqual(constants["token_info_ascii"].encode("ascii"), pairing.TOKEN_INFO_V3)+ self.assertEqual(constants["done_label_ascii"].encode("ascii"), pairing.DONE_LABEL)+ self.assertEqual(constants["role_requester_ascii"].encode("ascii"), pairing.ROLE_REQUESTER)+ self.assertEqual(constants["role_host_ascii"].encode("ascii"), pairing.ROLE_HOST)+ self.assertEqual(constants["id_bytes"], pairing.ID_BYTES)+ self.assertEqual(constants["qr_secret_bytes"], pairing.QR_SECRET_BYTES)+ self.assertEqual(constants["max_peers"], pairing.MAX_PEERS)+ self.assertEqual(constants["nonce_bytes"], pairing.NONCE_BYTES)+ self.assertEqual(constants["max_name_chars"], pairing.MAX_NAME_CHARS)+ self.assertEqual(constants["tcp_port"], pairing.PAIRING_PORT)+ self.assertEqual(constants["link_key_id_info_ascii"], "beamer-key-id")+++class PairingV3ExchangeTests(unittest.TestCase):+ def test_the_three_exchanges_are_the_ones_the_spec_lists(self):+ exchanges = P3["exchanges"]+ self.assertEqual(len(exchanges), 3)+ self.assertTrue(any(any(ord(char) > 0xFFFF for char in ex["requester"]["name"]) and any(ord(char) > 0x7F for char in ex["requester"]["name"]) for ex in exchanges))+ phone = [ex for ex in exchanges if ex["requester"]["port"] == 0]+ self.assertEqual(len(phone), 1)+ self.assertEqual(phone[0]["messages"]["pair_start"]["qr"], 1)+ self.assertEqual(len(unhex(phone[0]["prs_hex"])), 22)+ self.assertEqual(len([ex for ex in exchanges if "qr" not in ex["messages"]["pair_start"]]), 2)+ for ex in exchanges:+ self.assertEqual(len(unhex(ex["requester"]["id_hex"])), 16)+ self.assertEqual(len(unhex(ex["host"]["id_hex"])), 16)++ def test_one_exchange_needs_a_two_byte_length_in_its_associated_data(self):+ long_names = [ex for ex in P3["exchanges"] if len(ex["requester"]["name"].encode("utf-8")) >= 128]+ self.assertEqual(len(long_names), 1)+ self.assertEqual(len(long_names[0]["requester"]["name"]), 48)+ self.assertGreaterEqual(len(unhex(long_names[0]["ada_hex"])), 128)++ def test_the_module_reproduces_every_exchange(self):+ for ex in P3["exchanges"]:+ with self.subTest(comment=ex["comment"]):+ stored = []+ qr_secret = unhex(ex["qr_secret_hex"]) if ex["qr_secret_hex"] else None+ host = pairing.PairingHost(+ name=ex["host"]["name"], identity=unhex(ex["host"]["id_hex"]), version=3, platform=ex["host"]["platform"], port=ex["host"]["port"],+ entropy=_scripted(unhex(ex["pair_id"]), unhex(ex["qr_secret_hex"]) if qr_secret is not None else bytes(16), unhex(ex["host"]["scalar_hex"])),+ peers=list, store=lambda entry, replaced: stored.append(entry), wall=lambda: ex["wall"],+ )+ host.begin()+ host.code = ex["code"]+ self.assertEqual(host.beacon(ex["host"]["port"]), ex["beacon"])+ client = pairing.PairingClient(+ host.pair_id, ex["code"], ex["requester"]["name"], unhex(ex["requester"]["id_hex"]),+ _scripted(unhex(ex["requester"]["nonce_hex"]), unhex(ex["requester"]["scalar_hex"])),+ version=3, platform=ex["requester"]["platform"], port=ex["requester"]["port"], qr_secret=qr_secret, wall=lambda: ex["wall"],+ )+ start = client.start()+ self.assertEqual(start, ex["messages"]["pair_start"])+ answer = host.handle(start, "10.1.2.3")+ self.assertEqual(answer, ex["messages"]["pair_answer"])+ confirm = client.accept(answer)+ self.assertEqual(confirm, ex["messages"]["pair_confirm"])+ done = host.handle(confirm, "10.1.2.3")+ self.assertEqual(done, ex["messages"]["pair_done"])+ self.assertEqual(client.finish(done), ex["token"])+ self.assertEqual(len(stored), 1)+ self.assertEqual(protocol.key_id(ex["token"]).hex(), ex["key_id_hex"])++ def test_the_formulae_by_hand(self):+ for ex in P3["exchanges"]:+ with self.subTest(comment=ex["comment"]):+ lv = lv_cat+ requester, host = ex["requester"], ex["host"]+ ada = lv(b"requester", unhex(requester["id_hex"]), requester["name"].encode("utf-8"), requester["platform"].encode("ascii"), requester["port"].to_bytes(2, "big"))+ adb = lv(b"host", unhex(host["id_hex"]), host["name"].encode("utf-8"), host["platform"].encode("ascii"), host["port"].to_bytes(2, "big"))+ self.assertEqual(ada.hex(), ex["ada_hex"])+ self.assertEqual(adb.hex(), ex["adb_hex"])+ prs = ex["code"].encode("ascii") + (unhex(ex["qr_secret_hex"]) if ex["qr_secret_hex"] else b"")+ self.assertEqual(prs.hex(), ex["prs_hex"])+ self.assertEqual(len(prs), 22 if ex["qr_secret_hex"] else 6)+ sid = lv(ex["pair_id"].encode("ascii"), unhex(requester["nonce_hex"]))+ self.assertEqual(sid.hex(), ex["sid_hex"])+ padding = bytes(127 - len(pairing._prepend_len(prs)) - len(pairing._prepend_len(b"CPace255")))+ self.assertEqual(len(padding), 95 if ex["qr_secret_hex"] else 111)+ generator_string = lv(b"CPace255", prs, padding, b"beamer-pair-v3", sid)+ self.assertEqual(generator_string.hex(), ex["generator_string_hex"])+ digest = hashlib.sha512(generator_string).digest()[:32]+ generator = pairing._elligator2(int.from_bytes(digest, "little") & ((1 << 255) - 1)).to_bytes(32, "little")+ self.assertEqual(generator.hex(), ex["generator_hex"])+ ya = crypto_scalarmult(unhex(requester["scalar_hex"]), generator)+ yb = crypto_scalarmult(unhex(host["scalar_hex"]), generator)+ self.assertEqual((ya.hex(), yb.hex()), (ex["ya_hex"], ex["yb_hex"]))+ shared = crypto_scalarmult(unhex(requester["scalar_hex"]), yb)+ self.assertEqual(shared, crypto_scalarmult(unhex(host["scalar_hex"]), ya))+ self.assertEqual(shared.hex(), ex["k_hex"])+ isk = hashlib.sha512(lv(b"CPace255_ISK", sid, shared) + lv(ya, ada) + lv(yb, adb)).digest()+ self.assertEqual(isk.hex(), ex["isk_hex"])+ mac_key = hashlib.sha512(b"CPaceMac" + sid + isk).digest()+ self.assertEqual(mac_key.hex(), ex["mac_key_hex"])+ tags = [hmac.new(mac_key, message, hashlib.sha512).digest() for message in (lv(ya, ada), lv(yb, adb), lv(b"beamer-pair-done"))]+ self.assertEqual([tag.hex() for tag in tags], [ex["ta_hex"], ex["tb_hex"], ex["td_hex"]])+ messages = ex["messages"]+ self.assertEqual([messages["pair_confirm"]["tag"], messages["pair_answer"]["tag"], messages["pair_done"]["tag"]], [pairing._b64(tag) for tag in tags])+ token = pairing._b64(hkdf(isk, sid, b"beamer-pair-token-v3"))+ self.assertEqual(token, ex["token"])+ self.assertTrue(protocol.is_paired_token(token))+++class PairingV3FailureTests(unittest.TestCase):+ def test_wrong_prs_makes_tb_fail(self):+ vector = P3["wrong_prs"]+ client = pairing.PairingClient(+ vector["pair_id"], vector["code"], vector["requester"]["name"], unhex(vector["requester"]["id_hex"]),+ _scripted(unhex(vector["requester"]["nonce_hex"]), unhex(vector["requester"]["scalar_hex"])),+ version=3, platform=vector["requester"]["platform"], port=vector["requester"]["port"], qr_secret=unhex(vector["qr_secret_hex"]),+ )+ self.assertEqual(client.start(), vector["pair_start_sent"])+ self.assertNotIn("qr", vector["pair_start_received"])+ self.assertEqual({k: v for k, v in vector["pair_start_sent"].items() if k != "qr"}, vector["pair_start_received"])+ self.assertEqual(len(unhex(vector["prs_used_by_host_hex"])), 6)+ self.assertEqual(len(unhex(vector["prs_used_by_requester_hex"])), 22)+ with self.assertRaises(pairing.PairingError) as raised:+ client.accept(vector["pair_answer"])+ self.assertEqual(str(raised.exception), pairing.ERROR_REFUSED)+ self.assertNotEqual(vector["expected_tb_hex"], vector["answer_tb_hex"])+ self.assertEqual(pairing._b64(unhex(vector["answer_tb_hex"])), vector["pair_answer"]["tag"])+ self.assertEqual(vector["requester_must"], "refused")+ self.assertEqual(client.abort(), vector["pair_confirm_abort"])+ self.assertEqual(vector["host_reply_to_abort"], {"type": "pair_done", "pair": vector["pair_id"], "ok": False, "error": "refused"})++ def test_the_host_answers_the_stripped_start_with_the_committed_answer(self):+ vector = P3["wrong_prs"]+ host = pairing.PairingHost(+ name=vector["host"]["name"], identity=unhex(vector["host"]["id_hex"]), version=3, platform=vector["host"]["platform"], port=vector["host"]["port"],+ entropy=_scripted(unhex(vector["pair_id"]), unhex(vector["qr_secret_hex"]), unhex(vector["host"]["scalar_hex"])),+ )+ host.begin()+ host.code = vector["code"]+ self.assertEqual(host.handle(vector["pair_start_received"], "10.1.2.3"), vector["pair_answer"])+ self.assertEqual(host.handle(vector["pair_confirm_abort"], "10.1.2.3"), vector["host_reply_to_abort"])++ def test_the_refused_identities_are_refused_by_the_host(self):+ refusals = P3["refusals"]+ self.assertGreaterEqual(len(refusals["cases"]), 4)+ for case in refusals["cases"]:+ with self.subTest(case=case["comment"]):+ host = pairing.PairingHost(+ name=refusals["host"]["name"], identity=unhex(refusals["host"]["id_hex"]), version=3, platform=refusals["host"]["platform"],+ port=refusals["host"]["port"], entropy=_scripted(unhex(refusals["pair_id"]), unhex(refusals["qr_secret_hex"]), unhex(refusals["host"]["scalar_hex"])),+ )+ host.begin()+ host.code = refusals["code"]+ self.assertEqual(host.handle(case["pair_start"], "10.1.2.3"), case["must_answer"])+ self.assertEqual(case["must_answer"], {"type": "pair_answer", "pair": refusals["pair_id"], "ok": False, "error": "refused"})+ self.assertIsNone(host.code)+++ def test_the_requester_refuses_a_host_id_of_the_wrong_shape(self):+ refusals = P3["refusals"]+ requester = refusals["requester"]+ self.assertGreaterEqual(len(refusals["answer_cases"]), 4)+ for case in refusals["answer_cases"]:+ with self.subTest(case=case["comment"]):+ client = pairing.PairingClient(+ refusals["pair_id"], refusals["code"], requester["name"], unhex(requester["id_hex"]),+ _scripted(unhex(requester["nonce_hex"]), unhex(requester["scalar_hex"])),+ version=3, platform=requester["platform"], port=requester["port"],+ )+ self.assertEqual(client.start(), refusals["requester_start"])+ self.assertEqual(case["requester_must"], "refused")+ with self.assertRaises(pairing.PairingError) as raised:+ client.accept(case["pair_answer"])+ self.assertEqual(str(raised.exception), pairing.ERROR_REFUSED)+++class PairingV3TcpTests(unittest.TestCase):+ def test_the_frames_are_length_then_the_datagram(self):+ tcp = P3["tcp"]+ self.assertEqual([frame["from"] for frame in tcp["frames"]], ["host", "requester", "host", "requester", "host"])+ self.assertEqual([frame["message"]["type"] for frame in tcp["frames"]], ["beacon", "pair_start", "pair_answer", "pair_confirm", "pair_done"])+ exchange = next(ex for ex in P3["exchanges"] if ex["requester"]["port"] == 0)+ self.assertEqual(tcp["exchange_comment"], exchange["comment"])+ for frame in tcp["frames"]:+ with self.subTest(type=frame["message"]["type"]):+ data = unhex(frame["bytes_hex"])+ (length,) = struct.unpack(">I", data[:4])+ self.assertTrue(0 < length <= 1024)+ self.assertEqual(length, len(data) - 4)+ self.assertEqual(data[4:], pairing.encode(frame["message"]))+ self.assertEqual(pairing.decode(data[4:]), {"beamy": 1, **frame["message"]})+ self.assertEqual(tcp["frames"][0]["message"], exchange["beacon"])+ for frame, name in zip(tcp["frames"][1:], ("pair_start", "pair_answer", "pair_confirm", "pair_done")):+ self.assertEqual(frame["message"], exchange["messages"][name])+ self.assertIn("pair", tcp["frames"][0]["message"])+ self.assertIn("id", tcp["frames"][0]["message"])++[email protected](os.path.exists(os.path.join(_TOOLS, "phone_vectors.py")), "the vector generator is not part of the public source")+class GeneratorTests(unittest.TestCase):+ OLD_SECTIONS = {+ "protocol_version": "ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d",+ "preamble": "6517d3d862d57c606e41e8011c9fda7e6433f1e44c7669bf50aaddf998f39f5b",+ "derive_key": "e316f30ab87e15ebbf371e7f97270900dcffb382c68cbae4cdd32f5e0079d620",+ "frames": "e49055d12a6cccda7c866013c2965fc7c16ce9539e53e161085e2ad7bf8c9905",+ "pairing": "05d9382f56577edd834f93b4bb5f33dcb797df8f0d483154c8318b03e57ea31e",+ "messages": "20ca870fdb61ec2f85a5a58d430e1e0e173f2712789ccda46c92ae13125259bc",+ }++ @classmethod+ def setUpClass(cls):+ spec = importlib.util.spec_from_file_location("phone_vectors", os.path.join(_TOOLS, "phone_vectors.py"))+ cls.generator = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(cls.generator)+ with open(os.path.join(_TOOLS, "phone_vectors.json"), encoding="utf-8") as handle:+ cls.text = handle.read()+ cls.vectors = json.loads(cls.text)++ def test_the_committed_file_is_what_the_generator_writes_byte_for_byte(self):+ self.assertEqual(self.generator.render(self.generator.build(self.vectors)), self.text)++ def test_the_old_sections_have_the_bytes_they_had_when_version_6_was_added(self):+ for name, digest in self.OLD_SECTIONS.items():+ with self.subTest(section=name):+ self.assertEqual(hashlib.sha256(json.dumps(self.vectors[name], indent=2).encode("utf-8")).hexdigest(), digest)++ def test_the_old_sections_are_carried_not_computed(self):+ altered = {**self.vectors, "derive_key": {"carried": "as it stands"}}+ self.assertEqual(self.generator.build(altered)["derive_key"], {"carried": "as it stands"})++ def test_the_file_has_the_new_sections_and_the_test_copy_is_them(self):+ self.assertEqual(list(self.vectors)[-2:], ["v6", "pairing_v3"])+ self.assertEqual(self.vectors["v6"], V6)+ self.assertEqual(self.vectors["pairing_v3"], P3)+ copy_path = os.path.join(_TESTS_DIR, "v6_vectors.json")+ with open(copy_path, encoding="utf-8") as handle:+ self.assertEqual(handle.read(), json.dumps({"v6": V6, "pairing_v3": P3}, indent=2) + "\n")++ def test_the_version_5_copy_the_replay_reads_is_the_file_s_own(self):+ names = ("protocol_version", "preamble", "derive_key", "frames")+ with open(os.path.join(_TESTS_DIR, "v5_vectors.json"), encoding="utf-8") as handle:+ self.assertEqual(handle.read(), json.dumps({name: self.vectors[name] for name in names}, indent=2) + "\n")++ def test_the_pairing_copy_the_version_2_tests_read_is_unchanged(self):+ with open(os.path.join(_TESTS_DIR, "pairing_vectors.json"), encoding="utf-8") as handle:+ self.assertEqual(handle.read(), json.dumps(self.vectors["pairing"], indent=2) + "\n")+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_wire_vectors.py b/core/tests/test_wire_vectors.pyindex b82ad05..28d4c69 100644--- a/core/tests/test_wire_vectors.py+++ b/core/tests/test_wire_vectors.py@@ -1,10 +1,12 @@-"""The link's crypto against the committed v5 vectors in tools/phone_vectors.json, byte for byte.+"""Wire version 5 against its committed vectors, byte for byte: core/tests/v5_vectors.json, the+version 5 sections of the vector file the phone apps are built against, copied beside the tests,+replayed through the frozen version 5 link in core/tests/v5_link.py now that no app speaks it.The vectors were written by the cryptography-backed protocol.py of 1.4.x and are never-regenerated: libsodium through PyNaCl has to reproduce them exactly, in both directions, or a-1.5 app cannot talk to a 1.4 one or to the phone apps built against the same file. Each vector is-checked twice, once through protocol.py and once through the raw primitives with no protocol.py-in the way, so a mistake in the module and a mistake in the primitives cannot cancel out.+regenerated: libsodium through PyNaCl reproduces them exactly, in both directions, so the frozen+link is the 1.4.x peer the version 6 refusal tests talk to. Each vector is checked twice, once+through the frozen link and once through the raw primitives with no protocol.py in the way, so a+mistake in the copy and a mistake in the primitives cannot cancel out.Also here: the failures are refused the way callers expect (AuthenticationError, and thecounter not spent), the pairing section's low-order shares are still refused, and no module of@@ -23,12 +25,15 @@ from nacl.bindings import crypto_aead_chacha20poly1305_ietf_decrypt, crypto_aeadfrom core import pairingfrom core import protocol+from core.tests import v5_link_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))-with open(os.path.join(_REPO_ROOT, "tools", "phone_vectors.json"), encoding="utf-8") as _handle:+with open(os.path.join(_TESTS_DIR, "v5_vectors.json"), encoding="utf-8") as _handle:VECTORS = json.load(_handle)+with open(os.path.join(_TESTS_DIR, "pairing_vectors.json"), encoding="utf-8") as _handle:+ PAIRING = json.load(_handle)def _hkdf_sha256(key_material, salt, info):@@ -48,14 +53,14 @@ def _frame_parts(frame_hex):class DeriveKeyVectorTests(unittest.TestCase):def test_the_salt_and_info_are_the_ones_in_the_file(self):vector = VECTORS["derive_key"]- self.assertEqual(vector["salt_ascii"].encode("ascii"), protocol.KEY_SALT)- self.assertEqual(vector["info_label_ascii"].encode("ascii"), protocol.KEY_INFO)- self.assertEqual(VECTORS["protocol_version"], protocol.PROTOCOL_VERSION)+ self.assertEqual(vector["salt_ascii"].encode("ascii"), v5_link.KEY_SALT)+ self.assertEqual(vector["info_label_ascii"].encode("ascii"), v5_link.KEY_INFO)+ self.assertEqual(VECTORS["protocol_version"], v5_link.PROTOCOL_VERSION)def test_the_module_derives_the_committed_key(self):vector = VECTORS["derive_key"]sender, receiver = bytes.fromhex(vector["sender_prefix_hex"]), bytes.fromhex(vector["receiver_prefix_hex"])- self.assertEqual(protocol.derive_key(vector["token"], sender, receiver).hex(), vector["key_hex"])+ self.assertEqual(v5_link.derive_key(vector["token"], sender, receiver).hex(), vector["key_hex"])def test_hmac_by_hand_derives_the_committed_key(self):vector = VECTORS["derive_key"]@@ -66,11 +71,11 @@ class DeriveKeyVectorTests(unittest.TestCase):def test_the_two_directions_have_different_keys(self):vector = VECTORS["derive_key"]sender, receiver = bytes.fromhex(vector["sender_prefix_hex"]), bytes.fromhex(vector["receiver_prefix_hex"])- self.assertNotEqual(protocol.derive_key(vector["token"], sender, receiver), protocol.derive_key(vector["token"], receiver, sender))+ self.assertNotEqual(v5_link.derive_key(vector["token"], sender, receiver), v5_link.derive_key(vector["token"], receiver, sender))def test_the_preamble_is_the_committed_one(self):vector = VECTORS["preamble"]- session = protocol.SecureSession("any token", prefix=bytes.fromhex(vector["nonce_prefix_hex"]))+ session = v5_link.SecureSession("any token", prefix=bytes.fromhex(vector["nonce_prefix_hex"]))self.assertEqual(session.preamble().hex(), vector["preamble_hex"])@@ -86,8 +91,8 @@ class FrameVectorTests(unittest.TestCase):self.assertEqual({frame["direction"] for frame in self.frames}, {"a_to_b", "b_to_a"})def _pair(self):- side_a = protocol.SecureSession(self.token, prefix=self.prefix_a)- side_b = protocol.SecureSession(self.token, prefix=self.prefix_b)+ side_a = v5_link.SecureSession(self.token, prefix=self.prefix_a)+ side_b = v5_link.SecureSession(self.token, prefix=self.prefix_b)side_a.accept_preamble(side_b.preamble())side_b.accept_preamble(side_a.preamble())return side_a, side_b@@ -115,7 +120,7 @@ class FrameVectorTests(unittest.TestCase):for frame in self.frames:with self.subTest(direction=frame["direction"], counter=frame["counter"]):sender, receiver = self._ends(frame["direction"])- key = _hkdf_sha256(self.token.encode("utf-8"), protocol.KEY_SALT, protocol.KEY_INFO + sender + receiver)+ key = _hkdf_sha256(self.token.encode("utf-8"), v5_link.KEY_SALT, v5_link.KEY_INFO + sender + receiver)counter, sealed = _frame_parts(frame["frame_hex"])self.assertEqual(struct.unpack(">I", counter)[0], frame["counter"])plaintext = json.dumps(frame["plaintext"]).encode("utf-8")@@ -159,8 +164,8 @@ class FrameVectorTests(unittest.TestCase):self.assertEqual(side_b.open(bytearray(body)), self.frames[0]["plaintext"])def test_a_frame_sealed_under_another_token_is_refused(self):- stranger = protocol.SecureSession("another token", prefix=self.prefix_a)- stranger.accept_preamble(protocol.SecureSession("another token", prefix=self.prefix_b).preamble())+ stranger = v5_link.SecureSession("another token", prefix=self.prefix_a)+ stranger.accept_preamble(v5_link.SecureSession("another token", prefix=self.prefix_b).preamble())_, side_b = self._pair()self._refused(side_b, stranger.seal(self.frames[0]["plaintext"])[protocol.HEADER_SIZE:])@@ -171,8 +176,8 @@ class FrameVectorTests(unittest.TestCase):def test_a_connection_recorded_under_other_prefixes_is_refused(self):_, side_b = self._pair()- replayer = protocol.SecureSession(self.token, prefix=self.prefix_a)- replayer.accept_preamble(protocol.SecureSession(self.token, prefix=bytes(8)).preamble())+ replayer = v5_link.SecureSession(self.token, prefix=self.prefix_a)+ replayer.accept_preamble(v5_link.SecureSession(self.token, prefix=bytes(8)).preamble())self._refused(side_b, replayer.seal(self.frames[0]["plaintext"])[protocol.HEADER_SIZE:])@@ -180,7 +185,7 @@ class PairingShareVectorTests(unittest.TestCase):"""Pairing moved to libsodium in 1.4.3; its low-order shares, from the same file."""def test_low_order_and_all_zero_shares_are_refused(self):- low = VECTORS["pairing"]["low_order_shares"]+ low = PAIRING["low_order_shares"]scalar = bytes.fromhex(low["scalar_hex"])self.assertIn(bytes(32).hex(), low["must_refuse"])for share in low["must_refuse"]:diff --git a/core/tests/v5_link.py b/core/tests/v5_link.pynew file mode 100644index 0000000..da306dc--- /dev/null+++ b/core/tests/v5_link.py@@ -0,0 +1,126 @@+"""Wire version 5, frozen: the link of Beamer 1.4.x as core/protocol.py had it before version 6+replaced it (on libsodium, which reproduces 1.4.x's bytes exactly). No app speaks it any more; it+is kept beside the tests for two jobs only, the version 5 vector replay (test_wire_vectors.py) and+an older peer to refuse (WIRE.md section 2, Versions). Never change it: it is what a 1.4.x machine+sends, not what this one does. Errors are core/protocol.py's, so callers catch the one class."""++import json+import os+import struct+import threading++from nacl.bindings import (+ crypto_aead_chacha20poly1305_ietf_ABYTES,+ crypto_aead_chacha20poly1305_ietf_decrypt,+ crypto_aead_chacha20poly1305_ietf_encrypt,+)+from nacl.exceptions import CryptoError++from core.protocol import (+ AuthenticationError,+ ProtocolError,+ VersionMismatch,+ _recv_exact,+ hkdf_sha256,+)++WIRE_MAGIC = b"BEAMY"+PROTOCOL_VERSION = 5+NONCE_PREFIX_SIZE = 8+PREAMBLE_SIZE = len(WIRE_MAGIC) + 1 + NONCE_PREFIX_SIZE+HEADER_SIZE = 4+COUNTER_SIZE = 4+MAX_COUNTER = 0xFFFFFFFF+KEY_SALT = b"beamer-link-v5"+KEY_INFO = b"beamer-frames"+++def derive_key(token: str, sender_prefix: bytes, receiver_prefix: bytes) -> bytes:+ return hkdf_sha256(token.encode("utf-8"), KEY_SALT, KEY_INFO + bytes(sender_prefix) + bytes(receiver_prefix))+++class SecureSession:+ """One version 5 connection's cipher state for both directions."""++ def __init__(self, token: str, prefix: bytes = None):+ self._token = token+ self.prefix = os.urandom(NONCE_PREFIX_SIZE) if prefix is None else bytes(prefix)+ if len(self.prefix) != NONCE_PREFIX_SIZE:+ raise ValueError("nonce prefix must be 8 bytes")+ self.send_lock = threading.RLock()+ self._send_counter = 0+ self._send_key = None+ self.peer_prefix = None+ self._recv_key = None+ self._recv_counter = 0++ def preamble(self) -> bytes:+ return WIRE_MAGIC + bytes([PROTOCOL_VERSION]) + self.prefix++ def accept_preamble(self, data: bytes) -> None:+ if len(data) != PREAMBLE_SIZE or not data.startswith(WIRE_MAGIC):+ raise VersionMismatch(None, PROTOCOL_VERSION)+ version = data[len(WIRE_MAGIC)]+ if version != PROTOCOL_VERSION:+ raise VersionMismatch(version, PROTOCOL_VERSION)+ peer_prefix = data[len(WIRE_MAGIC) + 1:]+ if self.peer_prefix is not None:+ raise ProtocolError("second preamble on one connection")+ if peer_prefix == self.prefix:+ raise ProtocolError("peer echoed this side's nonce prefix")+ with self.send_lock:+ self._send_key = derive_key(self._token, self.prefix, peer_prefix)+ self._recv_key = derive_key(self._token, peer_prefix, self.prefix)+ self.peer_prefix = bytes(peer_prefix)++ def seal(self, msg: dict) -> bytes:+ body = json.dumps(msg).encode("utf-8")+ with self.send_lock:+ if self._send_key is None:+ raise ProtocolError("nothing is sealed before the peer's preamble")+ if self._send_counter >= MAX_COUNTER:+ raise ProtocolError("frame counter exhausted; reconnect")+ self._send_counter += 1+ counter = struct.pack(">I", self._send_counter)+ ciphertext = crypto_aead_chacha20poly1305_ietf_encrypt(body, None, self.prefix + counter, self._send_key)+ return struct.pack(">I", COUNTER_SIZE + len(ciphertext)) + counter + ciphertext++ def open(self, body: bytes) -> dict:+ if self._recv_key is None:+ raise ProtocolError("frame received before the peer's preamble")+ if len(body) <= COUNTER_SIZE:+ raise ProtocolError("frame too short")+ body = bytes(memoryview(body))+ (counter,) = struct.unpack(">I", body[:COUNTER_SIZE])+ if counter != self._recv_counter + 1:+ raise ProtocolError("frame counter did not advance; replay rejected")+ sealed = body[COUNTER_SIZE:]+ if len(sealed) < crypto_aead_chacha20poly1305_ietf_ABYTES:+ raise AuthenticationError() from None+ try:+ plain = crypto_aead_chacha20poly1305_ietf_decrypt(sealed, None, self.peer_prefix + body[:COUNTER_SIZE], self._recv_key)+ except CryptoError:+ raise AuthenticationError() from None+ self._recv_counter = counter+ try:+ message = json.loads(plain.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise ProtocolError(f"malformed message body: {exc}") from exc+ if not isinstance(message, dict):+ raise ProtocolError("message body must be a JSON object")+ return message+++def recv_preamble(sock, session, deadline: float = None) -> None:+ session.accept_preamble(_recv_exact(sock, PREAMBLE_SIZE, deadline))+++def hello_msg() -> dict:+ return {"type": "hello", "data": {"version": PROTOCOL_VERSION, "settings": 1}}+++def welcome_msg(error: str = None) -> dict:+ data = {"version": PROTOCOL_VERSION, "settings": 1}+ if error is not None:+ data["error"] = error+ return {"type": "welcome", "data": data}diff --git a/core/tests/v5_vectors.json b/core/tests/v5_vectors.jsonnew file mode 100644index 0000000..8d567ac--- /dev/null+++ b/core/tests/v5_vectors.json@@ -0,0 +1,80 @@+{+ "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"+ }+ ]+ }+}diff --git a/core/tests/v6_vectors.json b/core/tests/v6_vectors.jsonnew file mode 100644index 0000000..3680df8--- /dev/null+++ b/core/tests/v6_vectors.json@@ -0,0 +1,2234 @@+{+ "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 three 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"+ },+ {+ "key": "Mac right Control",+ "sender": "mac",+ "physical": "ctrl_r",+ "same_family": "ctrl_r",+ "across_semantic": "cmd",+ "across_positional": "ctrl"+ },+ {+ "key": "Mac Command",+ "sender": "mac",+ "physical": "cmd",+ "same_family": "cmd",+ "across_semantic": "ctrl",+ "across_positional": "cmd"+ },+ {+ "key": "Mac right Command",+ "sender": "mac",+ "physical": "cmd_r",+ "same_family": "cmd_r",+ "across_semantic": "ctrl",+ "across_positional": "cmd"+ },+ {+ "key": "Mac Option",+ "sender": "mac",+ "physical": "alt",+ "same_family": "alt",+ "across_semantic": "alt",+ "across_positional": "alt"+ },+ {+ "key": "Mac right Option",+ "sender": "mac",+ "physical": "alt_r",+ "same_family": "alt_r",+ "across_semantic": "alt",+ "across_positional": "alt"+ },+ {+ "key": "PC Control",+ "sender": "pc",+ "physical": "ctrl",+ "same_family": "ctrl",+ "across_semantic": "cmd",+ "across_positional": "ctrl"+ },+ {+ "key": "PC right Control",+ "sender": "pc",+ "physical": "ctrl_r",+ "same_family": "ctrl_r",+ "across_semantic": "cmd_r",+ "across_positional": "ctrl_r"+ },+ {+ "key": "PC Windows or Super",+ "sender": "pc",+ "physical": "cmd",+ "same_family": "cmd",+ "across_semantic": "ctrl",+ "across_positional": "cmd"+ },+ {+ "key": "PC right Windows or Super",+ "sender": "pc",+ "physical": "cmd_r",+ "same_family": "cmd_r",+ "across_semantic": "ctrl_r",+ "across_positional": "cmd_r"+ },+ {+ "key": "PC Alt",+ "sender": "pc",+ "physical": "alt",+ "same_family": "alt",+ "across_semantic": "alt",+ "across_positional": "alt"+ },+ {+ "key": "PC right Alt or AltGr",+ "sender": "pc",+ "physical": "alt_r",+ "same_family": "alt_r",+ "across_semantic": "alt_r",+ "across_positional": "alt_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+ }+ }+ }+ ]+ }+ },+ "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 --git a/mac_app/Beamer Tunnel.command b/mac_app/Beamer Tunnel.commandindex 4e61fee..6c66468 100755--- a/mac_app/Beamer Tunnel.command+++ b/mac_app/Beamer Tunnel.command@@ -5,7 +5,8 @@set -u-CONFIG="$HOME/Library/Application Support/Beamer/config.json"+CONFIG="$HOME/Library/Application Support/Beamer/settings.json"+[ -r "$CONFIG" ] || CONFIG="$HOME/Library/Application Support/Beamer/config.json"HOST=""if [ -r "$CONFIG" ]; thenHOST="$(sed -n 's/.*"host": *"\([^"]*\)".*/\1/p' "$CONFIG" | head -n 1)"diff --git a/mac_app/bridge.py b/mac_app/bridge.pyindex 17592c2..a5dfad7 100644--- a/mac_app/bridge.py+++ b/mac_app/bridge.py@@ -1,10 +1,10 @@import collections+import copyimport errnoimport loggingimport platformimport queueimport socket-import structimport threadingimport timeimport types@@ -15,6 +15,7 @@ import objcimport Quartzimport clipboard_mac+import config as config_moduleimport crossingimport desktop_macfrom input_injector_mac import INJECTED_MARK@@ -22,7 +23,13 @@ import gesturesfrom core import ignoredimport keyboard_layoutimport media_keys+from core import keytable+from core import link as link_module+from core import owner as owner_module+from core import peerlistfrom core import protocol+from core import receiver+from pointer_hide import PointerHiderfrom key_codes import (KEY_NAME_TO_CODE,MODIFIER_KEY_CODES,@@ -40,81 +47,38 @@ except ImportError: # pragma: no cover - exercised only off macOSAppKit = None-ACK_TIMEOUT_SECONDS = 2.0-CONNECT_TIMEOUT_SECONDS = 1.0-AUTH_TIMEOUT_SECONDS = 2.0+CONNECT_TIMEOUT_SECONDS = link_module.CONNECT_SECONDSSOCKET_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# 49152-65535 itself, and a forward whose local port is taken never comes up.SSH_FALLBACK_PORT = 24822-PING_INTERVAL_SECONDS = 1.0DESKTOP_BOUNDS_MAX_AGE_SECONDS = 1.0CROSSING_RETRY_SECONDS = 30.0ROUND_TRIP_SAMPLES = 8ROUND_TRIP_MAX_AGE_SECONDS = 5.0-# A receiver that accepts the TCP connection but never sends a preamble is, in practice, one-# running the pre-v4 cleartext protocol: it sits waiting for a hello frame it will never get.-OLD_RECEIVER_STATUS = "Windows did not answer the handshake — it is probably running an older Beamer; update it"-AUTH_FAILED_STATUS = "Windows could not be authenticated — check the shared token matches on both sides"--# Messages that must bypass both the outbound gate (they still need to go-# out when redirecting has just turned off, e.g. the switch-back focus-# message) and sequence assignment (like ping, they carry no `seq` and are-# never recorded by the receiver's ProcessedSequence). The sentinel is a-# purely local marker -- never sent on the wire -- that the outbound worker-# expands into a real clipboard message (or drops) at send time.-CONTROL_MESSAGE_TYPES = frozenset({protocol.MSG_FOCUS, protocol.MSG_CLIPBOARD, protocol.MSG_ARRANGEMENT})+# A driven Mac that is asked to drive waits this long for its owner to let go (the responder ends+# the ownership by force after one second), then goes ahead.+LET_GO_WAIT_SECONDS = 1.3+OWN_PLATFORM = "macos"+CAPABILITIES = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings")+MEDIA_KEY_NAMES = frozenset({"volume_mute", "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause"})++# The local sentinel a clipboard read is deferred with: the event tap must never wait on the+# pasteboard, so it queues this and the outbound worker reads it, in order with the input behind it._LOCAL_CLIPBOARD_SENTINEL_TYPE = "_local_clipboard"-_GATE_EXEMPT_TYPES = CONTROL_MESSAGE_TYPES | {_LOCAL_CLIPBOARD_SENTINEL_TYPE}---class _HandshakeError(protocol.ProtocolError):- """Raised for a handshake that completed but was rejected; carries the- exact user-facing status so the generic OSError/ProtocolError handler- doesn't wrap it with a less specific message."""-- def __init__(self, status):- super().__init__(status)- self.status = status---def connection_error_message(exc):- error_number = getattr(exc, "errno", None)- if error_number in {51, 64, 65}:- if "Beamer Tunnel.command" in str(exc):- return "macOS 27 blocked direct LAN access. Open /Applications/Beamer Tunnel.command."- return "Windows is unreachable from this Mac. Check that both devices can communicate on the local network."- if error_number == 61:- return "Windows is reachable, but Beamer is not listening on this port."- if isinstance(exc, (socket.timeout, TimeoutError)):- return "Windows did not answer before the connection timed out."- return f"Connection failed: {exc}"---class FrameDecoder:- """Reassembles and opens frames from the raw chunks the reader thread- receives. One per connection, like the session it opens frames with."""-- def __init__(self, session):- self.session = session- self.buffer = bytearray()-- def feed(self, chunk):- self.buffer.extend(chunk)- messages = []- while len(self.buffer) >= protocol.HEADER_SIZE:- length = struct.unpack_from(">I", self.buffer)[0]- if length < 1 or length > protocol.MAX_FRAME_BYTES:- raise protocol.ProtocolError(f"invalid message length: {length}")- frame_length = protocol.HEADER_SIZE + length- if len(self.buffer) < frame_length:- break- body = bytes(self.buffer[protocol.HEADER_SIZE:frame_length])- del self.buffer[:frame_length]- messages.append(self.session.open(body))- return messages++# Why input came home, in words, for the alert. A why that is not here comes home quietly.+WHY_TEXT = {+ "owned": "{name} is being driven from another machine",+ "not_allowed": "{name} does not accept input from this Mac",+ "busy": "{name} is driving another machine",+ "malformed": "{name} could not read the request to take it",+ "refused": "{name} refused the input",+ "no_answer": "{name} did not answer",+ "link_lost": "Lost the link to {name}",+}# NX device-specific modifier bits (IOLLEvent.h), keyed by keycode. Unlike the@@ -448,7 +412,84 @@ def _default_system_event_converter(cg_event):return int(ns_event.subtype()), int(ns_event.data1())+def links_from_store(settings_store, app_version):+ """The book and the identity the links run on, from the settings store; (None, None) when the+ settings cannot be read, so the controller starts from the defaults instead of failing."""+ try:+ settings_store.current()+ except Exception:+ logging.getLogger("Beamer").exception("the links start from the defaults, as the settings could not be read")+ return None, None++ def identity():+ settings = settings_store.current()+ name = (settings.get("name") or socket.gethostname().split(".")[0] or "Mac")[:48]+ return {"id": protocol.read_id(settings["machine_id"]), "name": name, "platform": OWN_PLATFORM, "app": app_version,+ "caps": list(CAPABILITIES), "port": settings["port"]}++ return settings_store.book(), identity+++class _Literal(dict):+ """A message whose key names are the receiver's own words already, which the key table must+ leave alone: the gestures press the PC's Control for a zoom, and that is Control there."""+++def _literal(messages):+ return [_Literal(message) for message in messages]+++class _MemoryBook(receiver.PeerBook):+ """The peers a controller built from a Config alone has: peers[0] from the flat fields, nothing+ on disk. The app hands in the settings store's book instead; this is what the controller has+ when it is given none, and what keeps `KVMController(cfg)` working for a caller with no store."""++ def __init__(self, cfg):+ self.data = {"schema": 6, "machine_id": protocol.id_text(_random_id()), "peers": [], "zones": []}+ super().__init__(lambda: self.data, self._store)+ self.follow(cfg)++ def _store(self, data):+ self.data = copy.deepcopy(data)++ def follow(self, cfg):+ """Keep peers[0] in step with the flat Config the app still speaks."""+ with self.lock:+ peers = self.data["peers"]+ if not cfg.auth_token:+ peers.clear()+ return+ entry = peers[0] if peers and peers[0].get("token") == cfg.auth_token else None+ if entry is None:+ entry = {+ "id": "", "name": "", "platform": "windows", "token": cfg.auth_token, "host": "", "port": 0, "hw": "",+ "send": True, "allow_drive": True, "side": "", "side_set_at": 0, "side_by": "", "paired_with": [],+ "paired_at": 0, "linked": False, "from_1_4": True,+ }+ peers[:1] = [entry]+ entry.update(host=cfg.host, port=cfg.port, name=cfg.pc_name or entry["name"], hw=cfg.mac_address,+ send=cfg.send_to_windows, allow_drive=cfg.allow_windows_to_drive)+++def _random_id():+ import secrets+ while True:+ data = secrets.token_bytes(protocol.MACHINE_ID_SIZE)+ if any(data):+ return data++class KVMController:+ @property+ def redirecting(self):+ return self._redirecting++ @redirecting.setter+ def redirecting(self, value):+ self._redirecting = bool(value)+ if not self._redirecting:+ self.pointer.show()+def __init__(self,cfg,@@ -462,6 +503,10 @@ class KVMController:dock_event_reader=None,macos_major=None,desktop_bounds=None,+ book=None,+ identity=None,+ link_factory=link_module.OutboundLink,+ hardware=None,):self.cfg = cfgself.logger = logger or logging.getLogger("Beamer")@@ -485,58 +530,39 @@ class KVMController:# back to this point on every captured mouse move/drag while# redirecting. None whenever not redirecting.self.cursor_pin_point = None+ # Hidden for as long as input is on the other machine. Made before `redirecting`, whose+ # setter shows it: input being local is the one condition under which it is never hidden.+ self.pointer = PointerHider(quartz, logger=self.logger)self._cursor_assoc_status_logged = Falseself._cursor_warp_error_logged = Falseself.redirecting = False- # True while the PC is driving this Mac over the other link. The tap- # passes everything through while it is, except this Mac's own trigger- # key, so the two directions can never both own the keyboard. Set by- # the app that owns both halves, which also hands in `send_peer_home`:- # the receiver's way of sending the PC's input back to it.+ # True while another machine is driving this Mac over a link it opened. The tap passes+ # everything through while it is, except this Mac's own trigger key, so the two directions+ # can never both own the keyboard. Set by the app that owns both halves, which also hands+ # in `send_peer_home`: the responder's way of sending its owner back.self.receiving = False+ self.driver = None # the id text of the machine driving this Mac, set by the appself.send_peer_home = None+ # The responder, once WindowsInput has made it: `driven` is how a take it is deciding is+ # seen from here (WIRE.md section 4, "a machine never drives and is driven at once").+ self.responder = Noneself.stop_event = threading.Event()self.outbound = queue.Queue(maxsize=OUTBOUND_QUEUE_SIZE)- self.socket_lock = threading.RLock()- self.sequence_lock = threading.Lock()- self.sock = None- # Replaced by every _connect_once, so each connection gets a fresh nonce prefix and- # counters that start from zero. Sealing happens on the outbound, watchdog and reader- # threads only -- the event tap enqueues and never touches it.- self.session = protocol.SecureSession(cfg.auth_token)- 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.redirect_started_at = 0.0self.on_user_alert = None- # Set by the app: called when Windows says the two machines have moved- # in relation to each other.+ # The peer's arrangement (mac_edge, set_at, by), its settings (data, peer id) and its+ # `paired` list (peer id, ids), handed to the app, which owns the settings file.self.on_arrangement = None- # Same on both machines, as the receiver's: `on_settings(data)` for each settings message- # from Windows, `announce()` for what to send the moment the link is up, `peer_settings`- # whether Windows's welcome said it keeps settings in step.self.on_settings = None+ self.on_paired = None+ # What to send a peer the moment its link is up: the app's own messages, of which only the+ # settings state goes on to a peer that keeps it (the arrangement and `paired` are made here).self.announce = lambda: []- self.peer_settings = Noneself.threads = []self.started = Falseself.capture_lock = threading.Lock()self.capture_thread = Noneself.input_error = None- self.connection_status = "Waiting to connect"- # The host, port and token that last completed a handshake. Silence after the preamble- # from a PC that has answered this run is a PC too busy to answer (Windows stalls every- # app for half a minute while it reconfigures its displays), not an older Beamer. The- # token is part of it so a re-pair, even to another PC at the same address, starts clean.- self.answered = None- # Set while Windows reports it is clearing its lock screen. Beamer- # cannot type on the secure desktop, so Windows unlocks first and- # drops input meanwhile; without this the switch just looks dead for- # the few seconds that takes.- self.windows_locked = False- self._status_before_unlock = None+ self._connection_status = "Waiting to connect"self.tap_ready = threading.Event()self.event_tap = Noneself.tap_source = None@@ -546,6 +572,7 @@ class KVMController:self.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]self.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@@ -553,12 +580,12 @@ class KVMController:# cached because they are read on every local mouse move. The notch# range needs NSScreen, so the app measures it on the main thread and# assigns it here. on_crossing is fed (kind, step) off the tap and- # ack threads for haptics and the glow; the app marshals it.+ # link threads for haptics and the glow; the app marshals it.# A PC whose address changed, after a router restart hands it a new lease, still beacons- # under its name. With `discovery` set, a failed connect tries the address the paired PC's- # name is heard at, and only once that address has passed the authenticated handshake does- # it become cfg.host and reach `on_host_learned(host)` on the connection thread, for the app- # to save. A spoofed beacon costs one failed attempt and changes nothing.+ # under its name. With `discovery` set (anything with `pcs()` or `machines()` giving dicts+ # of `name` and `address`), a link down for ten seconds tries the address its peer's name+ # is heard at, and only once that address has passed the authenticated handshake is it+ # saved (by the link, through the book) and `on_host_learned(host)` called for the app.self.discovery = Noneself.on_host_learned = Noneself.crossing = crossing.CrossingEngine.from_config(cfg.crossing)@@ -577,11 +604,112 @@ class KVMController:# while it is full screen, measured by the app on the main thread like notch_range.self.crossing_paused = Falseself._full_screen_app = None- # Round trip: (seq, sent at) for every input event still unacknowledged, oldest first,- # and the last few measured trips. Both under sequence_lock.- self._unacked_sent_at = collections.deque()- self._round_trips = collections.deque(maxlen=ROUND_TRIP_SAMPLES)- self._round_trip_at = 0.0+ # The links: one outbound link per peer with `send` on, and the owner (WIRE.md sections 4+ # and 5) that decides where this Mac's input is. Every call into the owner is made under+ # `_owner_lock`; what a call asks for locally (the pointer, an alert) is done under+ # `_effects_lock`, taken before the owner's is let go so it runs in the order it was decided.+ self._memory = None+ if book is None:+ self._memory = book = _MemoryBook(cfg)+ self.book = book+ self._identity_fn = identity+ self._hardware = hardware # host: this Mac's hardware address on the interface towards it+ self.link_factory = link_factory+ self.links = {} # token: OutboundLink+ self._peers_up = {} # peer id: link, while its handshake is done+ self._up_names = {}+ self._accepts = {} # peer id: whether it lets this Mac drive it+ self._primary_token = None+ self._primary_link = None+ self._links_lock = threading.RLock()+ # Whoever assigns `cfg` or builds a copy of it from the current one: a link thread learning+ # an address must not put back a settings change the main thread made meanwhile.+ self._cfg_lock = threading.Lock()+ self._owner_lock = threading.RLock()+ self._effects_lock = threading.RLock()+ self.owner = owner_module.Owner(protocol.id_text(self.identity()["id"]), clock, resistance_px=int(self.crossing.resistance_px))+ self._clipboard_stamp = None+ self._paired_ids = ()+ self._go_generation = 0+ self._home_notify = True+ self._home_presses = set()+ self._letting_go = False+ self._sync_links()++ # The machine, as its links say it++ def identity(self):+ """This machine as a `hello` says it: the app's, or a synthetic one for a controller made+ from a Config alone."""+ if self._identity_fn is not None:+ return self._identity_fn()+ settings = self.book._load() or {}+ ident = protocol.read_id(settings.get("machine_id")) or _random_id()+ return {"id": ident, "name": socket.gethostname().split(".")[0] or "Mac", "platform": OWN_PLATFORM,+ "app": "1.5.0", "caps": list(CAPABILITIES), "port": self.cfg.port}++ @property+ def own_port(self):+ """The port this Mac listens on and announces: its own setting, never a machine's."""+ return int(self.identity()["port"])++ @property+ def peer_label(self):+ """The first machine as the window shows it (its name, with the end of its id where two+ share one); None when nothing is paired."""+ return self._label(lambda peer: peer.get("token") == self._primary_token)++ @property+ def on_label(self):+ """The machine this Mac's input is on, or None at home."""+ on = self.owner.on+ return self._label(lambda peer: on is not None and peer.get("id") == on)++ @property+ def driver_label(self):+ """The machine driving this Mac, or None."""+ driver = self.driver+ return self._label(lambda peer: driver is not None and peer.get("id") == driver)++ def _label(self, wanted):+ peers = self.book.peers()+ labels = peerlist.labels(peers)+ return next((labels[peer["token"]] for peer in peers if wanted(peer)), None)++ @property+ def connection_status(self):+ link = self._primary_link+ if link is not None and link.peer_locked:+ return f"Unlocking {self.peer_label or 'the other machine'}…"+ return self._connection_status++ @connection_status.setter+ def connection_status(self, value):+ self._connection_status = value++ @property+ def status_kind(self):+ """What the primary link last did, as core.link.OutboundLink.kind says it."""+ link = self._primary_link+ return link.kind if link is not None else "none"++ @property+ def via_tunnel(self):+ link = self._primary_link+ return bool(link is not None and link.via_tunnel and link.live())++ @property+ def windows_locked(self):+ link = self._primary_link+ return bool(link is not None and link.peer_locked)++ @property+ def peer_settings(self):+ """Whether the primary peer keeps Same on all machines, None while there is no link."""+ link = self._primary_link+ if link is None or not link.live():+ return None+ return "settings" in link.caps@propertydef full_screen_app(self):@@ -597,8 +725,8 @@ class KVMController:@propertydef connected(self):- with self.socket_lock:- return self.sock is not None+ link = self._primary_link+ return link is not None and link.live()@propertydef input_ready(self):@@ -607,16 +735,17 @@ class KVMController:@propertydef round_trip_ms(self):"""The smoothed input round trip, or None whenever a figure would not be honest: input- is not on Windows, the link is down, or nothing fresh has been acknowledged for a few- seconds. The upper median of the last few trips, so an even count rounds towards the- slower one. The receiver acknowledges on a timer rather than per event, so each trip- includes however long the last event waited for that timer -- pessimistic by design."""+ is not on another machine, the link is down, or nothing fresh has been acknowledged for a+ few seconds. The upper median of the last few trips, so an even count rounds towards the+ slower one. The responder holds each `ack` for however long it waited to batch it and says+ so (`held_us`), which the link has already taken off."""if not self.redirecting or not self.connected:return None- with self.sequence_lock:- trips = sorted(self._round_trips)- measured_at = self._round_trip_at- if not trips or self.clock() - measured_at > ROUND_TRIP_MAX_AGE_SECONDS:+ link = self._peers_up.get(self.owner.on) or self._primary_link+ if link is None:+ return None+ trips = sorted(link.round_trips(ROUND_TRIP_MAX_AGE_SECONDS)[-ROUND_TRIP_SAMPLES:])+ if not trips:return Nonereturn int(round(trips[len(trips) // 2] * 1000))@@ -627,8 +756,6 @@ class KVMController:workers = (("connection", self._connection_worker),("outbound", self._outbound_worker),- ("ack-receiver", self._ack_worker),- ("ack-watchdog", self._watchdog_worker),)for name, target in workers:thread = threading.Thread(@@ -639,6 +766,8 @@ class KVMController:)self.threads.append(thread)thread.start()+ for link in list(self.links.values()):+ link.start()def start_input_capture(self):"""Spawn the event-tap thread and return immediately. This must never@@ -676,8 +805,11 @@ class KVMController:def stop(self):self._return_local()+ for link in list(self.links.values()):+ link.flush(0.3)self.stop_event.set()- self._drop_connection()+ for link in list(self.links.values()):+ link.stop()run_loop = self.tap_run_loopif run_loop is not None:try:@@ -690,7 +822,8 @@ class KVMController:def update_config(self, cfg):self._return_local()- self.cfg = cfg+ with self._cfg_lock:+ self.cfg = cfgself.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]self.last_trigger_down = 0.0self.trigger_suppressed = False@@ -700,8 +833,16 @@ class KVMController:self.ignore_gate.configure(cfg.ignored_inputs)self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)self._crossing_failed = False- self._drop_connection()+ if self._memory is not None:+ self._memory.follow(cfg)self._drain_outbound()+ self._sync_links()+ # A link made to an address that is no longer the saved one goes, and comes back to the new.+ for link in list(self.links.values()):+ entry = link.entry()+ if link.live() and entry is not None and link.dialled != (entry.get("host"), entry.get("port")):+ link.drop("Settings saved; reconnecting")+ link.refresh()self.connection_status = "Settings saved; reconnecting"self.logger.info("settings updated; redirect mode returned to local")@@ -711,74 +852,36 @@ class KVMController:window 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+ with self._cfg_lock:+ self.cfg = cfgedge = 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+ # here is a change for the other machine 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))self.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]self.ignore_gate.configure(cfg.ignored_inputs)self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)self._crossing_failed = False+ if self._memory is not None:+ self._memory.follow(cfg)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.-- 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."""+ """`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.++ 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 not value:+ self._go_generation += 1if value == self.redirecting: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+ return self._redirect(edge, offset)self._return_local()self.logger.info("input returned to this Mac")if came_home:@@ -787,31 +890,101 @@ class KVMController:self._notify_crossing("home", crossing.Step(pin=(pin[0], pin[1])))return True+ def _redirect(self, edge, offset):+ link = self._primary_link+ if not self.connected or not link.peer_id:+ self.logger.warning("cannot redirect: the other machine is not connected")+ self._alert("Beamer", f"Cannot switch — {self.connection_status}")+ return False+ if self.receiving:+ # Driven, so this Mac sends its owner home first and drives once the owner has let go+ # (the responder ends it by force after a second): a machine never does both.+ send_home = self.send_peer_home+ if send_home is not None and send_home():+ self._go_after_let_go(edge, offset)+ return True+ self.logger.warning("cannot redirect: another machine 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 the other machine is switched off")+ return False+ self.redirect_started_at = self.clock()+ self._note_clipboard()+ peer = link.peer_id+ self._step(lambda owner: owner.go(peer, edge, offset))+ if not self.redirecting:+ return False+ responder = self.responder+ if responder is not None and responder.driven:+ # A take on this Mac was being decided as this Mac's own began: it won the race, so+ # this Mac's input goes home (WIRE.md section 4, "a machine never drives and is driven at once").+ self.logger.warning("another machine took this Mac as it began to drive; input comes home")+ self._return_local()+ return False+ return True++ def _go_after_let_go(self, edge, offset, step=None):+ if self._letting_go:+ return+ self._letting_go = True+ generation = self._go_generation++ def wait_then_go():+ try:+ end = time.monotonic() + LET_GO_WAIT_SECONDS+ while self.receiving and not self.stop_event.is_set() and time.monotonic() < end:+ self.stop_event.wait(0.02)+ if generation != self._go_generation:+ return+ if self.receiving or self.stop_event.is_set():+ self.logger.warning("the machine driving this Mac did not let go; the move is dropped")+ return+ if self.set_redirecting(True, edge, offset) and step is not None:+ self._notify_crossing("cross", step)+ finally:+ self._letting_go = False++ threading.Thread(target=wait_then_go, name="Beamer-let-go", daemon=True).start()+def _return_local(self):"""Every way input comes back to this Mac ends here: the switch home,a dropped link, a crashed worker, a disabled tap, a settings change.The cursor association is the part that must not be skipped -- apath that only cleared `redirecting` left the pointer decoupled from- the hand, frozen on screen while the keyboard already worked. Windows- is told too, while the link is up: it keeps treating this Mac as+ the hand, frozen on screen while the keyboard already worked. The machine the+ input was on is told too, while its link is up: it keeps treating this Mac asdriving, with whatever keys it was holding still down, until it hears- otherwise. On a dead link the receiver hands back by itself."""- was_redirecting = self.redirecting+ otherwise. On a dead link the responder hands back by itself."""+ effects = []+ taken = False+ try:+ with self._owner_lock:+ effects = self._execute(self.owner.go(None) if self.owner.away else [])+ self._effects_lock.acquire()+ taken = True+ except Exception:+ self.logger.exception("telling the other machine its input is home failed")+ if not taken:+ self._effects_lock.acquire()+ try:+ self._apply_effects(effects)+ finally:+ try:+ self._local_cleanup()+ finally:+ self._effects_lock.release()++ def _local_cleanup(self):self.redirecting = Falseself._set_cursor_follows_mouse(True)self.cursor_pin_point = Noneself.translator.reset_mouse_accumulators()self.ignore_gate.reset()self.crossing.reset()- self._forget_round_trips()- if was_redirecting:- # Queued after redirecting has already flipped False: only reaches- # the wire because the outbound gate exempts control messages.- self._enqueue_control(protocol.focus_msg("mac"))def set_receiving(self, value):- """The PC has taken input on this Mac, or given it back. Input is- returned to this Mac's own hardware first: whatever the PC is about to+ """Another machine has taken input on this Mac, or given it back. Input is+ returned to this Mac's own hardware first: whatever the owner is about todo with the pointer, it must not read as a push against the edge."""value = bool(value)if value == self.receiving:@@ -822,10 +995,8 @@ class KVMController:self.crossing.reset()def _enqueue_control(self, message):- """Enqueue a control message (focus, or the local-clipboard sentinel)- from set_redirecting, which runs on the event-tap thread rather than- the outbound worker. Best-effort: a momentarily full queue drops the- message (logged) instead of blocking the tap thread."""+ """Queue a local control message (the clipboard sentinel) from the event tap, which must+ never block. Best-effort: a momentarily full queue drops it (logged)."""try:self.outbound.put_nowait(message)except queue.Full:@@ -1006,7 +1177,7 @@ class KVMController:and not self._was_injected(event)and self.quartz.CGEventGetIntegerValueField(event, self.quartz.kCGKeyboardEventKeycode) == self.trigger_code):- result = self.translator.key_result(event_type, event, self.trigger_code, self.cfg.key_map)+ result = self.translator.key_result(event_type, event, self.trigger_code, {})if result.is_trigger:return self._handle_trigger(result, event)# And this Mac's own pointer, which can push through the edge to take it back@@ -1038,10 +1209,12 @@ class KVMController:event_type,event,self.trigger_code,- self.cfg.key_map,+ {},)if result.is_trigger:return self._handle_trigger(result, event)+ had = len(result.messages)+ result.messages = self._after_home_presses(result.messages)if self.redirecting:keycode = self.quartz.CGEventGetIntegerValueField(event, self.quartz.kCGKeyboardEventKeycode)entry = ignored.key(keycode)@@ -1054,10 +1227,25 @@ class KVMController:if kept: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:+ 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._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)@@ -1066,6 +1254,8 @@ class KVMController:# rather than being swallowed and reaching neither.return eventif not self.redirecting:+ for message in messages:+ self._enqueue_control(message)return eventfor message in messages:try:@@ -1083,6 +1273,36 @@ class KVMController:self.logger.exception("event-tap callback failed; input forced local")return event+ def _after_home_presses(self, messages):+ """A press made while the input was home is released at home: at home its key is noted,+ and once the input has left, the release of a noted key is taken out of what is sent+ (WIRE.md section 4, "a key or button pressed on the owner while its input was at home is+ released at home")."""+ if not self.redirecting:+ # What comes back is the releases of keys that were not pressed here: pressed while the+ # input was away, they are the owner's to match against what it swallows.+ unmatched = []+ for message in messages:+ ident = ("key", message["data"]["key"])+ if message["type"] == protocol.MSG_KEYDOWN:+ self._home_presses.add(ident)+ elif ident in self._home_presses:+ self._home_presses.discard(ident)+ else:+ unmatched.append(message)+ return unmatched+ kept = []+ for message in messages:+ ident = ("key", message["data"].get("key"))+ if message["type"] == protocol.MSG_KEYUP and ident in self._home_presses:+ self._home_presses.discard(ident)+ continue+ if message["type"] == protocol.MSG_KEYDOWN:+ # Pressed now, with the input away: any earlier press of it at home is over.+ self._home_presses.discard(ident)+ kept.append(message)+ return kept+def _was_injected(self, event):"""Whether this event carries the mark input_injector_mac stamps intoevery event it posts. Never raises: an event whose source cannot be@@ -1145,14 +1365,15 @@ class KVMController:return eventif step.crossed:if self.receiving:- # The PC is driving this Mac and this Mac's own pointer pushed through: the PC's- # input goes home first, over its own link, and this Mac's follows it across. The- # PC's focus home clears receiving here too, later, and finds it already clear.+ # Another machine is driving this Mac and this Mac's own pointer pushed through:+ # that machine's input goes home first, and this Mac's follows it across once it+ # has let go (WIRE.md section 4).send_home = self.send_peer_homeif send_home is None or not send_home():- self.logger.warning("cannot cross: Windows is driving this Mac and cannot be reached")+ self.logger.warning("cannot cross: another machine is driving this Mac and cannot be reached")return event- self.receiving = False+ self._go_after_let_go(step.edge, step.offset, step)+ return eventif self.set_redirecting(True, edge=step.edge, offset=step.offset):self._notify_crossing("cross", step)return None@@ -1224,33 +1445,6 @@ class KVMController:against after the last mouse event."""return self.crossing.pressure_at(self.clock())- def _handle_switch(self, data):- """Windows asked for input back, having pushed through its return- edge. Stop redirecting first, then land the pointer where it left- Windows: `edge` is the Mac edge to arrive at and `offset` the fraction- along it. A malformed or unknown request is ignored; a switch that- arrives while already local still gets the haptic, since the pointer- genuinely came home."""- if not isinstance(data, dict) or data.get("target") != "mac":- return- edge = data.get("edge")- offset = data.get("offset")- crossed = edge in crossing.EDGES and isinstance(offset, (int, float)) and not isinstance(offset, bool)- # Without an edge the PC sent this Mac's input home by its own switch: that is a switch- # arriving here, and shows where the pointer is.- self.set_redirecting(False, came_home=not crossed)- 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 _handle_system_event(self, event):"""Forward a media/volume key press. Anything that is not one --brightness, keyboard backlight, and the undocumented subtypes that@@ -1272,7 +1466,7 @@ class KVMController:if self.ignore_gate.keeps(ignored.media(name), is_down):return eventmessage_type = protocol.MSG_KEYDOWN if is_down else protocol.MSG_KEYUP- wire_name = self.cfg.key_map.get(name, name)+ wire_name = nametry:self.outbound.put_nowait({"type": message_type, "data": {"key": wire_name}})except queue.Full:@@ -1298,12 +1492,12 @@ class KVMController:# would open Mission Control or switch Spaces on the Mac while# the user is looking at Windows.fields = self._read_dock_event(event)- messages = self.dock_classifier.translate(fields) if fields is not None else []+ messages = _literal(self.dock_classifier.translate(fields) if fields is not None else [])else:gesture_view = self._convert_gesture_event(event)if gesture_view is None:return event- messages = self.gesture_translator.translate(event_type, gesture_view)+ messages = _literal(self.gesture_translator.translate(event_type, gesture_view))if not self._gesture_capture_logged:self._gesture_capture_logged = Trueself.logger.info("gesture capture active")@@ -1337,7 +1531,7 @@ class KVMController:self._overlay_gesture_capture_logged = Trueself.logger.info("gesture capture active (overlay)")try:- messages = self.gesture_translator.translate(event_type, gesture_view)+ messages = _literal(self.gesture_translator.translate(event_type, gesture_view))except Exception:self.logger.exception("overlay gesture translation failed")return@@ -1404,163 +1598,77 @@ class KVMController: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()+ wanted = {peer["token"] for peer in peers if peer.get("token") and peer.get("send") is True}+ first = peers[0].get("token") if peers else 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, notice=self._notify_user,+ 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()+ 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._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)- self.peer_settings = protocol.keeps_settings(welcome_data)- 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)- try:- announcements = list(self.announce())- except Exception:- self.logger.exception("announce failed")- announcements = []- for announcement in announcements:- self._send_raw(announcement)- return True+ machines = list(discovery.pcs())+ for link in list(self.links.values()):+ link.follow(machines)def _connect_via_ssh_fallback(self):try:@@ -1574,50 +1682,325 @@ class KVMController:"Open /Applications/Beamer Tunnel.command",) from exc- def _outbound_worker(self):- while not self.stop_event.is_set():+ def _notify_user(self, text):+ self.logger.info("%s", text)+ self._alert("Beamer", text)++ 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._step(lambda owner: owner.link_down(peer))+ return+ self.logger.info("connected to %s", fields["name"])+ self._announce_to(link, fields)+ if link.token == self._primary_token:+ self._primary_up(link, fields)++ 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))+ 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 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("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):+ """The peer changed which edge of its screen faces this one. Handed to the app, which owns+ the settings file, as the edge of THIS Mac that leads to the peer; nothing is applied here.+ The app's flat settings hold the first peer's side only, so another's is not applied."""+ read = protocol.read_arrangement_v6(message, time.time())+ if read is None or self.on_arrangement is None:+ return+ peers = self.book.peers()+ if not peers or peers[0].get("id") != peer:+ self.logger.info("an arrangement from a peer other than the first is not applied yet")+ return+ self.on_arrangement(crossing.OPPOSITE[read["edge"]], read["set_at"], protocol.id_text(read["by"]))++ def send_arrangement(self, mac_edge, set_at):+ """Tell the primary peer which edge of this Mac faces it, when the change was made here.+ Sent straight out: it is not input, and it goes whether or not input is redirected."""+ link = self._primary_link+ if link is None or not link.live():+ return False+ return link.post(protocol.arrangement_v6(mac_edge, int(set_at), bytes(self.identity()["id"])))++ 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)):+ effects.append(action)continuetry:- self._process_outbound(message)+ if isinstance(action, owner_module.Send):+ self._deliver(action)+ elif isinstance(action, owner_module.SendClipboard):+ if threading.current_thread() is self.capture_thread:+ self._enqueue_control({"type": _LOCAL_CLIPBOARD_SENTINEL_TYPE, "data": {}, "peer": action.peer})+ else:+ self._send_clipboard(action.peer)+ else:+ self._set_clipboard(action.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()-- 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:+ # 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, send):+ link = self._peers_up.get(send.peer)+ if link is None:return- if message_type == _LOCAL_CLIPBOARD_SENTINEL_TYPE:- self._send_local_clipboard()+ message = send.message+ 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) or isinstance(message, _Literal):+ 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())+ return {"type": message["type"], "data": data}++ def _on_moved(self, moved):+ if moved.to is not None:+ 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.logger.info("redirecting input to %s", self._name_of(moved.to))return- if message_type in CONTROL_MESSAGE_TYPES:- self._send_raw(message)+ self._local_cleanup()+ why = WHY_TEXT.get(moved.why)+ if why is not None:+ text = why.format(name=self._name_of(moved.left))+ 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"+ 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):+ """Read this Mac's clipboard and send it as a clipboard message. 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 nothing is sent."""+ 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()+ text, image = self.clipboard.get_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 = None@@ -1629,277 +2012,77 @@ class KVMController:)image = Noneif not text and image is None:- self.logger.debug("local clipboard is empty or unchanged since the last sync; not sending it")+ self.logger.debug("local clipboard is empty; not sending it")return- self._send_raw(protocol.clipboard_msg(text or None, image))-- def _prepare_outbound(self, message):- with self.sequence_lock:- self.last_sent_seq += 1- seq = self.last_sent_seq- data = dict(message.get("data", {}))- data["seq"] = seq- return {"type": message["type"], "data": data}+ link.post(protocol.clipboard_msg(text or None, image))- def _send_prepared(self, message):- with self.socket_lock:- sock = self.sock- if sock is None:- self._connection_failed("connection disappeared before an input event could be sent")- return False- try:- protocol.send_msg(sock, self.session, message)- self.last_send_at = self.clock()- except (OSError, protocol.ProtocolError) as exc:- self._connection_failed(f"send failed: {exc}", expected_socket=sock)- return False- with self.sequence_lock:- self._unacked_sent_at.append((message["data"]["seq"], self.last_send_at))- return True-- def _send_raw(self, message):- """Serialize and send `message` directly under socket_lock, bypassing- the outbound queue and its redirecting gate. Used for the idle- heartbeat ping, which must go out whether or not input is redirected."""- with self.socket_lock:- sock = self.sock- if sock is None:- return False- try:- protocol.send_msg(sock, self.session, message)- self.last_send_at = self.clock()- return True- except (OSError, protocol.ProtocolError) as exc:- self._connection_failed(f"send failed: {exc}", expected_socket=sock)- return False+ def _set_clipboard(self, message):+ read = protocol.read_clipboard(message)+ if read is None or (read["text"] is None and read["image"] is None):+ return+ if not self.clipboard.set_contents(read["text"], read["image"]):+ self.logger.warning("failed to set the local clipboard from an inbound message")+ self._clipboard_stamp = self._clipboard_stamp_now()++ # The outbound worker- def _ack_worker(self):- active_socket = None- decoder = None+ def _outbound_worker(self):while not self.stop_event.is_set():- with self.socket_lock:- sock = self.sock- session = self.session- if sock is None:- active_socket = None- decoder = None- self.stop_event.wait(0.1)- continue- if sock is not active_socket:- active_socket = sock- decoder = FrameDecoder(session)+ message = Nonetry:- chunk = sock.recv(4096)- except socket.timeout:- continue- except OSError as exc:- self._connection_failed(f"ACK receive failed: {exc}", expected_socket=sock)- active_socket = None- continue- if not chunk:- self._connection_failed("Windows closed the connection", expected_socket=sock)- active_socket = None- continue- try:- messages = decoder.feed(chunk)- for message in messages:- 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 ACK stream: {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.- self.logger.exception("inbound handling failed")- self._connection_failed(f"inbound message failed: {exc}", expected_socket=sock)- active_socket = None-- def _handle_inbound(self, message):- """Dispatch one inbound message. `ack` updates the sequence bookkeeping- the watchdog relies on; any other well-formed message (a dict with a- known "type" string) still refreshes liveness — bytes arriving at all- prove the connection is alive — and is otherwise ignored, except for- `clipboard`, which is applied to the local pasteboard. Malformed- frames still drop the connection, since they mean the stream can no- longer be trusted."""- if message.get("type") == protocol.MSG_ACK:- self._record_ack(message)- return- 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_CLIPBOARD:- self._apply_inbound_clipboard(message.get("data", {}))- return- if message_type == protocol.MSG_SWITCH:- self._handle_switch(message.get("data", {}))- return- if message_type == protocol.MSG_ARRANGEMENT:- self._handle_arrangement(message.get("data", {}))- return- if message_type == protocol.MSG_SETTINGS:- data = message.get("data")- if isinstance(data, dict) and self.on_settings is not None:try:- self.on_settings(data)- except Exception:- self.logger.exception("settings handler failed")- return- self.logger.debug("ignoring inbound message of type %r", message_type)-- def _handle_arrangement(self, data):- """Windows changed which edge of this Mac leads to it. Handed to the- app, which owns the settings file; nothing is applied here."""- read = protocol.read_arrangement(data)- if read is None or self.on_arrangement is None:- return- try:- self.on_arrangement(*read)- except Exception:- self.logger.exception("arrangement handler failed")-- def send_arrangement(self, mac_edge, set_at):- """Tell Windows where the machines are, when the change was made here.- Sent straight out rather than queued: it is not input, and it must go- whether or not input is currently redirected."""- return self._send_raw(protocol.arrangement_msg(mac_edge, int(set_at)))+ message = self.outbound.get(timeout=0.05)+ except queue.Empty:+ self._owner_tick()+ continue+ try:+ self._process_outbound(message)+ finally:+ self.outbound.task_done()+ self._owner_tick()+ except Exception:+ # One bad message or tick 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" if message else "the owner's timer failed")+ self.logger.exception("outbound worker recovered")- def send_settings(self, data):- """Tell Windows this Mac's settings state, straight out like the arrangement."""- return self._send_raw(protocol.settings_msg(data))+ def _owner_tick(self):+ deadline = self.owner.deadline()+ if deadline is not None and self.clock() >= deadline:+ self._step(lambda owner: owner.tick())- def _apply_inbound_clipboard(self, data):- if not isinstance(data, dict):+ def _process_outbound(self, message):+ """Handle one dequeued item: the clipboard sentinel, or input the tap captured, which the+ owner routes (to the machine it is on, held for a hand-over, or dropped when it has+ already come home)."""+ kind = message.get("type")+ if kind == _LOCAL_CLIPBOARD_SENTINEL_TYPE:+ self._send_clipboard(message["peer"])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:- self.logger.warning("ignoring oversized inbound clipboard text")- text = None- image = protocol.clipboard_image(data)- if text is None and image is None:+ if kind in (protocol.MSG_KEYUP, protocol.MSG_MOUSEUP):+ # Whether or not the input is away: the release of a key pressed there that arrives+ # after it came home is what lets the owner stop swallowing it.+ self._step(lambda owner: owner.input(message))return- if not self.clipboard.set_contents(text, image):- self.logger.warning("failed to set the local clipboard from an inbound message")-- def _record_ack(self, message):- if message.get("type") != protocol.MSG_ACK:- raise protocol.ProtocolError(f"unexpected inbound message type: {message.get('type')!r}")- 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- self.last_ack_at = self.clock()- if advanced:- self._measure_round_trip(seq, self.last_ack_at)- self._note_windows_lock(data.get("locked") is True)-- def _measure_round_trip(self, seq, now):- """Under sequence_lock. Measured from the send of the event the ACK names, not the- oldest one it covers: the receiver acknowledges the highest seq it has processed on a- timer, so the oldest would only ever measure that timer. An ACK that repeats a seq --- every idle heartbeat does -- finds nothing left to measure and adds no sample."""- 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 _forget_round_trips(self):- with self.sequence_lock:- self._unacked_sent_at.clear()- self._round_trips.clear()- self._round_trip_at = 0.0-- def _note_windows_lock(self, locked):- """Surface Windows clearing its lock screen, on the transitions only:- an ACK arrives every 400ms and must not restate the status each time.- The previous status is restored verbatim rather than rebuilt, so the- macOS 27 SSH-fallback wording survives an unlock."""- if locked == self.windows_locked:+ if not self.redirecting:return- self.windows_locked = locked- if locked:- self._status_before_unlock = self.connection_status- self.connection_status = "Unlocking Windows…"- self.logger.info("Windows is on the lock screen; it is unlocking itself")- else:- if self._status_before_unlock is not None:- self.connection_status = self._status_before_unlock- self._status_before_unlock = None-- def _watchdog_worker(self):- while not self.stop_event.wait(0.1):- self._watchdog_tick()-- def _watchdog_tick(self):- """Runs at all times a socket exists, not just while redirecting, so a- half-open connection can't hide behind an idle UI: it is detected and- torn down the same way whether or not input is currently redirected.- Also drives the idle heartbeat ping so a silent connection is proven- alive well before the peer's own read timeout could fire."""- with self.socket_lock:- sock = self.sock- if sock is None:- 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("Windows stopped responding")- return True- if now - self.last_send_at >= PING_INTERVAL_SECONDS:- self._send_raw(protocol.ping_msg())- return False+ self._step(lambda owner: owner.input(message) if owner.away else [])def _force_local(self, reason):self._return_local()self.logger.error("%s; input forced local", reason)- def _connection_failed(self, reason, expected_socket=None):+ def _connection_failed(self, reason):was_redirecting = self.redirecting+ link = self._peers_up.get(self.owner.on) or self._primary_linkself._return_local()self.connection_status = reason- self._drop_connection(expected_socket)+ if link is not None:+ link.drop(reason)self.logger.error("%s; connection dropped and input forced local", reason)if was_redirecting:self._alert("Beamer", "Input returned to this Mac")- def _drop_connection(self, expected_socket=None):- with self.socket_lock:- if expected_socket is not None and self.sock is not expected_socket:- return- sock = self.sock- self.sock = None- self._forget_round_trips()- if sock is not None:- try:- sock.shutdown(socket.SHUT_RDWR)- except OSError:- pass- try:- sock.close()- except OSError:- pass-def _drain_outbound(self):while True:try:diff --git a/mac_app/build_dmg.sh b/mac_app/build_dmg.shindex ef4a008..04503c0 100755--- a/mac_app/build_dmg.sh+++ b/mac_app/build_dmg.sh@@ -195,15 +195,21 @@ codesign --verify --deep --strict --verbose=2 "$APP"codesign -dvv "$APP" 2>&1 | grep -E '^(Identifier|Signature|Authority|Timestamp|CodeDirectory)' || true# The bundle's own python runs under the same hardened runtime as the app, so code that needs an-# entitlement fails here rather than at a user's first launch.-env -i HOME="$HOME" PATH=/usr/bin:/bin PYTHONHOME="$APP/Contents/Resources" \- "$APP/Contents/MacOS/python" "$PROJECT_DIR/tools/runtime_probe.py"-# The same probe as an Intel Mac would run it, where Rosetta is here to run it.-if /usr/bin/arch -x86_64 /usr/bin/true 2>/dev/null; then- env -i HOME="$HOME" PATH=/usr/bin:/bin PYTHONHOME="$APP/Contents/Resources" \- /usr/bin/arch -x86_64 "$APP/Contents/MacOS/python" "$PROJECT_DIR/tools/runtime_probe.py"+# entitlement fails here rather than at a user's first launch. The probe lives with the project's+# own tools, which the public source does not carry; a build from that source says so and goes on.+PROBE="$PROJECT_DIR/tools/runtime_probe.py"+if [ ! -f "$PROBE" ]; then+ echo "No runtime probe in this source tree: the hardened-runtime probe was not run" >&2else- echo "Rosetta is not installed here: the x86_64 half of the bundle was not run" >&2+ env -i HOME="$HOME" PATH=/usr/bin:/bin PYTHONHOME="$APP/Contents/Resources" \+ "$APP/Contents/MacOS/python" "$PROBE"+ # The same probe as an Intel Mac would run it, where Rosetta is here to run it.+ if /usr/bin/arch -x86_64 /usr/bin/true 2>/dev/null; then+ env -i HOME="$HOME" PATH=/usr/bin:/bin PYTHONHOME="$APP/Contents/Resources" \+ /usr/bin/arch -x86_64 "$APP/Contents/MacOS/python" "$PROBE"+ else+ echo "Rosetta is not installed here: the x86_64 half of the bundle was not run" >&2+ fifinotarise() {diff --git a/mac_app/clipboard_mac.py b/mac_app/clipboard_mac.pyindex 7dc39c4..88ca73f 100644--- a/mac_app/clipboard_mac.py+++ b/mac_app/clipboard_mac.py@@ -77,6 +77,11 @@ def _change_count():return None+def change_stamp():+ """A number that changes whenever the pasteboard does, or None when it cannot be read."""+ return _change_count()++def changed_contents():"""get_contents(), or (None, None) when the pasteboard has not changed since it was last sentto or written from the peer. Either way the current contents count as sent from here on."""diff --git a/mac_app/config.py b/mac_app/config.pyindex 07bc8da..f6502ba 100644--- a/mac_app/config.py+++ b/mac_app/config.py@@ -1,4 +1,6 @@-"""Shared config.json loader for mac_sender.py and win_receiver.py."""+"""The Mac app's Config and the parser for config.json's shape.++settings_store reads settings.json (WIRE.md section 1) into that shape, so what is above it is unchanged."""import jsonimport os@@ -79,6 +81,9 @@ class Config:# seconds of the last change to that or to a shared value; see settings_sync.same_on_both: bool = Falsesame_set_at: int = 0+ # Who made the change the stamp above is for, as a machine id: the tie-break between two ends+ # that changed it in the same second (WIRE.md section 10).+ same_by: str = ""# How the PC's pointer and scroll feel on this Mac; see receiver.InputScale.pointer_speed: float = 1.0scroll_speed: float = 1.0@@ -111,7 +116,11 @@ def load_config(path: str = None) -> Config:with open(path, "r", encoding="utf-8") as f:raw = json.load(f)+ return parse_config(raw)++def parse_config(raw: dict) -> Config:+ """A Config from a dict in config.json's shape, the one settings_store hands over from settings.json."""missing = [k for k in ("host", "port", "auth_token") if k not in raw]if missing:raise ConfigError(f"config.json is missing required field(s): {', '.join(missing)}")@@ -146,6 +155,7 @@ def load_config(path: str = None) -> Config:if isinstance(crossing["edge_parts"], list):crossing["edge_parts"] = list(crossing["edge_parts"])crossing["resistance_px"] = int(crossing["resistance_px"])+ crossing["arrangement_set_at"] = _stamp(crossing["arrangement_set_at"])return Config(host=raw["host"],@@ -165,6 +175,7 @@ def load_config(path: str = None) -> Config:hide_addresses=raw.get("hide_addresses", False) is True,same_on_both=raw.get("same_on_both", False) is True,same_set_at=_stamp(raw.get("same_set_at", 0)),+ same_by=str(raw.get("same_by", "") or ""),pointer_speed=raw.get("pointer_speed", 1.0),scroll_speed=raw.get("scroll_speed", 1.0),reverse_scroll=raw.get("reverse_scroll", False),diff --git a/mac_app/crossing.py b/mac_app/crossing.pyindex 07cb677..fbdf3f5 100644--- a/mac_app/crossing.py+++ b/mac_app/crossing.py@@ -141,22 +141,6 @@ class CrossingEngine:self._last_x = Noneself._last_y = None- def home_edge(self, mac_edge=None):- """The Windows edge the pointer comes home through: opposite the Mac edge it left by or,- for a shortcut switch, opposite whichever pointer method is on. The notch and a corner come- first because the configured `edge` keeps its value while the edge method is off, and- reading it then armed the wrong Windows edge and left the notch's way home dead. With only- the shortcut on it is still the PC's edge facing this Mac: turning this Mac's own edge off- says nothing about the PC's, and the PC also learns from it which way its own push goes."""- if mac_edge is None:- if "notch" in self.methods and not self.methods & {"edge", "part"}:- mac_edge = "top"- elif "corner" in self.methods and not self.methods & {"edge", "part"}:- mac_edge = self.corner.split("_")[1]- else:- mac_edge = self.edge- return OPPOSITE[mac_edge]-def pressure_at(self, now):"""Pressure as a fraction, decayed to `now` without recording anything — for the glow,which has to keep fading after the last event arrives."""diff --git a/mac_app/gestures.py b/mac_app/gestures.pyindex 55031c6..b2bec3c 100644--- a/mac_app/gestures.py+++ b/mac_app/gestures.py@@ -137,8 +137,18 @@ _PHASE_RESET_MASK = NS_EVENT_PHASE_ENDED | NS_EVENT_PHASE_CANCELLEDMAGNIFY_STEP = 0.05+RECEIVERS = ("windows", "mac")++class GestureTranslator:- def __init__(self, logger=None):+ """`receiver` is the platform of the machine being driven: a zoom or a page swipe is the+ chord that machine answers to. The wire's key names are the receiver's own words, so a Mac's+ "cmd" is Command and Windows' "ctrl" is Control."""++ def __init__(self, logger=None, receiver="windows"):+ if receiver not in RECEIVERS:+ raise ValueError(f"unknown receiver platform: {receiver!r}")+ self.receiver = receiverself.logger = logger or logging.getLogger("Beamer")self._magnify_accum = 0.0self._warned_types = set()@@ -182,8 +192,9 @@ class GestureTranslator:self._magnify_accum = 0.0return messages- @staticmethod- def _zoom_step_messages(direction):+ def _zoom_step_messages(self, direction):+ if self.receiver == "mac":+ return _chord("cmd", "=" if direction > 0 else "-")return [{"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},protocol.scroll_msg(dy=direction, dx=0, mode="line"),@@ -192,15 +203,21 @@ class GestureTranslator:def _translate_swipe(self, ns_event):delta_x = float(ns_event.deltaX)- if delta_x > 0:- arrow = "left" # back- elif delta_x < 0:- arrow = "right" # forward- else:+ if delta_x == 0:return []- return [- {"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},- {"type": protocol.MSG_KEYDOWN, "data": {"key": arrow}},- {"type": protocol.MSG_KEYUP, "data": {"key": arrow}},- {"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},- ]+ back = delta_x > 0+ if self.receiver == "mac":+ return _chord("cmd", "[" if back else "]")+ return _chord("alt", "left" if back else "right")+++def _chord(modifier, key):+ # A character key names where it sits on a US keyboard, so a receiving Mac whose layout has+ # no such key still presses a key under the modifier rather than typing the character.+ data = {"key": key, "us": key} if len(key) == 1 else {"key": key}+ return [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": modifier}},+ {"type": protocol.MSG_KEYDOWN, "data": dict(data)},+ {"type": protocol.MSG_KEYUP, "data": dict(data)},+ {"type": protocol.MSG_KEYUP, "data": {"key": modifier}},+ ]diff --git a/mac_app/hardware_mac.py b/mac_app/hardware_mac.pynew file mode 100644index 0000000..40baa8c--- /dev/null+++ b/mac_app/hardware_mac.py@@ -0,0 +1,95 @@+"""This Mac's hardware address, for the handshake's `hw` field (WIRE.md section 2).++A peer sends wake-on-LAN to it, so it must be the interface this link leaves from, not the first one+the system lists. The route is read by connecting a UDP socket (nothing is sent) and the address by+walking getifaddrs through ctypes: no subprocess, so nothing can flash a window."""++import ctypes+import sys++from core import pairing++AF_INET = 2+AF_LINK = 18+++class Ifaddrs(ctypes.Structure):+ pass+++Ifaddrs._fields_ = [+ ("next", ctypes.POINTER(Ifaddrs)),+ ("name", ctypes.c_char_p),+ ("flags", ctypes.c_uint),+ ("addr", ctypes.c_void_p),+ ("netmask", ctypes.c_void_p),+ ("dstaddr", ctypes.c_void_p),+ ("data", ctypes.c_void_p),+]+++class SockaddrHeader(ctypes.Structure):+ _fields_ = [("length", ctypes.c_uint8), ("family", ctypes.c_uint8)]+++class SockaddrIn(ctypes.Structure):+ _fields_ = [("length", ctypes.c_uint8), ("family", ctypes.c_uint8), ("port", ctypes.c_uint16), ("addr", ctypes.c_ubyte * 4)]+++class SockaddrDl(ctypes.Structure):+ """sockaddr_dl up to sdl_data, where the interface name and then its link-layer address sit."""+ _fields_ = [+ ("length", ctypes.c_uint8), ("family", ctypes.c_uint8), ("index", ctypes.c_uint16),+ ("kind", ctypes.c_uint8), ("name_length", ctypes.c_uint8), ("address_length", ctypes.c_uint8), ("selector_length", ctypes.c_uint8),+ ]+++def format_mac(raw: bytes) -> str:+ """Six bytes as `aa:bb:cc:dd:ee:ff`; anything else, and all zeros, is unknown ('')."""+ if len(raw) != 6 or not any(raw):+ return ""+ return ":".join(f"{b:02x}" for b in raw)+++def _interface_table() -> tuple:+ """({IPv4 text: interface name}, {interface name: link-layer address bytes})."""+ libc = ctypes.CDLL(None, 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")+ ips, macs = {}, {}+ try:+ node = head+ while node:+ entry = node.contents+ if entry.addr and entry.name:+ name = entry.name.decode("ascii", "replace")+ family = ctypes.cast(entry.addr, ctypes.POINTER(SockaddrHeader)).contents.family+ if family == AF_INET:+ parsed = ctypes.cast(entry.addr, ctypes.POINTER(SockaddrIn)).contents+ ips[".".join(str(b) for b in parsed.addr)] = name+ elif family == AF_LINK:+ link = ctypes.cast(entry.addr, ctypes.POINTER(SockaddrDl)).contents+ # The data follows the 8-byte header; the sockaddr's own length bounds the read.+ whole = ctypes.string_at(entry.addr, max(link.length, 8))+ start = 8 + link.name_length+ macs[name] = whole[start:start + link.address_length]+ node = entry.next+ finally:+ libc.freeifaddrs(head)+ return ips, macs+++def hardware_address_towards(host: str) -> str:+ """The MAC of the interface that would reach `host` (an IPv4 string), or '' when unknown.+ Never raises: the field is optional on the wire, so a failure only costs the peer its wake."""+ if sys.platform != "darwin" or not host:+ return ""+ try:+ local = pairing.local_address_towards(host)+ ips, macs = _interface_table()+ return format_mac(macs.get(ips.get(local), b""))+ except Exception:+ return ""diff --git a/mac_app/input_injector_mac.py b/mac_app/input_injector_mac.pyindex ba96de3..8b37dda 100644--- a/mac_app/input_injector_mac.py+++ b/mac_app/input_injector_mac.py@@ -32,6 +32,13 @@ try:except ImportError: # pragma: no cover - exercised only off macOSQuartz = None+try:+ import AppKit+except ImportError: # pragma: no cover - exercised only off macOS+ AppKit = None++from core import protocol+LOGGER = logging.getLogger("Beamer")# Stamped into every injected event's kCGEventSourceUserData. Any non-zero@@ -65,11 +72,60 @@ DOUBLE_CLICK_SLOP_PX = 5# the knob to turn if a mouse wheel feels wrong on the Mac.LINES_PER_NOTCH = 1.0+# Media keys are not key events on a Mac: they arrive as NSSystemDefined events of subtype 8, the+# reverse of media_keys.decode. The NX key codes are IOKit's ev_keymap.h. There is no stop key on+# a Mac, and mapping it to play/pause would start playback that was paused, so it is dropped.+NX_SUBTYPE_AUX_CONTROL_BUTTONS = 8+NX_SYSDEFINED_EVENT_TYPE = 14+MEDIA_NX_KEYS = {+ "volume_up": 0,+ "volume_down": 1,+ "volume_mute": 7,+ "media_play_pause": 16,+ "media_next": 17,+ "media_prev": 18,+}+_MEDIA_STATE_DOWN = 0x0A+_MEDIA_STATE_UP = 0x0B++# Keys a PC has and a Mac keyboard does not, at the place an Apple extended keyboard puts them:+# F13, F14 and F15 are Print Screen, Scroll Lock and Pause, and the keypad's Clear is Num Lock.+WINDOWS_ONLY_KEY_CODES = {+ "print_screen": 0x69,+ "scroll_lock": 0x6B,+ "pause": 0x71,+ "num_lock": 0x47,+}+# The PC's browser back and forward keys, as the shortcut every Mac browser and Finder answers to.+BROWSER_KEY_CHORDS = {"browser_back": "[", "browser_forward": "]"}++# What each system gesture becomes: the shortcuts System Settings ships for them. Fingers moving+# left reveal the Space on the right, so swipe_left is Control+Right. Pinch was Launchpad, which+# macOS 26 removed along with its shortcut, so it has nothing to press.+GESTURE_CHORDS = {+ protocol.GESTURE_SWIPE_UP: ("ctrl", "up"),+ protocol.GESTURE_SWIPE_DOWN: ("ctrl", "down"),+ protocol.GESTURE_SWIPE_LEFT: ("ctrl", "right"),+ protocol.GESTURE_SWIPE_RIGHT: ("ctrl", "left"),+ protocol.GESTURE_SPREAD: ("f11",),+}++# A real arrow, function key, Home, End, Page Up, Page Down or forward delete event carries the Fn+# flag, and the arrows the numeric-pad flag too; system shortcuts (Control+arrows for Spaces, F11+# for Show Desktop) match on it, and a keyboard event made from nothing does not have it.+_ARROW_CODES = {KEY_NAME_TO_CODE[name] for name in ("left", "right", "up", "down")}+_FN_CODES = _ARROW_CODES | {KEY_NAME_TO_CODE[name] for name in ("home", "end", "page_up", "page_down", "delete")}+_FN_CODES |= {KEY_NAME_TO_CODE[f"f{number}"] for number in range(1, 21)}+_mods_down: Set[str] = set()_held_codes: Dict[str, int] = {}_buttons_down: Set[str] = set()_last_click: Dict[str, Tuple[float, int, int, int]] = {}_warned_names: Set[str] = set()+# The fraction of a wheel step not yet posted, per unit and axis (vertical, horizontal): a wheel+# event carries whole numbers only, so a scroll speed under one, or a trackpad's small deltas,+# would otherwise round to nothing every time.+_scroll_remainders: Dict[str, List[float]] = {"line": [0.0, 0.0], "pixel": [0.0, 0.0]}# One lock over the held-key bookkeeping and the post 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.@@ -101,6 +157,16 @@ def current_flags(mods_down: Set[str]) -> int:return flags+def key_flags(key_code: int) -> int:+ quartz = _require()+ flags = 0+ if key_code in _FN_CODES:+ flags |= quartz.kCGEventFlagMaskSecondaryFn+ if key_code in _ARROW_CODES:+ flags |= quartz.kCGEventFlagMaskNumericPad+ return flags++def _script(character: str) -> str:return unicodedata.name(character, "").split(" ")[0]@@ -139,6 +205,8 @@ def plan_key_event(name: str, down: bool, mods_down: Set[str], held: Optional[Dielse:mods_down.discard(lowered)key_code = KEY_NAME_TO_CODE.get(lowered)+ if key_code is None:+ key_code = WINDOWS_ONLY_KEY_CODES.get(lowered)if key_code is not None:return key_code, Noneif len(name) != 1:@@ -170,9 +238,59 @@ def plan_key_event(name: str, down: bool, mods_down: Set[str], held: Optional[Direturn 0, name+def handles_key(name: str) -> bool:+ """Whether `name` is a key this module posts by some route other than a key code."""+ lowered = name.lower()+ return lowered in MEDIA_NX_KEYS or lowered in BROWSER_KEY_CHORDS+++def _inject_media_key(nx_key: int, down: bool) -> None:+ if AppKit is None:+ raise RuntimeError("Media keys need AppKit, which is only available on macOS")+ state = _MEDIA_STATE_DOWN if down else _MEDIA_STATE_UP+ ns_event = AppKit.NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(+ NX_SYSDEFINED_EVENT_TYPE,+ (0, 0),+ state << 8,+ 0,+ 0,+ None,+ NX_SUBTYPE_AUX_CONTROL_BUTTONS,+ (nx_key << 16) | (state << 8),+ -1,+ )+ event = None if ns_event is None else ns_event.CGEvent()+ if event is None:+ raise RuntimeError(f"NSEvent failed for media key {nx_key}")+ _post(event)+++def _inject_browser_key(character: str) -> None:+ quartz = _require()+ # The US key, not this layout's: a German or French layout has no unshifted bracket, and its+ # plan would be key code 0, which under Command is Select All.+ code = US_KEY_CODES[character]+ flags = current_flags(_mods_down) | quartz.kCGEventFlagMaskCommand+ for down in (True, False):+ event = quartz.CGEventCreateKeyboardEvent(None, code, down)+ if event is None:+ raise RuntimeError(f"CGEventCreateKeyboardEvent failed for {character!r}")+ quartz.CGEventSetFlags(event, flags)+ _post(event)++@_lockeddef inject_key(name: str, down: bool, us: Optional[str] = None) -> None:quartz = _require()+ lowered = name.lower()+ if lowered in MEDIA_NX_KEYS:+ _inject_media_key(MEDIA_NX_KEYS[lowered], bool(down))+ return+ if lowered in BROWSER_KEY_CHORDS:+ # One shortcut per press: the release has nothing left to let go of.+ if down:+ _inject_browser_key(BROWSER_KEY_CHORDS[lowered])+ returnplan = plan_key_event(name, down, _mods_down, _held_codes, us)if plan is None:return@@ -181,7 +299,7 @@ def inject_key(name: str, down: bool, us: Optional[str] = None) -> None:if event is None:raise RuntimeError(f"CGEventCreateKeyboardEvent failed for {name!r}")if text is None:- quartz.CGEventSetFlags(event, current_flags(_mods_down))+ quartz.CGEventSetFlags(event, current_flags(_mods_down) | key_flags(key_code))else:quartz.CGEventKeyboardSetUnicodeString(event, len(text), text)# Flags are deliberately cleared: the string says what to type, and@@ -246,6 +364,41 @@ BUTTON_EVENTS = {}+# CGEventKeyboardSetUnicodeString carries a short string; longer text goes as several events.+TEXT_CHUNK_UNITS = 16+++def text_chunks(text: str) -> List[str]:+ """`text` cut so that no chunk is longer than TEXT_CHUNK_UNITS UTF-16 units and a character+ outside the BMP, which takes two, is never split."""+ chunks, current, units = [], [], 0+ for char in text:+ size = 2 if ord(char) > 0xFFFF else 1+ if units + size > TEXT_CHUNK_UNITS:+ chunks.append("".join(current))+ current, units = [], 0+ current.append(char)+ units += size+ if current:+ chunks.append("".join(current))+ return chunks+++@_locked+def inject_text(text: str) -> None:+ """Type `text` as characters rather than keys (WIRE.md section 10): each chunk is a key event+ that carries its string, with no flags so a held modifier cannot turn it into a shortcut."""+ quartz = _require()+ for chunk in text_chunks(text):+ for down in (True, False):+ event = quartz.CGEventCreateKeyboardEvent(None, 0, down)+ if event is None:+ raise RuntimeError("CGEventCreateKeyboardEvent failed for text")+ quartz.CGEventKeyboardSetUnicodeString(event, len(chunk.encode("utf-16-le")) // 2, chunk)+ quartz.CGEventSetFlags(event, 0)+ _post(event)++def _held_button() -> Optional[str]:for button in BUTTONS:if button in _buttons_down:@@ -314,15 +467,28 @@ def inject_mouse_button(button: str, down: bool) -> None:_post(event)-def inject_scroll(dy, dx=0.0, mode: str = "line") -> None:+def plan_scroll_units(dy, dx, mode: str, remainders: Dict[str, List[float]]) -> Tuple[int, int, int]:+ """Pure planning: (unit, whole vertical steps, whole horizontal steps) for one scroll, the+ fraction not yet whole kept in `remainders` for the next. The same arithmetic the PC's+ plan_scroll_units does, truncating toward zero so a remainder never reverses direction."""quartz = _require()if mode == "pixel":- unit = quartz.kCGScrollEventUnitPixel- wheel_y, wheel_x = int(round(float(dy))), int(round(float(dx)))+ unit, key, scale = quartz.kCGScrollEventUnitPixel, "pixel", 1.0else:- unit = quartz.kCGScrollEventUnitLine- wheel_y = int(round(float(dy) * LINES_PER_NOTCH))- wheel_x = int(round(float(dx) * LINES_PER_NOTCH))+ unit, key, scale = quartz.kCGScrollEventUnitLine, "line", LINES_PER_NOTCH+ accum = remainders[key]+ accum[0] += float(dy) * scale+ accum[1] += float(dx) * scale+ whole_y, whole_x = int(accum[0]), int(accum[1])+ accum[0] -= whole_y+ accum[1] -= whole_x+ return unit, whole_y, whole_x+++@_locked+def inject_scroll(dy, dx=0.0, mode: str = "line") -> None:+ quartz = _require()+ unit, wheel_y, wheel_x = plan_scroll_units(dy, dx, mode, _scroll_remainders)if not wheel_y and not wheel_x:returnevent = quartz.CGEventCreateScrollWheelEvent(None, unit, 2, wheel_y, wheel_x)@@ -332,11 +498,28 @@ def inject_scroll(dy, dx=0.0, mode: str = "line") -> None:_post(event)+def reset_scroll_remainders() -> None:+ for accum in _scroll_remainders.values():+ accum[0] = accum[1] = 0.0+++@_lockeddef inject_gesture(name: str) -> None:- """Windows sends no gestures -- there is no trackpad event it could- classify -- so this exists only to keep the injector interface the same- on both machines."""- LOGGER.warning("Gesture %r ignored: Beamer does not inject gestures on the Mac", name)+ """A system gesture the sender classified, pressed as the shortcut System Settings binds to+ it, so this Mac's own choices in Trackpad and Keyboard Shortcuts apply. A gesture with no+ shortcut is logged once and dropped."""+ chord = GESTURE_CHORDS.get(name)+ if chord is None:+ if name not in _warned_names:+ LOGGER.warning("Gesture %r has no shortcut on this Mac and is ignored", name)+ _warned_names.add(name)+ return+ # A modifier the sender is already holding is part of the chord and stays down after it.+ pressed = [key for key in chord if key not in _mods_down]+ for key in pressed:+ inject_key(key, down=True)+ for key in reversed(pressed):+ inject_key(key, down=False)@_locked@@ -357,3 +540,4 @@ def release_all() -> None:_mods_down.clear()_held_codes.clear()_buttons_down.clear()+ reset_scroll_remainders()diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.pyindex 3d8d58e..485787f 100644--- a/mac_app/kvm_bridge_app.py+++ b/mac_app/kvm_bridge_app.py@@ -5,6 +5,7 @@ import loggingimport logging.handlersimport osimport re+import socketimport subprocessimport sysimport threading@@ -21,6 +22,7 @@ from PyObjCTools import AppHelpersys.path.insert(0, str(Path(__file__).resolve().parent.parent))+import bridgeimport config as config_moduleimport crossingfrom core import return_edge@@ -28,6 +30,7 @@ import desktop_macfrom core import effectsimport effects_overlayimport gestures+import hardware_macimport ignored_titlesimport keyboard_layoutimport notch_beam@@ -39,11 +42,13 @@ from notch_island import NotchIslandfrom bridge import _GestureEventViewfrom key_codes import KEY_NAME_TO_CODEimport link_state+import machines_panelimport login_itemimport pagesfrom core import updatesfrom core import protocolfrom core import pairing+from core import peerlistfrom core import settings_syncfrom settings_store import (SettingsError,@@ -74,7 +79,7 @@ WIDE_WIDTH = 600.0MENU_BAR_STATES = {"local": "Input on this Mac","held": "Input held on this Mac; crossing is off",- "windows": "Input on Windows",+ "windows": "Input on another machine",}@@ -935,19 +940,16 @@ class ControlWindow(AppKit.NSObject):# Set by TrayApp once it exists: the listener for the PC's input, and# the second way an arrangement changed here can reach the PC.self.windows_input = None- # Set by TrayApp: saves one direction's switch, as its menu ticks do.+ # Set by TrayApp: saves one machine's direction switch (token, send= or allow_drive=).self.direction_handler = Noneself.last_capture_attempt = 0.0# macOS passes keys only to a process started after Input Monitoring is granted, so a grant# made during this run needs a relaunch before the keyboard crosses, however ready the tap looks.self.granted_at_launch = accessibility_granted() and input_monitoring_granted()- # Set by TrayApp: the beacon listener whose PCs the Pair module lists.- self.discovery = Noneself.update_checker = None- self._pcs = []- self._pcs_key = None- self.chosen_pc = None- self._pairing = False+ # The list of paired machines and the pairing sheet; TrayApp gives it the pairing service.+ self.panel = machines_panel.MachinesPanel(controller, settings_store, logger, self)+ self._machines_first = Noneself._preview_flashes = 0self.latency = collections.deque(maxlen=widgets.Spark.SAMPLES)self.wide = None@@ -1067,7 +1069,7 @@ class ControlWindow(AppKit.NSObject):@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_WIDTHif wide == self.wide:@@ -1089,15 +1091,17 @@ class ControlWindow(AppKit.NSObject):# 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()- AppKit.NSLayoutConstraint.deactivateConstraints_(self.pair_stacked)- self.pair_grid.setOrientation_(+ panel = self.panel+ panel.wide = wide+ AppKit.NSLayoutConstraint.deactivateConstraints_(panel.pair_stacked)+ panel.pair_grid.setOrientation_(AppKit.NSUserInterfaceLayoutOrientationHorizontal if wide else AppKit.NSUserInterfaceLayoutOrientationVertical)- self.pair_grid.setDistribution_(+ panel.pair_grid.setDistribution_(AppKit.NSStackViewDistributionFillEqually if wide else AppKit.NSStackViewDistributionFill)if narrow:- AppKit.NSLayoutConstraint.activateConstraints_(self.pair_stacked)+ AppKit.NSLayoutConstraint.activateConstraints_(panel.pair_stacked)@objc.python_methoddef _select_page(self, key):@@ -1140,9 +1144,6 @@ class ControlWindow(AppKit.NSObject):self.host_secret.setStringValue_(str(raw["host"]))self._show_host_field()self.port_field.setStringValue_(str(raw["port"]))- self.token_field.setStringValue_(str(raw["auth_token"]))- self.token_plain.setStringValue_(str(raw["auth_token"]))- self._say_pairing("Choose a PC, then type the code it shows.")self.ignored_entries = list(raw["ignored_inputs"])self._render_ignored()self.pointer_ruler.value = round(raw["pointer_speed"] * 100)@@ -1309,7 +1310,7 @@ class ControlWindow(AppKit.NSObject):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."))+ }.get(self.modifier_select.value, "Custom: the key map in settings.json is kept as it is."))@objc.python_methoddef _show_arrangement(self, methods):@@ -1339,13 +1340,72 @@ class ControlWindow(AppKit.NSObject):@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 input is on, 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()+ on = self.controller.owner.on+ return next((peer for peer in peers if on is not None and peer.get("id") == on), 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 ""+ 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."""+ try:+ cfg = self.settings_store.load()+ except SettingsError as exc:+ self.logger.warning("settings not read after the peers changed: %s", exc)+ return+ # The links first: apply_settings tells the primary link where this Mac's edge is, and that+ # must be the new first machine's link, not one that is about to be removed.+ 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):@@ -1411,6 +1471,8 @@ class ControlWindow(AppKit.NSObject):def windowWillClose_(self, _notification):self.key_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()@@ -1489,46 +1551,32 @@ class ControlWindow(AppKit.NSObject):@objc.python_methoddef _overview_page(self, body):- # 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)+ # 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).+ self.overview_body = bodywidgets.add(body, self._status_module().view)widgets.add(body, self._keyboard_module().view)- widgets.add(body, self._directions_module().view)+ widgets.add(body, self.panel.machines_module.view)+ widgets.add(body, self.panel.sheet.view)widgets.add(body, self._same_module().view)- widgets.add(body, self._paired_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()- return module-- @objc.python_method- def _set_direction(self, **change):- if self.direction_handler is not None:- self.direction_handler(**change)- self._show_directions()-- @objc.python_method- def _show_directions(self):- cfg = 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+ 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:+ return+ self._machines_first = first+ 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+ for offset, view in enumerate(views):+ body.insertArrangedSubview_atIndex_(view, at + offset)@objc.python_methoddef _same_module(self):@@ -1553,7 +1601,7 @@ class ControlWindow(AppKit.NSObject):"""Whether a link is up to a PC whose Beamer does not keep settings in step."""links = [(self.controller.connected, getattr(self.controller, "peer_settings", None))]if self.windows_input is not None:- links.append((self.windows_input.state == ServerState.CONNECTED, self.windows_input.server.peer_settings))+ 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@@ -1564,9 +1612,10 @@ class ControlWindow(AppKit.NSObject):if self.same_switch.value != on:self.same_switch.value = onself.same_switch.set_enabled(not old)- self.same_note.set(settings_sync.switch_note("PC", cfg.same_on_both, old), ink="amber" if old else "ink_2")+ who = settings_sync.who(list(peerlist.labels(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")for key, label in self.scope_labels.items():- text = settings_sync.scope(key, "PC", on, pages.SCOPE.get(key))+ text = settings_sync.scope(key, who, on, pages.SCOPE.get(key))if label.text != text:label.set(text)for note in self.own_notes:@@ -1580,6 +1629,7 @@ class ControlWindow(AppKit.NSObject):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:@@ -1595,27 +1645,36 @@ class ControlWindow(AppKit.NSObject):from the links' threads as well, so it reads the settings once."""cfg = self.controller.cfgreturn settings_sync.message_data(cfg.same_on_both, cfg.same_set_at,- settings_sync.mac_values(config_to_raw(cfg)))+ settings_sync.mac_values(config_to_raw(cfg)), by=cfg.same_by or self.own_id())++ @objc.python_method+ 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 = self.same_state()- self.controller.send_settings(data)+ 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.server.send_settings(data)+ self.windows_input.send_settings(data, source=source)@objc.python_method- def apply_same(self, data):- """The PC'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."""+ 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."""cfg = self.controller.cfg- taken = settings_sync.arrived(data, cfg.same_set_at, KEY_NAME_TO_CODE)+ taken = settings_sync.arrived(data, cfg.same_set_at, KEY_NAME_TO_CODE, by_here=cfg.same_by)if taken is None:returnon, set_at, values = takenraw = config_to_raw(cfg)raw["same_on_both"] = onraw["same_set_at"] = set_at+ raw["same_by"] = data.get("by", "")if on:raw = settings_sync.apply_mac(raw, values)try:@@ -1624,6 +1683,7 @@ class ControlWindow(AppKit.NSObject):self.logger.exception("could not save the settings the PC sent")returnself.controller.apply_settings(cfg)+ self._send_same(data, source=peer)if self.previews is not None:self.previews.repaint()self.logger.info("settings from the PC applied (same on both machines %s)", "on" if on else "off")@@ -1841,7 +1901,7 @@ class ControlWindow(AppKit.NSObject):self.round_trip = widgets.Readout("Delay", "ms", self.spark)self.peer_footer = widgets.Label("", theme.TYPE["small"], mono=True, ink="ink_3")widgets.squeeze(self.peer_footer.view)- self.peer = widgets.Readout("PC", "", self.peer_footer.view, sizes=(theme.PEER_SIZE, theme.PEER_SIZE_NARROW))+ self.peer = widgets.Readout("Machine", "", self.peer_footer.view, sizes=(theme.PEER_SIZE, theme.PEER_SIZE_NARROW))module.add(widgets.grid([self.round_trip.view, self.peer.view], 2))return module@@ -1852,7 +1912,7 @@ class ControlWindow(AppKit.NSObject):module = widgets.Module(spacing=12)module.add(widgets.eyebrow("Keyboard and pointer"))self.toggle_button = widgets.Button(- "Send input to Windows", self, "toggleRedirect:", style="primary", scale="big", full_width=True+ "Send input", self, "toggleRedirect:", style="primary", scale="big", full_width=True)module.add(self.toggle_button.view)self.pause_row = widgets.stack(spacing=8)@@ -2294,93 +2354,12 @@ class ControlWindow(AppKit.NSObject):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)+ # 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(@@ -2394,33 +2373,19 @@ class ControlWindow(AppKit.NSObject):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")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()module.add(self.wake_hint.view)module.add(widgets.hairline())line = widgets.stack(vertical=False, spacing=12)- line.addArrangedSubview_(widgets.note("A new address, port or token takes effect when you connect.").view)+ line.addArrangedSubview_(widgets.note("A new address or port takes effect when you connect.").view)line.addArrangedSubview_(widgets.Button("Connect", self, "connect:", style="primary").view)module.add(line)return module@@ -2512,10 +2477,6 @@ class ControlWindow(AppKit.NSObject):AppKit.NSApp.activateIgnoringOtherApps_(True)self._run_previews()- @objc.python_method- def _token(self):- return (self.token_plain if self.token_boxes[0].isHidden() else self.token_field).stringValue()-@objc.python_methoddef _set_hide_addresses(self, on):try:@@ -2533,7 +2494,7 @@ class ControlWindow(AppKit.NSObject):"""The address fields as dots while addresses are hidden, still editable."""hide = self.controller.cfg.hide_addressesfor (plain_box, secret_box), plain, secret in ((self.host_boxes, self.host_field, self.host_secret),- (self.find_boxes, self.find_field, self.find_secret)):+ (self.panel.find_boxes, self.panel.find_field, self.panel.find_secret)):if hide == plain_box.isHidden():continueif hide:@@ -2549,17 +2510,6 @@ class ControlWindow(AppKit.NSObject):def _host_text(self):return (self.host_secret if self.controller.cfg.hide_addresses else self.host_field).stringValue()- def showToken_(self, _sender):- secure_box, plain_box = self.token_boxes- showing = plain_box.isHidden()- if showing:- self.token_plain.setStringValue_(self.token_field.stringValue())- else:- self.token_field.setStringValue_(self.token_plain.stringValue())- secure_box.setHidden_(showing)- plain_box.setHidden_(not showing)- self.show_button.set_title("Hide" if showing else "Show")-def connect_(self, _sender):"""The Connection page's own commit: a new address, port or token has to reconnect, so itwaits for the button rather than applying as it is typed."""@@ -2567,7 +2517,6 @@ class ControlWindow(AppKit.NSObject):try:raw["host"] = self._host_text().strip()raw["port"] = int(self.port_field.stringValue().strip())- raw["auth_token"] = self._token()if raw["host"] != self.controller.cfg.host:# What was learned belonged to the old address.raw["pc_name"] = ""@@ -2620,13 +2569,14 @@ class ControlWindow(AppKit.NSObject):settings_sync.mac_values(config_to_raw(self.controller.cfg)), settings_sync.mac_values(raw))if shared:raw["same_set_at"] = settings_sync.next_stamp(self.controller.cfg.same_set_at, time.time())+ raw["same_by"] = self.own_id()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())+ raw["crossing"]["arrangement_set_at"] = settings_sync.next_stamp(self.controller.cfg.crossing.get("arrangement_set_at", 0), time.time())cfg = self.settings_store.save(raw)except (SettingsError, TypeError, ValueError) as exc:self._say(str(exc), "fault")@@ -2647,21 +2597,26 @@ class ControlWindow(AppKit.NSObject):self._say("Saved. Changes apply as you make them.", "ink_2")@objc.python_method- def apply_arrangement(self, mac_edge, set_at):- """Windows changed which edge of this Mac leads to it. Applied here+ def apply_arrangement(self, mac_edge, set_at, by=None):+ """The peer changed which edge of this Mac leads to it. Applied hererather than at either link, because this is the side that owns the- settings file. An arrangement older than this Mac's own is ignored:- both ends stamp their changes, and the newer one stands."""- if mac_edge == self.controller.cfg.crossing.get("edge"):- return+ settings file. An arrangement that is not newer than this Mac's own is ignored:+ both ends stamp their changes, and the newer one stands, a tie going to the+ larger `by` (WIRE.md section 8)."""+ held = self.settings_store.current()["peers"]+ held_by = protocol.read_id(held[0].get("side_by")) if held else None+ theirs = protocol.read_id(by) if by else Nonemine = self.controller.cfg.crossing.get("arrangement_set_at", 0)- if mine and not protocol.arrangement_wins(set_at, mine):- self.logger.info("ignoring an older arrangement from the PC (%s vs %s)", set_at, mine)+ if mac_edge == self.controller.cfg.crossing.get("edge") and set_at == mine:+ return+ newer = set_at > mine or (set_at == mine and (theirs or b"") > (held_by or b""))+ if not newer:+ self.logger.info("ignoring an older arrangement from the peer (%s vs %s)", set_at, mine)returnraw = config_to_raw(self.controller.cfg)raw["crossing"] = {**raw["crossing"], "edge": mac_edge, "arrangement_set_at": int(set_at)}try:- cfg = self.settings_store.save(raw)+ cfg = self.settings_store.save(raw, side_by=by)except (SettingsError, TypeError, ValueError):self.logger.exception("could not save the arrangement the PC sent")return@@ -2705,7 +2660,7 @@ class ControlWindow(AppKit.NSObject):returnif not self.controller.redirecting and self.controller.can_wake:self.controller.wake()- self._say("Waking Windows. It connects on its own once it is up.", "ink_2")+ self._say(f"Waking {self._first_label()}. It connects on its own once it is up.", "ink_2")elif not self.controller.set_redirecting(not self.controller.redirecting):self._say(self.controller.connection_status, "fault")self.refresh()@@ -2714,227 +2669,6 @@ class ControlWindow(AppKit.NSObject):self.controller.crossing_paused = not self.controller.crossing_pausedself.refresh()- def togglePairing_(self, _sender):- self._repairing = not getattr(self, "_repairing", False)- if not self._repairing:- self.code_boxes.clear()- self.chosen_pc = None- self._pcs_key = None- self._say_pairing("Choose a PC, then type the code it shows.")- self.refresh()-- @objc.python_method- def _refresh_paired(self, state):- cfg = self.controller.cfg- paired = bool(cfg.auth_token)- refused = state.key == "token"- repairing = getattr(self, "_repairing", False)- peer = self._shown(link_state.peer_name(cfg))- motion.set_hidden(self.paired_module.view, not paired)- motion.set_hidden(self.pair_module.view, paired and not refused and not repairing)- self.paired_name.set(peer)- self.paired_address.set(self._shown(f"{cfg.host} · port {cfg.port}"))- if refused:- self.paired_note.set(f"{peer} refused this Mac's token. Pair again below with the code it shows.", ink="fault")- elif state.key in ("mac", "windows", "paused", "full_screen", "unlocking"):- self.paired_note.set("Connected now.", ink="signal")- else:- self.paired_note.set("Beamer connects to it on its own whenever both are running.", ink="ink_2")- self.repair_button.set_title("Cancel" if repairing else "Pair a different PC")- self.repair_button.view.setHidden_(refused)-- @objc.python_method- def _say_pairing(self, message, ink="ink_2"):- self._pair_ink = ink- self.pair_status.set(message, ink=ink)-- @objc.python_method- def _refresh_pcs(self):- """Rebuilds the PC rows only when what they would show has changed; the timer that- drives this ticks several times a second."""- discovery = self.discovery- pcs = discovery.pcs() if discovery is not None else []- chosen = self.chosen_pc["address"] if self.chosen_pc is not None else None- key = (chosen, tuple(tuple(sorted(pc.items())) for pc in pcs))- if key == self._pcs_key:- return- self._pcs_key = key- self._pcs = pcs- # The chosen row is the PC's beacon at the moment of the click; a PC that starts,- # renews or stops its code after that must move the hint with it, not leave it stale.- current = next((pc for pc in pcs if pc["address"] == chosen), None)- if current is not None and current != self.chosen_pc:- showed = self.chosen_pc["pair_id"]- self.chosen_pc = current- # A refusal or a failed save stays up until the PC offers a fresh code.- fault = getattr(self, "_pair_ink", None) == "fault"- if current["pair_id"] != showed and not self._pairing and (current["pair_id"] or not fault):- self._say_choice()- self._find_answered(pcs)- for view in list(self.pc_list.arrangedSubviews()):- self.pc_list.removeArrangedSubview_(view)- view.removeFromSuperview()- for index, pc in enumerate(pcs):- picked = pc["address"] == chosen- row = widgets.pressable(lambda index=index: self._choose_pc(index), "well" if picked else "ground",- role=AppKit.NSAccessibilityRadioButtonRole)- row.ring_inset = 1.0- showing = pc["pair_id"] is not None- row.setAccessibilityLabel_(self._shown(f"{pc['name']}, {pc['address']}") + (", showing a code" if showing else ""))- row.setToolTip_(f"Port {pc['port']}" + (", showing a code" if showing else ""))- line = widgets.stack(vertical=False, spacing=9)- led = widgets.LED()- led.set("signal" if showing else "off")- line.addArrangedSubview_(led.view)- name = widgets.Label(pc["name"], theme.TYPE["note"], 600 if picked else 400)- line.addArrangedSubview_(widgets.hug(widgets.squeeze(name.view), AppKit.NSLayoutPriorityDefaultLow))- line.addArrangedSubview_(widgets.Label(self._shown(pc["address"]), theme.TYPE["small"], mono=True, ink="ink_3").view)- row.addSubview_(line)- widgets.pin(line, row, (7, 10, 7, 10))- widgets.add(self.pc_list, row)- if discovery is not None and discovery.error:- self.pc_empty.set(f"Beamer cannot look for PCs: {discovery.error}", ink="fault")- else:- self.pc_empty.set(- "Looking for PCs running Beamer. Open it on the PC and it appears here; across a VPN or "- "on guest Wi-Fi it may not, so type its address below.",- ink="ink_2",- )- self.pc_frame.setHidden_(not pcs)- self.pc_empty.view.setHidden_(bool(pcs))- if chosen is not None and chosen not in {pc["address"] for pc in pcs}:- self.chosen_pc = None- self._pcs_key = None- self.confirm_button.set_enabled(self.chosen_pc is not None and not self._pairing)-- @objc.python_method- def _choose_pc(self, index):- if not 0 <= index < len(self._pcs):- return- self.chosen_pc = self._pcs[index]- self.code_boxes.clear()- self.code_boxes.view.setAccessibilityLabel_(f"Code shown on {self.chosen_pc['name']}")- self._say_choice()- self._refresh_pcs()- self.code_boxes.focus(self.window)-- @objc.python_method- def _say_choice(self):- if self.chosen_pc["pair_id"] is None:- self._say_pairing(f"{self.chosen_pc['name']} is not showing a code yet. Start pairing in Beamer on it first.")- else:- self._say_pairing("Six digits, as shown on the PC.")-- def findPC_(self, _sender):- host = (self.find_secret if self.controller.cfg.hide_addresses else self.find_field).stringValue().strip()- if self.discovery is None:- return- self.discovery.find(host)- self._find_serial = getattr(self, "_find_serial", 0) + 1- serial = self._find_serial- # Discovery only logs an address it cannot resolve, so the page watches for the PC- # itself: a PC new to the list since the ask, or one at the typed address, is the answer.- self._finding = {"host": host, "known": {pc["address"] for pc in self._pcs}, "serial": serial} if host else None- self._said_find(self._shown(f"Asking {host}…") if host else "")- if host:- AppHelper.callLater(6.0, lambda: self._find_timed_out(serial))-- @objc.python_method- def _said_find(self, message, ink="ink_2"):- self.find_status.set(message, ink=ink)- motion.set_hidden(self.find_status.view, not message)-- @objc.python_method- def _find_answered(self, pcs):- finding = getattr(self, "_finding", None)- if finding is None:- return- found = next((pc for pc in pcs if pc["address"] == finding["host"] or pc["address"] not in finding["known"]), None)- if found is not None:- self._finding = None- self._said_find(f"Found {found['name']}. Choose it in the list.", "signal")-- @objc.python_method- def _find_timed_out(self, serial):- finding = getattr(self, "_finding", None)- if finding is not None and finding["serial"] == serial:- self._said_find(- self._shown(f"No answer from {finding['host']} yet. Check the address, and that Beamer is open on the PC; "- "this Mac keeps asking."),- "amber",- )-- def confirmPair_(self, _sender):- pc = self.chosen_pc- if pc is None or self._pairing or self.discovery is None:- return- code = re.sub(r"\D", "", self.code_boxes.value)- if len(code) != pairing.CODE_DIGITS:- self._say_pairing(f"The code is {pairing.CODE_DIGITS} digits.", "fault")- return- # The list may have refreshed since the row was chosen; pair with the PC's latest beacon.- current = next((entry for entry in self._pcs if entry["address"] == pc["address"]), pc)- if current["pair_id"] is None:- self._say_pairing(f"{current['name']} is not showing a code. Start pairing in Beamer on it, then try again.", "fault")- return- self._pairing = True- self.confirm_button.set_enabled(False)- self._say_pairing(f"Pairing with {current['name']}…")- discovery = self.discovery-- def work():- try:- result = discovery.pair(current, code)- except pairing.PairingError as exc:- result = exc- except Exception as exc:- self.logger.exception("pairing failed")- result = pairing.PairingError(str(exc))- AppHelper.callAfter(self._pairing_finished, current, result)-- threading.Thread(target=work, name="pair", daemon=True).start()-- @objc.python_method- def _pairing_finished(self, pc, result):- self._pairing = False- self.confirm_button.set_enabled(self.chosen_pc is not None)- name = pc["name"]- if isinstance(result, pairing.PairingError):- reason = str(result)- if reason == pairing.ERROR_NOT_PAIRING:- self._say_pairing(f"{name} is not showing a code. Start pairing in Beamer on it, then try again.", "fault")- elif reason == pairing.ERROR_REFUSED:- self._say_pairing("That code was not accepted, and the PC has cancelled it. Start pairing there again for a fresh one.", "fault")- elif reason == pairing.ERROR_VERSION:- self._say_pairing("The PC runs a different version of Beamer. Update Beamer on both machines, then pair again.", "fault")- elif reason == "no_answer":- self._say_pairing(f"{name} did not answer. Check both machines are on the same network, then try again.", "fault")- else:- self._say_pairing(f"Pairing failed: {reason}", "fault")- return- # The name the exchange proved, not the one the beacon claimed.- token, name = result- raw = config_to_raw(self.controller.cfg)- raw["host"] = pc["address"]- raw["port"] = pc["port"]- raw["auth_token"] = token- raw["pc_name"] = name- # The Mac has just exchanged packets with the PC, so its ARP entry is fresh.- raw["mac_address"] = lookup_mac(pc["address"]) or ""- try:- cfg = self.settings_store.save(raw)- except SettingsError as exc:- self._say_pairing(f"Paired, but the settings could not be saved: {exc}", "fault")- return- self.code_boxes.clear()- self.chosen_pc = None- self._pcs_key = None- self._repairing = False- self._load(config_to_raw(cfg))- self.controller.update_config(cfg)- self._say("Paired with " + name + ". Connecting…", "signal")- self.logger.info("paired with %s at %s", name, pc["address"])-@objc.python_methoddef _persist_mac(self, _mac):"""The controller has already put the learned address on cfg; this writes it down."""@@ -2981,7 +2715,7 @@ class ControlWindow(AppKit.NSObject):@objc.python_methoddef refresh(self):controller = self.controller- self._show_directions()+ self._follow_first_peer()self._show_same()access = accessibility_granted()listening = input_monitoring_granted()@@ -3007,14 +2741,16 @@ class ControlWindow(AppKit.NSObject):sentence = self._ways_in_sentence()self.ways_note.set(sentence + "." if sentence else "No way in is switched on. Choose one below.")state = link_state.describe(controller)- self._refresh_paired(state)- self.sidebar.set_link(state, self._shown(link_state.peer_name(controller.cfg)))- self.sidebar.set_dots(pages.dots(access, listening, state.key))+ rows = self.panel.rows()+ self._place_machines(not rows)+ refused = any(row.state.key == "token" for row in rows)+ self.sidebar.set_link(replace(state, word=self._shown(state.word)), self._shown(self._machine_label()) if rows else "—")+ self.sidebar.set_dots(pages.dots(access, listening, "token" if refused else state.key))self.link_led.set(state.led, state.blink)self.link_tag.set(state.tag)- if (state.word, state.tone) != (self.state_word.text, self.state_word.ink):+ if (self._shown(state.word), state.tone) != (self.state_word.text, self.state_word.ink):motion.cross_fade(self.state_word.view)- self.state_word.set(state.word, ink=state.tone)+ self.state_word.set(self._shown(state.word), ink=state.tone)self.state_detail.set(self._shown(state.detail))round_trip = controller.round_trip_ms@@ -3030,6 +2766,10 @@ class ControlWindow(AppKit.NSObject):self.spark.setNeedsDisplay_(True)cfg = controller.cfgself._show_peer()+ first = controller.peer_label+ 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")@@ -3049,11 +2789,12 @@ class ControlWindow(AppKit.NSObject):if controller.redirecting:self.toggle_button.set_title("Return input to Mac")elif controller.waking:- self.toggle_button.set_title("Waking Windows…")+ self.toggle_button.set_title(self._shown(f"Waking {self._first_label()}…"))elif controller.can_wake:- self.toggle_button.set_title("Wake Windows")+ self.toggle_button.set_title(self._shown(f"Wake {self._first_label()}"))else:- self.toggle_button.set_title("Send input to Windows")+ self.toggle_button.set_title(+ self._shown(f"Send input to {self._first_label()}") if controller.peer_label else "Send input")self.toggle_button.set_style("live" if controller.redirecting or controller.windows_locked else "primary")self.toggle_button.set_enabled(controller.input_ready@@ -3067,7 +2808,7 @@ class ControlWindow(AppKit.NSObject):if macelse "Read from the network the first time this Mac connects; nothing to type.")- self._refresh_pcs()+ self.panel.refresh()class StatusItemClick(AppKit.NSObject):@@ -3157,16 +2898,22 @@ class TrayApp(rumps.App):self.control_window.windows_input = self.windows_input# Same on both machines, over either link: applied on the main thread, and announced# with the arrangement the moment either link comes up.- for link in (self.windows_input.server, controller):- link.announce = self._announce- self.windows_input.server.settings_callback = self._settings+ controller.announce = self._announce+ self.windows_input.settings_callback = self._settingscontroller.on_settings = self._settingsself.windows_input.sync(controller.cfg)- self.discovery = pairing.Discovery(logger=logger)- self.control_window.discovery = self.discovery- self.discovery.start()- # A PC that changed address is followed by its beacon; bridge sets cfg.host, this saves it.- controller.discovery = self.discovery+ # Pairing, both ways: this Mac shows a code or enters one. `peers` and `store` run on the+ # service's socket threads under its lock, so they read and write through the settings+ # store's own lock and never wait on the main thread.+ identity = controller.identity()+ self.pairing = pairing.PairingService(+ identity["name"], bytes(identity["id"]), identity["platform"], lambda: controller.own_port,+ controller.book.peers, settings_store.add_peer, on_paired=self._hosted_pairing, logger=logger,+ )+ self.control_window.panel.service = self.pairing+ self.pairing.start()+ # A machine that changed address is followed by its beacon; bridge sets cfg.host, this saves it.+ controller.discovery = self.pairingcontroller.on_host_learned = lambda host: AppHelper.callAfter(self.control_window._persist_mac, None)self.update_checker = updates.Checker(VERSION, lambda: self.controller.cfg.check_updates,@@ -3177,11 +2924,11 @@ class TrayApp(rumps.App):self.header_item = header = rumps.MenuItem(f"Beamer {VERSION}", callback=None)self.update_url = Noneself.status_item = rumps.MenuItem("Starting", callback=None)- self.toggle_item = rumps.MenuItem("Send input to Windows", callback=self.toggle_redirect)+ self.toggle_item = rumps.MenuItem("Send input", callback=self.toggle_redirect)self.pause_item = rumps.MenuItem("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 Windows", callback=self.toggle_send_to_windows)- self.receive_item = rumps.MenuItem("Windows drives this Mac", callback=self.toggle_windows_drives)+ 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._symbol = Nonesuper().__init__("Beamer",@@ -3235,20 +2982,17 @@ class TrayApp(rumps.App):AppKit.NSWorkspace.sharedWorkspace().openURL_(AppKit.NSURL.fileURLWithPath_(str(LOG_DIRECTORY)))def _announce(self):- """What this Mac tells the PC on every new link: where the machines are, even never- changed (an unstamped arrangement from the Mac fills a PC that holds only what a hello- told it), and its settings state. On the link's own thread."""- crossing_cfg = self.controller.cfg.crossing- return [protocol.arrangement_msg(crossing_cfg["edge"], crossing_cfg.get("arrangement_set_at", 0)),- protocol.settings_msg(self.control_window.same_state())]+ """What this Mac tells a machine on every new link beyond what the link itself announces+ (where the two sit, who else this Mac has): its settings state. On the link's own thread."""+ return [protocol.settings_msg(self.control_window.same_state())]- def _settings(self, data):- AppHelper.callAfter(self.control_window.apply_same, data)+ def _settings(self, data, peer=None):+ AppHelper.callAfter(self.control_window.apply_same, data, peer)- def _arrangement(self, mac_edge, set_at):+ def _arrangement(self, mac_edge, set_at, by=None):"""An arrangement from the PC, over either link, applied on the mainthread -- it writes the settings file and redraws the window."""- AppHelper.callAfter(self.control_window.apply_arrangement, mac_edge, set_at)+ AppHelper.callAfter(self.control_window.apply_arrangement, mac_edge, set_at, by)def show_on_startup(self, _timer):self.startup_timer.stop()@@ -3280,14 +3024,32 @@ class TrayApp(rumps.App):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"else:- self.toggle_item.title = "Send input to Windows"+ self.toggle_item.title = pages.redact(+ f"Send input to {controller.peer_label}" if controller.peer_label else "Send input", hide)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+ self._direction_items()+ self.status_item.title = pages.redact(link_state.describe(controller).word, hide)++ 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+ for item, name in ((self.send_item, "send"), (self.receive_item, "allow_drive")):+ on = [peer.get(name) is True for peer in 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@@ -3316,30 +3078,50 @@ class TrayApp(rumps.App):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()+ 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: `send=` or `allow_drive=`."""+ 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}")+ # Some machines may have been saved before this one failed, and a switch the person+ # flipped shows a state that is not saved: read it all again.+ self.control_window.panel.invalidate()+ self.control_window.peers_changed()return- if not cfg.send_to_windows and self.controller.redirecting:- # Input comes home by this switch, and shows where the pointer is as any switch does;- # update_config would bring it home too, silently, as it does for a new address.- self.controller.set_redirecting(False)- self.controller.update_config(cfg)- self.windows_input.sync(cfg)- self.logger.info("directions: this Mac drives Windows %s, Windows drives this Mac %s",- "on" if cfg.send_to_windows else "off", "on" if cfg.allow_windows_to_drive else "off")+ if change.get("send") is False and any(entry.get("id") == controller.owner.on for entry in entries):+ # Input comes home by this switch, and shows where the pointer is as any switch does.+ controller.set_redirecting(False)+ self.control_window.peers_changed()+ self.logger.info("directions: %s", ", ".join(+ f"{entry.get('name')} send {'on' if entry['send'] else 'off'} drive {'on' if entry['allow_drive'] else 'off'}"+ for entry in entries))self.refresh_status(None)+ def _hosted_pairing(self, entry):+ """A machine paired with the code this Mac showed. On the pairing thread, after the entry+ was stored: the rest happens on the main thread."""+ AppHelper.callAfter(self.control_window.panel.hosted_pairing, entry)+def reload_config(self, _sender):- """Re-reads config.json, for the times it was edited outside the window."""+ """Re-reads settings.json, for the times it was edited outside the window."""try:cfg = self.settings_store.load()except SettingsError as exc:@@ -3491,7 +3273,7 @@ class TrayApp(rumps.App):def quit_app(self, _sender=None):self.status_timer.stop()self.update_checker.stop()- self.discovery.stop()+ self.pairing.stop()self.windows_input.stop()self.controller.stop()rumps.quit_application()@@ -3502,7 +3284,7 @@ def parse_args(argv=None):parser.add_argument("--config",default=None,- help="config path; defaults to ~/Library/Application Support/Beamer/config.json",+ help="settings path; defaults to ~/Library/Application Support/Beamer/settings.json",)parser.add_argument("--hidden", action="store_true", help="start in the menu bar without opening the window")return parser.parse_args(argv)@@ -3530,7 +3312,8 @@ def main(argv=None):else:logger.info("first run: no settings yet, starting from the defaults")cfg = editable_default_config()- controller = WakingController(cfg, logger=logger)+ book, identity = bridge.links_from_store(settings_store, VERSION)+ controller = WakingController(cfg, logger=logger, book=book, identity=identity, hardware=hardware_mac.hardware_address_towards)app = TrayApp(controller, settings_store, logger, hidden=args.hidden)controller.start()try:diff --git a/mac_app/link_state.py b/mac_app/link_state.pyindex 272623f..f33f614 100644--- a/mac_app/link_state.py+++ b/mac_app/link_state.py@@ -9,17 +9,13 @@ from __future__ import annotationsfrom dataclasses import dataclass-from bridge import AUTH_FAILED_STATUS, OLD_RECEIVER_STATUS-from wake import NOT_WOKEN_STATUS+from wake import NOT_WOKEN_SUFFIXSIGNAL = "signal"AMBER = "amber"FAULT = "fault"INK = "ink"-TUNNEL_STATUS = "Connected to Windows via secure macOS 27 fallback"--@dataclass(frozen=True)class LinkState:key: str@@ -32,23 +28,29 @@ class LinkState:def peer_name(cfg) -> str:- return cfg.pc_name or cfg.host or "Windows"+ return cfg.pc_name or cfg.host or "the other machine"def describe(controller) -> LinkState:+ """The controller may name each machine (`peer_label` the first, `on_label` the one input is+ on, `driver_label` the one driving this Mac), which tells two of one name apart; without, the+ first machine's saved name stands in."""cfg = controller.cfg- peer = peer_name(cfg)+ peer = getattr(controller, "peer_label", None) or peer_name(cfg)+ on = getattr(controller, "on_label", None) or peer+ driver = getattr(controller, "driver_label", None) or peerstatus = controller.connection_status or ""- tunnel = status.startswith(TUNNEL_STATUS) or getattr(controller, "_status_before_unlock", None) == TUNNEL_STATUS+ tunnel = bool(getattr(controller, "via_tunnel", False))+ kind = getattr(controller, "status_kind", "none")if getattr(controller, "receiving", False):return LinkState(- "receiving", SIGNAL, "From Windows", "Live",- f"{peer}'s keyboard and pointer are on this Mac. Push its pointer back through the edge "+ "receiving", SIGNAL, f"From {driver}", "Live",+ f"{driver}'s keyboard and pointer are on this Mac. Push its pointer back through the edge ""it arrived by to send them home.",SIGNAL,)if controller.waking:- return LinkState("waking", AMBER, "Waking", "Waking", "Waking Windows. It connects on its own once it is up.", AMBER, True)+ return LinkState("waking", AMBER, "Waking", "Waking", f"Waking {peer}. It connects on its own once it is up.", AMBER, True)if controller.connected:linked = "Tunnel" if tunnel else "Linked"if controller.windows_locked:@@ -59,8 +61,8 @@ def describe(controller) -> LinkState:)if controller.redirecting:return LinkState(- "windows", SIGNAL, "On Windows", "Live",- f"Keyboard and pointer are on {peer}. Do the same again to bring them home.", SIGNAL,+ "windows", SIGNAL, f"On {on}", "Live",+ f"Keyboard and pointer are on {on}. Do the same again to bring them home.", SIGNAL,)armed = controller.crossing.armedif armed and controller.crossing_paused:@@ -76,23 +78,21 @@ def describe(controller) -> LinkState:via = " through the macOS 27 tunnel" if tunnel else ""return LinkState("mac", INK, "On Mac", linked, f"Connected to {peer}{via}.", SIGNAL)if not (cfg.host and cfg.auth_token):- return LinkState("unpaired", AMBER, "Not paired", "Setup", "Pair with a PC on Overview and Beamer connects on its own.", AMBER)+ return LinkState("unpaired", AMBER, "Not paired", "Setup", "Pair a machine on Overview and Beamer connects on its own.", AMBER)address = f"{cfg.host} port {cfg.port}"- if status == AUTH_FAILED_STATUS:- return LinkState("token", FAULT, "Token mismatch", "Refused", f"{peer} refused this Mac's shared token. Pair again to write a fresh one.", FAULT)- if status == OLD_RECEIVER_STATUS or status.startswith("Windows receiver speaks Beamer protocol"):+ if kind in ("unauthenticated", "wrong_id", "different", "unreadable"):+ return LinkState("token", FAULT, "Token mismatch", "Refused", f"{peer} refused this Mac's token. Remove it, then pair again to write a fresh one.", FAULT)+ if kind in ("older", "newer", "not_beamer"):return LinkState("version", FAULT, "Version mismatch", "Refused", f"{peer} runs a different Beamer from this Mac. Update both to the same version.", FAULT)- if status.startswith("Windows rejected the connection"):- return LinkState("rejected", FAULT, "Refused", "Refused", status + ".", FAULT)- if status == NOT_WOKEN_STATUS:+ if status.endswith(NOT_WOKEN_SUFFIX):return LinkState("not_woken", FAULT, "Did not wake", "No reply", f"{peer} did not answer within a minute of the wake-up packet.", FAULT)- if status.startswith("macOS 27 blocked direct LAN access"):+ if kind == "blocked":return LinkState("blocked", FAULT, "Blocked", "Tunnel", "macOS 27 blocked direct LAN access. Open Beamer Tunnel from Applications.", FAULT)- if status.startswith("Windows is unreachable") or status.startswith("Windows did not answer before"):- return LinkState("unreachable", FAULT, "Unreachable", "No reply", f"{address} is not answering. The PC may be asleep or off this network.", FAULT)- if status.startswith("Windows is reachable, but Beamer is not listening"):- return LinkState("not_listening", FAULT, "Not listening", "No receiver", f"{peer} answers, but Beamer is not listening on port {cfg.port}. Open Beamer on the PC.", FAULT)- if status == "Windows stopped responding":+ if kind in ("unreachable", "timeout"):+ return LinkState("unreachable", FAULT, "Unreachable", "No reply", f"{address} is not answering. {peer} may be asleep or off this network.", FAULT)+ if kind == "refused":+ return LinkState("not_listening", FAULT, "Not listening", "No receiver", f"{peer} answers, but Beamer is not listening on port {cfg.port}. Open Beamer on {peer}.", FAULT)+ if kind in ("stopped", "closed"):return LinkState("stopped", FAULT, "No reply", "Dropped", f"{peer} stopped responding. Beamer keeps trying to reconnect.", FAULT)if status.startswith("Connecting to") or status in ("Waiting to connect", "Settings saved; reconnecting"):return LinkState("waiting", AMBER, "Waiting", "Looking", f"Looking for {peer}. It connects on its own once Beamer is open there.", AMBER, True)diff --git a/mac_app/machines.py b/mac_app/machines.pynew file mode 100644index 0000000..3de9513--- /dev/null+++ b/mac_app/machines.py@@ -0,0 +1,82 @@+"""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+ drives: bool+ driven: bool+++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("send") is True, entry.get("allow_drive") is True,+ )+++def _state(entry, label, live, kind, status, here, driving, inbound, has_link) -> LinkState:+ if not protocol.is_paired_token(entry.get("token")):+ return LinkState(+ "pair_again", AMBER, "Pair again", "Pair again",+ f"{label} was paired in 1.4.x with a typed token, which 1.5.0 does not use. Remove it and pair it again.", 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 --git a/mac_app/machines_panel.py b/mac_app/machines_panel.pynew file mode 100644index 0000000..039bd09--- /dev/null+++ b/mac_app/machines_panel.py@@ -0,0 +1,624 @@+"""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++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._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"))+ 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.")+ 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.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")+ 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.drives, r.driven)+ for r in rows))+ 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)+ 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)+ 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)+ widgets.add(body, head)+ 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)+ widgets.add(body, widgets.note(self._shown(state.detail)).view)+ 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.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.focus_id = (row.token, "driven")+ widgets.add(body, self._controls(row, 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, drives, driven, remove):+ """The two switches, and the way to remove them on the same line while there is room."""+ if self.removing == row.token:+ column = widgets.stack(spacing=6)+ for view in (drives.view, driven.view, remove):+ widgets.add(column, view)+ return column+ line = widgets.stack(vertical=False, spacing=24)+ for view in (drives.view, driven.view):+ line.addArrangedSubview_(view)+ widgets.hug(view, AppKit.NSLayoutPriorityRequired)+ line.addArrangedSubview_(widgets.hug(widgets.box(), AppKit.NSLayoutPriorityDefaultLow))+ if self.wide:+ line.addArrangedSubview_(remove)+ return line++ 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")+ 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+ 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()++ 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,+ 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))+ 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):+ self.qr_caption.set(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 in enumerate(heard):+ self._heard_row(index, item, item["address"] == chosen)+ 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):+ 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)+ line.addArrangedSubview_(widgets.hug(widgets.squeeze(name.view), AppKit.NSLayoutPriorityDefaultLow))+ detail = "Older Beamer" if older else " · ".join(part for part in (platform, self._shown(item["address"])) if part)+ line.addArrangedSubview_(widgets.Label(detail, theme.TYPE["small"], mono=True, ink="amber" if older else "ink_3").view)+ 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 --git a/mac_app/pages.py b/mac_app/pages.pyindex 69d98bf..8fe2b33 100644--- a/mac_app/pages.py+++ b/mac_app/pages.py@@ -14,8 +14,8 @@ from core import effects# 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."),("crossing", "Crossing", "cursorarrow.motionlines",@@ -26,7 +26,7 @@ PAGES = (("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 PC is and the token this Mac proves itself with. Pairing fills these in."),+ "Where the first machine you paired is. Pairing fills these in."),)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@@ -235,11 +235,11 @@ def crossing_state_sentence(paired, sending, connected, armed, paused, full_scre"""The Crossing page's line under Pause: why nothing can cross, first match wins, and only thenwhether crossing is on, held or paused."""if not paired:- return "Not paired yet, so no edge or shortcut moves input until you pair with a PC above."+ return "Not paired yet, so no edge or shortcut moves input until you pair a machine on Overview."if not sending:- return "This Mac drives Windows is off, so edges and the shortcut do nothing."+ return "No machine is driven by this Mac, so edges and the shortcut do nothing."if not connected:- return "Not connected to the PC, so edges and the shortcut do nothing yet."+ return "Not connected to any machine, so edges and the shortcut do nothing yet."if not armed:return "Only the shortcut is switched on; there is nothing to pause."if paused:diff --git a/mac_app/pointer_hide.py b/mac_app/pointer_hide.pynew file mode 100644index 0000000..43d773d--- /dev/null+++ b/mac_app/pointer_hide.py@@ -0,0 +1,85 @@+"""Hide the Mac's pointer while it drives the other machine.++With the mouse dissociated (bridge._set_cursor_follows_mouse) the pointer sits pinned where it+crossed, a sliver at a corner. Hiding it needs two things: CGDisplayHideCursor, which only works+for a process that is frontmost unless the connection is told otherwise, hence the private+CGSSetConnectionProperty call. Hide and show are counted by the window server, so this keeps one+flag and calls each once per redirect: a second hide would need a second show.++The hide belongs to this process's connection to the window server, so if Beamer dies while the+pointer is hidden the server gives it back with the connection. A normal exit shows it on the way+out (atexit, and the controller's stop).+"""++import atexit+import ctypes+import logging+import threading++try:+ import Quartz+except ImportError: # pragma: no cover - exercised only off macOS+ Quartz = None++_CORE_GRAPHICS = "/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics"+_CORE_FOUNDATION = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"+_UTF8 = 0x08000100+++def allow_background_hiding() -> None:+ """Tell the window server this connection may set the cursor while another app is frontmost."""+ cf = ctypes.CDLL(_CORE_FOUNDATION)+ cf.CFStringCreateWithCString.restype = ctypes.c_void_p+ cf.CFStringCreateWithCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32]+ key = cf.CFStringCreateWithCString(None, b"SetsCursorInBackground", _UTF8)+ true = ctypes.c_void_p.in_dll(cf, "kCFBooleanTrue").value+ cg = ctypes.CDLL(_CORE_GRAPHICS)+ cg._CGSDefaultConnection.restype = ctypes.c_int+ cg.CGSSetConnectionProperty.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p]+ cg.CGSSetConnectionProperty.restype = ctypes.c_int+ connection = cg._CGSDefaultConnection()+ status = cg.CGSSetConnectionProperty(connection, connection, key, true)+ if status != 0:+ raise OSError(f"CGSSetConnectionProperty returned {status}")+++class PointerHider:+ def __init__(self, quartz=Quartz, background=None, logger=None):+ self.quartz = quartz+ # The private call is for the real window server only; a fake Quartz gets a no-op.+ self.background = background or (allow_background_hiding if quartz is Quartz else (lambda: None))+ self.logger = logger or logging.getLogger("Beamer")+ self._lock = threading.Lock()+ self._hidden = False+ self._background_tried = False+ atexit.register(self.show)++ def hide(self) -> None:+ with self._lock:+ if self._hidden:+ return+ if not self._background_tried:+ self._background_tried = True+ try:+ self.background()+ except Exception:+ self.logger.exception("could not let the pointer hide while another app is frontmost")+ try:+ status = self.quartz.CGDisplayHideCursor(self.quartz.CGMainDisplayID())+ except Exception:+ self.logger.exception("could not hide the pointer")+ return+ if status == 0:+ self._hidden = True+ else:+ self.logger.warning("the system would not hide the pointer (%s)", status)++ def show(self) -> None:+ with self._lock:+ if not self._hidden:+ return+ self._hidden = False+ try:+ self.quartz.CGDisplayShowCursor(self.quartz.CGMainDisplayID())+ except Exception:+ self.logger.exception("could not show the pointer")diff --git a/mac_app/qr.py b/mac_app/qr.pynew file mode 100644index 0000000..874fe14--- /dev/null+++ b/mac_app/qr.py@@ -0,0 +1,52 @@+"""The pairing QR, drawn with Core Image's CIQRCodeGenerator through PyObjC, which adds no dependency.++The generator gives one pixel per module; this reads them back into a grid and draws it as+square modules, dark on a light tile with the four-module quiet zone every reader wants, whatever+the window's appearance is.+"""++import AppKit+import Foundation+import Quartz++QUIET_MODULES = 4+++def modules(text):+ """The QR's modules as rows of booleans (True is dark), without any border. ValueError when+ the text is too long for a code."""+ data = text.encode("utf-8")+ generator = Quartz.CIFilter.filterWithName_("CIQRCodeGenerator")+ generator.setValue_forKey_(Foundation.NSData.dataWithBytes_length_(data, len(data)), "inputMessage")+ generator.setValue_forKey_("M", "inputCorrectionLevel")+ output = generator.outputImage()+ if output is None or output.extent().size.width < 1:+ raise ValueError("the text does not fit in a QR code")+ size = int(output.extent().size.width)+ rep = AppKit.NSBitmapImageRep.alloc().initWithCIImage_(output)+ grid = [[rep.colorAtX_y_(x, y).redComponent() < 0.5 for x in range(size)] for y in range(size)]+ # The generator's own one-module border, which the quiet zone replaces.+ return [row[1:-1] for row in grid[1:-1]]+++def image(text, side):+ """An NSImage showing `text` as a QR, square and no bigger than `side` points: a whole number+ of points to a module, so the edges are sharp."""+ grid = modules(text)+ cells = len(grid) + 2 * QUIET_MODULES+ unit = max(1, int(side // cells))+ side = unit * cells++ def draw(_rect):+ AppKit.NSColor.whiteColor().setFill()+ AppKit.NSRectFill(Foundation.NSMakeRect(0, 0, side, side))+ AppKit.NSColor.blackColor().setFill()+ for row, line in enumerate(grid):+ for column, dark in enumerate(line):+ if dark:+ # NSImage's drawing space has its origin bottom left; the grid's row 0 is the top.+ AppKit.NSRectFill(Foundation.NSMakeRect(+ (column + QUIET_MODULES) * unit, side - (row + QUIET_MODULES + 1) * unit, unit, unit))+ return True++ return AppKit.NSImage.imageWithSize_flipped_drawingHandler_((side, side), False, draw)diff --git a/mac_app/settings_store.py b/mac_app/settings_store.pyindex f680faa..1bbb99f 100644--- a/mac_app/settings_store.py+++ b/mac_app/settings_store.py@@ -1,13 +1,28 @@+"""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+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 threadingfrom pathlib import Pathimport config as config_modulefrom core import effectsfrom core import ignored+from core import peerlistfrom core import protocol+from core import receiverfrom core import return_edgefrom crossing import CORNERS, EDGES, GLOW_COLOURS, GLOW_STYLES, HAPTIC_FEELS, HAPTIC_STEPS, METHODS, NOTCH_STYLES@@ -16,12 +31,58 @@ from wake import parse_macAPP_SUPPORT_DIRECTORY = Path.home() / "Library" / "Application Support" / "Beamer"-DEFAULT_SETTINGS_PATH = APP_SUPPORT_DIRECTORY / "config.json"+DEFAULT_SETTINGS_PATH = APP_SUPPORT_DIRECTORY / "settings.json"+LEGACY_FILE = "config.json"++SCHEMA = 6+MAX_PEERS = 32+# What moves out of `crossing` into the peer and the zones once a peer exists (WIRE.md sections 1 and 8).+MOVED_CROSSING = ("methods", "edge", "edge_parts", "corner", "arrangement_set_at")+ZONE_KINDS = tuple(method for method in METHODS if method != "shortcut")+# Fields settings.json has that Config has no name for; everything else in it is Config's own.+SETTINGS_ONLY = ("schema", "machine_id", "name", "port", "shortcut", "migrated_token_sha256", "peers", "zones", "crossing")+PEER_DEFAULTS = {+ "id": "", "name": "", "platform": "", "token": "", "host": "", "port": 0, "hw": "", "send": True,+ "allow_drive": True, "side": "", "side_set_at": 0, "side_by": "", "paired_with": [], "paired_at": 0,+ "linked": False, "from_1_4": False,+}+class SettingsError(Exception):pass+def _b64(data):+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")+++def _unb64(text, length):+ """The bytes of a b64 text of exactly `length` bytes, or None; one spelling only (WIRE.md, Encodings)."""+ if not isinstance(text, str):+ return None+ try:+ data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))+ except (binascii.Error, ValueError):+ return None+ return data if len(data) == length and _b64(data) == text else None+++def is_machine_id(text):+ data = _unb64(text, 16)+ return data is not None and any(data)+++def new_machine_id():+ while True:+ data = secrets.token_bytes(16)+ if any(data):+ return _b64(data)+++def _sha256(text):+ return hashlib.sha256(text.encode("utf-8")).hexdigest() if text else ""++def editable_default_config():return config_module.Config(# Learned by pairing. Nothing about the PC is known on a fresh install.@@ -42,6 +103,7 @@ def editable_default_config():hide_addresses=False,same_on_both=False,same_set_at=0,+ same_by="",pointer_speed=1.0,scroll_speed=1.0,reverse_scroll=False,@@ -73,6 +135,7 @@ def config_to_raw(cfg):"hide_addresses": cfg.hide_addresses,"same_on_both": cfg.same_on_both,"same_set_at": cfg.same_set_at,+ "same_by": cfg.same_by,"pointer_speed": cfg.pointer_speed,"scroll_speed": cfg.scroll_speed,"reverse_scroll": cfg.reverse_scroll,@@ -81,39 +144,394 @@ 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."""+ 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]+ 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, side_by=None):+ """`base` with the values of `cfg` written over it: the pairing fields into peers[0], the rest by name.+ `side_by` is who made a change to the side when it came from the peer's `arrangement`."""+ 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"]+ if not cfg.auth_token:+ if peers:+ gone = peers.pop(0)+ settings["zones"] = [zone for zone in zones if zone.get("peer") != gone["id"]]+ elif not peers or peers[0]["token"] != cfg.auth_token:+ entry = _entry_from_config(cfg, machine_id)+ if peers:+ zones = _rename_zones(zones, peers[0]["id"], "")+ peers[0] = entry+ else:+ peers.append(entry)+ settings["zones"] = _apply_zones(zones, "", crossing)+ else:+ peer = peers[0]+ stamp = crossing["arrangement_set_at"]+ side_by = side_by or (peer["side_by"] if stamp == peer["side_set_at"] else machine_id)+ peer.update(+ name=cfg.pc_name, 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=(side_by or machine_id) if stamp else "",+ )+ settings["zones"] = _apply_zones(zones, peer["id"], crossing)+ settings["crossing"] = {+ name: value for name, value in crossing.items() if not (peers 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: a link may have+ # given the migrated entry its id, or linked it, 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` (this Mac drives the machine) and `allow_drive` (it may drive this Mac) 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") or not isinstance(value, bool) for name, value in switches.items()):+ raise SettingsError("only send and allow_drive 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 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 save(self, raw, side_by=None):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)+ cfg = self._without_stale_pairing(cfg, base, handed)+ return self._config(self.save_settings(_merge_config(base, cfg, side_by)))- 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 ""+ 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._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._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"]]+ 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"]}+ return 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 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.++ The notch is not counted: it fires on a dwell, and 1.4.x let it stand beside the edge."""+ sides = {peer["id"]: peer["side"] for peer in settings["peers"]}+ seen = set()+ for zone in settings["zones"]:+ if zone.get("off") is True or zone["kind"] == "notch":+ continue+ side = sides[zone["peer"]]+ if zone["kind"] == "corner":+ stretch = {("corner", zone["corner"])}+ elif side:+ stretch = {(side, part) for part in (return_edge.PARTS if zone["kind"] == "edge" else zone["parts"])}+ else:+ continue+ if stretch & seen:+ raise SettingsError("two zones in use cover the same stretch of the screen")+ seen |= stretch++ def _write(self, settings):self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)try:os.chmod(self.path.parent, 0o700)@@ -125,23 +543,20 @@ class SettingsStore:mode="w",encoding="utf-8",dir=self.path.parent,- prefix=".config.",+ prefix=".settings.",suffix=".tmp",delete=False,) as handle:temporary_path = Path(handle.name)- json.dump(raw, handle, indent=2, ensure_ascii=False)+ json.dump(settings, handle, indent=2, ensure_ascii=False)handle.write("\n")handle.flush()os.fsync(handle.fileno())os.chmod(temporary_path, 0o600)- cfg = config_module.load_config(str(temporary_path))- self._validate(cfg)os.replace(temporary_path, self.path)temporary_path = Noneos.chmod(self.path, 0o600)- return cfg- except (config_module.ConfigError, json.JSONDecodeError, OSError, TypeError, ValueError) as exc:+ except (OSError, TypeError, ValueError) as exc:raise SettingsError(str(exc)) from excfinally:if temporary_path is not None:@@ -150,6 +565,60 @@ class SettingsStore: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)+ 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")diff --git a/mac_app/setup.py b/mac_app/setup.pyindex 587a38e..13e9a7c 100644--- a/mac_app/setup.py+++ b/mac_app/setup.py@@ -25,18 +25,27 @@ setup("config","crossing","desktop_mac",+ "diagram","effects_overlay","gestures",+ "hardware_mac",+ "ignored_titles","input_injector_mac","key_codes","keyboard_layout","link_state",+ "login_item",+ "machines",+ "machines_panel","media_keys",+ "motion","notch_beam","notch_island","pages",+ "pointer_hide","previews","no_unlock",+ "qr","settings_store","theme","tokens",@@ -63,10 +72,13 @@ setup("packages": ["rumps", "cffi", "nacl"],# core/effects.py imports its fx_* modules by name at first use, which py2app's import# scan cannot see, so they are named here or the bundle ships without a single effect.- # The rest of core/ is found by the scan, through the repo root put on sys.path above;- # naming the package whole would ship its tests too.+ # The rest of core/ is named too, through the repo root put on sys.path above, so a module+ # the scan misses cannot drop out; naming the package whole would ship its tests too."includes": ["objc", "AppKit", "ApplicationServices", "Quartz",+ "core.effects", "core.ignored", "core.keytable", "core.link", "core.owner", "core.pairing",+ "core.peerlist", "core.protocol", "core.receiver", "core.return_edge", "core.settings_sync",+ "core.updates", "core.wol","core.fx_ink", "core.fx_instrument", "core.fx_membrane", "core.fx_sparks", "core.fx_warp",],"iconfile": "../Beamer.icns",diff --git a/mac_app/tests/bridge_fakes.py b/mac_app/tests/bridge_fakes.pynew file mode 100644index 0000000..919fcb0--- /dev/null+++ b/mac_app/tests/bridge_fakes.py@@ -0,0 +1,186 @@+"""The fakes the Mac app's controller tests share: a Quartz that records, a clock that stands+still, a clipboard that never touches the pasteboard, and the Config a controller is made from."""++import base64+import logging++import config+from core import protocol++class FakeQuartz:+ kCGEventKeyDown = 10+ kCGEventKeyUp = 11+ kCGEventFlagsChanged = 12+ kCGEventMouseMoved = 5+ kCGEventLeftMouseDragged = 6+ kCGEventRightMouseDragged = 7+ kCGEventOtherMouseDragged = 27+ kCGEventLeftMouseDown = 1+ kCGEventLeftMouseUp = 2+ kCGEventRightMouseDown = 3+ kCGEventRightMouseUp = 4+ kCGEventOtherMouseDown = 25+ kCGEventOtherMouseUp = 26+ kCGEventScrollWheel = 22+ kCGEventTapDisabledByTimeout = 0xFFFFFFFE+ kCGEventTapDisabledByUserInput = 0xFFFFFFFF+ kCGEventSourceUserData = 42+ kCGKeyboardEventKeycode = 9+ kCGKeyboardEventAutorepeat = 8+ kCGMouseEventDeltaX = 4+ kCGMouseEventDeltaY = 5+ kCGMouseEventButtonNumber = 3+ kCGScrollWheelEventDeltaAxis1 = 11+ kCGScrollWheelEventDeltaAxis2 = 12+ kCGScrollWheelEventIsContinuous = 13+ kCGScrollWheelEventPointDeltaAxis1 = 96+ kCGScrollWheelEventPointDeltaAxis2 = 97+ kCGEventFlagMaskAlphaShift = 1 << 16+ kCGEventFlagMaskShift = 1 << 17+ kCGEventFlagMaskControl = 1 << 18+ kCGEventFlagMaskAlternate = 1 << 19+ kCGEventFlagMaskCommand = 1 << 20++ @staticmethod+ def CGEventGetIntegerValueField(event, field):+ return event.get(field, 0)++ @staticmethod+ def CGEventGetDoubleValueField(event, field):+ return float(event.get(field, 0))++ @staticmethod+ def CGEventGetFlags(event):+ return event.get("flags", 0)++ @staticmethod+ def CGEventKeyboardGetUnicodeString(event, maximum, length, characters):+ value = event.get("unicode", "")+ return len(value.encode("utf-16-le")) // 2, value++ # -- Cursor pinning (Bug 1: belt-and-braces warp) --------------------+ # Call lists are class-level so every KVMController built against+ # FakeQuartz in a test shares them; tests that care about counts reset+ # these in setUp, matching how InjectScrollDispatchTests (win_app) resets+ # its own module-level accumulator.+ cursor_pin_location = (111.0, 222.0)+ associate_calls = []+ warp_calls = []+ tap_enable_calls = []++ @classmethod+ def reset_cursor_spies(cls):+ cls.associate_calls = []+ cls.warp_calls = []+ cls.tap_enable_calls = []++ @staticmethod+ def CGEventCreate(source):+ return {"_fake_probe_event": True}++ @classmethod+ def CGEventGetLocation(cls, event):+ return event.get("location", cls.cursor_pin_location)++ @classmethod+ def CGAssociateMouseAndMouseCursorPosition(cls, follows):+ cls.associate_calls.append(follows)+ return 0++ @classmethod+ def CGWarpMouseCursorPosition(cls, point):+ cls.warp_calls.append(point)+ return 0++ @classmethod+ def CGEventTapEnable(cls, tap, enabled):+ cls.tap_enable_calls.append((tap, enabled))+++class FakeGestureEvent:+ """Stands in for bridge.py's `_GestureEventView` (the object a converted+ NSEvent is wrapped in): exposes exactly the plain attribute surface+ GestureTranslator reads, with no AppKit involved."""++ def __init__(self, magnification=0.0, deltaX=0.0, deltaY=0.0, phase=0):+ self.magnification = magnification+ self.deltaX = deltaX+ self.deltaY = deltaY+ self.phase = phase+++class FakeClock:+ def __init__(self, value=10.0):+ self.value = value++ def __call__(self):+ return self.value+++# A token the way pairing makes one: the b64 of 32 bytes, so a real link would dial under it.+PAIRED_TOKEN = base64.urlsafe_b64encode(bytes(range(32))).decode("ascii").rstrip("=")+++def make_config(token="synthetic-token"):+ return config.Config(+ host="192.0.2.10",+ port=51820,+ auth_token=token,+ trigger_key="alt_r",+ double_tap_ms=300,+ key_map=dict(config.DEFAULT_KEY_MAP),+ reconnect_interval_s=0.1,+ )+++def crossing_config(token="synthetic-token", **overrides):+ cfg = make_config(token)+ cfg.crossing = dict(config.DEFAULT_CROSSING, **overrides)+ return cfg+++def quiet_logger():+ logger = logging.getLogger("kvm-bridge-tests")+ logger.handlers = [logging.NullHandler()]+ logger.propagate = False+ return logger+++FAKE_PNG = protocol.PNG_SIGNATURE + b"\x00" * 64+++class FakeClipboard:+ """Drop-in replacement for clipboard_mac, injected via+ KVMController(clipboard=...) so tests never touch the real macOS+ pasteboard."""++ def __init__(self, text=None, image=None):+ self.text = text+ self.image = image+ self.set_calls = []+ self.stamp = 1++ def change_stamp(self):+ return self.stamp++ def copy(self, text):+ """The person copies something: a change by their own hand."""+ self.text = text+ self.stamp += 1++ def get_contents(self):+ return self.text, self.image++ def changed_contents(self):+ return self.text, self.image++ def forget_sync(self):+ pass++ def set_contents(self, text, image):+ self.set_calls.append((text, image))+ self.text, self.image = text, image+ self.stamp += 1+ return True++diff --git a/mac_app/tests/fake_link.py b/mac_app/tests/fake_link.pynew file mode 100644index 0000000..624c63b--- /dev/null+++ b/mac_app/tests/fake_link.py@@ -0,0 +1,128 @@+"""A stand-in for core.link.OutboundLink, so the controller's own behaviour (routing through the+owner, the pointer, the alerts, the clipboard) is tested without a socket.++ controller = KVMController(cfg, link_factory=FakeLink, ...)+ peer = bring_up(controller) # the primary peer's handshake done: owner.link_up, announcements+ controller.set_redirecting(True)+ peer.sent # input the controller gave the link, in order+ peer.posted # control messages: focus, clipboard, arrangement, paired, ...++The wire itself (handshake, framing, acks, liveness) is core/tests/test_link.py's; the two ends+together are test_mac_links.py's."""++from core import protocol++PEER_ID = bytes(range(1, 17))+OTHER_ID = bytes(range(41, 57))+CAPS = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings")+++class FakeLink:+ def __init__(self, token, book, identity, *, state=None, up=None, message=None, notice=None, socket_factory=None,+ tunnel=None, clock=None, reconnect_seconds=2.0, hardware=None, large=None):+ self.token = token+ self.hardware = hardware+ self.large = large+ self.book = book+ self.callbacks = {"state": state, "up": up, "message": message, "notice": notice}+ self.tunnel = tunnel+ self.started = False+ self.stopped = False+ self.peer_id = ""+ self.peer_platform = "windows"+ self.peer_name = ""+ self.caps = frozenset()+ self.via_tunnel = False+ self.kind = "failed"+ self.status = ""+ self.peer_locked = False+ self.dialled = None+ self.sent = []+ self.posted = []+ self.dropped = []+ self.followed = []+ self.samples = []+ self.full = False+ self._live = False++ def start(self):+ self.started = True++ def stop(self, wait=True):+ self.stopped = True+ self.stop_waited = wait+ self._live = False++ def refresh(self):+ pass++ def flush(self, timeout=0.5):+ pass++ def drop(self, reason):+ self.dropped.append(reason)++ def live(self):+ return self._live++ def entry(self):+ for peer in self.book.peers():+ if peer.get("token") == self.token:+ return peer+ return None++ def post(self, message):+ if not self._live or self.full:+ return False+ self.posted.append(message)+ return True++ def send_input(self, message):+ if not self._live or self.full:+ return False+ self.sent.append(message)+ return True++ def round_trips(self, max_age=30.0):+ return list(self.samples)++ def follow(self, machines):+ self.followed.append(list(machines))++ # What a test does to it++ def up(self, controller, ident=PEER_ID, name="Office PC", platform="windows", caps=CAPS, accepts=True, hw=None):+ """The handshake done, as the link would report it."""+ self._live = True+ self.peer_id = protocol.id_text(ident)+ self.peer_name, self.peer_platform = name, platform+ self.caps = frozenset(caps)+ self.kind = "connected"+ self.status = f"Connected to {name}"+ self.dialled = ("192.0.2.10", 24820)+ fields = {"id": ident, "name": name, "platform": platform, "app": "1.5.0", "caps": list(caps), "accepts": accepts, "hw": hw}+ controller._link_state(self, True, self.status)+ controller._link_up(self, fields)+ return fields++ def down(self, controller, text="Office PC stopped responding", kind="stopped"):+ self._live = False+ self.kind, self.status = kind, text+ controller._link_state(self, False, text)++ def arrives(self, controller, message, began=None):+ """A message from the peer, as the link hands it on."""+ message = protocol.Message(message)+ if began is not None:+ message.began_at = began+ controller._link_message(self, message)++ def types(self):+ return [message["type"] for message in self.posted]+++def bring_up(controller, **fields):+ """The controller's primary link, up."""+ link = controller._primary_link+ link.up(controller, **fields)+ return linkdiff --git a/mac_app/tests/fixtures/config_1_4_3.py b/mac_app/tests/fixtures/config_1_4_3.pynew file mode 100644index 0000000..3580a7c--- /dev/null+++ b/mac_app/tests/fixtures/config_1_4_3.py@@ -0,0 +1,164 @@+"""1.4.3 verbatim from 0ef920b, imports only re-pointed at core/ and this fixture (downgrade test)."""++"""Shared config.json loader for mac_sender.py and win_receiver.py."""++import json+import os+from dataclasses import dataclass, field++from core import effects+from crossing import DEFAULT_CROSSING++DEFAULT_CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")++DEFAULT_KEY_MAP = {+ "alt": "alt",+ "alt_r": "alt",+ "ctrl": "cmd",+ "ctrl_r": "cmd",+ "cmd": "ctrl",+ "cmd_r": "ctrl",+}++# The positional map Beamer used to ship as the default, written verbatim+# into every existing config.json. A saved key_map beats the default, so+# without this an upgraded install would silently keep sending Cmd as the+# Windows key.+# A saved map whose every entry matches this one is the old default rather+# than a deliberate choice, so it is discarded.+LEGACY_POSITIONAL_KEY_MAP = {+ "alt": "alt",+ "alt_r": "alt",+ "ctrl": "ctrl",+ "ctrl_r": "ctrl",+ "cmd": "cmd",+ "cmd_r": "cmd",+}+++# The two modifier styles the settings window offers. A saved key_map may be one of these+# names instead of a JSON object; Positional has to be saved by name, because its object form is+# the old default and is discarded on load (see LEGACY_POSITIONAL_KEY_MAP).+# The settings window's palette: follow the Mac, or keep one. tokens.APPEARANCES is the home of these+# values; this copy keeps config importable without the repo root, and test_shared_copies holds the+# two together.+APPEARANCES = ("system", "light", "dark")++KEY_MAP_STYLES = {+ "semantic": DEFAULT_KEY_MAP,+ "positional": LEGACY_POSITIONAL_KEY_MAP,+}+++class ConfigError(Exception):+ pass+++@dataclass+class Config:+ host: str+ port: int+ auth_token: str+ trigger_key: str = "alt_r"+ double_tap_ms: int = 300+ key_map: dict = field(default_factory=lambda: dict(DEFAULT_KEY_MAP))+ reconnect_interval_s: float = 2.0+ trigger_style: str = "double_tap"+ crossing: dict = field(default_factory=lambda: dict(DEFAULT_CROSSING))+ # Learned, never typed: the PC's name from its pairing beacon and its hardware address from+ # the ARP table, which is what wake-on-LAN needs.+ pc_name: str = ""+ mac_address: str = ""+ # One switch per direction, each in the menu bar: this Mac's input going to Windows, and+ # the PC's input arriving here. Off stops that direction only; the other keeps working.+ send_to_windows: bool = True+ allow_windows_to_drive: bool = True+ # Ask GitHub once a day whether a newer release is out; see updates.py.+ check_updates: bool = True+ # Every address the window shows is hidden; see pages.redact.+ hide_addresses: bool = False+ # How the PC's pointer and scroll feel on this Mac; see receiver.InputScale.+ pointer_speed: float = 1.0+ scroll_speed: float = 1.0+ reverse_scroll: bool = False+ appearance: str = "system"+ # Keys and buttons that stay on this Mac while its input is on Windows; see ignored.py.+ ignored_inputs: list = field(default_factory=list)+++def key_map_style(key_map):+ """The name of a key_map when it is one of the two offered styles, else None."""+ for name, mapping in KEY_MAP_STYLES.items():+ if key_map == mapping:+ return name+ return None+++def load_config(path: str = None) -> Config:+ path = path or DEFAULT_CONFIG_PATH+ if not os.path.exists(path):+ raise ConfigError(+ f"config file not found: {path}\n"+ f"Copy config.example.json to config.json and fill in your own values."+ )++ with open(path, "r", encoding="utf-8") as f:+ raw = json.load(f)++ missing = [k for k in ("host", "port", "auth_token") if k not in raw]+ if missing:+ raise ConfigError(f"config.json is missing required field(s): {', '.join(missing)}")++ # Empty means not yet paired, which every setting must still be able to save+ # around; only the example file's placeholder is refused.+ if raw["auth_token"] == "CHANGE_ME":+ raise ConfigError("config.json auth_token is still the placeholder — pair with a PC or pick a real shared secret")++ key_map = dict(DEFAULT_KEY_MAP)+ saved_key_map = raw.get("key_map", {})+ if isinstance(saved_key_map, str):+ if saved_key_map not in KEY_MAP_STYLES:+ raise ConfigError(f"config.json key_map style must be one of: {', '.join(KEY_MAP_STYLES)}")+ key_map = dict(KEY_MAP_STYLES[saved_key_map])+ elif not isinstance(saved_key_map, dict):+ raise ConfigError("config.json key_map must be a JSON object or a style name")+ elif saved_key_map != LEGACY_POSITIONAL_KEY_MAP:+ # Only the whole old default is the accident. A partial map whose+ # entries happen to agree with it -- {"cmd": "cmd"} on its own -- is a+ # choice, and was being thrown away.+ key_map.update(saved_key_map)++ crossing = dict(DEFAULT_CROSSING)+ saved_crossing = raw.get("crossing", {})+ if not isinstance(saved_crossing, dict):+ raise ConfigError("config.json crossing must be a JSON object")+ crossing.update(saved_crossing)+ crossing["glow_style"], crossing["glow_colour"], crossing["shortcut_arrival_style"] = effects.offered(+ crossing["glow_style"], crossing["glow_colour"], crossing["shortcut_arrival_style"])+ crossing["methods"] = list(crossing["methods"])+ if isinstance(crossing["edge_parts"], list):+ crossing["edge_parts"] = list(crossing["edge_parts"])+ crossing["resistance_px"] = int(crossing["resistance_px"])++ return Config(+ host=raw["host"],+ port=int(raw["port"]),+ auth_token=raw["auth_token"],+ trigger_key=raw.get("trigger_key", "alt_r"),+ double_tap_ms=int(raw.get("double_tap_ms", 300)),+ key_map=key_map,+ reconnect_interval_s=float(raw.get("reconnect_interval_s", 2.0)),+ trigger_style=str(raw.get("trigger_style", "double_tap")),+ crossing=crossing,+ pc_name=str(raw.get("pc_name", "") or ""),+ mac_address=str(raw.get("mac_address", "") or ""),+ send_to_windows=raw.get("send_to_windows", True) is not False,+ allow_windows_to_drive=raw.get("allow_windows_to_drive", True) is not False,+ check_updates=raw.get("check_updates", True) is not False,+ hide_addresses=raw.get("hide_addresses", False) is True,+ pointer_speed=raw.get("pointer_speed", 1.0),+ scroll_speed=raw.get("scroll_speed", 1.0),+ reverse_scroll=raw.get("reverse_scroll", False),+ appearance=raw.get("appearance") if raw.get("appearance") in APPEARANCES else "system",+ ignored_inputs=raw.get("ignored_inputs", []),+ )diff --git a/mac_app/tests/fixtures/settings_store_1_4_3.py b/mac_app/tests/fixtures/settings_store_1_4_3.pynew file mode 100644index 0000000..03568af--- /dev/null+++ b/mac_app/tests/fixtures/settings_store_1_4_3.py@@ -0,0 +1,213 @@+"""1.4.3 verbatim from 0ef920b, imports only re-pointed at core/ and config_1_4_3 (downgrade test)."""++import json+import os+import tempfile+from dataclasses import replace+from pathlib import Path++import config_1_4_3 as config_module+from core import effects+from core import ignored+from core import protocol+from core import return_edge++from crossing import CORNERS, EDGES, GLOW_COLOURS, GLOW_STYLES, HAPTIC_FEELS, HAPTIC_STEPS, METHODS, NOTCH_STYLES+from key_codes import KEY_NAME_TO_CODE+from wake import parse_mac+++APP_SUPPORT_DIRECTORY = Path.home() / "Library" / "Application Support" / "Beamer"+DEFAULT_SETTINGS_PATH = APP_SUPPORT_DIRECTORY / "config.json"++class SettingsError(Exception):+ pass+++def editable_default_config():+ return config_module.Config(+ # Learned by pairing. Nothing about the PC is known on a fresh install.+ host="",+ port=protocol.DEFAULT_PORT,+ auth_token="",+ trigger_key="alt_r",+ double_tap_ms=300,+ key_map=dict(config_module.DEFAULT_KEY_MAP),+ reconnect_interval_s=2.0,+ trigger_style="double_tap",+ crossing=dict(config_module.DEFAULT_CROSSING),+ pc_name="",+ mac_address="",+ send_to_windows=True,+ allow_windows_to_drive=True,+ check_updates=True,+ hide_addresses=False,+ pointer_speed=1.0,+ scroll_speed=1.0,+ reverse_scroll=False,+ appearance="system",+ ignored_inputs=[],+ )+++def config_to_raw(cfg):+ return {+ "host": cfg.host,+ "port": cfg.port,+ "auth_token": cfg.auth_token,+ "trigger_key": cfg.trigger_key,+ "double_tap_ms": cfg.double_tap_ms,+ "key_map": config_module.key_map_style(cfg.key_map) or dict(cfg.key_map),+ "reconnect_interval_s": cfg.reconnect_interval_s,+ "trigger_style": cfg.trigger_style,+ "crossing": {+ **cfg.crossing,+ "methods": list(cfg.crossing["methods"]),+ "edge_parts": list(cfg.crossing["edge_parts"]),+ },+ "pc_name": cfg.pc_name,+ "mac_address": cfg.mac_address,+ "send_to_windows": cfg.send_to_windows,+ "allow_windows_to_drive": cfg.allow_windows_to_drive,+ "check_updates": cfg.check_updates,+ "hide_addresses": cfg.hide_addresses,+ "pointer_speed": cfg.pointer_speed,+ "scroll_speed": cfg.scroll_speed,+ "reverse_scroll": cfg.reverse_scroll,+ "appearance": cfg.appearance,+ "ignored_inputs": list(cfg.ignored_inputs),+ }+++class SettingsStore:+ def __init__(self, path=None):+ self.path = Path(path).expanduser() if path else DEFAULT_SETTINGS_PATH++ def load(self):+ try:+ cfg = config_module.load_config(str(self.path))+ except (config_module.ConfigError, json.JSONDecodeError, OSError, TypeError, ValueError) 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.++ 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:+ return cfg+ cfg = replace(cfg, port=protocol.DEFAULT_PORT)+ try:+ self.save(config_to_raw(cfg))+ except SettingsError:+ # The port in hand is what matters; a read-only config directory must not+ # stop the app connecting on it.+ pass+ return cfg++ def save(self, raw):+ self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)+ try:+ os.chmod(self.path.parent, 0o700)+ except OSError:+ pass+ temporary_path = None+ try:+ with tempfile.NamedTemporaryFile(+ mode="w",+ encoding="utf-8",+ dir=self.path.parent,+ prefix=".config.",+ suffix=".tmp",+ delete=False,+ ) as handle:+ temporary_path = Path(handle.name)+ json.dump(raw, handle, indent=2, ensure_ascii=False)+ handle.write("\n")+ handle.flush()+ os.fsync(handle.fileno())+ os.chmod(temporary_path, 0o600)+ cfg = config_module.load_config(str(temporary_path))+ self._validate(cfg)+ os.replace(temporary_path, self.path)+ temporary_path = None+ os.chmod(self.path, 0o600)+ return cfg+ except (config_module.ConfigError, json.JSONDecodeError, OSError, TypeError, ValueError) as exc:+ raise SettingsError(str(exc)) from exc+ finally:+ if temporary_path is not None:+ try:+ temporary_path.unlink()+ except FileNotFoundError:+ pass++ def _validate(self, cfg):+ if not isinstance(cfg.host, str):+ raise SettingsError("Windows host must be text")+ if not 1 <= cfg.port <= 65535:+ raise SettingsError("Port must be between 1 and 65535")+ if cfg.trigger_key not in KEY_NAME_TO_CODE:+ supported = ", ".join(sorted(KEY_NAME_TO_CODE))+ raise SettingsError(f"Unsupported trigger key. Choose one of: {supported}")+ if not 50 <= cfg.double_tap_ms <= 2000:+ raise SettingsError("Double-tap threshold must be between 50 and 2000 ms")+ if not isinstance(cfg.key_map, dict):+ raise SettingsError("key_map must be a JSON object")+ if not all(isinstance(key, str) and isinstance(value, str) for key, value in cfg.key_map.items()):+ raise SettingsError("key_map keys and values must be strings")+ if cfg.reconnect_interval_s <= 0:+ raise SettingsError("Reconnect interval must be greater than zero")+ if cfg.trigger_style not in ("double_tap", "hold"):+ raise SettingsError("trigger_style must be double_tap or hold")+ crossing = cfg.crossing+ methods = crossing["methods"]+ if not isinstance(methods, list) or not all(method in METHODS for method in methods):+ raise SettingsError(f"crossing.methods must only contain: {', '.join(METHODS)}")+ if crossing["edge"] not in EDGES:+ raise SettingsError(f"crossing.edge must be one of: {', '.join(EDGES)}")+ parts = crossing["edge_parts"]+ if not isinstance(parts, list) or not parts or not all(part in return_edge.PARTS for part in parts):+ raise SettingsError(f"crossing.edge_parts must be one or more of: {', '.join(return_edge.PARTS)}")+ if crossing["corner"] not in CORNERS:+ raise SettingsError(f"crossing.corner must be one of: {', '.join(CORNERS)}")+ if isinstance(crossing["resistance_px"], bool) or not 0 <= crossing["resistance_px"] <= 500:+ raise SettingsError("crossing.resistance_px must be a whole number between 0 and 500")+ if crossing["notch_style"] not in NOTCH_STYLES:+ raise SettingsError(f"crossing.notch_style must be one of: {', '.join(NOTCH_STYLES)}")+ after = crossing["notch_after_ms"]+ if isinstance(after, bool) or not isinstance(after, int) or not 300 <= after <= 3000:+ raise SettingsError("crossing.notch_after_ms must be a whole number between 300 and 3000")+ choices = (+ ("haptic_feel", HAPTIC_FEELS),+ ("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),+ ("shortcut_arrival_style", effects.SWITCH_STYLES),+ ("effect_length", tuple(value for value, _name in effects.LENGTHS)),+ )+ for name, allowed in choices:+ if crossing[name] not in allowed:+ raise SettingsError(f"crossing.{name} must be one of: {', '.join(allowed)}")+ for name in ("haptics", "glow", "block_while_dragging", "shortcut_arrival"):+ if not isinstance(crossing[name], bool):+ raise SettingsError(f"crossing.{name} must be true or false")+ for name in ("pointer_speed", "scroll_speed"):+ value = getattr(cfg, name)+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not 0.25 <= value <= 4.0:+ raise SettingsError(f"{name} must be a number from 0.25 to 4")+ if not isinstance(cfg.reverse_scroll, bool):+ raise SettingsError("reverse_scroll must be true or false")+ try:+ ignored.validate(cfg.ignored_inputs)+ except ValueError as exc:+ raise SettingsError(str(exc)) from exc+ if cfg.mac_address and parse_mac(cfg.mac_address) is None:+ raise SettingsError("mac_address must be six hex pairs, such as 02:1A:2B:3C:0D:4E")diff --git a/mac_app/tests/test_appearance.py b/mac_app/tests/test_appearance.pyindex 31ecc87..39da359 100644--- a/mac_app/tests/test_appearance.py+++ b/mac_app/tests/test_appearance.py@@ -1,6 +1,6 @@"""The settings window's light and dark palettes: the choice, the Mac's own setting and a live switch.-The window is built for real, as tools/readme_shots_mac.py builds it, and never put on screen."""+The window is built for real, as the README's screenshots build it, and never put on screen."""import jsonimport loggingdiff --git a/mac_app/tests/test_arm_return_resistance.py b/mac_app/tests/test_arm_return_resistance.pydeleted file mode 100644index f3b173e..0000000--- a/mac_app/tests/test_arm_return_resistance.py+++ /dev/null@@ -1,37 +0,0 @@-import json-import unittest-import os-import sys--sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from core import return_edge-from core.receiver import ReceiverServer---class ArmReturnResistanceTest(unittest.TestCase):- """json.loads accepts the bare Infinity and NaN tokens, so an authenticated- peer can put either in `resistance_px`; int() of them raises, and nothing- above _arm_return caught it, so the session thread died unlogged. A bad- number now gets the default and the session carries on."""-- def _armed_with(self, literal):- server = ReceiverServer(status_callback=lambda state, text: None)- server._arm_return(json.loads('{"target": "windows", "return_edge": "left", "resistance_px": %s}' % literal))- return server._return_edge-- def test_infinite_resistance_falls_back_to_the_default(self):- model = self._armed_with("Infinity")- self.assertEqual(model.edge, "left")- self.assertEqual(model.resistance_px, return_edge.DEFAULT_RESISTANCE_PX)-- def test_nan_resistance_falls_back_to_the_default(self):- model = self._armed_with("NaN")- self.assertEqual(model.resistance_px, return_edge.DEFAULT_RESISTANCE_PX)-- def test_a_real_resistance_is_kept(self):- self.assertEqual(self._armed_with("40").resistance_px, 40)---if __name__ == "__main__":- unittest.main()diff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.pyindex 1b18796..4146979 100644--- a/mac_app/tests/test_bridge.py+++ b/mac_app/tests/test_bridge.py@@ -1,14 +1,17 @@-import dataclasses+"""The Mac controller's event tap, its pointer and its local effects, with the links faked. The+wire itself is core/tests/test_link.py's; where input goes, and the clipboard, are also+test_mac_links.py's. The names re-exported from bridge_fakes below are still imported from here by+the test modules that have not moved to bridge_fakes."""+import errno-import jsonimport loggingimport osimport queue-import struct+import sysimport threading+import timeimport typesimport unittest-import syssys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))@@ -16,312 +19,43 @@ import configimport media_keysfrom core import protocolfrom bridge import (- ACK_TIMEOUT_SECONDS,- AUTH_FAILED_STATUS,CONNECT_TIMEOUT_SECONDS,CROSSING_RETRY_SECONDS,- OLD_RECEIVER_STATUS,- PING_INTERVAL_SECONDS,- ROUND_TRIP_MAX_AGE_SECONDS,- ROUND_TRIP_SAMPLES,- SOCKET_IO_TIMEOUT_SECONDS,- FrameDecoder,KVMController,QuartzEventTranslator,- connection_error_message,)+from bridge_fakes import ( # noqa: F401 (re-exported)+ FAKE_PNG,+ PAIRED_TOKEN,+ FakeClipboard,+ FakeClock,+ FakeGestureEvent,+ FakeQuartz,+ crossing_config,+ make_config,+ quiet_logger,+)+from fake_link import OTHER_ID, PEER_ID, FakeLink, bring_upfrom gestures import DOCK_CONTROL_TYPE, MAGNIFY_TYPE, SWIPE_TYPEfrom input_injector_mac import INJECTED_MARK-def link(controller, sock=None, token="synthetic-token"):- """Hand `controller` a FakeSocket as _connect_once would: a new session- with the preambles exchanged, so both ends hold this connection's keys."""- sock = sock or FakeSocket()- sock.peer = protocol.SecureSession(token)- controller.session = protocol.SecureSession(controller.cfg.auth_token)- controller.session.accept_preamble(sock.peer.preamble())- sock.peer.accept_preamble(controller.session.preamble())- sock.mac_preamble = controller.session.preamble()- controller.sock = sock- return sock---def sent_messages(controller, sock):- """Open every frame `controller` sent over a FakeSocket, in order --- counters must advance, so a frame can only be read in sequence. A fresh- opener with the receiver's prefix each call, so this can be asked twice."""- opener = protocol.SecureSession(sock.peer._token, prefix=sock.peer.prefix)- opener.accept_preamble(sock.mac_preamble)- return [opener.open(payload[protocol.HEADER_SIZE:]) for payload in sock.sent if payload != sock.mac_preamble]---def seed_receiver_reply(sock, *messages, token="synthetic-token"):- """Queue a receiver's preamble on a FakeSocket, and replies it seals once- the Mac's preamble has gone out, as a Windows receiver holding `token`- would send them: a reply's key needs both prefixes."""- sock.peer = protocol.SecureSession(token)- sock.inbound.extend(sock.peer.preamble())- sock.pending.extend(messages)- return sock.peer---class FakeQuartz:- kCGEventKeyDown = 10- kCGEventKeyUp = 11- kCGEventFlagsChanged = 12- kCGEventMouseMoved = 5- kCGEventLeftMouseDragged = 6- kCGEventRightMouseDragged = 7- kCGEventOtherMouseDragged = 27- kCGEventLeftMouseDown = 1- kCGEventLeftMouseUp = 2- kCGEventRightMouseDown = 3- kCGEventRightMouseUp = 4- kCGEventOtherMouseDown = 25- kCGEventOtherMouseUp = 26- kCGEventScrollWheel = 22- kCGEventTapDisabledByTimeout = 0xFFFFFFFE- kCGEventTapDisabledByUserInput = 0xFFFFFFFF- kCGEventSourceUserData = 42- kCGKeyboardEventKeycode = 9- kCGKeyboardEventAutorepeat = 8- kCGMouseEventDeltaX = 4- kCGMouseEventDeltaY = 5- kCGMouseEventButtonNumber = 3- kCGScrollWheelEventDeltaAxis1 = 11- kCGScrollWheelEventDeltaAxis2 = 12- kCGScrollWheelEventIsContinuous = 13- kCGScrollWheelEventPointDeltaAxis1 = 96- kCGScrollWheelEventPointDeltaAxis2 = 97- kCGEventFlagMaskAlphaShift = 1 << 16- kCGEventFlagMaskShift = 1 << 17- kCGEventFlagMaskControl = 1 << 18- kCGEventFlagMaskAlternate = 1 << 19- kCGEventFlagMaskCommand = 1 << 20-- @staticmethod- def CGEventGetIntegerValueField(event, field):- return event.get(field, 0)-- @staticmethod- def CGEventGetDoubleValueField(event, field):- return float(event.get(field, 0))-- @staticmethod- def CGEventGetFlags(event):- return event.get("flags", 0)-- @staticmethod- def CGEventKeyboardGetUnicodeString(event, maximum, length, characters):- value = event.get("unicode", "")- return len(value.encode("utf-16-le")) // 2, value-- # -- Cursor pinning (Bug 1: belt-and-braces warp) --------------------- # Call lists are class-level so every KVMController built against- # FakeQuartz in a test shares them; tests that care about counts reset- # these in setUp, matching how InjectScrollDispatchTests (win_app) resets- # its own module-level accumulator.- cursor_pin_location = (111.0, 222.0)- associate_calls = []- warp_calls = []- tap_enable_calls = []-- @classmethod- def reset_cursor_spies(cls):- cls.associate_calls = []- cls.warp_calls = []- cls.tap_enable_calls = []-- @staticmethod- def CGEventCreate(source):- return {"_fake_probe_event": True}-- @classmethod- def CGEventGetLocation(cls, event):- return event.get("location", cls.cursor_pin_location)-- @classmethod- def CGAssociateMouseAndMouseCursorPosition(cls, follows):- cls.associate_calls.append(follows)- return 0-- @classmethod- def CGWarpMouseCursorPosition(cls, point):- cls.warp_calls.append(point)- return 0-- @classmethod- def CGEventTapEnable(cls, tap, enabled):- cls.tap_enable_calls.append((tap, enabled))---class FakeGestureEvent:- """Stands in for bridge.py's `_GestureEventView` (the object a converted- NSEvent is wrapped in): exposes exactly the plain attribute surface- GestureTranslator reads, with no AppKit involved."""-- def __init__(self, magnification=0.0, deltaX=0.0, deltaY=0.0, phase=0):- self.magnification = magnification- self.deltaX = deltaX- self.deltaY = deltaY- self.phase = phase---class FakeClock:- def __init__(self, value=10.0):- self.value = value-- def __call__(self):- return self.value---class FakeSocket:- def __init__(self):- self.timeout = None- self.sent = []- self.closed = False- self.shutdown_called = False- self.inbound = bytearray()- self.peer = None- self.mac_preamble = None- self.pending = []-- def settimeout(self, value):- self.timeout = value-- def setsockopt(self, level, option, value):- return None-- def sendall(self, payload):- self.sent.append(payload)-- def recv(self, size):- if self.peer is not None and self.peer.peer_prefix is None and self.sent:- self.mac_preamble = self.sent[0]- self.peer.accept_preamble(self.mac_preamble)- if self.pending and self.mac_preamble is not None:- for message in self.pending:- self.inbound.extend(self.peer.seal(message))- self.pending = []- if not self.inbound:- raise TimeoutError("no synthetic reply")- chunk = bytes(self.inbound[:size])- del self.inbound[:size]- return chunk-- def shutdown(self, how):- self.shutdown_called = True-- def close(self):- self.closed = True---def make_config():- return config.Config(- host="192.0.2.10",- port=51820,- auth_token="synthetic-token",- trigger_key="alt_r",- double_tap_ms=300,- key_map=dict(config.DEFAULT_KEY_MAP),- reconnect_interval_s=0.1,+def make_controller(clock, cfg=None, **overrides):+ """A controller whose links are FakeLinks and whose clipboard is not the pasteboard."""+ options = dict(+ logger=quiet_logger(), quartz=FakeQuartz, clock=clock, clipboard=FakeClipboard(),+ link_factory=FakeLink, desktop_bounds=lambda: (0, 0, 1920, 1080),)+ options.update(overrides)+ return KVMController(cfg or make_config(PAIRED_TOKEN), **options)-def crossing_config(**overrides):- cfg = make_config()- cfg.crossing = dict(config.DEFAULT_CROSSING, **overrides)- return cfg-+def drain(controller):+ messages = []+ while not controller.outbound.empty():+ messages.append(controller.outbound.get_nowait())+ return messages-def quiet_logger():- logger = logging.getLogger("kvm-bridge-tests")- logger.handlers = [logging.NullHandler()]- logger.propagate = False- return logger---FAKE_PNG = protocol.PNG_SIGNATURE + b"\x00" * 64---class FakeClipboard:- """Drop-in replacement for clipboard_mac, injected via- KVMController(clipboard=...) so tests never touch the real macOS- pasteboard."""-- def __init__(self, text=None, image=None):- self.text = text- self.image = image- self.set_calls = []-- def get_contents(self):- return self.text, self.image-- def changed_contents(self):- return self.text, self.image-- def forget_sync(self):- pass-- def set_contents(self, text, image):- self.set_calls.append((text, image))- return True---class FrameDecoderTests(unittest.TestCase):- def setUp(self):- self.windows = protocol.SecureSession("synthetic-token")- self.mac = protocol.SecureSession("synthetic-token")- self.mac.accept_preamble(self.windows.preamble())- self.windows.accept_preamble(self.mac.preamble())- self.decoder = FrameDecoder(self.mac)-- def test_decodes_fragmented_frames(self):- message = protocol.ack_msg(42)- frame = self.windows.seal(message)- self.assertEqual(self.decoder.feed(frame[:3]), [])- self.assertEqual(self.decoder.feed(frame[3:8]), [])- self.assertEqual(self.decoder.feed(frame[8:]), [message])-- def test_round_trip_through_the_framing(self):- messages = [protocol.ack_msg(1), protocol.clipboard_msg("copied"), protocol.switch_msg("mac", "left", 0.25)]- stream = b"".join(self.windows.seal(m) for m in messages)- self.assertEqual(self.decoder.feed(stream), messages)- self.assertNotIn(b"copied", stream)-- def test_largest_clipboard_fits_the_reply_stream(self):- image = protocol.PNG_SIGNATURE + os.urandom(protocol.CLIPBOARD_IMAGE_MAX_BYTES - len(protocol.PNG_SIGNATURE))- text = "x" * protocol.CLIPBOARD_MAX_BYTES- message = protocol.clipboard_msg(text, image)- self.assertEqual(self.decoder.feed(self.windows.seal(message)), [message])-- def test_wrong_token_fails_authentication(self):- stranger = protocol.SecureSession("another-token", prefix=self.windows.prefix)- stranger.accept_preamble(self.mac.preamble())- with self.assertRaises(protocol.AuthenticationError):- self.decoder.feed(stranger.seal(protocol.ack_msg(1)))-- def test_replayed_frame_is_rejected(self):- frame = self.windows.seal(protocol.ack_msg(1))- self.decoder.feed(frame)- with self.assertRaises(protocol.ProtocolError) as caught:- self.decoder.feed(frame)- self.assertNotIsInstance(caught.exception, protocol.AuthenticationError)-- def test_counter_going_backwards_is_rejected(self):- first = self.windows.seal(protocol.ack_msg(1))- second = self.windows.seal(protocol.ack_msg(2))- self.assertEqual(self.decoder.feed(first), [protocol.ack_msg(1)])- self.assertEqual(self.decoder.feed(second), [protocol.ack_msg(2)])- # Counter 1 arriving after counter 2 has been opened -- a rewound stream.- with self.assertRaises(protocol.ProtocolError) as caught:- self.decoder.feed(first)- self.assertNotIsInstance(caught.exception, protocol.AuthenticationError)-- def test_rejects_oversized_frame(self):- with self.assertRaises(protocol.ProtocolError):- self.decoder.feed(struct.pack(">I", protocol.MAX_FRAME_BYTES + 1))class TranslatorTests(unittest.TestCase):@@ -551,11 +285,24 @@ class TranslatorTests(unittest.TestCase):class ControllerTests(unittest.TestCase):def setUp(self):self.clock = FakeClock()- self.controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,+ self.controller = make_controller(self.clock)+ self.addCleanup(self.controller.stop_event.set)+ self.alerts = []+ self.controller.on_user_alert = lambda title, message: self.alerts.append((title, message))+ self.own = protocol.id_text(self.controller.identity()["id"])++ def _tap(self, event_type, event):+ return self.controller._event_tap_callback(None, event_type, event, None)++ def _double_tap(self):+ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": FakeQuartz.kCGEventFlagMaskAlternate}+ up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}+ self._tap(FakeQuartz.kCGEventFlagsChanged, down)+ self._tap(FakeQuartz.kCGEventFlagsChanged, up)+ self.clock.value = 10.2+ return (+ self._tap(FakeQuartz.kCGEventFlagsChanged, down),+ self._tap(FakeQuartz.kCGEventFlagsChanged, up),)def test_local_event_passes_through(self):@@ -564,12 +311,7 @@ class ControllerTests(unittest.TestCase):FakeQuartz.kCGKeyboardEventAutorepeat: 0,"unicode": "a",}- returned = self.controller._event_tap_callback(- None,- FakeQuartz.kCGEventKeyDown,- event,- None,- )+ returned = self._tap(FakeQuartz.kCGEventKeyDown, event)self.assertIs(returned, event)self.assertTrue(self.controller.outbound.empty())@@ -580,18 +322,27 @@ class ControllerTests(unittest.TestCase):"unicode": "a",}self.controller.redirecting = True- returned = self.controller._event_tap_callback(- None,- FakeQuartz.kCGEventKeyDown,- event,- None,- )+ returned = self._tap(FakeQuartz.kCGEventKeyDown, event)self.assertIsNone(returned)self.assertEqual(self.controller.outbound.get_nowait(),{"type": protocol.MSG_KEYDOWN, "data": {"key": "a", "us": "a"}},)+ def test_the_tap_queues_physical_key_names_and_the_link_gets_the_peers(self):+ link = bring_up(self.controller)+ self.assertTrue(self.controller.set_redirecting(True))+ command = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x37,+ "flags": FakeQuartz.kCGEventFlagMaskCommand,+ }+ self.assertIsNone(self._tap(FakeQuartz.kCGEventFlagsChanged, command))+ queued = drain(self.controller)+ self.assertEqual(queued, [{"type": protocol.MSG_KEYDOWN, "data": {"key": "cmd"}}])+ for message in queued:+ self.controller._process_outbound(message)+ self.assertEqual(link.sent, [{"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}}])+def test_queue_failure_restores_local_before_returning_event(self):event = {FakeQuartz.kCGKeyboardEventKeycode: 0x00,@@ -601,118 +352,58 @@ class ControllerTests(unittest.TestCase):self.controller.outbound = queue.Queue(maxsize=1)self.controller.outbound.put_nowait({"full": True})self.controller.redirecting = True- returned = self.controller._event_tap_callback(- None,- FakeQuartz.kCGEventKeyDown,- event,- None,- )+ returned = self._tap(FakeQuartz.kCGEventKeyDown, event)self.assertIs(returned, event)self.assertFalse(self.controller.redirecting)def test_double_tap_right_option_only_flips_redirect_flag(self):- sock = FakeSocket()- link(self.controller, sock)+ link = bring_up(self.controller)down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D,"flags": FakeQuartz.kCGEventFlagMaskAlternate,}up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}- first_down = self.controller._event_tap_callback(- None, FakeQuartz.kCGEventFlagsChanged, down, None- )- first_up = self.controller._event_tap_callback(- None, FakeQuartz.kCGEventFlagsChanged, up, None- )+ first_down = self._tap(FakeQuartz.kCGEventFlagsChanged, down)+ first_up = self._tap(FakeQuartz.kCGEventFlagsChanged, up)self.clock.value = 10.2- second_down = self.controller._event_tap_callback(- None, FakeQuartz.kCGEventFlagsChanged, down, None- )- second_up = self.controller._event_tap_callback(- None, FakeQuartz.kCGEventFlagsChanged, up, None- )+ second_down = self._tap(FakeQuartz.kCGEventFlagsChanged, down)+ second_up = self._tap(FakeQuartz.kCGEventFlagsChanged, up)self.assertIs(first_down, down)self.assertIs(first_up, up)self.assertIsNone(second_down)self.assertIsNone(second_up)self.assertTrue(self.controller.redirecting)- self.assertIs(self.controller.sock, sock)+ self.assertTrue(link.live())+ self.assertEqual(link.dropped, [])+ self.assertFalse(link.stopped)- def test_sequence_is_added_once_per_outbound_event(self):- first = self.controller._prepare_outbound(- {"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}}- )- second = self.controller._prepare_outbound(- {"type": protocol.MSG_KEYUP, "data": {"key": "a"}}- )- self.assertEqual(first["data"]["seq"], 1)- self.assertEqual(second["data"]["seq"], 2)-- def test_watchdog_drops_connection_after_two_seconds_without_ack(self):- alerts = []- self.controller.on_user_alert = lambda title, message: alerts.append((title, message))- sock = FakeSocket()- link(self.controller, sock)- self.controller.redirecting = True- self.controller.connected_at = 10.0- self.controller.last_ack_at = 10.0- self.clock.value = 10.0 + ACK_TIMEOUT_SECONDS + 0.01- self.assertTrue(self.controller._watchdog_tick())+ def test_a_failed_connection_while_redirecting_brings_input_home_and_alerts_at_once(self):+ # Otherwise input would simply vanish into a dead connection.+ link = bring_up(self.controller)+ self.assertTrue(self.controller.set_redirecting(True))+ self.controller._connection_failed("Windows stopped responding")self.assertFalse(self.controller.redirecting)- self.assertTrue(sock.closed)+ self.assertEqual(link.dropped, ["Windows stopped responding"])self.assertEqual(self.controller.connection_status, "Windows stopped responding")- # Killing an active redirect must alert the user immediately, since- # otherwise input would simply vanish into a dead connection.- self.assertEqual(alerts, [("Beamer", "Input returned to this Mac")])-- def test_watchdog_detects_a_dead_socket_while_not_redirecting(self):- # Previously the watchdog only ran while redirecting, so a half-open- # connection was invisible while idle: the UI stayed green and a- # double-tap would "succeed" into a void. It must now be detected and- # torn down the same way regardless of redirect state.- sock = FakeSocket()- link(self.controller, sock)- self.controller.redirecting = False- self.controller.connected_at = 10.0- self.controller.last_ack_at = 10.0- self.clock.value = 10.0 + ACK_TIMEOUT_SECONDS + 0.01- self.assertTrue(self.controller._watchdog_tick())+ self.assertEqual(self.alerts, [("Beamer", "Input returned to this Mac")])++ def test_a_failed_connection_while_idle_drops_the_link_without_an_alert(self):+ link = bring_up(self.controller)+ self.controller._connection_failed("Windows stopped responding")self.assertFalse(self.controller.redirecting)- self.assertIsNone(self.controller.sock)- self.assertTrue(sock.closed)+ self.assertEqual(link.dropped, ["Windows stopped responding"])self.assertEqual(self.controller.connection_status, "Windows stopped responding")+ self.assertEqual(self.alerts, [])- def test_watchdog_sends_idle_ping_after_a_second_of_silence(self):- sock = FakeSocket()- link(self.controller, sock)- self.controller.connected_at = 10.0- self.controller.last_ack_at = 10.0- self.controller.last_send_at = 10.0- self.clock.value = 10.0 + PING_INTERVAL_SECONDS- self.assertFalse(self.controller._watchdog_tick())- self.assertEqual(len(sock.sent), 1)- self.assertEqual(sent_messages(self.controller, sock)[-1], protocol.ping_msg())- self.assertEqual(self.controller.last_send_at, self.clock.value)-- def test_watchdog_suppresses_idle_ping_while_traffic_flows(self):- sock = FakeSocket()- link(self.controller, sock)- self.controller.connected_at = 10.0- self.controller.last_ack_at = 10.0- self.controller.last_send_at = 11.5- self.clock.value = 11.6- self.assertFalse(self.controller._watchdog_tick())- self.assertEqual(sock.sent, [])+ def test_input_is_dropped_while_not_redirecting(self):+ link = bring_up(self.controller)+ self.controller._process_outbound({"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}})+ self.assertEqual(link.sent, [])def test_set_redirecting_true_refuses_while_receiving(self):- # Invariant 2: redirecting and receiving must never both be True.- # set_receiving enforces this by turning redirecting off first- # (bridge.py:709-710); set_redirecting has no matching check, so a- # manual switch (the menu bar's toggleRedirect_, kvm_bridge_app.py:1703)- # while Windows is already driving this Mac corrupts the pair. This- # asserts the invariant, which the current code violates.- sock = FakeSocket()- link(self.controller, sock)+ # Redirecting and receiving must never both be True: a Mac driven by another machine+ # and driving one at once is a machine with two owners.+ bring_up(self.controller)self.controller.receiving = Trueself.controller.set_redirecting(True)self.assertFalse(@@ -725,7 +416,7 @@ class ControllerTests(unittest.TestCase):# the edge never fired, and the menu's switch only said Windows was# already driving. Switching now sends the PC's input home instead.sent_home = []- link(self.controller)+ bring_up(self.controller)self.controller.receiving = Trueself.controller.send_peer_home = lambda: sent_home.append(True) or Trueself.assertTrue(self.controller.set_redirecting(True))@@ -733,7 +424,7 @@ class ControllerTests(unittest.TestCase):self.assertFalse(self.controller.redirecting)def test_switching_while_receiving_with_the_pc_unreachable_is_refused(self):- link(self.controller)+ bring_up(self.controller)self.controller.receiving = Trueself.controller.send_peer_home = lambda: Falseself.assertFalse(self.controller.set_redirecting(True))@@ -741,23 +432,18 @@ class ControllerTests(unittest.TestCase):def test_this_macs_trigger_sends_the_pcs_input_home_while_receiving(self):sent_home = []- link(self.controller)+ bring_up(self.controller)self.controller.receiving = Trueself.controller.send_peer_home = lambda: sent_home.append(True) or True- down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": FakeQuartz.kCGEventFlagMaskAlternate}- up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}- tap = self.controller._event_tap_callback- tap(None, FakeQuartz.kCGEventFlagsChanged, down, None)- tap(None, FakeQuartz.kCGEventFlagsChanged, up, None)- self.clock.value = 10.2- self.assertIsNone(tap(None, FakeQuartz.kCGEventFlagsChanged, down, None))- self.assertIsNone(tap(None, FakeQuartz.kCGEventFlagsChanged, up, None))+ second_down, second_up = self._double_tap()+ self.assertIsNone(second_down)+ self.assertIsNone(second_up)self.assertEqual(sent_home, [True])self.assertFalse(self.controller.redirecting)def test_the_pcs_injected_trigger_is_not_this_macs_while_receiving(self):sent_home = []- link(self.controller)+ bring_up(self.controller)self.controller.receiving = Trueself.controller.send_peer_home = lambda: sent_home.append(True) or Truedown = {@@ -765,13 +451,12 @@ class ControllerTests(unittest.TestCase):"flags": FakeQuartz.kCGEventFlagMaskAlternate,FakeQuartz.kCGEventSourceUserData: INJECTED_MARK,}- tap = self.controller._event_tap_callbackfor _ in range(2):- self.assertIs(tap(None, FakeQuartz.kCGEventFlagsChanged, down, None), down)+ self.assertIs(self._tap(FakeQuartz.kCGEventFlagsChanged, down), down)self.assertEqual(sent_home, [])def test_sending_to_windows_switched_off_refuses_the_switch(self):- link(self.controller)+ bring_up(self.controller)self.controller.cfg.send_to_windows = Falseself.assertFalse(self.controller.set_redirecting(True))self.assertFalse(self.controller.redirecting)@@ -779,7 +464,7 @@ class ControllerTests(unittest.TestCase):def test_sending_to_windows_switched_off_still_sends_the_pcs_input_home(self):# Each switch covers one direction: the PC's input on this Mac still goes home.sent_home = []- link(self.controller)+ bring_up(self.controller)self.controller.cfg.send_to_windows = Falseself.controller.receiving = Trueself.controller.send_peer_home = lambda: sent_home.append(True) or True@@ -787,12 +472,10 @@ class ControllerTests(unittest.TestCase):self.assertEqual(sent_home, [True])def test_alert_fired_when_double_tap_cannot_switch_because_disconnected(self):- alerts = []- self.controller.on_user_alert = lambda title, message: alerts.append((title, message))self.controller.connection_status = "Waiting to connect"self.assertFalse(self.controller.set_redirecting(True))self.assertEqual(- alerts,+ self.alerts,[("Beamer", "Cannot switch — Waiting to connect")],)@@ -809,8 +492,7 @@ class ControllerTests(unittest.TestCase):# Regression: the old toggle-based modifier tracking desynced when a# key-up went missing (e.g. a tap restart never delivered it), which# silently killed the double-tap trigger on the very next press.- sock = FakeSocket()- link(self.controller, sock)+ bring_up(self.controller)down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D,"flags": FakeQuartz.kCGEventFlagMaskAlternate | 0x0040,@@ -818,29 +500,13 @@ class ControllerTests(unittest.TestCase):# Simulate the effect of the missed key-up: stale bookkeeping left# over as if the trigger key were still held down.self.controller.translator.modifier_down.add(0x3D)- first_down = self.controller._event_tap_callback(- None, FakeQuartz.kCGEventFlagsChanged, down, None- )+ first_down = self._tap(FakeQuartz.kCGEventFlagsChanged, down)self.clock.value = 10.2- second_down = self.controller._event_tap_callback(- None, FakeQuartz.kCGEventFlagsChanged, down, None- )+ second_down = self._tap(FakeQuartz.kCGEventFlagsChanged, down)self.assertIs(first_down, down)self.assertIsNone(second_down)self.assertTrue(self.controller.redirecting)- def test_handle_inbound_unknown_type_refreshes_liveness_and_is_ignored(self):- self.controller.last_ack_at = 0.0- self.clock.value = 42.0- self.controller._handle_inbound({"type": protocol.MSG_FOCUS, "data": {"target": "windows"}})- self.assertEqual(self.controller.last_ack_at, 42.0)- # Bookkeeping used to validate real ACKs must be untouched.- self.assertEqual(self.controller.last_ack_seq, -1)-- def test_handle_inbound_malformed_message_drops_connection(self):- with self.assertRaises(protocol.ProtocolError):- self.controller._handle_inbound({"data": {}})-def test_worker_exception_forces_local(self):self.controller.redirecting = True@@ -854,11 +520,14 @@ class ControllerTests(unittest.TestCase):# The only thread that drains the queue is never restarted, so a raise# inside one message (the clipboard read every switch does) must force# input local and leave the worker running for the next message.- self.controller.redirecting = True+ bring_up(self.controller)+ self.assertTrue(self.controller.set_redirecting(True))self.controller.clipboard = types.SimpleNamespace(- changed_contents=lambda: (_ for _ in ()).throw(RuntimeError("synthetic clipboard failure"))+ get_contents=lambda: (_ for _ in ()).throw(RuntimeError("synthetic clipboard failure"))+ )+ self.controller.outbound.put_nowait(+ {"type": "_local_clipboard", "data": {}, "peer": protocol.id_text(PEER_ID)})- self.controller.outbound.put_nowait({"type": "_local_clipboard", "data": {}})self.controller.stop_event.clear()def stop_after_one():@@ -870,234 +539,68 @@ class ControllerTests(unittest.TestCase):self.assertFalse(self.controller.redirecting)self.assertEqual(self.controller.outbound.qsize(), 0)- def test_an_ack_without_an_object_body_drops_the_connection_not_the_reader(self):- sock = FakeSocket()- link(self.controller, sock)- with self.assertRaises(protocol.ProtocolError):- self.controller._handle_inbound({"type": protocol.MSG_ACK, "data": None})-def test_every_way_home_tells_windows_while_the_link_is_up(self):# Windows keeps treating this Mac as driving, with whatever keys it was# holding still down, until it hears otherwise.+ link = bring_up(self.controller)for way_home in (lambda: self.controller._force_local("synthetic"),- lambda: self.controller._event_tap_callback(None, FakeQuartz.kCGEventTapDisabledByTimeout, {}, None),+ lambda: self._tap(FakeQuartz.kCGEventTapDisabledByTimeout, {}),):with self.subTest(way_home=way_home):- link(self.controller)self.controller.event_tap = object()- self.controller.set_redirecting(True)- self.controller._drain_outbound()+ self.assertTrue(self.controller.set_redirecting(True))+ link.posted.clear()way_home()- queued = []- while not self.controller.outbound.empty():- queued.append(self.controller.outbound.get_nowait())- self.assertIn(protocol.focus_msg("mac"), queued)+ lets_go = [+ message for message in link.posted+ if message["type"] == protocol.MSG_FOCUS and message["data"]["target"] == self.own+ ]+ self.assertEqual(len(lets_go), 1)def test_every_way_home_reassociates_the_cursor(self):# A path that only cleared `redirecting` left the pointer decoupled# from the hand: keyboard back, pointer frozen.+ bring_up(self.controller)for way_home in (lambda: self.controller._connection_failed("synthetic drop"),lambda: self.controller._force_local("synthetic"),- lambda: self.controller.update_config(crossing_config()),+ lambda: self.controller.update_config(crossing_config(PAIRED_TOKEN)),lambda: self.controller._thread_entry("synthetic", lambda: (_ for _ in ()).throw(RuntimeError())),):with self.subTest(way_home=way_home):- link(self.controller)- self.controller.set_redirecting(True)+ self.assertTrue(self.controller.set_redirecting(True))FakeQuartz.reset_cursor_spies()way_home()self.assertFalse(self.controller.redirecting)self.assertIn(True, FakeQuartz.associate_calls)- def test_connect_and_hello_use_explicit_timeouts(self):- sock = FakeSocket()- seed_receiver_reply(sock, protocol.welcome_msg())- calls = []+ def test_the_primary_link_gets_the_ssh_fallback_and_it_dials_the_local_tunnel(self):+ dialled = []+ sock = object()def socket_factory(address, timeout):- calls.append((address, timeout))+ dialled.append((address, timeout))return sock- controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- socket_factory=socket_factory,- )- self.assertTrue(controller._connect_once())- self.assertEqual(calls, [(('192.0.2.10', 51820), CONNECT_TIMEOUT_SECONDS)])- self.assertEqual(sock.timeout, SOCKET_IO_TIMEOUT_SECONDS)- self.assertEqual(sock.sent[0], controller.session.preamble())- # The hello carries the way home, which is how Windows knows which of- # its own edges leads back here before this Mac has ever crossed.- self.assertEqual(- sent_messages(controller, sock),- [protocol.hello_msg(return_edge="left", resistance_px=120)],- )- self.assertNotIn(b"synthetic-token", b"".join(sock.sent))- self.assertEqual(controller.connected_at, self.clock.value)- self.assertEqual(controller.last_send_at, self.clock.value)-- def test_silent_receiver_after_connect_reports_old_receiver(self):- # A pre-v4 receiver reads our preamble as a bogus frame length and waits- # for a hello that never comes; it says nothing, and never will.- sock = FakeSocket()- controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- socket_factory=lambda address, timeout: sock,- )- self.assertFalse(controller._connect_once())- self.assertEqual(controller.connection_status, OLD_RECEIVER_STATUS)- self.assertTrue(sock.closed)- self.assertIsNone(controller.sock)-- def test_a_pc_that_answered_before_and_falls_silent_is_not_called_old(self):- # Seen in practice: Windows stalled every app for 40s while it reconfigured its displays,- # and the Mac wrongly prompted to update a Beamer that was already current.- answering, silent = FakeSocket(), FakeSocket()- seed_receiver_reply(answering, protocol.welcome_msg())- sockets = iter([answering, silent])- controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- socket_factory=lambda address, timeout: next(sockets),- )- self.assertTrue(controller._connect_once())- self.assertFalse(controller._connect_once())- self.assertEqual(controller.connection_status, "Windows stopped responding")- self.assertTrue(silent.closed)-- def test_a_re_pair_forgets_that_the_old_pc_answered(self):- # A new token can be a different PC at the same address, and a silent one may be old.- answering, silent = FakeSocket(), FakeSocket()- seed_receiver_reply(answering, protocol.welcome_msg())- sockets = iter([answering, silent])- controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- socket_factory=lambda address, timeout: next(sockets),- )- self.assertTrue(controller._connect_once())- controller.update_config(dataclasses.replace(make_config(), auth_token="re-paired-token"))- self.assertFalse(controller._connect_once())- self.assertEqual(controller.connection_status, OLD_RECEIVER_STATUS)-- def test_other_wire_version_in_the_preamble_is_reported(self):- sock = FakeSocket()- sock.inbound.extend(protocol.WIRE_MAGIC + bytes([protocol.PROTOCOL_VERSION + 1]) + b"\x02" * protocol.NONCE_PREFIX_SIZE)- controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- socket_factory=lambda address, timeout: sock,- )- self.assertFalse(controller._connect_once())- self.assertIn(f"v{protocol.PROTOCOL_VERSION + 1}", controller.connection_status)- self.assertIn("update both apps", controller.connection_status)- self.assertTrue(sock.closed)-- def test_wrong_token_reports_authentication_failure(self):- sock = FakeSocket()- seed_receiver_reply(sock, protocol.welcome_msg(), token="a-different-token")- controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- socket_factory=lambda address, timeout: sock,- )- self.assertFalse(controller._connect_once())- self.assertEqual(controller.connection_status, AUTH_FAILED_STATUS)- self.assertTrue(sock.closed)- self.assertIsNone(controller.sock)-- def test_every_connection_draws_a_fresh_nonce_prefix(self):- prefixes = []- for _ in range(2):- sock = FakeSocket()- seed_receiver_reply(sock, protocol.welcome_msg())- controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- socket_factory=lambda address, timeout, sock=sock: sock,- )- initial = controller.session.prefix- self.assertTrue(controller._connect_once())- # _connect_once builds and installs a brand-new session, so the- # prefix it connects with differs from the one it was born holding.- self.assertNotEqual(controller.session.prefix, initial)- prefixes.append(controller.session.prefix)- self.assertNotEqual(prefixes[0], prefixes[1])-- def test_handshake_welcome_version_mismatch_reports_old_receiver(self):- sock = FakeSocket()- seed_receiver_reply(sock, protocol.welcome_msg(error="version_mismatch"))-- controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- socket_factory=lambda address, timeout: sock,- )- self.assertFalse(controller._connect_once())- self.assertEqual(controller.connection_status, OLD_RECEIVER_STATUS)-- def test_handshake_welcome_with_other_error_is_surfaced(self):- sock = FakeSocket()- seed_receiver_reply(sock, protocol.welcome_msg(error="rate_limited"))-- controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- socket_factory=lambda address, timeout: sock,- )- self.assertFalse(controller._connect_once())- self.assertIn("rate_limited", controller.connection_status)-- def test_no_route_uses_existing_ssh_fallback_and_authenticates_over_localhost(self):- sock = FakeSocket()- seed_receiver_reply(sock, protocol.welcome_msg())- socket_calls = []+ controller = make_controller(self.clock, socket_factory=socket_factory)+ link = controller._primary_link+ self.assertEqual(link.tunnel, controller._connect_via_ssh_fallback)+ self.assertIs(link.tunnel(), sock)+ self.assertEqual(dialled, [(("127.0.0.1", 24822), CONNECT_TIMEOUT_SECONDS)])+ def test_a_missing_ssh_tunnel_says_where_to_open_it(self):def socket_factory(address, timeout):- socket_calls.append((address, timeout))- if len(socket_calls) == 1:- raise OSError(errno.EHOSTUNREACH, "No route to host")- return sock+ raise ConnectionRefusedError("nothing listening")- controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- socket_factory=socket_factory,- )- self.assertTrue(controller._connect_once())- self.assertEqual(socket_calls[1][0], ("127.0.0.1", 24822))- self.assertEqual(- controller.connection_status,- "Connected to Windows via secure macOS 27 fallback",- )+ controller = make_controller(self.clock, socket_factory=socket_factory)+ with self.assertRaises(OSError) as caught:+ controller._primary_link.tunnel()+ self.assertEqual(caught.exception.errno, errno.EHOSTUNREACH)+ self.assertEqual(caught.exception.strerror, "Open /Applications/Beamer Tunnel.command")def test_set_redirecting_off_resets_mouse_accumulators(self):- sock = FakeSocket()- link(self.controller, sock)+ bring_up(self.controller)self.controller.redirecting = Trueself.controller.translator._move_accum_x = 0.4self.controller.translator._move_accum_y = -0.4@@ -1105,142 +608,84 @@ class ControllerTests(unittest.TestCase):self.assertEqual(self.controller.translator._move_accum_x, 0.0)self.assertEqual(self.controller.translator._move_accum_y, 0.0)- def test_no_route_error_explains_the_network_failure(self):- error = OSError(65, "No route to host")- self.assertEqual(- connection_error_message(error),- "Windows is unreachable from this Mac. Check that both devices can communicate on the local network.",- )-class ClipboardSyncTests(unittest.TestCase):+ """What the controller reads from and writes to the pasteboard. When the owner sends the+ clipboard and whether it takes a peer's is test_mac_links.py's ClipboardTests."""+def setUp(self):self.clock = FakeClock()- self.controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- )- self.sock = FakeSocket()- link(self.controller, self.sock)+ self.controller = make_controller(self.clock)+ self.link = bring_up(self.controller)+ self.link.posted.clear()- def _drain_outbound(self):- while not self.controller.outbound.empty():- self.controller._process_outbound(self.controller.outbound.get_nowait())-- def test_control_message_bypasses_the_gate_while_not_redirecting(self):- self.controller.redirecting = False- self.controller._process_outbound(protocol.focus_msg("mac"))- self.assertEqual(sent_messages(self.controller, self.sock)[-1], protocol.focus_msg("mac"))+ def _take_with(self, clipboard):+ self.controller.clipboard = clipboard+ self.assertTrue(self.controller.set_redirecting(True))- def test_non_control_message_is_dropped_while_not_redirecting(self):- self.controller.redirecting = False- self.controller._process_outbound({"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}})- self.assertEqual(self.sock.sent, [])+ def _arrives_from_a_machine_just_let_go(self, message):+ self.controller.set_redirecting(True)+ self.controller.set_redirecting(False)+ self.link.arrives(self.controller, message, began=self.clock.value)- def test_control_messages_do_not_consume_a_sequence_number(self):- self.controller.redirecting = True- self.controller._process_outbound(protocol.focus_msg("windows", return_edge="left", resistance_px=120))- self.assertEqual(self.controller.last_sent_seq, 0)- self.assertNotIn("seq", sent_messages(self.controller, self.sock)[-1]["data"])+ def test_the_clipboard_follows_the_focus(self):+ self._take_with(FakeClipboard("hello from the Mac"))+ self.assertEqual(self.link.types(), [protocol.MSG_FOCUS, protocol.MSG_CLIPBOARD])+ self.assertEqual(self.link.posted[1], protocol.clipboard_msg("hello from the Mac"))- def test_switch_to_windows_sends_clipboard_then_focus_in_order(self):- self.controller.clipboard = FakeClipboard("hello from the Mac")- self.assertTrue(self.controller.set_redirecting(True))- self._drain_outbound()- sent = sent_messages(self.controller, self.sock)- self.assertEqual(- sent,- [protocol.clipboard_msg("hello from the Mac"), protocol.focus_msg("windows", return_edge="left", resistance_px=120)],- )+ def test_an_empty_clipboard_sends_the_focus_only(self):+ self._take_with(FakeClipboard(""))+ self.assertEqual(self.link.types(), [protocol.MSG_FOCUS])- def test_switch_to_windows_with_empty_clipboard_sends_focus_only(self):- self.controller.clipboard = FakeClipboard("")- self.controller.set_redirecting(True)- self._drain_outbound()- sent = sent_messages(self.controller, self.sock)- self.assertEqual(sent, [protocol.focus_msg("windows", return_edge="left", resistance_px=120)])+ def test_an_oversized_text_is_skipped_but_the_focus_still_goes(self):+ self._take_with(FakeClipboard("z" * (protocol.CLIPBOARD_MAX_BYTES + 1)))+ self.assertEqual(self.link.types(), [protocol.MSG_FOCUS])- def test_switch_to_windows_skips_oversized_clipboard_but_still_sends_focus(self):- self.controller.clipboard = FakeClipboard("z" * (protocol.CLIPBOARD_MAX_BYTES + 1))- self.controller.set_redirecting(True)- self._drain_outbound()- sent = sent_messages(self.controller, self.sock)- self.assertEqual(sent, [protocol.focus_msg("windows", return_edge="left", resistance_px=120)])+ def test_text_and_image_go_together(self):+ self._take_with(FakeClipboard("shot.png", FAKE_PNG))+ self.assertEqual(self.link.types(), [protocol.MSG_FOCUS, protocol.MSG_CLIPBOARD])+ self.assertEqual(self.link.posted[1], protocol.clipboard_msg("shot.png", FAKE_PNG))- def test_switch_back_to_mac_queues_a_focus_message(self):- self.controller.redirecting = True- self.controller.set_redirecting(False)- self.assertEqual(self.controller.outbound.get_nowait(), protocol.focus_msg("mac"))+ def test_an_image_alone_sends_no_text_key(self):+ self._take_with(FakeClipboard(None, FAKE_PNG))+ self.assertEqual(self.link.posted[1], protocol.clipboard_msg(None, FAKE_PNG))- def test_switch_back_focus_message_survives_the_closed_gate(self):- # set_redirecting(False) flips redirecting False before the worker- # ever dequeues the focus message it just queued -- the gate must- # still let this specific message through.- self.controller.redirecting = True- self.controller.set_redirecting(False)- self.assertFalse(self.controller.redirecting)- message = self.controller.outbound.get_nowait()- self.controller._process_outbound(message)- self.assertEqual(sent_messages(self.controller, self.sock)[-1], protocol.focus_msg("mac"))+ def test_an_oversized_image_is_dropped_but_the_text_is_sent(self):+ big = protocol.PNG_SIGNATURE + b"\x00" * protocol.CLIPBOARD_IMAGE_MAX_BYTES+ self._take_with(FakeClipboard("shot.png", big))+ self.assertEqual(self.link.posted[1], protocol.clipboard_msg("shot.png"))- def test_handle_inbound_clipboard_sets_the_local_pasteboard(self):+ def test_an_inbound_clipboard_sets_text_and_image(self):fake = FakeClipboard()self.controller.clipboard = fake- self.controller._handle_inbound(protocol.clipboard_msg("copied on Windows"))- self.assertEqual(fake.set_calls, [("copied on Windows", None)])+ self._arrives_from_a_machine_just_let_go(protocol.clipboard_msg("shot.png", FAKE_PNG))+ self.assertEqual(fake.set_calls, [("shot.png", FAKE_PNG)])- def test_handle_inbound_clipboard_ignores_oversized_payload(self):+ def test_an_oversized_inbound_clipboard_is_ignored(self):fake = FakeClipboard()self.controller.clipboard = fake- oversized = "y" * (protocol.CLIPBOARD_MAX_BYTES + 1)- self.controller._handle_inbound(protocol.clipboard_msg(oversized))+ self._arrives_from_a_machine_just_let_go(protocol.clipboard_msg("y" * (protocol.CLIPBOARD_MAX_BYTES + 1)))self.assertEqual(fake.set_calls, [])- def test_handle_inbound_clipboard_refreshes_liveness(self):+ def test_a_malformed_inbound_image_is_ignored_but_the_text_is_kept(self):fake = FakeClipboard()self.controller.clipboard = fake- self.controller.last_ack_at = 0.0- self.clock.value = 42.0- self.controller._handle_inbound(protocol.clipboard_msg("hi"))- self.assertEqual(self.controller.last_ack_at, 42.0)-- def test_switch_to_windows_sends_text_and_image_together(self):- self.controller.clipboard = FakeClipboard("shot.png", FAKE_PNG)- self.controller.set_redirecting(True)- self._drain_outbound()- sent = sent_messages(self.controller, self.sock)- self.assertEqual(sent[0], protocol.clipboard_msg("shot.png", FAKE_PNG))- self.assertEqual(sent[1]["type"], protocol.MSG_FOCUS)-- def test_switch_to_windows_with_image_only_sends_no_text_key(self):- self.controller.clipboard = FakeClipboard(None, FAKE_PNG)- self.controller.set_redirecting(True)- self._drain_outbound()- self.assertEqual(sent_messages(self.controller, self.sock)[0], protocol.clipboard_msg(None, FAKE_PNG))-- def test_switch_to_windows_drops_an_oversized_image_but_sends_the_text(self):- big = protocol.PNG_SIGNATURE + b"\x00" * protocol.CLIPBOARD_IMAGE_MAX_BYTES- self.controller.clipboard = FakeClipboard("shot.png", big)- self.controller.set_redirecting(True)- self._drain_outbound()- self.assertEqual(sent_messages(self.controller, self.sock)[0], protocol.clipboard_msg("shot.png"))-- def test_handle_inbound_clipboard_sets_text_and_image(self):- fake = FakeClipboard()- self.controller.clipboard = fake- self.controller._handle_inbound(protocol.clipboard_msg("shot.png", FAKE_PNG))- self.assertEqual(fake.set_calls, [("shot.png", FAKE_PNG)])+ for image in ("not base64!", "", protocol.clipboard_msg(None, b"GIF89a")["data"]["image"]):+ message = {"type": protocol.MSG_CLIPBOARD, "data": {"text": "t", "image": image, "image_format": "png"}}+ self._arrives_from_a_machine_just_let_go(message)+ self._arrives_from_a_machine_just_let_go(+ {"type": protocol.MSG_CLIPBOARD, "data": {"image": "AAAA", "image_format": "bmp"}}+ )+ self.assertEqual(fake.set_calls, [("t", None)] * 3)- def test_handle_inbound_clipboard_ignores_a_malformed_image_but_keeps_the_text(self):+ def test_an_inbound_clipboard_whose_image_is_not_a_string_is_malformed_and_ignored_whole(self):+ # An image that is not text makes the whole message malformed (protocol.read_clipboard),+ # so the text beside it is not kept, unlike an image that is only unreadable.fake = FakeClipboard()self.controller.clipboard = fake- for image in ("not base64!", 42, "", protocol.clipboard_msg(None, b"GIF89a")["data"]["image"]):- message = {"type": protocol.MSG_CLIPBOARD, "data": {"text": "t", "image": image, "image_format": "png"}}- self.controller._handle_inbound(message)- self.controller._handle_inbound({"type": protocol.MSG_CLIPBOARD, "data": {"image": "AAAA", "image_format": "bmp"}})- self.assertEqual(fake.set_calls, [("t", None)] * 4)+ message = {"type": protocol.MSG_CLIPBOARD, "data": {"text": "t", "image": 42, "image_format": "png"}}+ self._arrives_from_a_machine_just_let_go(message)+ self.assertEqual(fake.set_calls, [])class CursorPinningTests(unittest.TestCase):@@ -1254,14 +699,8 @@ class CursorPinningTests(unittest.TestCase):def setUp(self):FakeQuartz.reset_cursor_spies()self.clock = FakeClock()- self.controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- )- self.sock = FakeSocket()- link(self.controller, self.sock)+ self.controller = make_controller(self.clock)+ bring_up(self.controller)def test_pin_captured_and_association_disabled_at_redirect_start(self):self.assertTrue(self.controller.set_redirecting(True))@@ -1311,15 +750,16 @@ class CursorPinningTests(unittest.TestCase):self.controller.set_redirecting(True)self.controller.set_redirecting(False)self.assertIsNone(self.controller.cursor_pin_point)- self.assertEqual(FakeQuartz.associate_calls, [False, True])+ # The way home re-associates once as the owner's move is applied and once more in+ # _return_local, which is what every other way home ends in.+ self.assertEqual(FakeQuartz.associate_calls[0], False)+ self.assertEqual(set(FakeQuartz.associate_calls[1:]), {True})def test_association_status_logged_once_not_every_toggle(self):logger = logging.getLogger("kvm-bridge-tests.cursor-assoc")logger.setLevel(logging.INFO)- controller = KVMController(- make_config(), logger=logger, quartz=FakeQuartz, clock=self.clock,- )- link(controller)+ controller = make_controller(self.clock, logger=logger)+ bring_up(controller)with self.assertLogs(logger, level="INFO") as captured:controller.set_redirecting(True)controller.set_redirecting(False)@@ -1341,7 +781,8 @@ class CursorPinningTests(unittest.TestCase):)self.assertFalse(self.controller.redirecting)self.assertEqual(FakeQuartz.tap_enable_calls, [(self.controller.event_tap, True)])- self.assertEqual(FakeQuartz.associate_calls, [True])+ self.assertTrue(FakeQuartz.associate_calls)+ self.assertEqual(set(FakeQuartz.associate_calls), {True})def test_warp_error_logged_once_not_spammed(self):logger = logging.getLogger("kvm-bridge-tests.warp-error")@@ -1354,10 +795,8 @@ class CursorPinningTests(unittest.TestCase):return 1 # non-zero: a synthetic CGErrorErroringQuartz.reset_cursor_spies()- controller = KVMController(- make_config(), logger=logger, quartz=ErroringQuartz, clock=self.clock,- )- link(controller)+ controller = make_controller(self.clock, logger=logger, quartz=ErroringQuartz)+ bring_up(controller)controller.set_redirecting(True)move_event = {ErroringQuartz.kCGMouseEventDeltaX: 4,@@ -1381,32 +820,27 @@ class OverlayGestureTests(unittest.TestCase):def setUp(self):self.clock = FakeClock()- self.controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- )- self.sock = FakeSocket()- link(self.controller, self.sock)+ self.controller = make_controller(self.clock)+ self.link = bring_up(self.controller)def test_overlay_gesture_translated_and_enqueued_while_redirecting(self):- self.controller.redirecting = True+ self.assertTrue(self.controller.set_redirecting(True))self.controller.handle_overlay_gesture(MAGNIFY_TYPE, FakeGestureEvent(magnification=0.05))- drained = []- while not self.controller.outbound.empty():- drained.append(self.controller.outbound.get_nowait())+ drained = drain(self.controller)self.assertEqual(drained, [{"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},protocol.scroll_msg(dy=1, dx=0, mode="line"),{"type": protocol.MSG_KEYUP, "data": {"key": "ctrl"}},])- # Fed back through the normal outbound path, these get a `seq` the- # same way any other input event does.+ # Fed back through the normal outbound path, they reach the link+ # the same way any other input event does.for message in drained:self.controller._process_outbound(message)- sent = sent_messages(self.controller, self.sock)- self.assertEqual([entry["data"]["seq"] for entry in sent], [1, 2, 3])+ self.assertEqual(+ [message["type"] for message in self.link.sent],+ [protocol.MSG_KEYDOWN, protocol.MSG_SCROLL, protocol.MSG_KEYUP],+ )+ self.assertEqual([m["data"]["key"] for m in self.link.sent if "key" in m["data"]], ["ctrl", "ctrl"])def test_overlay_gesture_ignored_when_not_redirecting(self):self.controller.redirecting = False@@ -1427,12 +861,7 @@ class OverlayGestureTests(unittest.TestCase):def test_overlay_gesture_capture_logged_once_on_first_gesture(self):logger = logging.getLogger("kvm-bridge-tests.overlay-gesture-capture")logger.setLevel(logging.INFO)- controller = KVMController(- make_config(),- logger=logger,- quartz=FakeQuartz,- clock=self.clock,- )+ controller = make_controller(self.clock, logger=logger)controller.redirecting = Truewith self.assertLogs(logger, level="INFO") as captured:controller.handle_overlay_gesture(MAGNIFY_TYPE, FakeGestureEvent(magnification=0.01))@@ -1464,13 +893,7 @@ class MediaKeyWiringTests(unittest.TestCase):SYSDEFINED = media_keys.NX_SYSDEFINED_EVENT_TYPEdef _controller(self, converter):- return KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=FakeClock(),- system_event_converter=converter,- )+ return make_controller(FakeClock(), system_event_converter=converter)@staticmethoddef _data1(nx_code, down=True):@@ -1547,36 +970,26 @@ class GestureWiringTests(unittest.TestCase):self.clock = FakeClock()def _controller(self, converter):- return KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- gesture_event_converter=converter,- )+ return make_controller(self.clock, gesture_event_converter=converter)def test_gesture_while_redirecting_is_translated_enqueued_and_swallowed(self):controller = self._controller(lambda event: FakeGestureEvent(deltaX=1.0))- controller.redirecting = True- sock = FakeSocket()- link(controller, sock)+ link = bring_up(controller)+ self.assertTrue(controller.set_redirecting(True))returned = controller._event_tap_callback(None, SWIPE_TYPE, object(), None)self.assertIsNone(returned)- drained = []- while not controller.outbound.empty():- drained.append(controller.outbound.get_nowait())+ drained = drain(controller)self.assertEqual(drained, [{"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},{"type": protocol.MSG_KEYDOWN, "data": {"key": "left"}},{"type": protocol.MSG_KEYUP, "data": {"key": "left"}},{"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},])- # Fed back through the normal outbound path, these get a `seq` the- # same way any other input event does.+ # Fed back through the normal outbound path, they reach the link+ # the same way any other input event does.for message in drained:controller._process_outbound(message)- sent = sent_messages(controller, sock)- self.assertEqual([entry["data"]["seq"] for entry in sent], [1, 2, 3, 4])+ self.assertEqual(link.sent, drained)def test_gesture_while_not_redirecting_is_passed_through_untouched(self):calls = []@@ -1641,11 +1054,8 @@ class GestureWiringTests(unittest.TestCase):def test_gesture_capture_active_logged_once_on_first_success(self):logger = logging.getLogger("kvm-bridge-tests.gesture-capture")logger.setLevel(logging.INFO)- controller = KVMController(- make_config(),- logger=logger,- quartz=FakeQuartz,- clock=self.clock,+ controller = make_controller(+ self.clock, logger=logger,gesture_event_converter=lambda event: FakeGestureEvent(magnification=0.01),)controller.redirecting = True@@ -1663,51 +1073,6 @@ class GestureWiringTests(unittest.TestCase):-class WindowsLockStatusTests(unittest.TestCase):- """Windows sets `locked` on its ACKs while it clears the lock screen, so- the Mac can explain the pause instead of just looking dead."""-- def setUp(self):- self.controller = KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=FakeClock(),- )- self.controller.connection_status = "Connected to 192.168.1.3:51820"-- def test_locked_ack_shows_the_unlock_and_clearing_it_restores_the_status(self):- self.controller._note_windows_lock(True)- self.assertTrue(self.controller.windows_locked)- self.assertEqual(self.controller.connection_status, "Unlocking Windows…")- self.controller._note_windows_lock(False)- self.assertFalse(self.controller.windows_locked)- self.assertEqual(self.controller.connection_status, "Connected to 192.168.1.3:51820")-- def test_the_ssh_fallback_wording_survives_an_unlock(self):- """The status is restored verbatim, not rebuilt, so the macOS 27- fallback does not silently become an ordinary connection."""- self.controller.connection_status = "Connected to Windows via secure macOS 27 fallback"- self.controller._note_windows_lock(True)- self.controller._note_windows_lock(False)- self.assertEqual(- self.controller.connection_status,- "Connected to Windows via secure macOS 27 fallback",- )-- def test_repeated_locked_acks_do_not_overwrite_the_saved_status(self):- """An ACK lands every 400ms; only transitions may touch the status, or- the saved one becomes 'Unlocking Windows…' and is lost."""- self.controller._note_windows_lock(True)- self.controller._note_windows_lock(True)- self.controller._note_windows_lock(False)- self.assertEqual(self.controller.connection_status, "Connected to 192.168.1.3:51820")-- def test_an_ack_without_the_field_is_not_a_lock(self):- self.controller._record_ack(protocol.ack_msg(0))- self.assertFalse(self.controller.windows_locked)--class DockControlWiringTests(unittest.TestCase):"""The tap's type-30 event is a system swipe (DockControl), read throughan injected dock_event_reader standing in for the private CGEvent@@ -1715,14 +1080,7 @@ class DockControlWiringTests(unittest.TestCase):and Spaces stay shut on the Mac; classified or not."""def _controller(self, reader):- return KVMController(- make_config(),- logger=quiet_logger(),- quartz=FakeQuartz,- clock=FakeClock(),- dock_event_reader=reader,- macos_major=26,- )+ return make_controller(FakeClock(), dock_event_reader=reader, macos_major=26)def _ended(self, motion, progress):return types.SimpleNamespace(hid=23, motion=motion, phase=4, progress=progress, velocity=0.0)@@ -1770,17 +1128,15 @@ class CrossingWiringTests(unittest.TestCase):FakeQuartz.reset_cursor_spies()self.clock = FakeClock()self.feedback = []- self.controller = self._controller(crossing_config())+ self.controller = self._controller(crossing_config(PAIRED_TOKEN))def _controller(self, cfg):- controller = KVMController(- cfg,- logger=quiet_logger(),- quartz=FakeQuartz,- clock=self.clock,- desktop_bounds=lambda: self.BOUNDS,+ controller = make_controller(+ self.clock, cfg, clipboard=FakeClipboard("copied here"), desktop_bounds=lambda: self.BOUNDS,)- link(controller)+ self.addCleanup(controller.stop_event.set)+ self.link = bring_up(controller)+ self.link.posted.clear()controller.on_crossing = lambda kind, step: self.feedback.append((kind, step))return controller@@ -1801,11 +1157,11 @@ class CrossingWiringTests(unittest.TestCase):breakreturn event, returned- def _sent(self):- messages = []- while not self.controller.outbound.empty():- messages.append(self.controller.outbound.get_nowait())- return messages+ def _focuses(self):+ return [message for message in self.link.posted if message["type"] == protocol.MSG_FOCUS]++ def _own(self):+ return protocol.read_id(protocol.id_text(self.controller.identity()["id"]))def test_movement_away_from_the_edge_passes_through(self):event, returned = self._move(800.0, 500.0, 30)@@ -1822,27 +1178,35 @@ class CrossingWiringTests(unittest.TestCase):_event, returned = self._push(10)self.assertIsNone(returned)self.assertTrue(self.controller.redirecting)- focus = [m for m in self._sent() if m["type"] == protocol.MSG_FOCUS]self.assertEqual(- focus,- [protocol.focus_msg("windows", edge="left", offset=0.5, return_edge="left", resistance_px=120)],+ self._focuses(),+ [protocol.focus_v6(1, PEER_ID, edge="left", offset=0.5, resistance_px=120, reach=[])],)kinds = [kind for kind, _ in self.feedback]self.assertEqual(kinds[-1], "cross")self.assertEqual(kinds.count("tick"), 3)def test_this_macs_own_push_while_windows_drives_sends_the_pc_home_and_crosses(self):- # Regression: this Mac's trackpad could not push back while the PC drove it.+ # Regression: this Mac's trackpad could not push back while the PC drove it. The push+ # itself is let through; this Mac's input follows once the PC's has let go.sent_home = []self.controller.receiving = Trueself.controller.send_peer_home = lambda: sent_home.append(True) or True- _event, returned = self._push(10)- self.assertIsNone(returned)+ for _ in range(10):+ _event, returned = self._move(1727.0, 558.0, 30)+ if sent_home:+ break+ self.assertIs(returned, _event)self.assertEqual(sent_home, [True])- self.assertFalse(self.controller.receiving)+ self.assertFalse(self.controller.redirecting)+ self.controller.set_receiving(False)+ deadline = time.monotonic() + 2+ while not self.controller.redirecting and time.monotonic() < deadline:+ time.sleep(0.01)self.assertTrue(self.controller.redirecting)- focus = [m for m in self._sent() if m["type"] == protocol.MSG_FOCUS]- self.assertEqual(focus[0]["data"]["target"], "windows")+ focus = self._focuses()[0]["data"]+ self.assertEqual((focus["target"], focus["edge"], focus["offset"]), (protocol.id_text(PEER_ID), "left", 0.5))+ self.assertEqual(self.feedback[-1][0], "cross")def test_the_pcs_own_moves_never_push_while_it_drives(self):sent_home = []@@ -1878,7 +1242,7 @@ class CrossingWiringTests(unittest.TestCase):self.assertFalse(self.controller.redirecting)def test_no_crossing_while_disconnected(self):- self.controller.sock = None+ self.link.down(self.controller)event, returned = self._push(10)self.assertIs(returned, event)self.assertFalse(self.controller.redirecting)@@ -1898,7 +1262,7 @@ class CrossingWiringTests(unittest.TestCase):self.assertEqual(self.controller.crossing.pressure, 0)def test_shortcut_only_leaves_the_edge_alone(self):- self.controller = self._controller(crossing_config(methods=["shortcut"]))+ self.controller = self._controller(crossing_config(PAIRED_TOKEN, methods=["shortcut"]))event, returned = self._push(10)self.assertIs(returned, event)self.assertFalse(self.controller.redirecting)@@ -1912,7 +1276,7 @@ class CrossingWiringTests(unittest.TestCase):self.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_passing_failure_in_the_crossing_path_heals_by_itself(self):@@ -1928,31 +1292,27 @@ class CrossingWiringTests(unittest.TestCase):self.assertTrue(self.controller.redirecting)def test_applying_settings_keeps_the_link(self):- sock = self.controller.sock- self.controller.apply_settings(crossing_config(resistance_px=40, methods=["shortcut", "notch"]))- self.assertIs(self.controller.sock, sock)+ link = self.controller._primary_link+ self.controller.apply_settings(crossing_config(PAIRED_TOKEN, resistance_px=40, methods=["shortcut", "notch"]))+ self.assertIs(self.controller._primary_link, link)+ self.assertTrue(link.live())+ self.assertEqual(link.dropped, [])+ self.assertFalse(link.stopped)self.assertEqual(self.controller.crossing.resistance_px, 40)- self.assertEqual(self.controller.crossing.home_edge(), "bottom")-- def test_shortcut_switch_sends_the_way_home_but_no_arrival(self):- self.controller.set_redirecting(True)- focus = [m for m in self._sent() if m["type"] == protocol.MSG_FOCUS]- self.assertEqual(focus, [protocol.focus_msg("windows", return_edge="left", resistance_px=120)])- def test_shortcut_switch_with_only_the_notch_on_sends_the_notch_way_home(self):- self.controller = self._controller(crossing_config(methods=["shortcut", "notch"]))+ def test_shortcut_switch_takes_with_no_position_and_shows_no_arrival(self):self.controller.set_redirecting(True)- focus = [m for m in self._sent() if m["type"] == protocol.MSG_FOCUS]- self.assertEqual(focus, [protocol.focus_msg("windows", return_edge="bottom", resistance_px=120)])+ self.assertEqual(self._focuses(), [protocol.focus_v6(1, PEER_ID, resistance_px=120, reach=[])])+ self.assertEqual(self.feedback, [])def test_inbound_switch_returns_input_and_lands_the_pointer(self):self.controller.set_redirecting(True)- self._sent()+ taken = len(self.link.posted)FakeQuartz.reset_cursor_spies()- self.controller._handle_inbound(protocol.switch_msg("mac", "right", 0.5))+ self.link.arrives(self.controller, protocol.switch_v6(1, self._own(), "right", 0.5))self.assertFalse(self.controller.redirecting)self.assertEqual(FakeQuartz.warp_calls, [(1725.0, 558.0)])- self.assertEqual([m["type"] for m in self._sent()], [protocol.MSG_FOCUS])+ self.assertEqual([m["type"] for m in self.link.posted[taken:]], [protocol.MSG_FOCUS])self.assertEqual(self.feedback[-1][0], "arrive")# Where it landed, for the arrival effect.self.assertEqual((self.feedback[-1][1].mac_edge, self.feedback[-1][1].pin), ("right", (1725.0, 558.0)))@@ -1960,7 +1320,7 @@ class CrossingWiringTests(unittest.TestCase):def test_inbound_switch_without_a_position_still_returns_input(self):self.controller.set_redirecting(True)FakeQuartz.reset_cursor_spies()- self.controller._handle_inbound(protocol.switch_msg("mac"))+ self.link.arrives(self.controller, protocol.switch_v6(1, self._own()))self.assertFalse(self.controller.redirecting)self.assertEqual(FakeQuartz.warp_calls, [])self.assertIsNone(self.feedback[-1][1].pin)@@ -1978,14 +1338,14 @@ class CrossingWiringTests(unittest.TestCase):def test_a_crossing_home_reports_only_its_own_arrival(self):self.controller.set_redirecting(True)self.feedback.clear()- self.controller._handle_inbound(protocol.switch_msg("mac", "right", 0.5))+ self.link.arrives(self.controller, protocol.switch_v6(1, self._own(), "right", 0.5))self.assertEqual(self._kinds(), ["arrive"])def test_the_pc_sending_input_home_by_its_switch_reports_it_once(self):self.controller.set_redirecting(True)self.feedback.clear()- self.controller._handle_inbound(protocol.switch_msg("mac"))- self.assertEqual(self._kinds().count("home"), 1)+ self.link.arrives(self.controller, protocol.switch_v6(1, self._own()))+ self.assertEqual(self._kinds(), ["arrive"])def test_the_pc_taking_this_mac_over_is_not_a_switch_home(self):self.controller.set_redirecting(True)@@ -2005,11 +1365,11 @@ class CrossingWiringTests(unittest.TestCase):def test_inbound_switch_to_an_unknown_target_is_ignored(self):self.controller.set_redirecting(True)- self.controller._handle_inbound(protocol.switch_msg("toaster", "right", 0.5))+ self.link.arrives(self.controller, protocol.switch_v6(1, OTHER_ID, "right", 0.5))self.assertTrue(self.controller.redirecting)def test_hold_style_redirects_only_while_the_key_is_down(self):- cfg = crossing_config()+ cfg = crossing_config(PAIRED_TOKEN)cfg.trigger_style = "hold"self.controller = self._controller(cfg)down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": FakeQuartz.kCGEventFlagMaskAlternate}@@ -2019,8 +1379,8 @@ class CrossingWiringTests(unittest.TestCase):self.assertIsNone(self.controller._event_tap_callback(None, FakeQuartz.kCGEventFlagsChanged, up, None))self.assertFalse(self.controller.redirecting)self.assertEqual(- [m["type"] for m in self._sent()],- ["_local_clipboard", protocol.MSG_FOCUS, protocol.MSG_FOCUS],+ self.link.types(),+ [protocol.MSG_FOCUS, protocol.MSG_CLIPBOARD, protocol.MSG_FOCUS],)def test_default_desktop_bounds_is_the_union_of_every_display(self):@@ -2043,7 +1403,7 @@ class CrossingWiringTests(unittest.TestCase):}return rects[display]- controller = KVMController(crossing_config(), logger=quiet_logger(), quartz=DisplayQuartz, clock=self.clock)+ controller = make_controller(self.clock, crossing_config(PAIRED_TOKEN), quartz=DisplayQuartz, desktop_bounds=None)self.assertEqual(controller._default_desktop_bounds(), (0.0, -300.0, 3648.0, 1117.0))def test_a_sleeping_display_still_bounds_the_desktop(self):@@ -2065,7 +1425,7 @@ class CrossingWiringTests(unittest.TestCase):size=types.SimpleNamespace(width=1728.0, height=1117.0),)- controller = KVMController(crossing_config(), logger=quiet_logger(), quartz=SleepingQuartz, clock=self.clock)+ controller = make_controller(self.clock, crossing_config(PAIRED_TOKEN), quartz=SleepingQuartz, desktop_bounds=None)self.assertEqual(controller._default_desktop_bounds(), (0.0, 0.0, 1728.0, 1117.0))def test_paused_crossing_leaves_the_edge_alone_while_the_shortcut_still_switches(self):@@ -2115,136 +1475,73 @@ class CrossingWiringTests(unittest.TestCase):self.controller._event_tap_callback(None, FakeQuartz.kCGEventFlagsChanged, event, None)-class RoundTripTests(unittest.TestCase):- """The smoothed round trip shown in the control window: measured from the send of the- event an ACK names, upper-median smoothed, and blank whenever it would be stale."""+class WindowsLockStatusTests(unittest.TestCase):+ """Windows says on its acks that it is clearing the lock screen, which the link reads as+ `peer_locked`, so the Mac can explain the pause instead of just looking dead."""def setUp(self):- self.clock = FakeClock(10.0)- self.controller = KVMController(- crossing_config(), logger=quiet_logger(), quartz=FakeQuartz, clock=self.clock+ self.controller = make_controller(FakeClock())+ self.link = bring_up(self.controller)+ self.controller.connection_status = "Connected to 192.168.1.3:51820"++ def test_a_locked_peer_shows_the_unlock_and_clearing_it_restores_the_status(self):+ self.link.peer_locked = True+ self.assertTrue(self.controller.windows_locked)+ self.assertEqual(self.controller.connection_status, "Unlocking 192.0.2.10…")+ # Read again while still locked: the saved status must not be lost to the unlock text.+ self.assertEqual(self.controller.connection_status, "Unlocking 192.0.2.10…")+ self.link.peer_locked = False+ self.assertFalse(self.controller.windows_locked)+ self.assertEqual(self.controller.connection_status, "Connected to 192.168.1.3:51820")++ def test_the_ssh_fallback_wording_survives_an_unlock(self):+ """The status is restored verbatim, not rebuilt, so the macOS 27+ fallback does not silently become an ordinary connection."""+ self.controller.connection_status = "Connected to Windows via secure macOS 27 fallback"+ self.link.peer_locked = True+ self.link.peer_locked = False+ self.assertEqual(+ self.controller.connection_status,+ "Connected to Windows via secure macOS 27 fallback",)- link(self.controller)- self.controller.redirecting = True- def _send(self):- self.controller._process_outbound({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 1, "dy": 0}})- return self.controller.last_sent_seq+ def test_a_peer_that_does_not_say_it_is_locked_is_not_locked(self):+ self.assertFalse(self.controller.windows_locked)+ self.assertEqual(self.controller.connection_status, "Connected to 192.168.1.3:51820")- def _ack(self, seq, after):- self.clock.value += after- self.controller._handle_inbound(protocol.ack_msg(seq))- def test_nothing_to_show_before_anything_is_acknowledged(self):- self.assertIsNone(self.controller.round_trip_ms)- self._send()+class RoundTripTests(unittest.TestCase):+ """The figure shown in the control window is the link's samples (their smoothing and how stale+ they may be are core/tests/test_link.py's; the upper median is test_mac_links.py's); this is+ when the controller shows one at all."""++ def setUp(self):+ self.controller = make_controller(FakeClock())+ self.link = bring_up(self.controller)+ self.link.samples = [0.02]++ def test_nothing_is_shown_when_there_are_no_samples(self):+ self.link.samples = []+ self.assertTrue(self.controller.set_redirecting(True))self.assertIsNone(self.controller.round_trip_ms)- def test_one_trip_is_measured_from_the_send_of_the_acknowledged_event(self):- first = self._send()- self.clock.value += 0.3- second = self._send()- self._ack(second, 0.05)- self.assertEqual(self.controller.round_trip_ms, 50, "the ACK names seq 2, sent 50ms ago, not seq 1")- self.assertNotEqual(first, second)-- def test_the_reading_is_the_upper_median_of_the_last_few_trips(self):- for delay in (0.010, 0.040, 0.020, 0.030):- seq = self._send()- self._ack(seq, delay)- self.assertEqual(self.controller.round_trip_ms, 30)-- def test_a_repeated_ack_of_the_same_seq_adds_no_sample(self):- seq = self._send()- self._ack(seq, 0.02)- self._ack(seq, 1.0)- self._ack(seq, 1.0)+ def test_a_sample_is_shown_while_input_is_on_the_other_machine(self):+ self.assertTrue(self.controller.set_redirecting(True))self.assertEqual(self.controller.round_trip_ms, 20)- def test_only_the_last_handful_of_trips_count(self):- for _ in range(ROUND_TRIP_SAMPLES):- self._ack(self._send(), 0.5)- for _ in range(ROUND_TRIP_SAMPLES):- self._ack(self._send(), 0.01)- self.assertEqual(self.controller.round_trip_ms, 10)-- def test_nothing_is_shown_when_input_is_not_on_windows(self):- self._ack(self._send(), 0.02)+ def test_nothing_is_shown_when_input_is_not_on_the_other_machine(self):+ self.assertIsNone(self.controller.round_trip_ms)+ self.controller.set_redirecting(True)self.controller.set_redirecting(False)self.assertIsNone(self.controller.round_trip_ms)self.controller.set_redirecting(True)- self.assertIsNone(self.controller.round_trip_ms, "the last session's figure does not carry over")+ self.assertEqual(self.controller.round_trip_ms, 20)def test_nothing_is_shown_when_the_link_is_down(self):- self._ack(self._send(), 0.02)- self.controller._connection_failed("Windows stopped responding")- link(self.controller)- self.controller.redirecting = True- self.assertIsNone(self.controller.round_trip_ms)-- def test_a_figure_goes_stale_after_a_few_seconds_without_a_fresh_ack(self):- self._ack(self._send(), 0.02)- self.clock.value += ROUND_TRIP_MAX_AGE_SECONDS - 0.1- self.assertEqual(self.controller.round_trip_ms, 20)- self.clock.value += 0.2+ self.controller.set_redirecting(True)+ self.link.down(self.controller)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, [])--if __name__ == "__main__":unittest.main()diff --git a/mac_app/tests/test_clipboard_mac.py b/mac_app/tests/test_clipboard_mac.pyindex 791e28e..e15e42e 100644--- a/mac_app/tests/test_clipboard_mac.py+++ b/mac_app/tests/test_clipboard_mac.py@@ -147,6 +147,13 @@ class ChangedContentsTests(unittest.TestCase):clipboard_mac.forget_sync()self.assertEqual(clipboard_mac.changed_contents()[0], "copied")+ def test_the_change_stamp_is_the_change_count(self):+ # Wire version 6's responder compares it across a visit (core.receiver.LinkResponder).+ before = clipboard_mac.change_stamp()+ self.assertEqual(before, self.board.count)+ clipboard_mac.set_contents("from a peer", None)+ self.assertNotEqual(clipboard_mac.change_stamp(), before)+if __name__ == "__main__":unittest.main()diff --git a/mac_app/tests/test_crossing.py b/mac_app/tests/test_crossing.pyindex a729344..a94ca21 100644--- a/mac_app/tests/test_crossing.py+++ b/mac_app/tests/test_crossing.py@@ -181,19 +181,6 @@ class BreakthroughTests(unittest.TestCase):self.assertEqual(step.edge, windows_edge)self.assertAlmostEqual(step.offset, offset, places=3)- def test_home_edge(self):- machine = engine(edge="right")- self.assertEqual(machine.home_edge(), "left")- self.assertEqual(machine.home_edge("top"), "bottom")-- def test_shortcut_home_edge_follows_the_method_that_is_on(self):- # `edge` stays "right" in config with the edge method off; it must not arm Windows' left.- self.assertEqual(engine(methods=("shortcut", "notch"), edge="right").home_edge(), "bottom")- self.assertEqual(engine(methods=("corner",), corner="top_left").home_edge(), "right")- # With only the shortcut on, the PC's edge facing this Mac still leads home.- self.assertEqual(engine(methods=("shortcut",), edge="right").home_edge(), "left")- self.assertEqual(engine(methods=("shortcut",), edge="top").home_edge(), "bottom")-def test_arrival_point_sits_just_inside_the_edge(self):self.assertEqual(CrossingEngine.arrival_point("left", 0.5, BOUNDS), (2.0, 558.0))self.assertEqual(CrossingEngine.arrival_point("right", 0.0, BOUNDS), (1725.0, 0.0))@@ -328,8 +315,7 @@ class PartOfTheEdgeTests(unittest.TestCase):breakself.assertTrue(result.crossed)- def test_it_is_the_way_home_as_the_edge_would_be(self):- self.assertEqual(engine(methods=("part",)).home_edge(), "left")+ def test_part_of_the_edge_arms_the_engine(self):self.assertTrue(engine(methods=("part",)).armed)diff --git a/mac_app/tests/test_crossing_matrix.py b/mac_app/tests/test_crossing_matrix.pyindex 44136d9..8699bb7 100644--- a/mac_app/tests/test_crossing_matrix.py+++ b/mac_app/tests/test_crossing_matrix.py@@ -1,23 +1,28 @@-"""Every way in on this Mac, on each arrangement and in each state, both directions, against the-PC's own code over loopback. What each row proves, and which setting governs it, is written up in-docs/crossing-matrix-28-09-2026.md."""+"""Every way in on this Mac, on each arrangement and in each state, both directions, against a+version 6 PC over loopback: the Mac's real controller driving a real LinkResponder (the PC), and+the Mac's real responder driven by a scripted initiator (the PC's own pointer and take). The v6+differences are named where a test pins one."""import itertoolsimport os+import sysimport typesimport unittest-import syssys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from bridge_fakes import FakeQuartz, crossing_config+from core import protocol+from core.tests.responder_harness import HEREfrom crossing import CORNERS, EDGES, OPPOSITE, CrossingEnginefrom settings_store import config_to_raw-from test_bridge import FakeQuartz, crossing_configfrom two_machines import Duo, wait_forBOUNDS = (0, 0, 1728, 1117)NOTCH = (782.0, 946.0)THIRDS = {"start": 0.17, "middle": 0.5, "end": 0.83}+PC_EDGE_POINT = {"left": (0, 540), "right": (1919, 540), "top": (960, 0), "bottom": (960, 1079)}+MAC_EDGE_POINT = {"left": (0, 558), "right": (1727, 558), "top": (863, 0), "bottom": (863, 1116)}def side_point(side, third):@@ -139,38 +144,6 @@ class MacWaysInTests(unittest.TestCase):self.assertAlmostEqual(step.offset, fraction, places=2)-class MacWayHomeNamedInTheHelloTests(unittest.TestCase):- """`home_edge` is the PC edge facing this Mac: what the hello tells the PC, and what a- shortcut switch arms as the PC's way home."""-- def home(self, methods, edge="right", corner="top_right"):- return CrossingEngine(methods=methods, edge=edge, corner=corner).home_edge()-- def test_the_arrangement_side_is_the_way_home_for_edge_part_and_shortcut(self):- for methods in (("edge",), ("part",), ("shortcut",), ("shortcut", "edge"), ("shortcut", "part"), ("edge", "corner")):- for edge in EDGES:- with self.subTest(methods=methods, edge=edge):- self.assertEqual(self.home(methods, edge), OPPOSITE[edge])-- def test_the_notch_alone_names_the_pcs_bottom_edge_whatever_the_arrangement_says(self):- for edge in EDGES:- self.assertEqual(self.home(("notch",), edge), "bottom")- self.assertEqual(self.home(("notch", "shortcut"), edge), "bottom")-- def test_a_corner_alone_names_the_side_of_the_corner_whatever_the_arrangement_says(self):- for edge in EDGES:- for corner in CORNERS:- self.assertEqual(self.home(("corner",), edge, corner), OPPOSITE[corner.split("_")[1]])-- def test_with_the_edge_on_too_the_arrangement_wins_and_the_notch_and_corner_arrive_elsewhere(self):- # Pinned known gap (G6 in the report): the way home differs by how the pointer left.- engine = CrossingEngine(methods=("edge", "notch", "corner"), edge="right", corner="top_left", resistance_px=40)- self.assertEqual(engine.home_edge(), "left")- by_notch = push_on_engine(engine, 850.0, 0.0, 0, -30)- by_corner = push_on_engine(engine, 0.0, 0.0, -30, -30)- self.assertEqual((by_notch.edge, by_corner.edge), ("bottom", "right"))--class ArrangementFromEitherSideTests(unittest.TestCase):"""The arrangement is one value both machines hold: which Mac edge leads to the PC. One thatarrives from the PC is applied by ControlWindow.apply_arrangement, the side that owns the@@ -226,28 +199,67 @@ class ArrangementFromEitherSideTests(unittest.TestCase):class ArrangementOverTheLinksTests(unittest.TestCase):- def test_a_change_reaches_the_other_machine_over_either_link(self):- duo = Duo().listen()+ """One change reaches the other machine over whichever link is up, never over both: the link a+ machine opened carries what it says, and the one the other opened carries it only while it has+ none of its own open."""++ def duo(self, **options):+ duo = Duo(**options).listen()self.addCleanup(duo.close)+ return duo++ @staticmethod+ def heard(duo, set_at):+ return [(peer, read) for peer, read in duo.pc_responder.arrangements if read["set_at"] == set_at]++ def test_a_change_made_here_goes_over_this_macs_own_link(self):+ duo = self.duo()+ duo.link_mac_to_pc()+ self.assertTrue(duo.mac.send_arrangement("left", 500))+ self.assertTrue(wait_for(lambda: self.heard(duo, 500)), "the PC never heard the arrangement")+ peer, read = self.heard(duo, 500)[0]+ self.assertEqual((peer, read["edge"], read["by"]), (duo.mac_id, "left", duo.mac_id))++ def test_with_no_link_of_its_own_open_it_goes_over_the_link_the_pc_opened(self):+ duo = self.duo()+ duo.link_pc_to_mac()+ self.assertTrue(duo.mac_input.send_arrangement("left", 500))+ message = duo.pc.expect(protocol.MSG_ARRANGEMENT, where=lambda data: data["set_at"] == 500)+ self.assertEqual((message["edge"], message["by"]), ("left", duo.mac_text))++ def test_with_both_links_open_it_goes_over_this_macs_own_only(self):+ duo = self.duo()duo.link_mac_to_pc()duo.link_pc_to_mac()- # From the Mac: over its own link, and over the link the PC opened to it.+ self.assertFalse(duo.mac_input.send_arrangement("left", 500))self.assertTrue(duo.mac.send_arrangement("left", 500))- self.assertTrue(duo.mac_server.send_arrangement("left", 500))- self.assertTrue(wait_for(lambda: len(duo.pc_arrangements) == 2), duo.pc_arrangements)- self.assertEqual(set(duo.pc_arrangements), {("left", 500)})- # From the PC, the same two ways.- self.assertTrue(duo.pc.send_arrangement("top", 600))- self.assertTrue(duo.pc_server.send_arrangement("top", 600))+ self.assertTrue(wait_for(lambda: self.heard(duo, 500)))+ self.assertIsNone(duo.pc.expect(protocol.MSG_ARRANGEMENT, 0.3))++ def test_a_change_made_on_the_pc_reaches_the_app_as_this_macs_edge_over_either_link(self):+ duo = self.duo()+ duo.link_mac_to_pc()+ duo.link_pc_to_mac()+ # Over the link the PC opened, and over the one this Mac opened to it.+ duo.pc.send(protocol.arrangement_v6("right", 600, HERE))+ self.assertTrue(duo.pc_responder.responder.send(duo.mac_id, protocol.arrangement_v6("right", 700, HERE)))self.assertTrue(wait_for(lambda: len(duo.mac_arrangements) == 2), duo.mac_arrangements)- self.assertEqual(set(duo.mac_arrangements), {("top", 600)})+ self.assertEqual(sorted(duo.mac_arrangements), [("left", 600, protocol.id_text(HERE)), ("left", 700, protocol.id_text(HERE))])- def test_the_hello_carries_the_way_home_and_the_resistance_and_no_stamp(self):- duo = Duo(crossing={"methods": ["notch", "shortcut"], "edge": "top", "resistance_px": 96}).listen()- self.addCleanup(duo.close)+ def test_a_link_coming_up_announces_the_saved_side_with_its_stamp_and_who_made_it(self):+ duo = self.duo(side="top", side_stamp=300, side_by=protocol.id_text(HERE))+ duo.link_mac_to_pc()+ self.assertTrue(wait_for(lambda: duo.pc_responder.arrangements))+ peer, read = duo.pc_responder.arrangements[0]+ self.assertEqual((read["edge"], read["set_at"], read["by"]), ("top", 300, HERE))++ def test_a_side_never_learnt_is_announced_as_nothing(self):+ duo = self.duo(side="")duo.link_mac_to_pc()- self.assertTrue(wait_for(lambda: duo.pc_peer))- self.assertEqual(duo.pc_peer[0][1:], ("bottom", 96))+ # What a link announces goes before anything sent after it, so this one is the fence.+ self.assertTrue(duo.mac.send_arrangement("left", 9))+ self.assertTrue(wait_for(lambda: self.heard(duo, 9)))+ self.assertEqual([read["set_at"] for _, read in duo.pc_responder.arrangements], [9])class WhatIsSharedTests(unittest.TestCase):@@ -265,205 +277,257 @@ def pc_at_edge(duo, edge):class MacToPcTests(unittest.TestCase):- """This Mac's own pointer out to the PC, and home again through the PC's edge while it drives."""+ """This Mac's own pointer out to the PC, and home again through the PC's zone while it drives.+ The PC's way home is the zones it keeps for this Mac (WIRE.md section 8), not anything this+ Mac chose."""- def duo(self, **crossing):- crossing.setdefault("resistance_px", 40)- duo = Duo(crossing=crossing).listen()+ def duo(self, crossing=None, **options):+ duo = Duo(crossing={"resistance_px": 40, **(crossing or {})}, **options).listen()self.addCleanup(duo.close)return duo- def cross(self, duo, edge):+ def arrival(self, duo):+ """The step the pointer's arrival home was shown with."""+ self.assertTrue(wait_for(lambda: duo.feedback and duo.feedback[-1][0] == "arrive"), "no arrival was shown")+ return duo.feedback[-1][1]++ def cross(self, duo, edge, times=12):x, y = side_point(edge, "middle")- self.assertTrue(duo.mac_push(x, y, *outward(edge)), "the push never crossed")- self.assertTrue(wait_for(lambda: duo.pc_server.return_edge is not None), "the PC was never armed")+ self.assertTrue(duo.mac_push(x, y, *outward(edge), times=times), "the push never crossed")+ self.assertTrue(wait_for(lambda: duo.pc_responder.responder.owner == duo.mac_id), "the PC was never taken")+ self.assertTrue(wait_for(lambda: duo.pc_responder.arrivals), "the pointer never landed on the PC")- def test_each_arrangement_crosses_to_the_opposite_edge_and_arms_that_edge_as_the_way_home(self):+ def test_each_arrangement_crosses_to_the_opposite_edge_and_that_edge_leads_home(self):for edge in EDGES:with self.subTest(pc_is=edge):- duo = self.duo(edge=edge)+ duo = self.duo(crossing={"edge": edge})duo.link_mac_to_pc()self.cross(duo, edge)self.assertTrue(pc_at_edge(duo, OPPOSITE[edge]))- self.assertEqual(duo.pc_server.return_edge, OPPOSITE[edge])+ self.assertEqual(duo.pc_responder.arrivals[-1][0], OPPOSITE[edge])+ self.assertTrue(duo.mac_lean(*outward(OPPOSITE[edge])), "the PC's edge facing this Mac never led home")+ self.assertEqual(self.arrival(duo).mac_edge, edge)duo.close()- def test_the_way_home_uses_the_resistance_this_mac_sends_with_the_switch(self):- # 77 is neither the default nor the PC's own 400: the PC's setting is never consulted.- duo = Duo(crossing={"resistance_px": 77}, pc={"crossing_resistance_px": 400}).listen()- self.addCleanup(duo.close)+ def test_the_way_home_uses_the_resistance_this_mac_sends_with_the_take(self):+ # 50 and 400 sit either side of the 120 the PC assumes when none is sent, so neither+ # passing nor failing to pass could be the default.+ duo = self.duo(crossing={"resistance_px": 50})duo.link_mac_to_pc()self.cross(duo, "right")- self.assertEqual(duo.pc_server.return_resistance, 77)+ self.assertTrue(duo.mac_lean(-30, times=4), "50 px of resistance did not give within four pushes")+ duo = self.duo(crossing={"resistance_px": 400})+ duo.link_mac_to_pc()+ self.cross(duo, "right", times=60)+ self.assertFalse(duo.mac_lean(-30, times=6), "400 px of resistance gave to 180 px of push")+ self.assertTrue(duo.mac.redirecting)- def test_home_through_any_part_of_the_pcs_edge_whatever_the_pcs_own_ways_are(self):- pc = {"crossing_methods": ["corner"], "crossing_corner": "bottom_right", "mac_return_edge": "top"}+ def test_home_through_any_third_of_an_edge_zone(self):for third in THIRDS:with self.subTest(third=third):- duo = Duo(crossing={"resistance_px": 40}, pc=pc).listen()- self.addCleanup(duo.close)+ duo = self.duo()duo.link_mac_to_pc()self.cross(duo, "right")- x, y = 0, int(THIRDS[third] * 1079)- duo.pc_desktop.cursor = (x, y)- for _ in range(6):- duo.mac_move(1727.0, 558.0, -30)- if not duo.mac.redirecting:- break- wait_for(lambda: False, 0.02)- self.assertTrue(wait_for(lambda: not duo.mac.redirecting), "the push through the PC's left edge never came home")+ duo.pc_desktop.cursor = (0, int(THIRDS[third] * 1079))+ self.assertTrue(duo.mac_lean(-30), "the push through the PC's left edge never came home")duo.close()- def test_a_push_along_the_way_home_is_the_pcs_edge_facing_this_mac_even_with_only_the_shortcut_on(self):- duo = self.duo(methods=["shortcut"], edge="top")+ def test_a_part_zone_leads_home_only_through_its_thirds(self):+ duo = self.duo(pc_zones=[{"peer": "mac", "kind": "part", "parts": ["middle"]}])duo.link_mac_to_pc()- duo.mac.set_redirecting(True)- self.assertTrue(wait_for(lambda: duo.pc_server.return_edge == "bottom"))+ self.cross(duo, "right")+ duo.pc_desktop.cursor = (0, int(THIRDS["start"] * 1079))+ self.assertFalse(duo.mac_lean(-30, times=4), "the start third is outside the zone and still led home")+ duo.pc_desktop.cursor = (0, int(THIRDS["middle"] * 1079))+ self.assertTrue(duo.mac_lean(-30), "the middle third did not lead home")++ def test_a_corner_zone_leads_home_through_its_corner_and_only_by_a_diagonal_push(self):+ duo = self.duo(pc_zones=[{"peer": "mac", "kind": "corner", "corner": "top_left", "edge": "left"}])+ duo.link_mac_to_pc()+ self.cross(duo, "right")+ duo.pc_desktop.cursor = (0, 0)+ self.assertFalse(duo.mac_lean(-30, 0, times=4), "a straight push into the corner led home")+ self.assertTrue(duo.mac_lean(-30, -30), "the diagonal push into the corner did not lead home")++ def test_a_shortcut_take_names_no_position_and_the_pcs_zone_still_leads_home(self):+ # Whatever the Mac's own ways are: its engine arms nothing here, the PC's zone does.+ duo = self.duo(crossing={"methods": ["shortcut"], "edge": "top"})+ duo.link_mac_to_pc()+ self.assertTrue(duo.mac.set_redirecting(True))+ self.assertTrue(wait_for(lambda: duo.pc_responder.responder.owner == duo.mac_id))+ self.assertTrue(wait_for(lambda: duo.pc_responder.arrivals))+ self.assertEqual(duo.pc_responder.arrivals[-1][0], None)+ duo.pc_desktop.cursor = (960, 1079)+ self.assertTrue(duo.mac_lean(0, 30), "the PC's bottom edge, facing this Mac, never led home")+ self.assertEqual(self.arrival(duo).mac_edge, "top")++ def test_a_notch_crossing_lands_on_the_pcs_bottom_edge_and_the_way_home_is_still_the_zone(self):+ # Replaces the 1.4.x gap G6: the way home no longer depends on how the pointer left. It is+ # the PC's zone for this Mac, so the edge the pointer arrived by is only where it landed.+ duo = self.duo(crossing={"methods": ["edge", "notch"], "edge": "right"}, notch=NOTCH)+ duo.link_mac_to_pc()+ self.assertTrue(duo.mac_push(850.0, 0.0, 0, -30), "the push into the notch never crossed")+ self.assertTrue(wait_for(lambda: duo.pc_responder.arrivals))+ self.assertEqual(duo.pc_responder.arrivals[-1][0], "bottom")+ duo.pc_desktop.cursor = (960, 1079)+ self.assertFalse(duo.mac_lean(0, 30, times=6), "the edge it landed by led home")+ duo.pc_desktop.cursor = (0, 540)+ self.assertTrue(duo.mac_lean(-30), "the zone's edge did not lead home")def test_nothing_crosses_while_the_link_is_down_and_nothing_is_swallowed(self):- duo = self.duo(edge="right")+ duo = self.duo(crossing={"edge": "right"})for _ in range(12):event = {"location": (1727.0, 558.0), FakeQuartz.kCGMouseEventDeltaX: 30, FakeQuartz.kCGMouseEventDeltaY: 0}self.assertIs(duo.mac._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved, event, None), event)self.assertFalse(duo.mac.redirecting)self.assertEqual(FakeQuartz.warp_calls, [])- def test_this_macs_direction_switch_off_stops_every_way_out_but_not_the_way_back_by_shortcut(self):- duo = self.duo(edge="right")+ def test_this_macs_direction_switch_off_stops_every_way_out(self):+ duo = self.duo(crossing={"edge": "right"})duo.link_mac_to_pc()duo.mac.cfg.send_to_windows = Falsex, y = side_point("right", "middle")self.assertFalse(duo.mac_push(x, y, 30))self.assertFalse(duo.mac.set_redirecting(True))+ self.assertIsNone(duo.pc_responder.responder.owner)++ def test_a_pc_that_does_not_allow_this_mac_to_drive_it_is_never_taken(self):+ duo = self.duo(crossing={"edge": "right"})+ duo.pc_responder.settings.peer(duo.mac_text)["allow_drive"] = False+ duo.link_mac_to_pc()+ self.assertTrue(wait_for(lambda: duo.mac._accepts.get(protocol.id_text(HERE)) is False))+ x, y = side_point("right", "middle")+ self.assertFalse(duo.mac_push(x, y, 30))+ self.assertIsNone(duo.pc_responder.responder.owner)+ self.assertIn("does not accept input from this Mac", duo.alerts[-1])def test_paused_and_full_screen_hold_the_mac_pointer_but_not_the_pc_pointer_coming_home(self):for held in ("crossing_paused", "full_screen_app"):with self.subTest(held=held):- duo = self.duo(edge="right")+ duo = self.duo(crossing={"edge": "right"})duo.link_mac_to_pc()self.cross(duo, "right")setattr(duo.mac, held, True if held == "crossing_paused" else "Steam")duo.pc_desktop.cursor = (0, 540)- for _ in range(6):- duo.mac_move(1727.0, 558.0, -30)- wait_for(lambda: False, 0.02)- if not duo.mac.redirecting:- break- self.assertTrue(wait_for(lambda: not duo.mac.redirecting), "the PC's edge stopped leading home while held")+ self.assertTrue(duo.mac_lean(-30), "the PC's edge stopped leading home while held")duo.close()-def mac_at_edge(duo, edge):- x, y = duo.mac_desktop.cursor- return {"left": x == 0, "right": x == 1727, "top": y == 0, "bottom": y == 1116}[edge]---def pc_settings(edge, **more):- return dict(mac_return_edge=edge, crossing_methods=["edge"], **more)+class MacDrivenTests(unittest.TestCase):+ """The PC's pointer and take arriving on this Mac, which a scripted initiator stands in for,+ and home again through this Mac's zone for the PC. The PC's own zones, its resistance and its+ settings are the PC's; what is proved here is what this Mac's responder does with them."""--class PcToMacTests(unittest.TestCase):- """The PC's own mouse out to this Mac, and home again through this Mac's edge while the PC- drives."""-- def duo(self, pc=None, **crossing):- crossing.setdefault("resistance_px", 40)- duo = Duo(crossing=crossing, pc=pc).listen()+ def duo(self, crossing=None, **options):+ duo = Duo(crossing={"resistance_px": 40, **(crossing or {})}, **options).listen()self.addCleanup(duo.close)return duo- def cross(self, duo, pc_edge):- x, y = {"left": (0, 540), "right": (1919, 540), "top": (960, 0), "bottom": (960, 1079)}[pc_edge]- self.assertTrue(duo.pc_push(x, y, *outward(pc_edge)), "the PC's push never crossed")- self.assertTrue(wait_for(lambda: duo.mac_server.return_edge is not None), "the Mac was never armed")-- def test_each_arrangement_crosses_to_the_opposite_mac_edge_and_arms_it_as_the_way_home(self):- for edge in EDGES:- with self.subTest(mac_is=edge):- duo = self.duo(pc=pc_settings(edge, crossing_resistance_px=40))- duo.link_pc_to_mac()- self.cross(duo, edge)- self.assertTrue(wait_for(lambda: mac_at_edge(duo, OPPOSITE[edge])))- self.assertEqual(duo.mac_server.return_edge, OPPOSITE[edge])+ def drive(self, duo, side):+ duo.link_pc_to_mac()+ duo.pc_drives(side, 0.5)+ self.assertTrue(wait_for(lambda: duo.mac_arrivals), "the pointer never landed on the Mac")++ def at_edge(self, duo, edge):+ x, y = duo.mac_desktop.cursor+ return {"left": x == 0, "right": x == 1727, "top": y == 0, "bottom": y == 1116}[edge]++ def test_each_arrangement_lands_on_the_edge_facing_the_pc_and_that_edge_leads_home(self):+ for side in EDGES:+ with self.subTest(pc_is=side):+ duo = self.duo(crossing={"edge": side})+ self.drive(duo, side)+ self.assertTrue(self.at_edge(duo, side))+ self.assertEqual(duo.mac_responder.owner, HERE)+ duo.pc_leans(MAC_EDGE_POINT[side], *outward(side), times=3)+ switch = duo.pc_switch()+ self.assertEqual((switch["next"], switch["edge"]), (protocol.id_text(HERE), OPPOSITE[side]))+ duo.pc.let_go()+ self.assertTrue(wait_for(lambda: not duo.mac.receiving))duo.close()- def test_the_way_home_uses_the_resistance_the_pc_sends_with_the_switch(self):- duo = self.duo(pc=pc_settings("right", crossing_resistance_px=77, mac_resistance_px=5), resistance_px=400)+ def test_the_way_home_uses_the_resistance_the_pc_sends_with_the_take(self):+ # 50 against this Mac's own 400, and the 120 assumed when none is sent.+ duo = self.duo(crossing={"resistance_px": 400})duo.link_pc_to_mac()- self.cross(duo, "right")- self.assertEqual(duo.mac_server.return_resistance, 77)+ duo.pc_drives("right", 0.5, resistance_px=50)+ duo.pc_leans(MAC_EDGE_POINT["right"], 30)+ self.assertIsNone(duo.pc_switch(0.05), "30 px gave against 50 px of resistance")+ duo.pc_leans(MAC_EDGE_POINT["right"], 30, times=2)+ self.assertIsNotNone(duo.pc_switch(), "90 px did not give against 50 px of resistance")- def test_home_through_this_macs_arrival_edge_whatever_this_macs_own_ways_and_arrangement_are(self):+ def test_home_through_this_macs_zone_whatever_this_macs_own_ways_and_arrangement_are(self):for methods in (["notch"], ["corner"], ["part"], ["shortcut"]):with self.subTest(macs_ways=methods):- duo = self.duo(pc=pc_settings("right", crossing_resistance_px=40), methods=methods, edge="top")- duo.link_pc_to_mac()- self.cross(duo, "right")- duo.mac_desktop.cursor = (0.0, 558.0)- for _ in range(6):- duo.pc.on_motion(-30, 0)- wait_for(lambda: False, 0.02)- if not duo.pc.redirecting:- break- self.assertTrue(wait_for(lambda: not duo.pc.redirecting), "the Mac's left edge never led home")+ duo = self.duo(crossing={"methods": methods, "edge": "top"}, side="left")+ self.drive(duo, "left")+ duo.pc_leans(MAC_EDGE_POINT["left"], -30, times=3)+ self.assertIsNotNone(duo.pc_switch(), "this Mac's left edge never led home")duo.close()- def test_a_pc_that_has_learned_no_edge_has_no_way_out_however_it_is_pushed(self):- duo = self.duo(pc=pc_settings("", crossing_resistance_px=40))+ def test_a_mac_that_has_learned_no_side_for_the_pc_has_no_way_home_however_it_is_pushed(self):+ duo = self.duo(side="")duo.link_pc_to_mac()+ duo.pc_drives("left", 0.5)for edge in EDGES:- x, y = {"left": (0, 540), "right": (1919, 540), "top": (960, 0), "bottom": (960, 1079)}[edge]- self.assertFalse(duo.pc_push(x, y, *outward(edge)), edge)- self.assertFalse(duo.pc.redirecting)-- def test_no_link_no_crossing_and_the_pc_says_nothing(self):- duo = self.duo(pc=pc_settings("right"))- self.assertFalse(duo.pc_push(1919, 540, 30))- self.assertFalse(duo.pc.redirecting)- self.assertEqual(duo.pc.status, "Not connected to the Mac")-- def test_a_mac_that_is_not_listening_leaves_the_pc_with_no_link(self):- duo = Duo(pc=pc_settings("right"))- self.addCleanup(duo.close)- duo.pc.start(duo.pc_config)- self.assertFalse(wait_for(lambda: duo.pc.connected, 0.5))- self.assertFalse(duo.pc_push(1919, 540, 30))+ duo.pc_leans(MAC_EDGE_POINT[edge], *outward(edge), times=3)+ self.assertIsNone(duo.pc_switch(0.2), edge)+ self.assertTrue(duo.mac.receiving)++ def test_a_pc_this_mac_does_not_allow_to_drive_it_is_refused(self):+ duo = self.duo(allow_drive=False)+ duo.link_pc_to_mac()+ route = duo.pc_takes("left", 0.5)+ self.assertEqual(duo.pc.answer(route), (protocol.MSG_REFUSE, {"route": route, "why": "not_allowed"}))+ self.assertFalse(duo.mac.receiving)- def test_the_pcs_pause_and_full_screen_hold_its_own_edges(self):+ def test_the_macs_pause_and_full_screen_hold_its_edges_against_the_pcs_pointer(self):+ # 1.5.0 differs from 1.4.x here: the Mac's responder takes the hold, so the PC's pointer+ # no longer passes a held edge. Lifted, the same push leads home.for held in ("crossing_paused", "full_screen_app"):with self.subTest(held=held):- duo = self.duo(pc=pc_settings("right"))- duo.link_pc_to_mac()- setattr(duo.pc, held, True if held == "crossing_paused" else "Steam")- self.assertFalse(duo.pc_push(1919, 540, 30))+ duo = self.duo(crossing={"edge": "right"})+ self.drive(duo, "right")+ setattr(duo.mac, held, True if held == "crossing_paused" else "Steam")+ duo.pc_leans(MAC_EDGE_POINT["right"], 30, times=4)+ self.assertIsNone(duo.pc_switch(0.2), "a held edge led home")+ setattr(duo.mac, held, False if held == "crossing_paused" else None)+ duo.pc_leans(MAC_EDGE_POINT["right"], 30, times=3)+ self.assertIsNotNone(duo.pc_switch(), "the edge did not lead home once released")duo.close()def test_this_macs_own_pointer_can_take_input_back_only_with_its_own_link_to_the_pc_up(self):# Pinned known gap (G7 in the report): the push back needs the Mac's own link.- duo = self.duo(pc=pc_settings("right", crossing_resistance_px=40), edge="right")- duo.link_pc_to_mac()- self.cross(duo, "right")- self.assertTrue(wait_for(lambda: duo.mac.receiving))+ duo = self.duo(crossing={"edge": "right"})+ self.drive(duo, "right")self.assertFalse(duo.mac_push(1727.0, 558.0, 30, times=6), "crossed with no link of its own")self.assertTrue(duo.mac.receiving)+ self.assertIsNone(duo.pc_switch(0.2))duo.link_mac_to_pc()- self.assertTrue(duo.mac_push(1727.0, 558.0, 30), "the Mac's pointer could not take input back")- self.assertTrue(wait_for(lambda: not duo.pc.redirecting))-- def test_a_shortcut_while_the_other_machine_drives_only_sends_its_input_home(self):- duo = self.duo(pc=pc_settings("right"))- duo.link_pc_to_mac()+ duo.mac_push(1727.0, 558.0, 30)+ switch = duo.pc_switch()+ self.assertEqual(switch, {"route": switch["route"], "next": protocol.id_text(HERE)}, "the PC was sent home with a position")+ duo.pc.let_go()+ self.assertTrue(wait_for(lambda: duo.mac.redirecting), "the Mac's pointer could not follow the PC home")+ self.assertTrue(wait_for(lambda: duo.pc_responder.responder.owner == duo.mac_id))+ self.assertFalse(duo.mac.receiving)++ def test_a_shortcut_while_the_other_machine_drives_sends_its_input_home_and_then_drives(self):+ duo = self.duo(crossing={"edge": "right"})duo.link_mac_to_pc()- self.assertTrue(duo.pc.set_redirecting(True))- self.assertTrue(wait_for(lambda: duo.mac.receiving))- self.assertTrue(duo.mac.set_redirecting(True))- self.assertTrue(wait_for(lambda: not duo.pc.redirecting))- self.assertFalse(duo.mac.redirecting, "the shortcut also crossed this Mac's input, which only a push does")+ duo.link_pc_to_mac()+ duo.pc_drives()self.assertTrue(duo.mac.set_redirecting(True))- self.assertTrue(wait_for(lambda: duo.pc_server.return_edge is not None))- self.assertTrue(duo.pc.set_redirecting(True))- self.assertTrue(wait_for(lambda: not duo.mac.redirecting))- self.assertFalse(duo.pc.redirecting)+ switch = duo.pc_switch()+ self.assertEqual(switch["next"], protocol.id_text(HERE))+ self.assertFalse(duo.mac.redirecting, "this Mac drove before the PC had let go")+ duo.pc.let_go()+ self.assertTrue(wait_for(lambda: duo.mac.redirecting), "this Mac never took over once the PC let go")+ self.assertTrue(wait_for(lambda: duo.pc_responder.responder.owner == duo.mac_id))+ # And while it drives, the PC cannot take it: one machine never drives and is driven at once.+ route = duo.pc_takes()+ self.assertEqual(duo.pc.answer(route), (protocol.MSG_REFUSE, {"route": route, "why": "busy"}))+ self.assertTrue(duo.mac.redirecting)if __name__ == "__main__":diff --git a/mac_app/tests/test_driven_mac.py b/mac_app/tests/test_driven_mac.pynew file mode 100644index 0000000..ab683cb--- /dev/null+++ b/mac_app/tests/test_driven_mac.py@@ -0,0 +1,407 @@+"""The Mac as a machine that is driven, whichever machine drives it: media keys, gestures, the+keys only a PC has, and fractional scroll. Each test reads the event the injector posts, through+a fake Quartz and AppKit that record it, so nothing here touches the real pointer or keyboard."""++import logging+import os+import sys+import unittest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import input_injector_mac as injector+from core import protocol+from gestures import GestureTranslator+++class FakeEvent:+ def __init__(self, kind, **fields):+ self.kind = kind+ self.fields = dict(fields)+++class FakeQuartz:+ kCGEventSourceUserData = 42+ kCGScrollEventUnitLine = 1+ kCGScrollEventUnitPixel = 0+ kCGEventFlagMaskCommand = 1 << 20+ kCGEventFlagMaskControl = 1 << 18+ kCGEventFlagMaskShift = 1 << 17+ kCGEventFlagMaskAlternate = 1 << 19+ kCGEventFlagMaskAlphaShift = 1 << 16+ kCGEventFlagMaskSecondaryFn = 1 << 23+ kCGEventFlagMaskNumericPad = 1 << 21+ kCGHIDEventTap = 0++ def __init__(self):+ self.posted = []++ def CGEventCreateKeyboardEvent(self, source, code, down):+ return FakeEvent("key", code=code, down=down, flags=0)++ def CGEventKeyboardSetUnicodeString(self, event, length, text):+ event.fields["text"] = text++ def CGEventCreateScrollWheelEvent(self, source, unit, count, wheel_y, wheel_x):+ return FakeEvent("scroll", unit=unit, wheel_y=wheel_y, wheel_x=wheel_x, flags=0)++ def CGEventSetFlags(self, event, flags):+ event.fields["flags"] = flags++ def CGEventSetIntegerValueField(self, event, field, value):+ event.fields[field] = value++ def CGEventPost(self, tap, event):+ self.posted.append(event)+++class FakeNSEvent:+ def __init__(self, data):+ self.data = data++ def CGEvent(self):+ return FakeEvent("system", **self.data)+++class FakeAppKit:+ NSEventTypeSystemDefined = 14++ class NSEvent:+ @staticmethod+ def otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(+ kind, location, flags, timestamp, window, context, subtype, data1, data2+ ):+ return FakeNSEvent({"type": kind, "flags": flags, "subtype": subtype, "data1": data1, "data2": data2})+++FN = FakeQuartz.kCGEventFlagMaskSecondaryFn+ARROW_FLAGS = FN | FakeQuartz.kCGEventFlagMaskNumericPad+++class InjectorCase(unittest.TestCase):+ def setUp(self):+ self.quartz = FakeQuartz()+ self._saved = (injector.Quartz, getattr(injector, "AppKit", None))+ injector.Quartz = self.quartz+ injector.AppKit = FakeAppKit+ injector.release_all()+ injector._warned_names.clear()+ injector.reset_scroll_remainders()++ def tearDown(self):+ injector.release_all()+ injector.Quartz, injector.AppKit = self._saved++ def keys(self):+ return [(e.fields["code"], e.fields["down"], e.fields["flags"]) for e in self.quartz.posted if e.kind == "key"]+++class NavigationKeyFlagTests(InjectorCase):+ """A real arrow, F key, Home, End, Page Up, Page Down or forward delete carries the Fn flag+ (arrows the numeric-pad flag too), and system shortcuts match on it, so every such key the PC+ sends carries it, up as well as down. Ordinary keys carry neither."""++ def flags_of(self, name, down=True):+ self.quartz.posted.clear()+ injector.inject_key(name, down=down)+ return self.keys()[0][2]++ def test_arrows_carry_fn_and_numeric_pad(self):+ for name in ("left", "right", "up", "down"):+ self.assertEqual(self.flags_of(name), ARROW_FLAGS, name)+ self.assertEqual(self.flags_of(name, down=False), ARROW_FLAGS, name)++ def test_function_keys_carry_fn(self):+ for number in range(1, 21):+ self.assertEqual(self.flags_of(f"f{number}"), FN, f"f{number}")++ def test_home_end_paging_and_forward_delete_carry_fn(self):+ for name in ("home", "end", "page_up", "page_down", "delete"):+ self.assertEqual(self.flags_of(name), FN, name)++ def test_the_keys_the_pc_alone_has_carry_fn_when_they_land_on_a_function_key(self):+ for name in ("print_screen", "scroll_lock", "pause"):+ self.assertEqual(self.flags_of(name), FN, name)++ def test_fn_joins_a_held_modifier_rather_than_replacing_it(self):+ injector.inject_key("shift", down=True)+ self.assertEqual(self.flags_of("left"), FakeQuartz.kCGEventFlagMaskShift | ARROW_FLAGS)++ def test_ordinary_keys_carry_neither(self):+ for name in ("a", "enter", "space", "backspace", "tab", "esc"):+ self.assertEqual(self.flags_of(name), 0, name)+++class MediaKeyTests(InjectorCase):+ def system(self):+ return [e for e in self.quartz.posted if e.kind == "system"]++ def test_each_media_name_is_posted_as_an_aux_control_event(self):+ # NX_KEYTYPE_SOUND_UP 0, SOUND_DOWN 1, MUTE 7, PLAY 16, NEXT 17, PREVIOUS 18.+ expected = {+ "volume_up": 0,+ "volume_down": 1,+ "volume_mute": 7,+ "media_play_pause": 16,+ "media_next": 17,+ "media_prev": 18,+ }+ for name, nx_key in expected.items():+ self.quartz.posted.clear()+ injector.inject_key(name, down=True)+ (event,) = self.system()+ self.assertEqual(event.fields["subtype"], 8, name)+ self.assertEqual(event.fields["data1"] >> 16, nx_key, name)++ def test_down_and_up_carry_the_states_media_keys_decodes(self):+ import media_keys++ injector.inject_key("media_next", down=True)+ injector.inject_key("media_next", down=False)+ down, up = self.system()+ self.assertEqual(media_keys.decode(down.fields["subtype"], down.fields["data1"]), ("media_next", True, False))+ self.assertEqual(media_keys.decode(up.fields["subtype"], up.fields["data1"]), ("media_next", False, False))+ self.assertEqual(down.fields["flags"], 0xA00)+ self.assertEqual(up.fields["flags"], 0xB00)++ def test_the_event_is_marked_as_beamers_own(self):+ injector.inject_key("volume_up", down=True)+ (event,) = self.system()+ self.assertEqual(event.fields[FakeQuartz.kCGEventSourceUserData], injector.INJECTED_MARK)++ def test_media_keys_never_type_or_press_an_ordinary_key(self):+ injector.inject_key("media_play_pause", down=True)+ self.assertEqual(self.keys(), [])++ def test_stop_is_dropped_and_logged_once(self):+ # macOS has no stop key; mapping it to play/pause would start playback that was paused.+ with self.assertLogs("Beamer", level="WARNING") as logged:+ injector.inject_key("media_stop", down=True)+ injector.inject_key("media_stop", down=False)+ self.assertEqual(len(logged.records), 1)+ self.assertEqual(self.quartz.posted, [])+++class WindowsOnlyKeyTests(InjectorCase):+ def test_print_screen_scroll_lock_and_pause_land_on_the_keys_a_mac_keyboard_puts_there(self):+ # An Apple extended keyboard's F13, F14 and F15 are Print Screen, Scroll Lock and Pause.+ for name, code in (("print_screen", 0x69), ("scroll_lock", 0x6B), ("pause", 0x71)):+ self.quartz.posted.clear()+ injector.inject_key(name, down=True)+ self.assertEqual(self.keys(), [(code, True, FN)], name)++ def test_num_lock_lands_on_the_keypad_clear_key(self):+ injector.inject_key("num_lock", down=True)+ self.assertEqual(self.keys(), [(0x47, True, 0)])++ def test_browser_back_and_forward_are_command_bracket(self):+ for name, character in (("browser_back", "["), ("browser_forward", "]")):+ self.quartz.posted.clear()+ injector.inject_key(name, down=True)+ injector.inject_key(name, down=False)+ code = {"[": 0x21, "]": 0x1E}[character]+ command = FakeQuartz.kCGEventFlagMaskCommand+ self.assertEqual(self.keys(), [(code, True, command), (code, False, command)], name)++ def test_browser_keys_stay_on_the_bracket_key_on_a_layout_without_one(self):+ # A German or French layout has no unshifted bracket; planning it there gives key code 0,+ # which under Command is Select All.+ saved = injector.keyboard_layout.code_for+ injector.keyboard_layout.code_for = lambda character: None+ try:+ injector.inject_key("browser_back", down=True)+ finally:+ injector.keyboard_layout.code_for = saved+ self.assertEqual([code for code, _, _ in self.keys()], [0x21, 0x21])++ def test_browser_keys_keep_a_held_modifier_on_the_chord(self):+ injector.inject_key("shift", down=True)+ self.quartz.posted.clear()+ injector.inject_key("browser_back", down=True)+ flags = self.keys()[0][2]+ self.assertEqual(flags, FakeQuartz.kCGEventFlagMaskCommand | FakeQuartz.kCGEventFlagMaskShift)++ def test_menu_has_no_mac_key_and_is_logged_once(self):+ with self.assertLogs("Beamer", level="WARNING") as logged:+ injector.inject_key("menu", down=True)+ injector.inject_key("menu", down=False)+ self.assertEqual(len(logged.records), 1)+ self.assertEqual(self.quartz.posted, [])++ def test_every_name_the_pc_sends_is_placed_or_knowingly_dropped(self):+ root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+ with open(os.path.join(root, "win_app", "capture_win.py"), encoding="utf-8") as source:+ block = source.read().split("VK_TO_NAME: Dict[int, str] = {", 1)[1].split("\n}\n", 1)[0]+ names = {part.split('"')[1] for part in block.splitlines() if ': "' in part}+ unplaced = {+ name+ for name in names+ if name not in injector.KEY_NAME_TO_CODE+ and name not in injector.WINDOWS_ONLY_KEY_CODES+ and not injector.handles_key(name)+ }+ self.assertEqual(unplaced, {"media_stop", "menu"})+++class ScrollRemainderTests(InjectorCase):+ def scrolls(self):+ return [(e.fields["unit"], e.fields["wheel_y"], e.fields["wheel_x"]) for e in self.quartz.posted if e.kind == "scroll"]++ def test_small_notches_add_up_to_a_click_instead_of_rounding_to_nothing(self):+ for _ in range(10):+ injector.inject_scroll(0.25)+ # Ten quarter notches are two whole clicks and a half, posted as each one completes.+ self.assertEqual([y for _, y, _ in self.scrolls()], [1, 1])++ def test_the_remainder_is_carried_per_direction(self):+ injector.inject_scroll(0.6)+ injector.inject_scroll(-0.6)+ self.assertEqual(sum(y for _, y, _ in self.scrolls()), 0)++ def test_a_whole_notch_posts_at_once(self):+ injector.inject_scroll(2)+ self.assertEqual(self.scrolls(), [(FakeQuartz.kCGScrollEventUnitLine, 2, 0)])++ def test_horizontal_carries_its_own_remainder(self):+ for _ in range(3):+ injector.inject_scroll(0, 0.5)+ self.assertEqual(sum(x for _, _, x in self.scrolls()), 1)++ def test_pixel_mode_carries_fractions_and_does_not_share_the_line_remainder(self):+ injector.inject_scroll(0.5)+ injector.inject_scroll(0.25, mode="pixel")+ injector.inject_scroll(0.25, mode="pixel")+ injector.inject_scroll(0.5)+ posted = self.scrolls()+ self.assertEqual([p for p in posted if p[0] == FakeQuartz.kCGScrollEventUnitLine], [(FakeQuartz.kCGScrollEventUnitLine, 1, 0)])+ # Pixel 0.25 + 0.25 is half a pixel: nothing yet, and the line remainder stayed put.+ self.assertEqual([p for p in posted if p[0] == FakeQuartz.kCGScrollEventUnitPixel], [])++ def test_release_all_drops_a_remainder_so_it_cannot_tick_after_a_reconnect(self):+ injector.inject_scroll(0.5)+ injector.release_all()+ injector.inject_scroll(0.25)+ injector.inject_scroll(0.25)+ self.assertEqual(self.scrolls(), [])+++class GestureInjectionTests(InjectorCase):+ def chord(self):+ return [(code, down) for code, down, _ in self.keys()]++ def test_the_system_swipes_press_the_control_arrow_shortcuts(self):+ ctrl = injector.KEY_NAME_TO_CODE["ctrl"]+ arrows = {+ protocol.GESTURE_SWIPE_UP: "up", # Mission Control+ protocol.GESTURE_SWIPE_DOWN: "down", # App Expose+ protocol.GESTURE_SWIPE_LEFT: "right", # fingers left: the next Space, on the right+ protocol.GESTURE_SWIPE_RIGHT: "left",+ }+ for gesture, arrow in arrows.items():+ self.quartz.posted.clear()+ injector.inject_gesture(gesture)+ code = injector.KEY_NAME_TO_CODE[arrow]+ self.assertEqual(self.chord(), [(ctrl, True), (code, True), (code, False), (ctrl, False)], gesture)++ def test_the_arrow_goes_down_with_control_in_its_flags(self):+ injector.inject_gesture(protocol.GESTURE_SWIPE_UP)+ arrow_down = [k for k in self.keys() if k[0] == injector.KEY_NAME_TO_CODE["up"]][0]+ self.assertEqual(arrow_down[2], FakeQuartz.kCGEventFlagMaskControl | ARROW_FLAGS)++ def test_spread_shows_the_desktop(self):+ injector.inject_gesture(protocol.GESTURE_SPREAD)+ code = injector.KEY_NAME_TO_CODE["f11"]+ self.assertEqual(self.chord(), [(code, True), (code, False)])++ def test_pinch_has_no_shortcut_and_is_logged_once(self):+ # Launchpad left macOS in 26 and its shortcut went with it.+ with self.assertLogs("Beamer", level="WARNING") as logged:+ injector.inject_gesture(protocol.GESTURE_PINCH)+ injector.inject_gesture(protocol.GESTURE_PINCH)+ self.assertEqual(len(logged.records), 1)+ self.assertEqual(self.quartz.posted, [])++ def test_an_unknown_gesture_is_logged_and_ignored(self):+ with self.assertLogs("Beamer", level="WARNING"):+ injector.inject_gesture("wave")+ self.assertEqual(self.quartz.posted, [])++ def test_the_chord_leaves_no_modifier_held(self):+ injector.inject_gesture(protocol.GESTURE_SWIPE_DOWN)+ self.assertEqual(injector._mods_down, set())++ def test_a_modifier_the_sender_holds_is_not_released_by_the_chord(self):+ injector.inject_key("ctrl", down=True)+ self.quartz.posted.clear()+ injector.inject_gesture(protocol.GESTURE_SWIPE_UP)+ code = injector.KEY_NAME_TO_CODE["up"]+ self.assertEqual(self.chord(), [(code, True), (code, False)])+ self.assertEqual(injector._mods_down, {"ctrl"})++ def test_every_gesture_the_wire_names_is_handled_or_knowingly_dropped(self):+ for name in protocol.GESTURE_NAMES:+ self.quartz.posted.clear()+ if name == protocol.GESTURE_PINCH:+ with self.assertLogs("Beamer", level="WARNING"):+ injector.inject_gesture(name)+ else:+ injector.inject_gesture(name)+ self.assertTrue(self.quartz.posted, name)+++class FakeNSGesture:+ def __init__(self, magnification=0.0, delta_x=0.0, phase=0):+ self.magnification = magnification+ self.deltaX = delta_x+ self.deltaY = 0.0+ self.phase = phase+++class MacShapedGestureTranslatorTests(unittest.TestCase):+ def keys(self, messages):+ return [(m["type"], m["data"]["key"]) for m in messages if m["type"] in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP)]++ def test_the_default_is_still_the_windows_shaped_chord(self):+ translator = GestureTranslator()+ swipe = translator.translate(31, FakeNSGesture(delta_x=1))+ self.assertEqual(+ self.keys(swipe),+ [(protocol.MSG_KEYDOWN, "alt"), (protocol.MSG_KEYDOWN, "left"), (protocol.MSG_KEYUP, "left"), (protocol.MSG_KEYUP, "alt")],+ )++ def test_a_page_swipe_to_a_mac_is_command_bracket(self):+ translator = GestureTranslator(receiver="mac")+ back = translator.translate(31, FakeNSGesture(delta_x=1))+ forward = translator.translate(31, FakeNSGesture(delta_x=-1))+ self.assertEqual(+ self.keys(back),+ [(protocol.MSG_KEYDOWN, "cmd"), (protocol.MSG_KEYDOWN, "["), (protocol.MSG_KEYUP, "["), (protocol.MSG_KEYUP, "cmd")],+ )+ self.assertEqual(self.keys(forward)[1], (protocol.MSG_KEYDOWN, "]"))++ def test_a_pinch_to_a_mac_zooms_with_command_plus_and_minus(self):+ translator = GestureTranslator(receiver="mac")+ zoom_in = translator.translate(30, FakeNSGesture(magnification=0.06))+ zoom_out = translator.translate(30, FakeNSGesture(magnification=-0.06))+ self.assertEqual(self.keys(zoom_in)[:2], [(protocol.MSG_KEYDOWN, "cmd"), (protocol.MSG_KEYDOWN, "=")])+ self.assertEqual(self.keys(zoom_out)[:2], [(protocol.MSG_KEYDOWN, "cmd"), (protocol.MSG_KEYDOWN, "-")])+ self.assertFalse([m for m in zoom_in if m["type"] == protocol.MSG_SCROLL])++ def test_the_mac_chord_names_its_us_key_so_another_layout_still_presses_a_key(self):+ translator = GestureTranslator(receiver="mac")+ keys = [m["data"] for m in translator.translate(31, FakeNSGesture(delta_x=1)) if m["type"] == protocol.MSG_KEYDOWN]+ self.assertEqual(keys, [{"key": "cmd"}, {"key": "[", "us": "["}])+ down = injector.plan_key_event("[", True, {"cmd"}, us="[")+ self.assertEqual(down, (0x21, None))++ def test_a_pinch_to_windows_is_still_control_wheel(self):+ zoom = GestureTranslator().translate(30, FakeNSGesture(magnification=0.06))+ self.assertTrue([m for m in zoom if m["type"] == protocol.MSG_SCROLL])++ def test_an_unknown_receiver_is_refused(self):+ with self.assertRaises(ValueError):+ GestureTranslator(receiver="linux")+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_effect_fires.py b/mac_app/tests/test_effect_fires.pyindex a5cab41..eab3981 100644--- a/mac_app/tests/test_effect_fires.py+++ b/mac_app/tests/test_effect_fires.py@@ -5,7 +5,7 @@ EffectsOverlay / EdgeGlow / NotchBeam / NotchIsland.bridge.py raising each crossing kind ("pressure", "tick", "cross", "arrive", "home") with theright Step fields (region, pin, via, mac_edge) is already proven by test_bridge.py's-CrossingWiringTests and the switch_msg("mac", ...) tests around line 1920 -- not repeated here.+CrossingWiringTests and core/tests/test_owner.py -- not repeated here.This file starts from a Step already shaped the way bridge.py builds one, and checks where itlands."""@@ -208,7 +208,7 @@ class HomeArrivalTest(unittest.TestCase):class DrivenReturnEdgeTest(unittest.TestCase):- """The PC-driven return edge: receiver.py's pressure_callback and arrival_callback, wired in+ """The PC-driven return edge: LinkResponder's pressure_callback and arrival_callback, wired inkvm_bridge_app.py's TrayApp.__init__ as WindowsInput(pressure_callback=self._driven_pressure,arrival_callback=self._driven_arrival), land here after the main-thread hop proved above."""@@ -300,7 +300,7 @@ class EdgeGlowDrawTest(unittest.TestCase):class MenuBarArmTest(unittest.TestCase):- """Toby, 28-09-2026: the Mac's Glow corner was lopsided, the top arm a faint stripe inside the+ """Reported 28-09-2026: the Mac's Glow corner was lopsided, the top arm a faint stripe inside themenu bar beside a full side arm. Both arms measured the same 18.5pt on film, half the 37pt bar."""BOUNDS = (0.0, 0.0, 1728.0, 1117.0)diff --git a/mac_app/tests/test_handshake_deadline.py b/mac_app/tests/test_handshake_deadline.pydeleted file mode 100644index 7bda966..0000000--- a/mac_app/tests/test_handshake_deadline.py+++ /dev/null@@ -1,101 +0,0 @@-import socket-import struct-import threading-import time-import unittest-import os-import sys--sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from core import protocol-from core import receiver-from core.receiver import ReceiverServer, ServerState---class HandshakeDeadlineTests(unittest.TestCase):- """The handshake is bounded as a whole, and only handshakes count against- the pending cap, so a stranger trickling bytes cannot hold a slot for- long and the real peer never finds every slot taken by strangers."""-- def test_a_trickled_read_ends_at_the_deadline_not_per_byte(self):- a, b = socket.socketpair()- self.addCleanup(a.close)- self.addCleanup(b.close)- b.settimeout(1.0)- deadline = time.monotonic() + 0.3-- def trickle():- for _ in range(6):- time.sleep(0.1)- try:- a.send(b"\0")- except OSError:- return-- threading.Thread(target=trickle, daemon=True).start()- started = time.monotonic()- with self.assertRaises(socket.timeout):- protocol._recv_exact(b, 64, deadline)- self.assertLess(time.monotonic() - started, 0.9)-- def test_strangers_free_their_slots_and_the_peer_gets_in(self):- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))- self.addCleanup(server.stop)- with unittest_patch(receiver, "HELLO_TIMEOUT_SECONDS", 0.3):- server.start(_config(port=0))- port = _wait_for_port(server)- strangers = []- for _ in range(receiver.MAX_PENDING_CONNECTIONS):- s = socket.create_connection(("127.0.0.1", port), timeout=2.0)- s.sendall(b"\0")- strangers.append(s)- self.addCleanup(lambda: [s.close() for s in strangers])- # Every slot is a stranger's, so a fifth connection is refused at once.- refused = socket.create_connection(("127.0.0.1", port), timeout=2.0)- self.addCleanup(refused.close)- refused.settimeout(2.0)- self.assertEqual(refused.recv(1), b"")- # Their handshakes time out, and the next connection is served.- time.sleep(0.6)- served = socket.create_connection(("127.0.0.1", port), timeout=2.0)- self.addCleanup(served.close)- session = protocol.SecureSession("shared-token")- served.sendall(session.preamble())- served.settimeout(2.0)- protocol.recv_preamble(served, session)---class unittest_patch:- def __init__(self, module, name, value):- self.module, self.name, self.value = module, name, value-- def __enter__(self):- self.old = getattr(self.module, self.name)- setattr(self.module, self.name, self.value)-- def __exit__(self, *exc):- setattr(self.module, self.name, self.old)---def _config(port):- class Config:- auth_token = "shared-token"-- Config.port = port- return Config()---def _wait_for_port(server, timeout=2.0):- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- listener = server._listener- if listener is not None:- return listener.getsockname()[1]- time.sleep(0.01)- raise AssertionError("the listener did not come up")---if __name__ == "__main__":- unittest.main()diff --git a/mac_app/tests/test_hardware_mac.py b/mac_app/tests/test_hardware_mac.pynew file mode 100644index 0000000..b737f87--- /dev/null+++ b/mac_app/tests/test_hardware_mac.py@@ -0,0 +1,79 @@+"""This Mac's hardware address for the handshake's `hw` field. The getifaddrs walk runs only on macOS."""++import os+import re+import sys+import unittest+from unittest import mock++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import hardware_mac+from core import pairing++MAC_FORM = re.compile(r"^([0-9a-f]{2}:){5}[0-9a-f]{2}$")+TABLE = ({"192.168.1.5": "en0", "10.9.0.2": "utun3"}, {"en0": b"\xaa\xbb\xcc\x0d\xee\xff", "utun3": b""})+++class FormatMacTest(unittest.TestCase):+ def test_six_bytes_become_lower_case_colon_groups(self):+ self.assertEqual(hardware_mac.format_mac(b"\xaa\xbb\xcc\x0d\xee\xff"), "aa:bb:cc:0d:ee:ff")++ def test_wrong_length_and_all_zero_are_unknown(self):+ self.assertEqual(hardware_mac.format_mac(b"\xaa\xbb\xcc\xdd\xee"), "")+ self.assertEqual(hardware_mac.format_mac(b""), "")+ self.assertEqual(hardware_mac.format_mac(bytes(6)), "")+++class HardwareAddressTowardsTest(unittest.TestCase):+ def towards(self, host, local, table=TABLE):+ with mock.patch.object(pairing, "local_address_towards", return_value=local), \+ mock.patch.object(hardware_mac, "_interface_table", return_value=table):+ return hardware_mac.hardware_address_towards(host)++ def test_the_adapter_that_carries_the_route_names_the_address(self):+ self.assertEqual(self.towards("192.168.1.9", "192.168.1.5"), "aa:bb:cc:0d:ee:ff")++ def test_an_interface_with_no_link_layer_address_is_unknown(self):+ self.assertEqual(self.towards("10.9.0.1", "10.9.0.2"), "")++ def test_an_address_on_no_interface_is_unknown(self):+ self.assertEqual(self.towards("172.16.0.1", "172.16.0.2"), "")++ def test_failures_are_unknown_not_raised(self):+ with mock.patch.object(hardware_mac, "_interface_table", side_effect=OSError("getifaddrs")):+ self.assertEqual(hardware_mac.hardware_address_towards("192.168.1.9"), "")+ with mock.patch.object(pairing, "local_address_towards", side_effect=OSError("unreachable")):+ self.assertEqual(hardware_mac.hardware_address_towards("192.168.1.9"), "")++ def test_no_host_is_unknown_without_touching_the_network(self):+ with mock.patch.object(pairing, "local_address_towards") as route:+ self.assertEqual(hardware_mac.hardware_address_towards(""), "")+ route.assert_not_called()++ def test_off_macos_is_unknown_without_touching_the_network(self):+ with mock.patch.object(hardware_mac.sys, "platform", "win32"), \+ mock.patch.object(pairing, "local_address_towards") as route:+ self.assertEqual(hardware_mac.hardware_address_towards("192.168.1.9"), "")+ route.assert_not_called()++[email protected](sys.platform == "darwin", "getifaddrs layout is macOS's")+class LiveInterfaceTableTest(unittest.TestCase):+ def test_the_table_reads_this_macs_interfaces(self):+ ips, macs = hardware_mac._interface_table()+ self.assertIn("127.0.0.1", ips)+ self.assertTrue(macs)+ for raw in macs.values():+ self.assertIn(len(raw), (0, 6, 8))++ def test_every_real_address_is_well_formed(self):+ ips, macs = hardware_mac._interface_table()+ for name in ips.values():+ mac = hardware_mac.format_mac(macs.get(name, b""))+ self.assertTrue(mac == "" or MAC_FORM.match(mac), mac)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_hello_limit.py b/mac_app/tests/test_hello_limit.pydeleted file mode 100644index 5e6efca..0000000--- a/mac_app/tests/test_hello_limit.py+++ /dev/null@@ -1,52 +0,0 @@-import socket-import struct-import threading-import unittest-import os-import sys--sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from core import protocol---class HelloFrameLimitTests(unittest.TestCase):- """Before the first frame's tag is checked the peer has proved nothing, so- the receiver reads that frame under HELLO_MAX_BYTES rather than the- clipboard-sized MAX_FRAME_BYTES a stranger could otherwise make it buffer- per connection."""-- def _pair(self):- a, b = socket.socketpair()- self.addCleanup(a.close)- self.addCleanup(b.close)- return a, b-- def test_an_oversized_first_frame_is_refused_before_it_is_read(self):- sender, receiver = self._pair()- session = protocol.SecureSession("t")- sender.sendall(struct.pack(">I", protocol.HELLO_MAX_BYTES + 1))- with self.assertRaises(protocol.ProtocolError):- protocol.recv_msg(receiver, session, limit=protocol.HELLO_MAX_BYTES)-- def test_a_real_hello_fits_under_the_limit(self):- sender, receiver = self._pair()- theirs = protocol.SecureSession("t")- mine = protocol.SecureSession("t")- mine.accept_preamble(theirs.preamble())- theirs.accept_preamble(mine.preamble())- frame = theirs.seal(protocol.hello_msg(return_edge="left", resistance_px=120))- self.assertLess(len(frame) - protocol.HEADER_SIZE, protocol.HELLO_MAX_BYTES)- sender.sendall(frame)- self.assertEqual(protocol.recv_msg(receiver, mine, limit=protocol.HELLO_MAX_BYTES)["type"], protocol.MSG_HELLO)-- def test_the_default_limit_is_still_the_frame_cap(self):- sender, receiver = self._pair()- session = protocol.SecureSession("t")- sender.sendall(struct.pack(">I", protocol.MAX_FRAME_BYTES + 1))- with self.assertRaises(protocol.ProtocolError):- protocol.recv_msg(receiver, session)---if __name__ == "__main__":- unittest.main()diff --git a/mac_app/tests/test_hide_addresses_window.py b/mac_app/tests/test_hide_addresses_window.pyindex e1970c5..494a91c 100644--- a/mac_app/tests/test_hide_addresses_window.py+++ b/mac_app/tests/test_hide_addresses_window.py@@ -1,5 +1,5 @@-"""Hide addresses in the real settings window: the pairing card's typed address and what it says-about it. Built as tools/readme_shots_mac.py builds it, never put on screen, starting no network."""+"""Hide addresses in the real settings window: the pairing sheet's typed address, the machines list+and what they say. Built as the README's screenshots build it, never put on screen, starting no network."""import jsonimport logging@@ -37,28 +37,32 @@ class HideAddressesWindowTests(unittest.TestCase):self.window = kvm_bridge_app.ControlWindow.alloc().initWithController_settingsStore_logger_(WakingController(store.load(), logger=logger), store, logger)- self.window.discovery = mock.Mock(pcs=mock.Mock(return_value=[]))+ self.service = mock.Mock(machines=mock.Mock(return_value=[]), error=None, code=None)+ self.window.panel.service = self.servicedef tearDown(self):self.window.appearance_watch.stop()self.directory.cleanup()def test_the_typed_address_is_dots_and_is_never_said_back(self):- plain_box, secret_box = self.window.find_boxes+ panel = self.window.panel+ plain_box, secret_box = panel.find_boxesself.assertTrue(plain_box.isHidden())self.assertFalse(secret_box.isHidden())- self.window.find_secret.setStringValue_("192.0.2.10")- with mock.patch.object(kvm_bridge_app.AppHelper, "callLater"):- self.window.findPC_(None)- self.window.discovery.find.assert_called_once_with("192.0.2.10")- self.window._find_timed_out(self.window._find_serial)- self.assertNotIn("192.0.2.10", self.window.find_status.view.stringValue())+ panel.find_secret.setStringValue_("192.0.2.10")+ for field, digit in zip(panel.code_boxes.fields, "123456"):+ field.setStringValue_(digit)+ with mock.patch.object(kvm_bridge_app.machines_panel.threading, "Thread"):+ panel._pair()+ self.assertIn("Pairing with", panel.pair_status.text)+ self.assertNotIn("192.0.2.10", panel.pair_status.text)def test_switching_it_off_shows_the_typed_address_again(self):- self.window.find_secret.setStringValue_("192.0.2.10")+ panel = self.window.panel+ panel.find_secret.setStringValue_("192.0.2.10")self.window._set_hide_addresses(False)- self.assertEqual(self.window.find_field.stringValue(), "192.0.2.10")- self.assertFalse(self.window.find_boxes[0].isHidden())+ self.assertEqual(panel.find_field.stringValue(), "192.0.2.10")+ self.assertFalse(panel.find_boxes[0].isHidden())def test_the_footer_hides_an_address_in_a_failed_switch(self):# Codex, 29-09-2026: a failed switch put the connection status, which names the PC's@@ -66,12 +70,28 @@ class HideAddressesWindowTests(unittest.TestCase):self.window._say("Connecting to 192.0.2.20:24820", "fault")self.assertNotIn("192.0.2.20", self.window.message_label.view.stringValue())- def test_an_unnamed_pc_is_not_named_by_its_address(self):- # peer_name falls back to the address when the PC has no name.+ def test_an_unnamed_machine_is_not_named_by_its_address(self):+ # labels() falls back to the address when a machine has no name.self.window.controller.cfg.pc_name = ""- self.window._refresh_paired(mock.Mock(key="token"))- self.assertNotIn("192.0.2.20", self.window.paired_name.view.stringValue())- self.assertNotIn("192.0.2.20", self.window.paired_note.view.stringValue())+ peer = self.window.controller.book.peers()[0]+ self.window.settings_store.set_peer(peer["token"], send=True)+ settings = self.window.settings_store.current()+ settings["peers"][0]["name"] = ""+ self.window.settings_store.save_settings(settings)+ self.window.panel.refresh()+ texts = []++ def walk(view):+ if isinstance(view, kvm_bridge_app.AppKit.NSTextField):+ texts.append(view.stringValue())+ texts.append(view.accessibilityLabel() or "")+ for sub in view.subviews():+ walk(sub)++ for row in self.window.panel.list.arrangedSubviews():+ walk(row)+ self.assertTrue(texts)+ self.assertNotIn("192.0.2.20", " ".join(texts))class ReloadTests(unittest.TestCase):diff --git a/mac_app/tests/test_ignored_inputs.py b/mac_app/tests/test_ignored_inputs.pyindex d51e621..99d92e4 100644--- a/mac_app/tests/test_ignored_inputs.py+++ b/mac_app/tests/test_ignored_inputs.py@@ -15,7 +15,8 @@ from core import ignoredfrom core import protocolimport settings_storefrom bridge import KVMController-from tests.test_bridge import FakeClock, FakeQuartz, make_config, quiet_logger+from bridge_fakes import PAIRED_TOKEN, FakeClock, FakeQuartz, make_config, quiet_logger+from fake_link import FakeLinkKEY_F13 = 0x69KEY_A = 0x00@@ -32,10 +33,11 @@ def other_button(number):class TapTests(unittest.TestCase):def setUp(self):self.controller = KVMController(- replace(make_config(), ignored_inputs=[ignored.key(KEY_F13), ignored.button("back"), ignored.media("volume_up")]),+ replace(make_config(PAIRED_TOKEN), ignored_inputs=[ignored.key(KEY_F13), ignored.button("back"), ignored.media("volume_up")]),logger=quiet_logger(),quartz=FakeQuartz,clock=FakeClock(),+ link_factory=FakeLink,system_event_converter=lambda event: event,)self.controller.redirecting = Truediff --git a/mac_app/tests/test_input_injector_mac.py b/mac_app/tests/test_input_injector_mac.pyindex 513d5ad..70c6d00 100644--- a/mac_app/tests/test_input_injector_mac.py+++ b/mac_app/tests/test_input_injector_mac.py@@ -53,6 +53,27 @@ class KeyPlanTests(unittest.TestCase):self.assertIsNone(self.plan("nonsense_key"))+class TextChunkTests(unittest.TestCase):+ def test_short_text_is_one_chunk(self):+ self.assertEqual(injector.text_chunks("héllo"), ["héllo"])++ def test_long_text_is_cut_inside_the_events_limit_of_utf_16_units(self):+ chunks = injector.text_chunks("a" * 40)+ self.assertEqual("".join(chunks), "a" * 40)+ self.assertTrue(all(len(chunk) <= injector.TEXT_CHUNK_UNITS for chunk in chunks))++ def test_a_character_outside_the_bmp_is_never_split(self):+ text = "x" * (injector.TEXT_CHUNK_UNITS - 1) + "\U0001F600" + "y"+ chunks = injector.text_chunks(text)+ self.assertEqual("".join(chunks), text)+ self.assertTrue(all(len(chunk.encode("utf-16-le")) // 2 <= injector.TEXT_CHUNK_UNITS for chunk in chunks))+ self.assertIn("\U0001F600", "".join(chunks))+ self.assertFalse(any(chunk.endswith("\ud83d") for chunk in chunks))++ def test_nothing_is_no_chunks(self):+ self.assertEqual(injector.text_chunks(""), [])++class ClampTests(unittest.TestCase):SCREENS = [Rect(0, 0, 1000, 1000), Rect(1000, 200, 800, 600)]diff --git a/mac_app/tests/test_keyboard_layout.py b/mac_app/tests/test_keyboard_layout.pyindex aa08497..b3df47c 100644--- a/mac_app/tests/test_keyboard_layout.py+++ b/mac_app/tests/test_keyboard_layout.py@@ -15,7 +15,7 @@ import keyboard_layoutimport input_injector_mac as injectorfrom core import protocolfrom bridge import QuartzEventTranslator-from tests.test_bridge import FakeQuartz+from bridge_fakes import FakeQuartzGERMAN = {0x00: "a", 0x06: "y", 0x07: "x", 0x08: "c", 0x09: "v", 0x0C: "q", 0x10: "z", 0x18: None, 0x21: "ü", 0x29: "ö", 0x32: "<"}FRENCH = {0x00: "q", 0x06: "w", 0x0C: "a", 0x0D: "z", 0x10: "y", 0x12: "&", 0x29: "m"}diff --git a/mac_app/tests/test_link_state.py b/mac_app/tests/test_link_state.pyindex 31bed75..5074280 100644--- a/mac_app/tests/test_link_state.py+++ b/mac_app/tests/test_link_state.py@@ -7,14 +7,18 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))import link_stateimport widgets-from bridge import AUTH_FAILED_STATUS, OLD_RECEIVER_STATUS, connection_error_message-from wake import NOT_WOKEN_STATUS+from bridge_fakes import PAIRED_TOKEN, FakeClock, FakeQuartz, make_config, quiet_logger+from fake_link import FakeLink, bring_up+from core.link import connection_ended+from wake import WakingController, not_woken_status-def controller(status="Connected to 192.168.1.3:51820", connected=True, **overrides):+def controller(status="Connected to 192.168.1.3:51820", connected=True, kind="connected", **overrides):values = dict(cfg=SimpleNamespace(host="192.168.1.3", port=51820, auth_token="t", pc_name="STUDIO-PC"),connection_status=status,+ status_kind=kind,+ via_tunnel=False,connected=connected,waking=False,windows_locked=False,@@ -45,44 +49,99 @@ class LinkStateTest(unittest.TestCase):self.assertState("receiving", "signal", receiving=True, redirecting=True)self.assertState("receiving", "signal", receiving=True, connected=False)+ def test_the_states_name_the_machine_they_are_about(self):+ driving = link_state.describe(controller(receiving=True, driver_label="Laptop", peer_label="Desk"))+ self.assertEqual(driving.word, "From Laptop")+ self.assertIn("Laptop's keyboard", driving.detail)+ sending = link_state.describe(controller(redirecting=True, on_label="Laptop", peer_label="Desk"))+ self.assertEqual(sending.word, "On Laptop")+ self.assertIn("Laptop", sending.detail)+ idle = link_state.describe(controller(peer_label="Desk (AAAA)"))+ self.assertIn("Desk (AAAA)", idle.detail)++ def test_with_no_label_the_saved_name_stands_in_and_nothing_says_windows(self):+ cfg = SimpleNamespace(host="192.168.1.3", port=51820, auth_token="t", pc_name="")+ words = [link_state.describe(controller(cfg=cfg, **kwargs)) for kwargs in (+ dict(receiving=True), dict(redirecting=True), dict(waking=True, connected=False),+ dict(connected=False, kind="unreachable"), dict(connected=False, kind="refused"))]+ for state in words:+ self.assertNotIn("Windows", state.word + state.detail)+ self.assertNotIn("PC", state.word + state.detail)+ bare = SimpleNamespace(host="", port=51820, auth_token="t", pc_name="")+ self.assertEqual(link_state.peer_name(bare), "the other machine")++ def test_a_refused_token_says_remove_then_pair_again(self):+ state = link_state.describe(controller(kind="unauthenticated", connected=False))+ self.assertIn("Remove it, then pair again", state.detail)+def test_connected_states(self):self.assertState("mac", "ink")self.assertState("windows", "signal", redirecting=True)- self.assertState("unlocking", "amber", status="Unlocking Windows…", windows_locked=True, redirecting=True)+ self.assertState("unlocking", "amber", status="Unlocking STUDIO-PC…", windows_locked=True, redirecting=True)self.assertState("paused", "ink", crossing_paused=True)self.assertState("full_screen", "ink", full_screen_app="Final Cut Pro")self.assertState("waking", "amber", waking=True, connected=False)def test_tunnel_is_tagged(self):- state = link_state.describe(controller(status=link_state.TUNNEL_STATUS))+ state = link_state.describe(controller(via_tunnel=True))self.assertEqual((state.key, state.tag), ("mac", "Tunnel"))-- def test_every_failure_status_has_a_word(self):- cases = {- AUTH_FAILED_STATUS: "token",- OLD_RECEIVER_STATUS: "version",- "Windows receiver speaks Beamer protocol v3, this Mac v4 — update both apps": "version",- "Windows rejected the connection: busy": "rejected",- NOT_WOKEN_STATUS: "not_woken",- connection_error_message(OSError(65, "No route")): "unreachable",- connection_error_message(OSError(65, "Open /Applications/Beamer Tunnel.command")): "blocked",- connection_error_message(OSError(61, "Refused")): "not_listening",- connection_error_message(TimeoutError()): "unreachable",- "Windows stopped responding": "stopped",- "Connecting to 192.168.1.3:51820": "waiting",- "Waiting to connect": "waiting",- "Settings saved; reconnecting": "waiting",- "Windows closed the connection": "dropped",- "send failed: broken pipe": "dropped",- "": "dropped",- }- for status, key in cases.items():- with self.subTest(status=status):- self.assertState(key, "amber" if key == "waiting" else "fault", status=status, connected=False)+ self.assertIn("tunnel", state.detail)++ def test_every_failure_kind_has_a_word(self):+ ended = lambda number, name="Windows": connection_ended(OSError(number, "x"), name)+ cases = [+ ("unauthenticated", "Windows could not be authenticated", "token"),+ ("wrong_id", "Windows has this pairing under another machine", "token"),+ ("different", "A different Beamer answered", "token"),+ ("unreadable", "Windows could not read what this machine sent first", "token"),+ ("older", "Update Beamer on Windows: it is older than this one", "version"),+ ("newer", "Windows runs a newer Beamer", "version"),+ ("not_beamer", "Windows did not answer as a Beamer", "version"),+ ("failed", not_woken_status("Windows"), "not_woken"),+ ("failed", not_woken_status("Desk (AAAA)"), "not_woken"),+ (ended(65).kind, ended(65).text, "unreachable"),+ (ended(51).kind, ended(51).text, "unreachable"),+ (connection_ended(TimeoutError(), "Windows").kind, connection_ended(TimeoutError(), "Windows").text, "unreachable"),+ ("blocked", "macOS 27 blocked direct LAN access. Open /Applications/Beamer Tunnel.command.", "blocked"),+ (ended(61).kind, ended(61).text, "not_listening"),+ ("stopped", "Windows stopped responding", "stopped"),+ ("closed", "Windows closed the connection", "stopped"),+ ("failed", "Connecting to 192.168.1.3:51820", "waiting"),+ ("failed", "Waiting to connect", "waiting"),+ ("failed", "Settings saved; reconnecting", "waiting"),+ ("failed", "Connection failed: broken pipe", "dropped"),+ ("failed", "", "dropped"),+ ("off", "This link was stopped", "dropped"),+ ("none", "", "dropped"),+ ]+ for kind, status, key in cases:+ with self.subTest(kind=kind, status=status):+ self.assertState(key, "amber" if key == "waiting" else "fault", kind=kind, status=status, connected=False)++ def test_the_word_comes_from_the_kind_not_the_sentence(self):+ self.assertState("token", "fault", kind="unauthenticated", status="Something this build never said", connected=False)+ self.assertState("dropped", "fault", kind="failed", status="Windows is unreachable from this machine.", connected=False)++ def test_a_stale_failure_kind_is_ignored_while_connected(self):+ self.assertState("mac", "ink", kind="refused")def test_unpaired(self):cfg = SimpleNamespace(host="192.168.1.3", port=51820, auth_token="", pc_name="")- self.assertEqual(link_state.describe(controller(connected=False, cfg=cfg)).key, "unpaired")+ self.assertEqual(link_state.describe(controller(connected=False, kind="refused", cfg=cfg)).key, "unpaired")+++class ARealControllerTest(unittest.TestCase):+ def test_the_primary_links_kind_reaches_the_word(self):+ real = WakingController(make_config(PAIRED_TOKEN), logger=quiet_logger(), quartz=FakeQuartz, clock=FakeClock(),+ link_factory=FakeLink, desktop_bounds=lambda: (0, 0, 1920, 1080))+ self.assertEqual(link_state.describe(real).key, "waiting")+ link = bring_up(real)+ self.assertEqual(link_state.describe(real).key, "mac")+ link.down(real, "Office PC is reachable, but Beamer is not listening on this port.", "refused")+ self.assertEqual(real.status_kind, "refused")+ self.assertEqual(link_state.describe(real).key, "not_listening")+ link.down(real, "Update Beamer on Office PC: it is older than this one", "older")+ self.assertEqual(link_state.describe(real).key, "version")class RulerScaleTest(unittest.TestCase):diff --git a/mac_app/tests/test_mac_links.py b/mac_app/tests/test_mac_links.pynew file mode 100644index 0000000..397526a--- /dev/null+++ b/mac_app/tests/test_mac_links.py@@ -0,0 +1,530 @@+"""The Mac's controller and the owner (WIRE.md sections 4 and 5) with the links faked: where input+goes, what is sent to the machine it leaves and the one it takes, the pointer and the alerts each+way home, the key table on the way out, and the clipboard. The links themselves are+core/tests/test_link.py's; the two ends together are test_mac_loopback.py's."""++import os+import sys+import threading+import time+import unittest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from bridge import KVMController+from core import protocol+from bridge_fakes import PAIRED_TOKEN, FakeClipboard, FakeClock, FakeQuartz, make_config, quiet_logger+from fake_link import CAPS, OTHER_ID, PEER_ID, FakeLink, bring_up+++class Base(unittest.TestCase):+ def setUp(self):+ FakeQuartz.reset_cursor_spies()+ self.clock = FakeClock()+ self.clipboard = FakeClipboard("hello")+ self.controller = KVMController(+ make_config(PAIRED_TOKEN), logger=quiet_logger(), quartz=FakeQuartz, clock=self.clock,+ clipboard=self.clipboard, link_factory=FakeLink, desktop_bounds=lambda: (0, 0, 1920, 1080),+ )+ self.alerts = []+ self.controller.on_user_alert = lambda title, message: self.alerts.append(message)+ self.crossings = []+ self.controller.on_crossing = lambda kind, step: self.crossings.append((kind, step))+ self.link = self.controller._primary_link+ self.own = protocol.id_text(self.controller.identity()["id"])+ self.peer = protocol.id_text(PEER_ID)++ def up(self, **fields):+ return bring_up(self.controller, **fields)++ def focus(self, index=0):+ focuses = [m for m in self.link.posted if m["type"] == protocol.MSG_FOCUS]+ return focuses[index]["data"]+++class HardwareHookTests(unittest.TestCase):+ def controller(self, **kwargs):+ return KVMController(+ make_config(PAIRED_TOKEN), logger=quiet_logger(), quartz=FakeQuartz, clock=FakeClock(),+ clipboard=FakeClipboard("hello"), link_factory=FakeLink, desktop_bounds=lambda: (0, 0, 1920, 1080), **kwargs,+ )++ def test_each_link_is_handed_the_controllers_hardware_hook(self):+ hook = lambda host: "aa:bb:cc:dd:ee:ff"+ self.assertIs(self.controller(hardware=hook)._primary_link.hardware, hook)++ def test_no_hook_leaves_the_link_without_one(self):+ self.assertIsNone(self.controller()._primary_link.hardware)++ def test_each_link_reads_a_large_frame_only_while_the_owner_expects_its_clipboard(self):+ controller = self.controller()+ link = controller._primary_link+ link.peer_id = "B"+ now = controller.owner._clock()+ self.assertFalse(link.large(link, now))+ controller.owner._let_go["B"] = now+ self.assertTrue(link.large(link, now))+++class RemovedLinksTests(Base):+ def test_a_link_for_a_machine_that_went_is_stopped_without_waiting_for_it(self):+ # Stopping joins the link's thread, which can be in a connect: never on the main thread.+ self.controller.book.data["peers"][0]["send"] = False+ self.controller._sync_links()+ self.assertTrue(self.link.stopped)+ self.assertFalse(self.link.stop_waited)++ def test_a_link_that_goes_down_after_its_machine_went_cannot_bring_input_back_or_report_up(self):+ self.up()+ self.controller.book.data["peers"][0]["send"] = False+ self.controller._sync_links()+ self.controller._link_up(self.link, {"id": PEER_ID, "name": "Late", "accepts": True, "caps": CAPS})+ self.assertNotIn(self.peer, self.controller._peers_up)++ def test_a_link_whose_machine_goes_as_it_comes_up_is_not_left_registered(self):+ controller, link, peer = self.controller, self.link, self.peer++ class RemovesTheMachine(dict):+ # The machine goes between the check that its link is still wanted and the registration.+ def __setitem__(self, key, value):+ super().__setitem__(key, value)+ controller.book.data["peers"][0]["send"] = False+ controller._sync_links()++ controller._up_names = RemovesTheMachine()+ link._live = True+ link.peer_id = peer+ controller._link_up(link, {"id": PEER_ID, "name": "Late", "accepts": True, "caps": CAPS})+ self.assertNotIn(peer, controller._peers_up)+ self.assertNotIn(peer, controller.owner._links)++ def test_stopping_the_controller_still_waits_for_its_links(self):+ self.controller.stop()+ self.assertTrue(self.link.stop_waited)+++class TakingAndLeavingTests(Base):+ def test_a_take_sends_the_focus_then_the_clipboard(self):+ self.up()+ self.assertTrue(self.controller.set_redirecting(True, edge="left", offset=0.4))+ take = self.focus()+ self.assertEqual((take["route"], take["target"], take["edge"], take["offset"]), (1, self.peer, "left", 0.4))+ self.assertEqual(take["resistance_px"], int(self.controller.crossing.resistance_px))+ self.assertEqual(take["reach"], [])+ kinds = [m["type"] for m in self.link.posted if m["type"] in (protocol.MSG_FOCUS, protocol.MSG_CLIPBOARD)]+ self.assertEqual(kinds, [protocol.MSG_FOCUS, protocol.MSG_CLIPBOARD])+ self.assertEqual(self.link.posted[-1]["data"]["text"], "hello")+ self.assertTrue(self.controller.redirecting)+ self.assertEqual(FakeQuartz.associate_calls, [False])++ def test_the_shortcut_takes_with_no_position(self):+ self.up()+ self.controller.set_redirecting(True)+ self.assertNotIn("edge", self.focus())++ def test_input_follows_the_take_to_the_link(self):+ self.up()+ self.controller.set_redirecting(True)+ self.controller._process_outbound({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 3, "dy": 4}})+ self.assertEqual(self.link.sent, [{"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 3, "dy": 4}}])++ def test_going_home_releases_what_was_pressed_then_lets_go(self):+ self.up()+ self.controller.set_redirecting(True)+ self.controller._process_outbound({"type": protocol.MSG_KEYDOWN, "data": {"key": "a", "us": "a"}})+ self.link.posted.clear()+ self.link.sent.clear()+ self.assertTrue(self.controller.set_redirecting(False))+ self.assertEqual(self.link.sent, [{"type": protocol.MSG_KEYUP, "data": {"key": "a", "us": "a"}}])+ let_go = self.focus()+ self.assertEqual((let_go["route"], let_go["target"]), (2, self.own))+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(FakeQuartz.associate_calls[-1], True)+ self.assertEqual([kind for kind, _ in self.crossings], ["home"])++ def test_nothing_is_taken_when_the_peer_does_not_accept_this_machine(self):+ self.up(accepts=False)+ self.assertFalse(self.controller.set_redirecting(True))+ self.assertFalse(self.controller.redirecting)+ self.assertIn("does not accept input from this Mac", self.alerts[-1])++ def test_nothing_is_taken_while_the_link_is_down(self):+ self.assertFalse(self.controller.set_redirecting(True))+ self.assertTrue(self.alerts)++ def test_sending_off_refuses_the_take(self):+ self.up()+ self.controller.cfg.send_to_windows = False+ self.assertFalse(self.controller.set_redirecting(True))+ self.assertEqual(self.link.posted.count(None), 0)+ self.assertEqual(self.focus_count(), 0)++ def focus_count(self):+ return len([m for m in self.link.posted if m["type"] == protocol.MSG_FOCUS])+++class ModifierNamesTests(Base):+ def send(self, key, **link):+ self.up(**link)+ self.controller.set_redirecting(True)+ self.link.sent.clear()+ self.controller._process_outbound({"type": protocol.MSG_KEYDOWN, "data": {"key": key}})+ return self.link.sent[-1]["data"]["key"] if self.link.sent else None++ def test_command_goes_to_a_pc_as_control_and_control_as_the_windows_key(self):+ self.assertEqual(self.send("cmd"), "ctrl")+ self.link.sent.clear()+ self.controller._process_outbound({"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}})+ self.assertEqual(self.link.sent[-1]["data"]["key"], "cmd")++ def test_a_mac_peer_gets_every_key_as_itself(self):+ self.assertEqual(self.send("cmd", platform="macos"), "cmd")++ def test_the_positional_style_keeps_each_key_in_place(self):+ self.controller.cfg.key_map = {"alt": "alt", "alt_r": "alt", "ctrl": "ctrl", "ctrl_r": "ctrl", "cmd": "cmd", "cmd_r": "cmd"}+ self.assertEqual(self.send("cmd"), "cmd")++ def test_a_media_key_is_dropped_for_a_peer_that_does_not_act_on_it(self):+ self.assertIsNone(self.send("volume_up", caps=("clipboard",)))++ def test_a_media_key_goes_to_a_peer_that_does(self):+ self.assertEqual(self.send("volume_up"), "volume_up")+++class ComingHomeTests(Base):+ def setUp(self):+ super().setUp()+ self.up()+ self.controller.set_redirecting(True, edge="left", offset=0.5)+ self.link.posted.clear()++ def arrives(self, message):+ self.link.arrives(self.controller, message)++ def test_the_peer_sending_input_home_lands_the_pointer_where_it_left(self):+ self.arrives(protocol.switch_v6(1, protocol.read_id(self.own), "right", 0.25))+ self.assertFalse(self.controller.redirecting)+ self.assertEqual([kind for kind, _ in self.crossings], ["arrive"])+ self.assertEqual(self.crossings[0][1].mac_edge, "right")+ self.assertTrue(FakeQuartz.warp_calls)+ let_go = self.focus()+ self.assertEqual(let_go["target"], self.own)+ self.assertEqual(self.alerts, [])++ def test_a_send_home_without_a_position_still_returns_input_and_shows_the_arrival(self):+ self.arrives(protocol.switch_v6(1, protocol.read_id(self.own)))+ self.assertFalse(self.controller.redirecting)+ self.assertEqual([(kind, step.mac_edge) for kind, step in self.crossings], [("arrive", None)])++ def test_a_refusal_for_the_current_route_sends_input_home_with_the_reason(self):+ self.arrives(protocol.refuse_msg(1, "owned"))+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(self.alerts, ["Office PC is being driven from another machine"])++ def test_a_refusal_for_an_old_route_is_ignored(self):+ self.arrives(protocol.accept_msg(1))+ self.controller.owner.route = 5+ self.arrives(protocol.refuse_msg(1, "busy"))+ self.assertTrue(self.controller.redirecting)++ def test_losing_the_link_brings_input_home(self):+ self.link.down(self.controller)+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(self.alerts, ["Lost the link to Office PC"])+ self.assertEqual(FakeQuartz.associate_calls[-1], True)++ def test_no_answer_within_a_second_brings_input_home(self):+ self.clock.value += 1.2+ self.controller._owner_tick()+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(self.alerts, ["Office PC did not answer"])++ def test_an_accept_keeps_input_there(self):+ self.arrives(protocol.accept_msg(1))+ self.clock.value += 5+ self.controller._owner_tick()+ self.assertTrue(self.controller.redirecting)++ def test_a_stale_switch_is_ignored(self):+ self.arrives(protocol.accept_msg(1))+ self.controller.owner.route = 6+ self.arrives(protocol.switch_v6(5, OTHER_ID))+ self.assertTrue(self.controller.redirecting)+++class ClipboardTests(Base):+ def test_a_clipboard_from_the_machine_just_let_go_is_taken_once(self):+ self.up()+ self.controller.set_redirecting(True)+ self.controller.set_redirecting(False)+ self.link.arrives(self.controller, protocol.clipboard_msg("from the pc"), began=self.clock.value)+ self.assertEqual(self.clipboard.set_calls, [("from the pc", None)])+ self.link.arrives(self.controller, protocol.clipboard_msg("again"), began=self.clock.value)+ self.assertEqual(len(self.clipboard.set_calls), 1)++ def test_a_clipboard_from_a_machine_never_taken_is_dropped(self):+ self.up()+ self.link.arrives(self.controller, protocol.clipboard_msg("unasked"), began=self.clock.value)+ self.assertEqual(self.clipboard.set_calls, [])++ def test_a_clipboard_that_began_arriving_too_late_is_dropped(self):+ self.up()+ self.controller.set_redirecting(True)+ self.controller.set_redirecting(False)+ self.link.arrives(self.controller, protocol.clipboard_msg("late"), began=self.clock.value + 11)+ self.assertEqual(self.clipboard.set_calls, [])++ def test_the_clipboard_is_sent_again_only_after_it_changed_here(self):+ self.up()+ self.controller.set_redirecting(True)+ self.link.arrives(self.controller, protocol.accept_msg(1))+ self.controller.set_redirecting(False)+ self.link.posted.clear()+ self.controller.set_redirecting(True)+ self.assertNotIn(protocol.MSG_CLIPBOARD, self.link.types())+ self.link.arrives(self.controller, protocol.accept_msg(3))+ self.controller.set_redirecting(False)+ self.clipboard.copy("something new")+ self.link.posted.clear()+ self.controller.set_redirecting(True)+ self.assertIn(protocol.MSG_CLIPBOARD, self.link.types())++ def test_an_oversized_text_is_skipped_but_the_take_still_goes(self):+ self.clipboard.text = "x" * (protocol.CLIPBOARD_MAX_BYTES + 1)+ self.up()+ self.controller.set_redirecting(True)+ self.assertNotIn(protocol.MSG_CLIPBOARD, self.link.types())+ self.assertEqual(self.focus_count(), 1)++ def arrivals(self):+ """What the owner is handed when a clipboard arrives from the machine just let go."""+ taken = []+ self.controller.owner.clipboard_arrived = lambda peer, began, message: taken.append(message) or []+ return taken++ def test_a_clipboard_with_a_text_that_is_not_a_string_goes_nowhere(self):+ self.up()+ taken = self.arrivals()+ self.link.arrives(self.controller, {"type": protocol.MSG_CLIPBOARD, "data": {"text": 5}}, began=self.clock.value)+ self.assertEqual(taken, [])++ def test_the_clipboard_goes_before_input_the_same_move_hands_on(self):+ # WIRE.md section 5: on the next machine's accept it gets the clipboard, then the held+ # input, in order. The pasteboard is read under the owner's lock so nothing overtakes it.+ from core import owner as owner_module+ self.up()+ order = []+ post, send_input = self.link.post, self.link.send_input+ self.link.post = lambda message: order.append(message["type"]) or post(message)+ self.link.send_input = lambda message: order.append(message["type"]) or send_input(message)+ key = {"type": protocol.MSG_KEYDOWN, "data": {"key": "v"}}+ self.controller._step(lambda owner: [owner_module.SendClipboard(self.peer), owner_module.Send(self.peer, key)])+ self.assertEqual(order, [protocol.MSG_CLIPBOARD, protocol.MSG_KEYDOWN])++ def test_a_clipboard_is_handed_on_as_rebuilt_from_what_was_read(self):+ self.up()+ taken = self.arrivals()+ self.link.arrives(self.controller, {"type": protocol.MSG_CLIPBOARD, "data": {"text": "hi", "z": [{}, {}]}, "extra": 1}, began=self.clock.value)+ self.assertEqual(taken, [protocol.clipboard_msg("hi", None)])++ def focus_count(self):+ return len([m for m in self.link.posted if m["type"] == protocol.MSG_FOCUS])+++class AnnouncementTests(Base):+ def test_the_link_up_announces_the_side_the_settings_and_who_else_is_paired(self):+ entry = self.controller.book.peers()[0]+ with self.controller.book.lock:+ self.controller.book.data["peers"][0].update(side="left", side_set_at=7, id=self.peer)+ self.controller.book.data["peers"].append({**entry, "id": protocol.id_text(OTHER_ID), "token": "other", "send": False})+ self.controller.announce = lambda: [protocol.settings_msg({"on": False, "set_at": 3, "by": ""})]+ self.up()+ types = self.link.types()+ self.assertIn(protocol.MSG_ARRANGEMENT, types)+ self.assertIn(protocol.MSG_SETTINGS, types)+ paired = next(m for m in self.link.posted if m["type"] == protocol.MSG_PAIRED)+ self.assertEqual(paired["data"]["ids"], [protocol.id_text(OTHER_ID)])+ arrangement = next(m for m in self.link.posted if m["type"] == protocol.MSG_ARRANGEMENT)+ self.assertEqual((arrangement["data"]["edge"], arrangement["data"]["set_at"]), ("left", 7))++ def test_settings_are_not_announced_to_a_peer_that_does_not_keep_them(self):+ self.controller.announce = lambda: [protocol.settings_msg({"on": False, "set_at": 3, "by": ""})]+ self.up(caps=("clipboard",))+ self.assertNotIn(protocol.MSG_SETTINGS, self.link.types())++ def test_an_arrangement_from_the_peer_reaches_the_app_as_this_macs_edge(self):+ seen = []+ self.controller.on_arrangement = lambda *args: seen.append(args)+ with self.controller.book.lock:+ self.controller.book.data["peers"][0]["id"] = self.peer+ self.up()+ self.link.arrives(self.controller, protocol.arrangement_v6("right", int(time.time()) - 5, PEER_ID))+ self.assertEqual(seen, [("left", seen[0][1], self.peer)])++ def test_a_peers_settings_reach_the_app_with_who_sent_them(self):+ seen = []+ self.controller.on_settings = lambda data, peer: seen.append((data, peer))+ self.up()+ self.link.arrives(self.controller, protocol.settings_msg({"on": True, "set_at": 5}))+ self.assertEqual(seen, [({"on": True, "set_at": 5}, self.peer)])++ def test_settings_go_on_to_every_peer_but_the_one_they_came_from(self):+ self.up()+ self.controller.send_settings({"on": True, "set_at": 9}, source=self.peer)+ self.assertNotIn(protocol.MSG_SETTINGS, self.link.types())+ self.controller.send_settings({"on": True, "set_at": 9})+ self.assertIn(protocol.MSG_SETTINGS, self.link.types())++ def test_an_arrangement_made_here_goes_to_the_primary_peer(self):+ self.up()+ self.controller.send_arrangement("top", 12)+ sent = [m for m in self.link.posted if m["type"] == protocol.MSG_ARRANGEMENT][-1]["data"]+ self.assertEqual((sent["edge"], sent["set_at"], sent["by"]), ("top", 12, self.own))+++class DrivenTests(Base):+ def test_a_driven_mac_sends_its_owner_home_then_takes_once_it_has_let_go(self):+ self.up()+ homes = []++ def send_home():+ homes.append(True)+ threading.Timer(0.1, lambda: self.controller.set_receiving(False)).start()+ return True++ self.controller.send_peer_home = send_home+ self.controller.set_receiving(True)+ self.assertTrue(self.controller.set_redirecting(True))+ self.assertEqual(homes, [True])+ self.assertFalse(self.controller.redirecting)+ deadline = time.monotonic() + 2+ while not self.controller.redirecting and time.monotonic() < deadline:+ time.sleep(0.01)+ self.assertTrue(self.controller.redirecting)++ def test_a_driven_mac_whose_owner_cannot_be_reached_does_not_take(self):+ self.up()+ self.controller.send_peer_home = lambda: False+ self.controller.set_receiving(True)+ self.assertFalse(self.controller.set_redirecting(True))++ def test_a_take_that_won_the_race_sends_this_macs_input_home(self):+ self.up()+ self.controller.responder = type("Driven", (), {"driven": True})()+ self.assertFalse(self.controller.set_redirecting(True))+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(self.focus_count(), 2)++ def focus_count(self):+ return len([m for m in self.link.posted if m["type"] == protocol.MSG_FOCUS])+++class LinkSetTests(Base):+ def test_one_link_per_peer_with_send_on(self):+ self.assertEqual(len(self.controller.links), 1)+ with self.controller.book.lock:+ peers = self.controller.book.data["peers"]+ peers.append({**peers[0], "id": protocol.id_text(OTHER_ID), "token": "second", "send": False})+ self.controller._sync_links()+ self.assertEqual(len(self.controller.links), 1)++ def test_a_new_token_makes_a_new_link_and_ends_the_old(self):+ old = self.link+ self.controller.update_config(make_config("a-different-token"))+ self.assertTrue(old.stopped)+ self.assertIsNot(self.controller._primary_link, old)++ def test_removing_the_peer_ends_its_link_and_brings_input_home(self):+ self.up()+ self.controller.set_redirecting(True)+ with self.controller.book.lock:+ self.controller.book.data["peers"].clear()+ self.controller._sync_links()+ self.assertFalse(self.controller.redirecting)++ def test_the_connection_status_follows_the_primary_link(self):+ self.controller._link_state(self.link, False, "Office PC is unreachable from this machine.")+ self.assertEqual(self.controller.connection_status, "Office PC is unreachable from this machine.")++ def test_a_locked_peer_is_called_unlocking(self):+ self.up()+ self.link.peer_locked = True+ self.assertTrue(self.controller.windows_locked)+ self.assertEqual(self.controller.connection_status, "Unlocking 192.0.2.10…")++ def test_the_round_trip_is_the_upper_median_of_the_last_trips_on_the_machine_input_is_on(self):+ self.up()+ self.assertIsNone(self.controller.round_trip_ms)+ self.controller.set_redirecting(True)+ self.link.samples = [0.010, 0.030, 0.020, 0.040]+ self.assertEqual(self.controller.round_trip_ms, 30)++ def test_the_beacons_are_offered_to_every_link(self):+ beacons = [{"name": "Office PC", "address": "192.0.2.77"}]+ self.controller.discovery = type("Found", (), {"pcs": lambda self: beacons})()+ self.controller._follow_the_peers()+ self.assertEqual(self.link.followed, [beacons])++ def test_a_learnt_address_is_handed_to_the_app(self):+ learnt = []+ self.controller.on_host_learned = learnt.append+ with self.controller.book.lock:+ self.controller.book.data["peers"][0]["host"] = "192.0.2.99"+ self.up()+ self.assertEqual(learnt, ["192.0.2.99"])+ self.assertEqual(self.controller.cfg.host, "192.0.2.99")+++class PressedAtHomeTests(Base):+ """A key pressed while the input was home is released at home (WIRE.md section 4)."""++ def tap(self, kind, keycode=0x00, character="a"):+ event = {FakeQuartz.kCGKeyboardEventKeycode: keycode, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "unicode": character}+ returned = self.controller._event_tap_callback(None, kind, event, None)+ return event, returned++ def test_the_release_of_a_key_pressed_at_home_stays_at_home(self):+ self.up()+ event, returned = self.tap(FakeQuartz.kCGEventKeyDown)+ self.assertIs(returned, event)+ self.controller.set_redirecting(True)+ event, returned = self.tap(FakeQuartz.kCGEventKeyUp)+ self.assertIs(returned, event)+ self.assertTrue(self.controller.outbound.empty())++ def test_a_key_pressed_after_the_input_left_is_sent_and_released_there(self):+ self.up()+ self.controller.set_redirecting(True)+ _, down = self.tap(FakeQuartz.kCGEventKeyDown)+ _, up = self.tap(FakeQuartz.kCGEventKeyUp)+ self.assertIsNone(down)+ self.assertIsNone(up)+ self.assertEqual([m["type"] for m in list(self.controller.outbound.queue)], [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP])++ def test_a_key_pressed_and_released_at_home_is_not_remembered(self):+ self.up()+ self.tap(FakeQuartz.kCGEventKeyDown)+ self.tap(FakeQuartz.kCGEventKeyUp)+ self.controller.set_redirecting(True)+ _, down = self.tap(FakeQuartz.kCGEventKeyDown)+ _, up = self.tap(FakeQuartz.kCGEventKeyUp)+ self.assertIsNone(down)+ self.assertIsNone(up)+ self.assertEqual(self.controller.outbound.qsize(), 2)+++class GestureNamesTests(Base):+ def test_a_pinch_reaches_a_pc_as_control_and_scroll_not_as_the_windows_key(self):+ from gestures import MAGNIFY_TYPE+ from bridge_fakes import FakeGestureEvent+ self.up()+ self.controller.set_redirecting(True)+ self.controller.handle_overlay_gesture(MAGNIFY_TYPE, FakeGestureEvent(magnification=0.05))+ while not self.controller.outbound.empty():+ self.controller._process_outbound(self.controller.outbound.get_nowait())+ keys = [m["data"]["key"] for m in self.link.sent if m["type"] in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP)]+ self.assertEqual(keys, ["ctrl", "ctrl"])+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_mac_listener_port.py b/mac_app/tests/test_mac_listener_port.pynew file mode 100644index 0000000..454ce04--- /dev/null+++ b/mac_app/tests/test_mac_listener_port.py@@ -0,0 +1,60 @@+"""This Mac's listener and its beacon use its own port setting, never a machine's."""++import json+import logging+import os+import sys+import tempfile+import unittest+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 bridge+import settings_store+from bridge_fakes import PAIRED_TOKEN+from fake_link import FakeLink+from wake import WakingController+from windows_input import WindowsInput+++class OwnPortTests(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", port=9100, auth_token=PAIRED_TOKEN, pc_name="Studio")+ path.write_text(json.dumps(raw))+ self.store = settings_store.SettingsStore(path)+ self.cfg = self.store.load()+ book, identity = bridge.links_from_store(self.store, "1.5.0")+ self.controller = WakingController(self.cfg, logger=logging.getLogger("t"), book=book, identity=identity, link_factory=FakeLink)++ def test_the_port_is_the_settings_own_not_the_first_machines(self):+ # Migrated from 1.4.x, both are 9100; they part when the machines change.+ self.assertEqual(self.controller.own_port, 9100)+ settings = self.store.current()+ settings["port"] = 24820+ self.store.save_settings(settings)+ self.assertEqual(self.controller.cfg.port, 9100)+ self.assertEqual(self.controller.own_port, 24820)++ def test_the_listener_follows_the_own_port_and_stays_when_the_first_machine_changes(self):+ settings = self.store.current()+ settings["port"] = 24820+ self.store.save_settings(settings)+ wire = WindowsInput(self.controller)+ self.addCleanup(wire.server.stop)+ wire.server = mock.Mock(input_scale=None, listening=False)+ wire.sync(self.cfg)+ wire.server.start.assert_called_once_with(24820)++ def test_a_controller_built_from_a_config_alone_still_listens_where_it_dials(self):+ controller = WakingController(self.cfg, logger=logging.getLogger("t"), link_factory=FakeLink)+ self.assertEqual(controller.own_port, self.cfg.port)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_mac_loopback.py b/mac_app/tests/test_mac_loopback.pynew file mode 100644index 0000000..3c3c135--- /dev/null+++ b/mac_app/tests/test_mac_loopback.py@@ -0,0 +1,130 @@+"""The Mac's two halves with a real second end on loopback: input, keys and the clipboard going to a+version 6 PC, and a PC's input arriving on the Mac. test_mac_links.py has the controller against+fake links; core/tests/test_link.py has the link against the responder; this is the two together,+through the controller's event tap and the Mac's responder."""++import os+import sys+import unittest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from bridge_fakes import FakeQuartz+from core import protocol+from two_machines import PC_TEXT, Duo, wait_for++A_KEYCODE, COMMAND_KEYCODE = 0x00, 0x37+++def key_event(down, keycode, character=None):+ event = {FakeQuartz.kCGKeyboardEventKeycode: keycode}+ if character is not None:+ event["unicode"] = character+ return (FakeQuartz.kCGEventKeyDown if down else FakeQuartz.kCGEventKeyUp), event+++def command_event(down):+ return FakeQuartz.kCGEventFlagsChanged, {+ FakeQuartz.kCGKeyboardEventKeycode: COMMAND_KEYCODE,+ "flags": FakeQuartz.kCGEventFlagMaskCommand if down else 0,+ }+++class MacDrivesPcTests(unittest.TestCase):+ def setUp(self):+ self.duo = Duo(crossing={"edge": "right", "resistance_px": 40}).listen()+ self.addCleanup(self.duo.close)+ self.duo.link_mac_to_pc()+ self.pc = self.duo.pc_responder++ def tap(self, event):+ event_type, fields = event+ return self.duo.mac._event_tap_callback(None, event_type, fields, None)++ def cross(self):+ self.assertTrue(self.duo.mac_push(1727, 558, 30), "the push never crossed")+ self.assertTrue(wait_for(lambda: self.pc.responder.owner == self.duo.mac_id))++ def test_a_key_goes_to_the_pc_swallowed_here_with_the_command_key_as_control(self):+ self.cross()+ self.assertIsNone(self.tap(command_event(True)), "the Mac let the command key through")+ self.assertIsNone(self.tap(key_event(True, A_KEYCODE, "a")))+ self.assertIsNone(self.tap(key_event(False, A_KEYCODE, "a")))+ self.assertIsNone(self.tap(command_event(False)))+ keys = [("key", "ctrl", True), ("key", "a", True), ("key", "a", False), ("key", "ctrl", False)]+ self.assertTrue(wait_for(lambda: [call for call in self.pc.injected() if call[0] == "key"] == keys), self.pc.injected())++ def test_a_key_held_when_the_input_comes_home_is_released_on_the_pc_first(self):+ self.cross()+ self.tap(key_event(True, A_KEYCODE, "a"))+ self.assertTrue(wait_for(lambda: ("key", "a", True) in self.pc.injected()))+ self.pc.desktop.cursor = (0, 540)+ self.assertTrue(self.duo.mac_lean(-30))+ self.assertTrue(wait_for(lambda: ("key", "a", False) in self.pc.injected()), "the key stayed down on the PC")+ self.assertTrue(wait_for(lambda: self.pc.responder.owner is None))++ def test_the_macs_clipboard_goes_with_the_take_and_the_pcs_comes_back_once_after_the_let_go(self):+ self.cross()+ self.assertTrue(wait_for(lambda: ("on the Mac", None) in self.pc.clipboard.set_calls), "the Mac's clipboard never reached the PC")+ self.pc.clipboard.copy("copied on the PC")+ self.assertTrue(self.duo.mac.set_redirecting(False))+ self.assertTrue(wait_for(lambda: self.duo.clipboard.set_calls == [("copied on the PC", None)]), self.duo.clipboard.set_calls)+ self.assertEqual(self.duo.mac.owner.on, None)++ def test_losing_the_pcs_link_brings_the_pointer_home_and_says_so(self):+ self.cross()+ self.pc.stop()+ self.assertTrue(wait_for(lambda: not self.duo.mac.redirecting), "input stayed on a PC that is gone")+ self.assertTrue(wait_for(lambda: any("Lost the link" in text for text in self.duo.alerts)), self.duo.alerts)+ self.assertEqual(FakeQuartz.associate_calls[-1], True)++ def test_a_pc_that_stops_allowing_this_mac_to_drive_it_leaves_the_keyboard_here(self):+ self.pc.settings.peer(self.duo.mac_text)["allow_drive"] = False+ self.pc.responder.peers_changed()+ self.assertTrue(wait_for(lambda: self.duo.mac._accepts.get(PC_TEXT) is False), "the Mac was never told")+ self.assertFalse(self.duo.mac.set_redirecting(True))+ self.assertFalse(self.duo.mac.redirecting)+ event_type, fields = key_event(True, A_KEYCODE, "a")+ self.assertIs(self.duo.mac._event_tap_callback(None, event_type, fields, None), fields)+++class PcDrivesMacTests(unittest.TestCase):+ def setUp(self):+ self.duo = Duo(crossing={"edge": "right", "resistance_px": 40}).listen()+ self.addCleanup(self.duo.close)+ self.duo.link_pc_to_mac()+ self.duo.pc_drives("right", 0.5)++ def test_the_pcs_keys_and_pointer_are_injected_on_the_mac_in_order(self):+ pc = self.duo.pc+ pc.acked(pc.key(protocol.MSG_KEYDOWN, "a"))+ pc.acked(pc.move(-4, 5))+ pc.acked(pc.key(protocol.MSG_KEYUP, "a"))+ calls = [call for call in self.duo.mac_injector.seen() if call[0] in ("key", "move")]+ self.assertEqual(calls, [("key", "a", True), ("move", -4, 5), ("key", "a", False)])++ def test_the_macs_own_events_pass_through_untouched_while_the_pc_drives(self):+ event = {"location": (400.0, 300.0), FakeQuartz.kCGMouseEventDeltaX: 5, FakeQuartz.kCGMouseEventDeltaY: 0}+ self.assertIs(self.duo.mac._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved, event, None), event)+ key_down = {FakeQuartz.kCGKeyboardEventKeycode: A_KEYCODE, "unicode": "a"}+ self.assertIs(self.duo.mac._event_tap_callback(None, FakeQuartz.kCGEventKeyDown, key_down, None), key_down)+ self.assertFalse(self.duo.mac.redirecting)++ def test_a_key_the_pc_holds_when_it_lets_go_is_released_on_the_mac(self):+ pc = self.duo.pc+ pc.acked(pc.key(protocol.MSG_KEYDOWN, "a"))+ pc.let_go()+ self.assertTrue(wait_for(lambda: not self.duo.mac.receiving))+ self.assertIn(("key", "a", False), self.duo.mac_injector.seen())++ def test_losing_the_pcs_link_hands_the_mac_back_and_releases_what_it_held(self):+ pc = self.duo.pc+ pc.acked(pc.key(protocol.MSG_KEYDOWN, "a"))+ pc.sock.shutdown(2)+ self.assertTrue(wait_for(lambda: not self.duo.mac.receiving), "the Mac stayed driven by a PC that is gone")+ self.assertIn(("key", "a", False), self.duo.mac_injector.seen())+ self.assertIsNone(self.duo.mac_responder.owner)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_mac_pairing.py b/mac_app/tests/test_mac_pairing.pynew file mode 100644index 0000000..c8b5a60--- /dev/null+++ b/mac_app/tests/test_mac_pairing.py@@ -0,0 +1,87 @@+"""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_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)),+ )+ self.service.start()+ self.addCleanup(self.service.stop)+ self.pc = Machine(self, "Desk PC", PC_ID, "windows")++ 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"])+ self.assertEqual(self.store.current()["zones"], [])+ 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)+ 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 --git a/mac_app/tests/test_mac_review.py b/mac_app/tests/test_mac_review.pynew file mode 100644index 0000000..b3790db--- /dev/null+++ b/mac_app/tests/test_mac_review.py@@ -0,0 +1,236 @@+"""What the cold review of the Mac controller found, each shown failing before it was fixed."""++import os+import sys+import tempfile+import threading+import time+import unittest+from pathlib import Path++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import bridge+from bridge_fakes import PAIRED_TOKEN, FakeClipboard, FakeClock, FakeQuartz, make_config, quiet_logger+from core import protocol+from fake_link import OTHER_ID, PEER_ID, FakeLink, bring_up+from settings_store import SettingsStore+++class Base(unittest.TestCase):+ def setUp(self):+ FakeQuartz.reset_cursor_spies()+ self.clock = FakeClock()+ self.clipboard = FakeClipboard("hello")+ self.made = []++ def factory(*args, **kwargs):+ link = FakeLink(*args, **kwargs)+ self.made.append(link)+ return link++ self.controller = bridge.KVMController(+ make_config(PAIRED_TOKEN), logger=quiet_logger(), quartz=FakeQuartz, clock=self.clock,+ clipboard=self.clipboard, link_factory=factory, desktop_bounds=lambda: (0, 0, 1920, 1080),+ )+ self.alerts = []+ self.controller.on_user_alert = lambda title, message: self.alerts.append(message)+ self.link = self.controller._primary_link+ self.own = protocol.id_text(self.controller.identity()["id"])++ def tap(self, kind, keycode=0x00, character="a"):+ event = {FakeQuartz.kCGKeyboardEventKeycode: keycode, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "unicode": character}+ return self.controller._event_tap_callback(None, kind, event, None)++ def drain(self):+ while not self.controller.outbound.empty():+ self.controller._process_outbound(self.controller.outbound.get_nowait())++ def take(self):+ self.controller.set_redirecting(True)+ self.link.arrives(self.controller, protocol.accept_msg(self.controller.owner.route))+++class StartupTests(unittest.TestCase):+ def test_unreadable_settings_start_from_the_defaults_instead_of_crashing(self):+ folder = Path(tempfile.mkdtemp())+ (folder / "settings.json").write_text("{ not json")+ store = SettingsStore(folder / "settings.json")+ book, identity = bridge.links_from_store(store, "1.5.0")+ self.assertIsNone(book)+ self.assertIsNone(identity)++ def test_readable_settings_give_the_book_and_the_identity(self):+ store = SettingsStore(Path(tempfile.mkdtemp()) / "settings.json")+ book, identity = bridge.links_from_store(store, "1.5.0-beta.2")+ self.assertEqual(identity()["app"], "1.5.0-beta.2")+ self.assertEqual(identity()["platform"], "macos")+ self.assertEqual(book.peers(), [])+++class ReleasesAtHomeTests(Base):+ def test_a_key_held_when_input_comes_home_does_not_swallow_its_next_press(self):+ bring_up(self.controller)+ self.take()+ self.tap(FakeQuartz.kCGEventKeyDown)+ self.drain()+ self.link.arrives(self.controller, protocol.switch_v6(1, protocol.read_id(self.own)))+ self.assertFalse(self.controller.redirecting)+ self.tap(FakeQuartz.kCGEventKeyUp)+ self.drain()+ self.link.sent.clear()+ self.take()+ self.tap(FakeQuartz.kCGEventKeyDown)+ self.drain()+ self.assertEqual([m["type"] for m in self.link.sent], [protocol.MSG_KEYDOWN])++ def test_a_stale_home_press_does_not_swallow_the_release_of_a_key_pressed_while_away(self):+ bring_up(self.controller)+ self.tap(FakeQuartz.kCGEventKeyDown)+ self.controller.receiving = True+ self.tap(FakeQuartz.kCGEventKeyUp)+ self.controller.receiving = False+ self.take()+ self.tap(FakeQuartz.kCGEventKeyDown)+ self.tap(FakeQuartz.kCGEventKeyUp)+ self.drain()+ self.assertEqual([m["type"] for m in self.link.sent], [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP])++ def test_a_press_that_reaches_the_owner_after_it_came_home_is_not_remembered(self):+ bring_up(self.controller)+ self.take()+ self.tap(FakeQuartz.kCGEventKeyDown)+ self.link.arrives(self.controller, protocol.switch_v6(1, protocol.read_id(self.own)))+ self.drain()+ self.assertEqual(self.controller.owner._here, set())+++class LinkSetRaceTests(Base):+ def test_concurrent_syncs_make_one_link_for_one_peer(self):+ self.controller.started = True+ self.controller.links.clear()+ self.made.clear()+ threads = [threading.Thread(target=self.controller._sync_links) for _ in range(12)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()+ self.assertEqual(len(self.made), 1)+ self.assertEqual(len(self.controller.links), 1)+++class ArrangementOriginTests(Base):+ def test_an_arrangement_from_a_peer_that_is_not_the_first_is_not_applied_to_the_first(self):+ seen = []+ self.controller.on_arrangement = lambda *args: seen.append(args)+ with self.controller.book.lock:+ peers = self.controller.book.data["peers"]+ peers[0]["id"] = protocol.id_text(PEER_ID)+ peers.append({**peers[0], "id": protocol.id_text(OTHER_ID), "token": "second", "send": False})+ bring_up(self.controller)+ message = protocol.arrangement_v6("right", int(time.time()) - 5, OTHER_ID)+ self.controller._handle_arrangement(message, protocol.id_text(OTHER_ID))+ self.assertEqual(seen, [])+ self.controller._handle_arrangement(message, protocol.id_text(PEER_ID))+ self.assertEqual(len(seen), 1)+++class LetGoWaitTests(Base):+ def test_a_take_waiting_for_the_owner_to_let_go_is_cancelled_by_coming_home(self):+ bring_up(self.controller)+ self.controller.send_peer_home = lambda: True+ self.controller.set_receiving(True)+ self.assertTrue(self.controller.set_redirecting(True))+ self.controller.set_redirecting(False)+ self.controller.set_receiving(False)+ time.sleep(0.4)+ self.assertFalse(self.controller.redirecting)+++class FailureTests(Base):+ def test_coming_home_cleans_up_the_pointer_even_when_a_send_raises(self):+ bring_up(self.controller)+ self.take()++ def broken(message):+ raise RuntimeError("synthetic")++ self.link.post = broken+ self.link.send_input = broken+ self.controller.set_redirecting(False)+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(FakeQuartz.associate_calls[-1], True)++ def test_an_exception_in_the_owner_tick_does_not_end_the_outbound_worker(self):+ original = self.controller._owner_tick+ calls = []++ def broken():+ calls.append(1)+ raise RuntimeError("synthetic")++ self.controller._owner_tick = broken+ thread = threading.Thread(target=self.controller._outbound_worker, daemon=True)+ thread.start()+ time.sleep(0.3)+ self.assertTrue(thread.is_alive())+ self.assertGreater(len(calls), 1)+ self.controller.stop_event.set()+ thread.join(2)++ def test_the_clipboard_sentinel_is_read_without_the_owner_lock(self):+ bring_up(self.controller)+ held = []+ original = self.controller._send_clipboard++ def spy(peer):+ held.append(self.controller._owner_lock._is_owned())+ original(peer)++ self.controller._send_clipboard = spy+ self.controller._process_outbound({"type": bridge._LOCAL_CLIPBOARD_SENTINEL_TYPE, "data": {}, "peer": self.link.peer_id})+ self.assertEqual(held, [False])+++class CapabilityAndPairedTests(Base):+ def test_settings_from_a_peer_that_does_not_keep_them_are_ignored(self):+ seen = []+ self.controller.on_settings = lambda data, peer: seen.append(data)+ bring_up(self.controller, caps=("clipboard",))+ self.link.arrives(self.controller, protocol.settings_msg({"on": True, "set_at": 1}))+ self.assertEqual(seen, [])++ def test_a_changed_list_of_peers_is_announced_again(self):+ bring_up(self.controller)+ self.link.posted.clear()+ with self.controller.book.lock:+ peers = self.controller.book.data["peers"]+ peers.append({**peers[0], "id": protocol.id_text(OTHER_ID), "token": "second", "send": False})+ self.controller._announce_changes()+ self.assertIn(protocol.MSG_PAIRED, self.link.types())+ self.link.posted.clear()+ self.controller._announce_changes()+ self.assertNotIn(protocol.MSG_PAIRED, self.link.types())++ def test_a_peers_paired_list_is_stored_with_its_entry(self):+ with self.controller.book.lock:+ self.controller.book.data["peers"][0]["id"] = protocol.id_text(PEER_ID)+ bring_up(self.controller)+ self.link.arrives(self.controller, protocol.paired_msg([OTHER_ID]))+ self.assertEqual(self.controller.book.peers()[0]["paired_with"], [protocol.id_text(OTHER_ID)])+++class WrongLinkTests(Base):+ def test_a_failure_drops_the_link_input_was_on_not_the_first(self):+ second = FakeLink("second", self.controller.book, self.controller.identity)+ self.controller.links["second"] = second+ second.up(self.controller, ident=OTHER_ID, name="Second")+ bring_up(self.controller)+ self.controller.owner.on = protocol.id_text(OTHER_ID)+ self.controller._connection_failed("synthetic")+ self.assertEqual(second.dropped, ["synthetic"])+ self.assertEqual(self.link.dropped, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_mac_wire.py b/mac_app/tests/test_mac_wire.pynew file mode 100644index 0000000..d58b5a2--- /dev/null+++ b/mac_app/tests/test_mac_wire.py@@ -0,0 +1,227 @@+"""The Mac's real controller, with its real links, against a real LinkResponder on loopback+(core/tests/responder_harness.Machine, standing in for a PC): the whole path from a captured+event to the other machine's injector, and back. Only the platform edges are faked."""++import os+import socket+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from bridge import KVMController+from core import protocol+from core.tests import responder_harness as harness+from bridge_fakes import PAIRED_TOKEN, FakeClipboard, FakeQuartz, quiet_logger+from settings_store import SettingsStore, config_to_raw+from windows_input import WindowsInput++wait_for = harness.wait_for+PEER = harness.B+HERE = harness.HERE+++def _accepting(port):+ try:+ with socket.create_connection(("127.0.0.1", port), timeout=0.2):+ return True+ except OSError:+ return False+++class Wire(unittest.TestCase):+ """A Mac (the controller) with one peer entry for the machine `Machine` stands for."""++ def setUp(self):+ FakeQuartz.reset_cursor_spies()+ self.machine = harness.Machine([harness.entry(PEER, "Mac", token=PAIRED_TOKEN, platform="macos")])+ self.machine.start()+ self.addCleanup(self.machine.stop)+ folder = Path(tempfile.mkdtemp())+ self.store = SettingsStore(folder / "settings.json")+ cfg = self.store.load()+ raw = {**config_to_raw(cfg), "host": "127.0.0.1", "port": self.machine.port, "auth_token": PAIRED_TOKEN, "pc_name": "Far PC"}+ cfg = self.store.save(raw)+ self.settings_machine_id = self.store.current()["machine_id"]+ # The far machine knows this Mac by the id the Mac made for itself.+ self.machine.settings.peer(PAIRED_TOKEN)["id"] = self.settings_machine_id+ self.clipboard = FakeClipboard("copied here")+ self.alerts = []+ self.controller = KVMController(+ cfg, logger=quiet_logger(), quartz=FakeQuartz, clipboard=self.clipboard,+ book=self.store.book(), identity=self.identity, desktop_bounds=lambda: (0, 0, 1920, 1080),+ )+ self.controller.on_user_alert = lambda title, message: self.alerts.append(message)+ self.controller.start()+ self.addCleanup(self.controller.stop)++ def identity(self):+ return {"id": protocol.read_id(self.store.current()["machine_id"]), "name": "This Mac", "platform": "macos",+ "app": "1.5.0", "caps": ["clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings"],+ "port": 24820}++ def connected(self):+ return wait_for(lambda: self.controller.connected and self.controller._peers_up, 5.0)++ def key_event(self, kind, keycode, character=""):+ event = {FakeQuartz.kCGKeyboardEventKeycode: keycode, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "unicode": character}+ return self.controller._event_tap_callback(None, kind, event, None)++ def flags_event(self, keycode, flags):+ return self.controller._event_tap_callback(None, FakeQuartz.kCGEventFlagsChanged, {FakeQuartz.kCGKeyboardEventKeycode: keycode, "flags": flags}, None)+++class TakingTheFarMachineTests(Wire):+ def test_a_take_makes_this_mac_the_owner_and_its_input_is_injected_there(self):+ self.assertTrue(self.connected())+ self.assertTrue(self.controller.set_redirecting(True, edge="left", offset=0.5))+ self.assertTrue(wait_for(lambda: self.machine.responder.owner == protocol.read_id(self.settings_machine_id)), self.machine.owners)+ self.assertTrue(wait_for(lambda: ("move", 0, 0) not in self.machine.injected() and self.machine.arrivals))+ self.key_event(FakeQuartz.kCGEventKeyDown, 0x00, "a")+ self.assertTrue(wait_for(lambda: ("key", "a", True) in self.machine.injected()), self.machine.injected())+ self.assertEqual(self.machine.clipboard.text, "copied here")++ def test_command_arrives_as_control_on_a_pc_and_stays_command_on_a_mac(self):+ self.assertTrue(self.connected())+ self.controller.set_redirecting(True)+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is not None))+ command = FakeQuartz.kCGEventFlagMaskCommand+ self.flags_event(0x37, command)+ self.assertTrue(wait_for(lambda: ("key", "ctrl", True) in self.machine.injected()), self.machine.injected())++ def test_going_home_releases_the_keys_then_the_far_machine_is_let_go(self):+ self.assertTrue(self.connected())+ self.controller.set_redirecting(True)+ self.key_event(FakeQuartz.kCGEventKeyDown, 0x00, "a")+ self.assertTrue(wait_for(lambda: ("key", "a", True) in self.machine.injected()))+ self.controller.set_redirecting(False)+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))+ injected = self.machine.injected()+ self.assertLess(injected.index(("key", "a", True)), injected.index(("key", "a", False)))+ self.assertFalse(self.controller.redirecting)++ def test_a_far_machine_that_is_driving_another_refuses_and_the_input_comes_home(self):+ self.machine.away = True+ self.assertTrue(self.connected())+ self.controller.set_redirecting(True)+ self.assertTrue(wait_for(lambda: not self.controller.redirecting), self.alerts)+ self.assertIn("is driving another machine", self.alerts[-1])++ def test_the_far_machine_sending_input_home_brings_it_back_to_the_edge_it_left(self):+ self.assertTrue(self.connected())+ self.controller.set_redirecting(True, edge="left", offset=0.5)+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is not None))+ self.assertTrue(self.machine.responder.send_home())+ self.assertTrue(wait_for(lambda: not self.controller.redirecting), "the Mac did not come home")+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is None))++ def test_the_far_machine_going_away_brings_input_home_with_a_reason(self):+ self.assertTrue(self.connected())+ self.controller.set_redirecting(True)+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is not None))+ self.machine.responder.stop()+ self.assertTrue(wait_for(lambda: not self.controller.redirecting, 5.0), self.alerts)+ self.assertTrue(any("Lost the link" in text or "closed" in text for text in self.alerts), self.alerts)++ def test_a_pairing_that_does_not_let_this_mac_drive_is_not_taken(self):+ self.machine.settings.peer(PAIRED_TOKEN)["allow_drive"] = False+ self.assertTrue(self.connected())+ self.controller.set_redirecting(True)+ self.assertFalse(self.controller.redirecting)+ self.assertIn("does not accept input from this Mac", self.alerts[-1])++ def test_the_far_machines_clipboard_follows_the_input_home(self):+ self.assertTrue(self.connected())+ self.controller.set_redirecting(True)+ self.assertTrue(wait_for(lambda: self.machine.responder.owner is not None))+ self.machine.clipboard.copy("copied there")+ self.controller.set_redirecting(False)+ self.assertTrue(wait_for(lambda: ("copied there", None) in self.clipboard.set_calls), self.clipboard.set_calls)+++class DrivenMacTests(unittest.TestCase):+ """This Mac as the driven machine: its real WindowsInput (a LinkResponder) with a scripted+ initiator, and the injector, desktop and clipboard faked at the platform edge."""++ def setUp(self):+ FakeQuartz.reset_cursor_spies()+ folder = Path(tempfile.mkdtemp())+ self.store = SettingsStore(folder / "settings.json")+ cfg = self.store.load()+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ port = probe.getsockname()[1]+ cfg = self.store.save({**config_to_raw(cfg), "host": "127.0.0.1", "port": port, "auth_token": PAIRED_TOKEN, "pc_name": "Initiator"})+ settings = self.store.current()+ settings["peers"][0]["id"] = protocol.id_text(PEER)+ settings["peers"][0]["send"] = False+ self.store.save_settings(settings)+ self.controller = KVMController(+ cfg, logger=quiet_logger(), quartz=FakeQuartz, clipboard=FakeClipboard(),+ book=self.store.book(), identity=lambda: {+ "id": protocol.read_id(self.store.current()["machine_id"]), "name": "This Mac", "platform": "macos",+ "app": "1.5.0", "caps": ["clipboard", "text", "settings"], "port": port},+ desktop_bounds=lambda: (0, 0, 1920, 1080),+ )+ self.input = WindowsInput(self.controller)+ self.injector = harness.FakeInjector()+ self.input.server._injector = self.injector+ self.input.server._desktop = harness.FakeDesktop()+ self.input.server._clipboard = harness.FakeClipboard()+ self.input.sync(cfg)+ self.addCleanup(self.input.stop)+ self.addCleanup(self.controller.stop)+ self.assertTrue(harness.wait_for(lambda: self.input.server.listening and _accepting(port)), "the Mac did not listen")+ self.machine = type("Far", (), {"port": port})()+ self.initiator = harness.Initiator(self.machine, peer=PEER, key=PAIRED_TOKEN)+ self.addCleanup(self.initiator.close)+ self.mac_id = protocol.read_id(self.store.current()["machine_id"])++ def handshake(self):+ return self.initiator.handshake(self.initiator.hello(platform="windows"))++ def test_a_peer_takes_the_mac_and_its_input_is_injected_and_the_controller_knows(self):+ welcome = self.handshake()+ self.assertEqual(welcome["id"], self.mac_id)+ self.initiator.send(protocol.focus_v6(1, self.mac_id, resistance_px=120, reach=[]))+ self.assertEqual(self.initiator.answer(1)[0], protocol.MSG_ACCEPT)+ self.assertTrue(harness.wait_for(lambda: self.controller.receiving))+ self.initiator.key("keydown", "a")+ self.assertTrue(harness.wait_for(lambda: ("key", "a", True) in self.injector.seen()), self.injector.seen())++ def test_this_mac_asked_to_drive_sends_its_owner_home_and_goes_when_it_has_let_go(self):+ self.handshake()+ self.initiator.send(protocol.focus_v6(1, self.mac_id, resistance_px=120, reach=[]))+ self.assertEqual(self.initiator.answer(1)[0], protocol.MSG_ACCEPT)+ self.assertTrue(harness.wait_for(lambda: self.controller.receiving))+ self.assertTrue(self.controller.send_peer_home())+ switch = self.initiator.expect(protocol.MSG_SWITCH)+ self.assertEqual(switch["next"], protocol.id_text(PEER))+ self.assertEqual(switch["route"], 1)+ self.initiator.let_go()+ self.assertTrue(harness.wait_for(lambda: not self.controller.receiving))++ def test_an_owner_that_ignores_the_send_home_is_ended_by_force_after_a_second(self):+ self.handshake()+ self.initiator.send(protocol.focus_v6(1, self.mac_id, resistance_px=120, reach=[]))+ self.assertEqual(self.initiator.answer(1)[0], protocol.MSG_ACCEPT)+ self.assertTrue(harness.wait_for(lambda: self.controller.receiving))+ self.controller.send_peer_home()+ refused = self.initiator.expect(protocol.MSG_REFUSE, timeout=3.0)+ self.assertEqual(refused["why"], "sent_home")+ self.assertTrue(harness.wait_for(lambda: not self.controller.receiving))++ def test_a_take_is_refused_busy_while_this_macs_own_input_is_away(self):+ self.handshake()+ self.controller.owner.on = "somewhere"+ self.initiator.send(protocol.focus_v6(1, self.mac_id, resistance_px=120, reach=[]))+ answer = self.initiator.answer(1)+ self.assertEqual(answer[0], protocol.MSG_REFUSE)+ self.assertEqual(answer[1]["why"], "busy")+ self.assertFalse(self.controller.receiving)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_machines.py b/mac_app/tests/test_machines.pynew file mode 100644index 0000000..88911be--- /dev/null+++ b/mac_app/tests/test_machines.py@@ -0,0 +1,117 @@+"""The Overview's list of machines: what each row says, decided without AppKit."""++import base64+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++import machines++A = "AAAAAAAAAAAAAAAAAAAAAA"+TOKEN = base64.urlsafe_b64encode(bytes(range(32))).decode().rstrip("=")+++def entry(**extra):+ return {"id": A, "name": "STUDIO-PC", "platform": "windows", "token": TOKEN, "host": "10.1.1.2", "port": 24820,+ "send": True, "allow_drive": True, "linked": True, **extra}+++def row(**kwargs):+ values = dict(entry=entry(), label="STUDIO-PC", live=False, kind="connected", status="", here=False, driving=False,+ inbound=False, has_link=True)+ values.update(kwargs)+ return machines.row(**values)+++class StateTests(unittest.TestCase):+ def test_a_machine_driving_this_mac_beats_the_rest(self):+ state = row(driving=True, live=True, here=True).state+ self.assertEqual((state.key, state.tone, state.word), ("driving", "signal", "Driving this Mac"))++ def test_input_here_beats_a_plain_link(self):+ state = row(live=True, here=True).state+ self.assertEqual((state.key, state.tone), ("here", "signal"))++ def test_a_live_link_says_linked(self):+ self.assertEqual(row(live=True).state.key, "linked")++ def test_the_details_are_the_ones_windows_uses(self):+ self.assertEqual(row(driving=True).state.detail,+ "STUDIO-PC's keyboard and pointer are on this Mac. Push the pointer back through the edge it arrived by to send them home.")+ self.assertEqual(row(here=True).state.detail,+ "This Mac's keyboard and pointer are on STUDIO-PC. Do the same again to bring them home.")+ self.assertEqual(row(live=True).state.detail, "Connected to STUDIO-PC.")+ self.assertEqual(row(kind="none").state.detail, "Looking for STUDIO-PC. It connects on its own once Beamer is open there.")+ self.assertEqual(row(has_link=False, entry=entry(send=False)).state.detail, "Waiting for STUDIO-PC to connect.")++ def test_a_typed_1_4_token_is_asked_to_be_paired_again(self):+ state = row(entry=entry(token="typed-in-1.4", id="", from_1_4=True), kind="failed").state+ self.assertEqual((state.key, state.tone, state.word), ("pair_again", "amber", "Pair again"))+ self.assertEqual(state.detail, "STUDIO-PC was paired in 1.4.x with a typed token, which 1.5.0 does not use. Remove it and pair it again.")++ def test_a_machine_linked_in_but_not_dialled_is_linked_too(self):+ state = row(has_link=False, inbound=True, entry=entry(send=False)).state+ self.assertEqual(state.key, "linked")++ def test_a_machine_this_mac_does_not_drive_and_nothing_is_linked_waits_for_it(self):+ state = row(has_link=False, entry=entry(send=False)).state+ self.assertEqual((state.key, state.tone), ("waiting", "amber"))+ self.assertIn("STUDIO-PC", state.detail)++ def test_faults_say_what_the_link_said(self):+ for kind, key in (("unauthenticated", "token"), ("wrong_id", "token"), ("different", "token"),+ ("unreadable", "token"), ("older", "version"), ("newer", "version"), ("not_beamer", "version"),+ ("unreachable", "unreachable"), ("timeout", "unreachable"), ("refused", "not_listening"),+ ("blocked", "blocked"), ("stopped", "dropped")):+ state = row(kind=kind, status=f"said {kind}").state+ self.assertEqual((state.key, state.tone), (key, "fault"), kind)+ self.assertEqual(state.detail, f"said {kind}" if key != "dropped" else "said stopped. Beamer keeps trying to reconnect.", kind)++ def test_a_v5_machine_that_closed_on_a_first_link_is_a_version_fault_in_the_links_words(self):+ said = "Update Beamer on STUDIO-PC to 1.5.0; if it is up to date, pair the two again"+ state = row(entry=entry(linked=False), kind="closed", status=said).state+ self.assertEqual((state.key, state.tone, state.detail), ("version", "fault", said))++ def test_a_machine_that_closed_after_linking_once_is_only_dropped(self):+ state = row(kind="closed", status="STUDIO-PC closed the connection: it may have removed this machine").state+ self.assertEqual((state.key, state.tone), ("dropped", "fault"))+ self.assertTrue(state.detail.endswith(". Beamer keeps trying to reconnect."))++ def test_a_link_that_failed_in_some_way_is_dropped_and_one_with_nothing_to_say_is_waiting(self):+ self.assertEqual(row(kind="failed", status="The link to STUDIO-PC failed: broken pipe").state.key, "dropped")+ self.assertEqual(row(kind="failed", status="").state.key, "waiting")++ def test_a_link_still_looking_is_waiting_not_a_fault(self):+ for kind in ("none", "off", "connected", "removed"):+ state = row(kind=kind, status="Connecting to 10.1.1.2:24820").state+ self.assertEqual((state.key, state.tone), ("waiting", "amber"), kind)+ self.assertIn("STUDIO-PC", state.detail)+++class RowTests(unittest.TestCase):+ def test_the_row_names_the_machine_and_what_it_is(self):+ shown = row(label="STUDIO-PC (AAAA)")+ self.assertEqual((shown.label, shown.platform, shown.token), ("STUDIO-PC (AAAA)", "Windows", TOKEN))++ def test_the_address_is_the_saved_one_with_its_port(self):+ self.assertEqual(row().address, "10.1.1.2 · port 24820")++ def test_a_machine_with_no_address_says_so(self):+ self.assertEqual(row(entry=entry(host="", port=0)).address, "No address")++ def test_each_direction_is_the_entrys_own_switch(self):+ shown = row(entry=entry(send=False, allow_drive=True))+ self.assertEqual((shown.drives, shown.driven), (False, True))++ def test_platforms_have_names_and_an_unknown_one_is_shown_as_it_came(self):+ self.assertEqual(machines.platform_name("macos"), "Mac")+ self.assertEqual(machines.platform_name("linux"), "Linux")+ self.assertEqual(machines.platform_name("ios"), "iPhone")+ self.assertEqual(machines.platform_name("plan9"), "Other")+ self.assertEqual(machines.platform_name(""), "Other")+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_machines_panel.py b/mac_app/tests/test_machines_panel.pynew file mode 100644index 0000000..fee2a57--- /dev/null+++ b/mac_app/tests/test_machines_panel.py@@ -0,0 +1,624 @@+"""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()]+++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):+ 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.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]+ switches = [view for view in self.descend(row) if view.accessibilityRole() == AppKit.NSAccessibilityCheckBoxRole]+ self.assertEqual(len(switches), 2)+ switches[0].callback()+ switches[1].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.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.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.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.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_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_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 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 --git a/mac_app/tests/test_pages.py b/mac_app/tests/test_pages.pyindex e496382..599c25d 100644--- a/mac_app/tests/test_pages.py+++ b/mac_app/tests/test_pages.py@@ -177,8 +177,8 @@ class CrossingPageRulesTests(unittest.TestCase):def 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"))diff --git a/mac_app/tests/test_pairing_selection.py b/mac_app/tests/test_pairing_selection.pydeleted file mode 100644index a5d719a..0000000--- a/mac_app/tests/test_pairing_selection.py+++ /dev/null@@ -1,134 +0,0 @@-"""Pairing selection follows current discovery without opening a window or a socket."""--import unittest-from types import MethodType, SimpleNamespace-from unittest import mock--import kvm_bridge_app---class PairingSelectionTests(unittest.TestCase):- def setUp(self):- self.window = SimpleNamespace(- discovery=mock.Mock(error=None, pcs=mock.Mock(return_value=[])),- chosen_pc=None, _pcs=[], _pcs_key=None, _pairing=False,- pc_list=mock.Mock(arrangedSubviews=mock.Mock(return_value=[])),- pc_frame=mock.Mock(), pc_empty=mock.Mock(), pair_status=mock.Mock(),- confirm_button=mock.Mock(), code_boxes=mock.Mock(value=""),- window=mock.Mock(), _find_answered=mock.Mock(), _pairing_finished=mock.Mock(),- _shown=lambda text: text,- )- self.window.code_boxes.clear.side_effect = lambda: setattr(self.window.code_boxes, "value", "")- self.window.pair_status.set.side_effect = lambda text, **kwargs: setattr(self, "status_text", text)- self.status_text = ""- for name in ("_refresh_pcs", "_choose_pc", "_say_choice", "_say_pairing", "confirmPair_"):- method = getattr(kvm_bridge_app.ControlWindow, name)- setattr(self.window, name, MethodType(getattr(method, "callable", method), self.window))- for name in ("pressable", "stack", "LED", "Label", "hug", "squeeze", "pin", "add"):- patcher = mock.patch.object(kvm_bridge_app.widgets, name)- patcher.start()- self.addCleanup(patcher.stop)-- def beacon(self, pair_id=None, reply_port=24821):- return dict(name="TEST-PC", address="192.0.2.20", port=24820,- reply_port=reply_port, pair_id=pair_id)-- def refresh(self, pc):- self.window.discovery.pcs.return_value = [pc] if pc is not None else []- self.window._refresh_pcs()-- def choose(self, pc):- self.refresh(pc)- self.window._choose_pc(0)-- def enter(self, code):- self.window.code_boxes.value = code-- def status(self):- return self.status_text-- def test_selected_pc_starting_pairing_updates_hint_and_keeps_partial_code(self):- self.choose(self.beacon())- self.assertIn("not showing a code", self.status())- self.enter("123")- active = self.beacon("first-code")- self.refresh(active)- self.assertEqual(self.window.chosen_pc, active)- self.assertEqual(self.status(), "Six digits, as shown on the PC.")- self.assertEqual(self.window.code_boxes.value, "123")-- def test_selected_pc_stopping_pairing_updates_hint(self):- self.choose(self.beacon("first-code"))- self.refresh(self.beacon())- self.assertIsNone(self.window.chosen_pc["pair_id"])- self.assertIn("not showing a code", self.status())-- def test_active_code_rotation_updates_selected_and_submission_state(self):- self.choose(self.beacon("first-code"))- current = self.beacon("second-code")- self.refresh(current)- self.assertEqual(self.window.chosen_pc, current)- self.assertEqual(self.window._pcs, [current])-- def test_reply_port_change_updates_selected_and_submission_state(self):- self.choose(self.beacon("first-code"))- current = self.beacon("first-code", reply_port=24822)- self.refresh(current)- self.assertEqual(self.window.chosen_pc, current)- self.assertEqual(self.window._pcs, [current])-- def test_submit_uses_latest_pairing_id_and_reply_port(self):- self.choose(self.beacon("first-code"))- current = self.beacon("second-code", reply_port=24822)- self.refresh(current)- self.enter("123456")- with mock.patch.object(kvm_bridge_app.threading, "Thread") as thread, \- mock.patch.object(kvm_bridge_app.AppHelper, "callAfter"):- self.window.confirmPair_(None)- thread.assert_called_once()- thread.call_args.kwargs["target"]()- self.window.discovery.pair.assert_called_once_with(current, "123456")-- def test_pairing_progress_survives_beacon_changes(self):- self.choose(self.beacon("first-code"))- self.window._pairing = True- self.window._say_pairing("Pairing with TEST-PC…")- self.refresh(self.beacon())- self.assertEqual(self.status(), "Pairing with TEST-PC…")-- def test_unchanged_beacon_preserves_error_message(self):- pc = self.beacon("first-code")- self.choose(pc)- self.window._say_pairing("That code was not accepted.", "fault")- self.refresh(dict(pc))- self.assertEqual(self.status(), "That code was not accepted.")-- def test_refusal_stays_up_when_the_pc_drops_its_code(self):- self.choose(self.beacon("first-code"))- self.window._say_pairing("That code was not accepted.", "fault")- self.refresh(self.beacon())- self.assertEqual(self.status(), "That code was not accepted.")- self.refresh(self.beacon("fresh-code"))- self.assertEqual(self.status(), "Six digits, as shown on the PC.")-- def test_disappeared_pc_clears_selection_and_disables_submission(self):- self.choose(self.beacon("first-code"))- self.refresh(None)- self.assertIsNone(self.window.chosen_pc)- self.assertEqual(self.window._pcs, [])- self.window.confirm_button.set_enabled.assert_called_with(False)-- def test_a_pc_on_another_version_of_the_exchange_is_said_plainly(self):- pc = self.beacon("first-code")- self.choose(pc)- finished = kvm_bridge_app.ControlWindow._pairing_finished- finished = MethodType(getattr(finished, "callable", finished), self.window)- finished(pc, kvm_bridge_app.pairing.PairingError(kvm_bridge_app.pairing.ERROR_VERSION))- self.assertEqual(- self.status(),- "The PC runs a different version of Beamer. Update Beamer on both machines, then pair again.",- )---if __name__ == "__main__":- unittest.main()diff --git a/mac_app/tests/test_peer_labels.py b/mac_app/tests/test_peer_labels.pynew file mode 100644index 0000000..44fe7c6--- /dev/null+++ b/mac_app/tests/test_peer_labels.py@@ -0,0 +1,58 @@+"""The controller names each machine as the window shows it, so a status can say which one it is about."""++import copy+import os+import sys+import unittest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from bridge import KVMController+from bridge_fakes import PAIRED_TOKEN, FakeClock, FakeQuartz, make_config, quiet_logger+from fake_link import FakeLink++FIRST = "AAAAAAAAAAAAAAAAAAAAAA"+SECOND = "BBBBBBBBBBBBBBBBBBBBBw"+++class PeerLabelTests(unittest.TestCase):+ def setUp(self):+ self.controller = KVMController(+ make_config(PAIRED_TOKEN), logger=quiet_logger(), quartz=FakeQuartz, clock=FakeClock(),+ link_factory=FakeLink, desktop_bounds=lambda: (0, 0, 1920, 1080),+ )+ first = self.controller.book.data["peers"][0]+ first.update(id=FIRST, name="Desk")+ second = copy.deepcopy(first)+ second.update(id=SECOND, name="Desk", token="other-token")+ self.controller.book.data["peers"].append(second)++ def test_the_first_machine_is_the_peer_label(self):+ self.assertEqual(self.controller.peer_label, "Desk (AAAA)")++ def test_the_machine_input_is_on_is_named_by_its_own_label(self):+ self.assertIsNone(self.controller.on_label)+ self.controller.owner.on = SECOND+ self.assertEqual(self.controller.on_label, "Desk (BBBw)")++ def test_the_machine_driving_this_mac_is_named_by_its_own_label(self):+ self.assertIsNone(self.controller.driver_label)+ self.controller.driver = SECOND+ self.assertEqual(self.controller.driver_label, "Desk (BBBw)")++ def test_a_machine_no_longer_in_the_list_has_no_label(self):+ self.controller.driver = "CCCCCCCCCCCCCCCCCCCCCg"+ self.assertIsNone(self.controller.driver_label)++ def test_an_alert_about_a_machine_names_it_by_its_label(self):+ self.controller._up_names[SECOND] = "Desk"+ self.assertEqual(self.controller._name_of(SECOND), "Desk (BBBw)")+ self.assertEqual(self.controller._name_of("CCCCCCCCCCCCCCCCCCCCCg"), "the other machine")++ def test_no_peers_no_label(self):+ self.controller.book.data["peers"].clear()+ self.assertIsNone(self.controller.peer_label)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_pointer_hide.py b/mac_app/tests/test_pointer_hide.pynew file mode 100644index 0000000..eccf244--- /dev/null+++ b/mac_app/tests/test_pointer_hide.py@@ -0,0 +1,170 @@+"""Hiding the Mac's pointer while it drives the other machine. The invariant is one line: the+pointer is visible whenever input is local, by whichever path it came home, so a hide is never+left behind. A fake Quartz counts the hide and show calls, which must balance."""++import os+import sys+import threading+import unittest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from bridge import KVMController+from pointer_hide import PointerHider+from bridge_fakes import PAIRED_TOKEN, FakeClipboard, FakeClock, FakeQuartz, make_config, quiet_logger+from fake_link import FakeLink, bring_up+++class CountingQuartz(FakeQuartz):+ hide_calls = []+ show_calls = []+ hide_status = 0++ @classmethod+ def reset_cursor_spies(cls):+ super().reset_cursor_spies()+ cls.hide_calls = []+ cls.show_calls = []+ cls.hide_status = 0++ @staticmethod+ def CGMainDisplayID():+ return 7++ @classmethod+ def CGDisplayHideCursor(cls, display):+ cls.hide_calls.append(display)+ return cls.hide_status++ @classmethod+ def CGDisplayShowCursor(cls, display):+ cls.show_calls.append(display)+ return 0+++class PointerHiderTests(unittest.TestCase):+ def setUp(self):+ CountingQuartz.reset_cursor_spies()+ self.background = []+ self.hider = PointerHider(CountingQuartz, background=lambda: self.background.append(True), logger=quiet_logger())++ def test_hiding_twice_hides_once_so_one_show_undoes_it(self):+ self.hider.hide()+ self.hider.hide()+ self.hider.show()+ self.assertEqual((len(CountingQuartz.hide_calls), len(CountingQuartz.show_calls)), (1, 1))++ def test_show_without_a_hide_does_nothing(self):+ self.hider.show()+ self.assertEqual(CountingQuartz.show_calls, [])++ def test_the_background_permission_is_asked_for_once_before_the_first_hide(self):+ self.hider.hide()+ self.hider.show()+ self.hider.hide()+ self.assertEqual(self.background, [True])++ def test_a_hide_the_system_refused_is_not_counted_as_hidden(self):+ CountingQuartz.hide_status = 1001+ self.hider.hide()+ self.hider.show()+ self.assertEqual(CountingQuartz.show_calls, [])++ def test_a_failing_background_call_still_tries_to_hide_and_never_raises(self):+ def broken():+ raise OSError("no such symbol")++ hider = PointerHider(CountingQuartz, background=broken, logger=quiet_logger())+ hider.hide()+ hider.show()+ self.assertEqual((len(CountingQuartz.hide_calls), len(CountingQuartz.show_calls)), (1, 1))+++class ControllerPointerTests(unittest.TestCase):+ def setUp(self):+ CountingQuartz.reset_cursor_spies()+ self.controller = KVMController(make_config(PAIRED_TOKEN), logger=quiet_logger(), quartz=CountingQuartz, clock=FakeClock(),+ clipboard=FakeClipboard(""), link_factory=FakeLink, desktop_bounds=lambda: (0, 0, 1920, 1080))+ self.controller.pointer = PointerHider(CountingQuartz, background=lambda: None, logger=quiet_logger())+ self.link = bring_up(self.controller)++ def hidden(self):+ return len(CountingQuartz.hide_calls) - len(CountingQuartz.show_calls)++ def test_redirecting_hides_the_pointer(self):+ self.assertTrue(self.controller.set_redirecting(True))+ self.assertEqual(self.hidden(), 1)++ def test_switching_home_shows_it(self):+ self.controller.set_redirecting(True)+ self.controller.set_redirecting(False)+ self.assertEqual(self.hidden(), 0)++ def test_a_dropped_link_shows_it(self):+ self.controller.set_redirecting(True)+ self.controller._connection_failed("the link dropped")+ self.assertEqual(self.hidden(), 0)++ def test_the_peer_going_silent_shows_it(self):+ self.controller.set_redirecting(True)+ self.link.down(self.controller)+ self.assertEqual(self.hidden(), 0)++ def test_a_forced_local_shows_it(self):+ self.controller.set_redirecting(True)+ self.controller._force_local("the tap died")+ self.assertEqual(self.hidden(), 0)++ def test_a_settings_change_shows_it(self):+ self.controller.set_redirecting(True)+ self.controller.update_config(self.controller.cfg)+ self.assertEqual(self.hidden(), 0)++ def test_the_pc_taking_this_mac_over_shows_it(self):+ self.controller.set_redirecting(True)+ self.controller.set_receiving(True)+ self.assertEqual(self.hidden(), 0)++ def test_stopping_shows_it(self):+ self.controller.set_redirecting(True)+ self.controller.stop()+ self.assertEqual(self.hidden(), 0)++ def test_going_local_by_any_assignment_shows_it(self):+ # The handshake-failure branches clear the flag directly; the flag itself is the gate.+ self.controller.set_redirecting(True)+ self.controller.redirecting = False+ self.assertEqual(self.hidden(), 0)++ def test_a_link_failing_as_the_hide_runs_leaves_it_shown(self):+ # The owner's effects run under one lock in the order they were decided, so a link going+ # down on its own thread waits for the hide and its show comes after it.+ real_hide = self.controller.pointer.hide+ failing = threading.Thread(target=lambda: self.link.down(self.controller))++ def hide_as_the_link_drops():+ failing.start()+ failing.join(0.05)+ real_hide()++ self.controller.pointer.hide = hide_as_the_link_drops+ self.controller.set_redirecting(True)+ failing.join(5)+ self.assertFalse(failing.is_alive())+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(self.hidden(), 0)++ def test_a_refused_redirect_hides_nothing(self):+ self.controller.cfg = self.controller.cfg.__class__(**{**self.controller.cfg.__dict__, "send_to_windows": False})+ self.assertFalse(self.controller.set_redirecting(True))+ self.assertEqual(CountingQuartz.hide_calls, [])++ def test_redirect_and_return_many_times_keeps_the_counts_equal(self):+ for _ in range(5):+ self.controller.set_redirecting(True)+ self.controller.set_redirecting(False)+ self.assertEqual((len(CountingQuartz.hide_calls), len(CountingQuartz.show_calls)), (5, 5))+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_qr.py b/mac_app/tests/test_qr.pynew file mode 100644index 0000000..adeb6f6--- /dev/null+++ b/mac_app/tests/test_qr.py@@ -0,0 +1,52 @@+"""The pairing QR is drawn with Core Image's generator and must read back as the text it was given."""++import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++import AppKit+import Quartz++import qr++TEXT = "beamer://pair?host=192.168.1.20&port=24821&code=123456&k=" + "Ab_-" * 5 + "Ab"+++def decoded(image):+ rep = AppKit.NSBitmapImageRep.imageRepWithData_(image.TIFFRepresentation())+ ci = Quartz.CIImage.alloc().initWithBitmapImageRep_(rep)+ detector = Quartz.CIDetector.detectorOfType_context_options_("CIDetectorTypeQRCode", None, {"CIDetectorAccuracy": "CIDetectorAccuracyHigh"})+ return [feature.messageString() for feature in detector.featuresInImage_(ci)]+++class QRTests(unittest.TestCase):+ def test_the_drawing_reads_back_as_the_text(self):+ self.assertEqual(decoded(qr.image(TEXT, 220)), [TEXT])++ def test_the_modules_are_a_square_with_the_finder_pattern_in_three_corners(self):+ grid = qr.modules(TEXT)+ size = len(grid)+ self.assertTrue(all(len(row) == size for row in grid))+ for row, col in ((0, 0), (0, size - 7), (size - 7, 0)):+ self.assertTrue(all(grid[row][col + i] and grid[row + 6][col + i] for i in range(7)))++ def test_the_image_is_whole_modules_no_bigger_than_asked_and_dark_on_light_whatever_the_appearance(self):+ image = qr.image(TEXT, 180)+ width = image.size().width+ self.assertEqual(width, image.size().height)+ self.assertLessEqual(width, 180)+ self.assertGreater(width, 180 - (len(qr.modules(TEXT)) + 2 * qr.QUIET_MODULES))+ self.assertEqual(width % (len(qr.modules(TEXT)) + 2 * qr.QUIET_MODULES), 0)+ rep = AppKit.NSBitmapImageRep.imageRepWithData_(image.TIFFRepresentation())+ corner = rep.colorAtX_y_(1, 1).redComponent()+ self.assertGreater(corner, 0.95)++ def test_a_text_that_does_not_fit_is_refused(self):+ with self.assertRaises(ValueError):+ qr.modules("x" * 4000)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_replay.py b/mac_app/tests/test_replay.pyindex 94e4d52..dae0cdf 100644--- a/mac_app/tests/test_replay.py+++ b/mac_app/tests/test_replay.py@@ -1,19 +1,23 @@-"""Whole-connection replay, over both links with the real link code at each end.+"""Whole-connection replay, with the Mac's real link code at one end and the version 6 responder at+the other.An attacker on the LAN who recorded one connection opens a new one and sends the recordedinitiator bytes in order: the preamble, the hello and every input frame after it. Per-framereplay inside a connection was always refused; this is the whole stream again, into a fresh-responder, and it must fail the tag rather than inject what was recorded."""+responder, and it must fail the first tag rather than inject what was recorded."""+import copy+import osimport socket+import sysimport timeimport unittest-import os-import syssys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from bridge_fakes import PAIRED_TOKENfrom core import protocol+from core.tests.responder_harness import HERE, Machinefrom two_machines import Duo, wait_for@@ -52,6 +56,15 @@ def recording_factory(recordings):return connect+def recorder(recordings):+ def wrap(sock):+ recording = Recording(sock)+ recordings.append(recording)+ return recording++ return wrap++def replay(port, data):"""Send `data` as a fresh connection and return every byte the responder sent back before itclosed."""@@ -83,56 +96,83 @@ def settle():class WholeConnectionReplayTests(unittest.TestCase):def test_the_macs_recorded_link_replayed_into_the_pc_is_refused(self):- duo = Duo(crossing={"resistance_px": 40}).listen()- self.addCleanup(duo.close)recordings = []- duo.mac.socket_factory = recording_factory(recordings)+ duo = Duo(crossing={"resistance_px": 40}, socket_factory=recording_factory(recordings)).listen()+ self.addCleanup(duo.close)+ pc = duo.pc_responderduo.link_mac_to_pc()self.assertTrue(duo.mac_push(1727, 500, 30), "the push never crossed")- self.assertTrue(wait_for(lambda: duo.pc_desktop.cursor[0] == 0), "the switch never placed the PC's pointer")+ self.assertTrue(wait_for(lambda: pc.arrivals), "the take never placed the PC's pointer")+ duo.mac_move(1727, 500, 7)+ self.assertTrue(wait_for(lambda: ("move", 7, 0) in pc.injected()), "the Mac's input never arrived")self.assertTrue(duo.mac.send_arrangement("left", 500))- self.assertTrue(wait_for(lambda: duo.pc_arrangements), "the arrangement never arrived")+ self.assertTrue(wait_for(lambda: any(read["set_at"] == 500 for _, read in pc.arrangements)), "the arrangement never arrived")duo.mac.stop()- duo.pc_desktop.cursor = (900, 500)- arrangements = len(duo.pc_arrangements)+ self.assertTrue(wait_for(lambda: pc.responder.owner is None and not pc.responder.links()))self.assertEqual(len(recordings), 1)+ self.assertGreater(len(recordings[0].sent), protocol.LINK_PREAMBLE_SIZE + 6 * protocol.MIN_FRAME_BYTES)- reply = replay(duo.pc_port, recordings[0].sent)- settle()+ pc.desktop.cursor = (900, 500)+ before = (len(pc.desktop.placed), len(pc.injected()), len(pc.arrangements), list(pc.owners), len(pc.arrivals))+ fresh = Machine(copy.deepcopy(pc.settings.data["peers"]), pc.settings.data["zones"]).start()+ self.addCleanup(fresh.stop)- self.assertEqual(duo.pc_desktop.cursor, (900, 500), "a replayed switch moved the PC's pointer")- self.assertEqual(len(duo.pc_arrangements), arrangements, "a replayed arrangement was applied")- self.assertEqual(len(reply), protocol.PREAMBLE_SIZE, "the PC answered past its preamble")+ for name, target in (("the PC it was taken from", pc), ("a fresh responder", fresh)):+ with self.subTest(into=name):+ reply = replay(target.port, recordings[0].sent)+ settle()+ self.assertEqual(len(reply), protocol.LINK_PREAMBLE_SIZE, "the responder answered past its preamble")+ self.assertEqual(target.responder.links(), set())+ self.assertIsNone(target.responder.owner)++ self.assertEqual(pc.desktop.cursor, (900, 500), "a replayed take moved the PC's pointer")+ self.assertEqual((len(pc.desktop.placed), len(pc.injected()), len(pc.arrangements), list(pc.owners), len(pc.arrivals)), before)+ self.assertEqual((fresh.injected(), fresh.arrangements, fresh.owners, fresh.arrivals, fresh.desktop.placed), ([], [], [], [], []))def test_the_pcs_recorded_link_replayed_into_the_mac_is_refused(self):+ recordings = []duo = Duo().listen()self.addCleanup(duo.close)- recordings = []- duo.pc._socket_factory = recording_factory(recordings)- duo.link_pc_to_mac()- self.assertTrue(duo.pc.send_arrangement("top", 600))- self.assertTrue(wait_for(lambda: duo.mac_arrangements), "the arrangement never arrived")- duo.pc.stop()- arrangements = len(duo.mac_arrangements)+ duo.link_pc_to_mac(wrap=recorder(recordings))+ duo.pc_drives("left", 0.5)+ self.assertTrue(wait_for(lambda: duo.mac_arrivals), "the take never placed the Mac's pointer")+ duo.pc.acked(duo.pc.move(5, 0))+ duo.pc.acked(duo.pc.key(protocol.MSG_KEYDOWN, "a"))+ duo.pc.send(protocol.arrangement_v6("top", 600, HERE))+ self.assertTrue(wait_for(lambda: any(item[1] == 600 for item in duo.mac_arrangements)), "the arrangement never arrived")+ duo.pc.let_go()+ self.assertTrue(wait_for(lambda: not duo.mac.receiving))+ duo.pc.sock.shutdown(socket.SHUT_RDWR)+ duo.pc.close()+ self.assertTrue(wait_for(lambda: not duo.mac_responder.links()))self.assertEqual(len(recordings), 1)+ self.assertGreater(len(recordings[0].sent), protocol.LINK_PREAMBLE_SIZE + 6 * protocol.MIN_FRAME_BYTES)+ self.assertTrue(any(call[0] == "move" for call in duo.mac_injector.seen()), "the recorded input was never injected")++ duo.mac_desktop.cursor = (900, 500)+ before = (len(duo.mac_desktop.placed), len(duo.mac_injector.seen()), len(duo.mac_arrangements), len(duo.mac_arrivals))reply = replay(duo.mac_port, recordings[0].sent)settle()- self.assertEqual(len(duo.mac_arrangements), arrangements, "a replayed arrangement was applied")- self.assertEqual(len(reply), protocol.PREAMBLE_SIZE, "the Mac answered past its preamble")+ self.assertEqual(duo.mac_desktop.cursor, (900, 500), "a replayed take moved the Mac's pointer")+ self.assertEqual((len(duo.mac_desktop.placed), len(duo.mac_injector.seen()), len(duo.mac_arrangements), len(duo.mac_arrivals)), before)+ self.assertFalse(duo.mac.receiving, "a replayed take made the Mac driven")+ self.assertEqual(duo.mac_responder.links(), set())+ self.assertEqual(len(reply), protocol.LINK_PREAMBLE_SIZE, "the Mac answered past its preamble")class SessionKeyTests(unittest.TestCase):def pair(self):- a, b = protocol.SecureSession("t"), protocol.SecureSession("t")- a.accept_preamble(b.preamble())+ a = protocol.LinkSession(PAIRED_TOKEN, protocol.ROLE_INITIATOR)+ b = protocol.LinkSession(PAIRED_TOKEN, protocol.ROLE_RESPONDER)b.accept_preamble(a.preamble())+ a.accept_preamble(b.preamble())return a, bdef test_nothing_is_sealed_before_the_peers_preamble(self):with self.assertRaises(protocol.ProtocolError):- protocol.SecureSession("t").seal(protocol.ping_msg())+ protocol.LinkSession(PAIRED_TOKEN, protocol.ROLE_INITIATOR).seal(protocol.ping_msg())def test_a_sides_own_frames_reflected_back_fail_the_tag(self):a, b = self.pair()@@ -142,7 +182,7 @@ class SessionKeyTests(unittest.TestCase):def test_a_frame_from_another_connection_fails_the_tag(self):a, b = self.pair()frame = a.seal(protocol.ping_msg())- fresh = protocol.SecureSession("t")+ fresh = protocol.LinkSession(PAIRED_TOKEN, protocol.ROLE_RESPONDER)fresh.accept_preamble(a.preamble())with self.assertRaises(protocol.AuthenticationError):fresh.open(frame[protocol.HEADER_SIZE:])@@ -150,8 +190,11 @@ class SessionKeyTests(unittest.TestCase):def test_a_second_preamble_is_refused(self):a, b = self.pair()+ other_initiator = protocol.LinkSession(PAIRED_TOKEN, protocol.ROLE_INITIATOR)+ other = protocol.LinkSession(PAIRED_TOKEN, protocol.ROLE_RESPONDER)+ other.accept_preamble(other_initiator.preamble())with self.assertRaises(protocol.ProtocolError):- a.accept_preamble(protocol.SecureSession("t").preamble())+ a.accept_preamble(other.preamble())if __name__ == "__main__":diff --git a/mac_app/tests/test_same_on_both.py b/mac_app/tests/test_same_on_both.pyindex de70053..1c6406a 100644--- a/mac_app/tests/test_same_on_both.py+++ b/mac_app/tests/test_same_on_both.py@@ -19,17 +19,23 @@ AppKit.NSApplication.sharedApplication()import kvm_bridge_app # noqa: E402import pages # noqa: E402import settings_store # noqa: E402-from core import settings_sync # 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: E402from 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, **values):- base = dict(methods=["corner"], edge_parts=["start"], corner="bottom_left", resistance_px=60,++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)+ return settings_sync.message_data(on, set_at, base, by=by)class SameOnBothTests(unittest.TestCase):@@ -38,7 +44,7 @@ class SameOnBothTests(unittest.TestCase):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="synthetic")+ raw.update(host="192.0.2.20", auth_token=PAIRED_TOKEN)raw["crossing"]["methods"] = ["shortcut", "edge", "notch"]path.write_text(json.dumps(raw))self.store = settings_store.SettingsStore(path)@@ -46,11 +52,12 @@ class SameOnBothTests(unittest.TestCase):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), self.store, logger+ WakingController(self.store.load(), logger=logger, link_factory=FakeLink), self.store, logger)self.addCleanup(self.window.appearance_watch.stop)self.sent = []- self.window.controller.send_settings = lambda data: self.sent.append(data) or True+ self.sources = []+ self.window.controller.send_settings = lambda data, source=None: self.sent.append(data) or self.sources.append(source) or Trueself.window._show_same()def test_off_by_default_with_each_page_its_own(self):@@ -62,7 +69,7 @@ class SameOnBothTests(unittest.TestCase):self.window.apply_same(pc_message(True, 100))cfg = self.window.controller.cfgself.assertTrue(cfg.same_on_both)- self.assertEqual(cfg.crossing["methods"], ["corner", "notch"])+ 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")@@ -70,15 +77,14 @@ class SameOnBothTests(unittest.TestCase):self.assertEqual(self.window.resistance_ruler.value, 60)self.assertTrue(self.window.same_switch.value)self.assertEqual(self.window.scope_labels["crossing"].text,- "Kept the same as your PC. Change it on either machine.")- self.assertEqual(self.sent, [])+ f"Kept the same as {self.window.controller.peer_label}. Change it on any 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._say_pairing("That code was not accepted.", "fault")+ 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.pair_status.text, "That code was not accepted.")+ 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.controller.full_screen_app = "Game"@@ -104,7 +110,7 @@ class SameOnBothTests(unittest.TestCase):self.window._set_same(True)self.assertEqual(len(self.sent), 1)self.assertTrue(self.sent[0]["on"])- self.assertEqual(self.sent[0]["crossing"]["methods"], ["shortcut", "edge"])+ 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)@@ -124,12 +130,43 @@ class SameOnBothTests(unittest.TestCase):def test_an_old_pc_turns_the_switch_off_and_says_why(self):self.window._set_same(True)- self.window.controller.peer_settings = False- with mock.patch.object(type(self.window.controller), "connected", new_callable=mock.PropertyMock, return_value=True):- self.window._show_same()+ 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_state_is_sent_on_unchanged_to_the_others_but_not_back_to_it(self):+ data = pc_message(True, 100, by=PEER)+ self.window.apply_same(data, peer=PEER)+ self.assertEqual(self.sent, [data])+ self.assertEqual(self.sources, [PEER])++ def test_who_made_the_change_is_kept_with_it(self):+ 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.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):+ 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)+if __name__ == "__main__":unittest.main()diff --git a/mac_app/tests/test_settings_store.py b/mac_app/tests/test_settings_store.pyindex 60a1488..d16d18f 100644--- a/mac_app/tests/test_settings_store.py+++ b/mac_app/tests/test_settings_store.py@@ -28,7 +28,7 @@ class SettingsStoreTests(unittest.TestCase):def test_save_is_private_and_round_trips_shared_schema(self):with tempfile.TemporaryDirectory() as directory:- path = Path(directory) / "config.json"+ path = Path(directory) / "settings.json"store = SettingsStore(path)saved = store.save(self.valid_raw())loaded = store.load()@@ -39,7 +39,7 @@ class SettingsStoreTests(unittest.TestCase):def test_both_directions_default_on_and_each_switch_round_trips(self):with tempfile.TemporaryDirectory() as directory:- store = SettingsStore(Path(directory) / "config.json")+ store = SettingsStore(Path(directory) / "settings.json")loaded = store.save(self.valid_raw())self.assertTrue(loaded.send_to_windows)self.assertTrue(loaded.allow_windows_to_drive)@@ -52,7 +52,7 @@ class SettingsStoreTests(unittest.TestCase):def test_the_full_screen_hold_defaults_on_and_round_trips(self):with tempfile.TemporaryDirectory() as directory:- store = SettingsStore(Path(directory) / "config.json")+ store = SettingsStore(Path(directory) / "settings.json")loaded = store.save(self.valid_raw())self.assertTrue(loaded.crossing["hold_full_screen"])raw = config_to_raw(loaded)@@ -65,7 +65,7 @@ class SettingsStoreTests(unittest.TestCase):def test_appearance_defaults_to_system_and_each_choice_round_trips(self):with tempfile.TemporaryDirectory() as directory:- store = SettingsStore(Path(directory) / "config.json")+ store = SettingsStore(Path(directory) / "settings.json")self.assertEqual(store.save(self.valid_raw()).appearance, "system")for choice in ("light", "dark", "system"):raw = config_to_raw(store.load())@@ -78,7 +78,7 @@ class SettingsStoreTests(unittest.TestCase):def test_a_hand_edited_appearance_loads_as_system(self):with tempfile.TemporaryDirectory() as directory:- path = Path(directory) / "config.json"+ path = Path(directory) / "settings.json"path.write_text(json.dumps({**self.valid_raw(), "appearance": "sepia"}), encoding="utf-8")self.assertEqual(config_module.load_config(str(path)).appearance, "system")@@ -90,7 +90,7 @@ class SettingsStoreTests(unittest.TestCase):def test_legacy_positional_key_map_is_replaced_by_the_semantic_default(self):with tempfile.TemporaryDirectory() as directory:- path = Path(directory) / "config.json"+ path = Path(directory) / "settings.json"raw = self.valid_raw()raw["key_map"] = {"alt": "alt", "alt_r": "alt",@@ -103,7 +103,7 @@ class SettingsStoreTests(unittest.TestCase):def test_hand_edited_key_map_survives(self):with tempfile.TemporaryDirectory() as directory:- path = Path(directory) / "config.json"+ path = Path(directory) / "settings.json"raw = self.valid_raw()raw["key_map"] = {"cmd": "cmd", "ctrl": "alt"}loaded = SettingsStore(path).save(raw)@@ -115,14 +115,14 @@ class SettingsStoreTests(unittest.TestCase):raw = self.valid_raw()raw["auth_token"] = "CHANGE_ME"with self.assertRaises(SettingsError):- SettingsStore(Path(directory) / "config.json").save(raw)+ SettingsStore(Path(directory) / "settings.json").save(raw)def test_rejects_unknown_trigger(self):with tempfile.TemporaryDirectory() as directory:raw = self.valid_raw()raw["trigger_key"] = "not_a_key"with self.assertRaises(SettingsError):- SettingsStore(Path(directory) / "config.json").save(raw)+ SettingsStore(Path(directory) / "settings.json").save(raw)def test_config_without_crossing_keys_loads_the_defaults(self):with tempfile.TemporaryDirectory() as directory:@@ -182,7 +182,7 @@ class SettingsStoreTests(unittest.TestCase):raw = self.valid_raw()raw["crossing"] = {"edge": "left", "resistance_px": 40}raw["trigger_style"] = "hold"- loaded = SettingsStore(Path(directory) / "config.json").save(raw)+ loaded = SettingsStore(Path(directory) / "settings.json").save(raw)self.assertEqual(loaded.crossing["edge"], "left")self.assertEqual(loaded.crossing["resistance_px"], 40)self.assertEqual(loaded.crossing["methods"], ["shortcut", "edge"])@@ -220,7 +220,7 @@ class SettingsStoreTests(unittest.TestCase):raw = self.valid_raw()raw["crossing"] = crossingwith self.assertRaises(SettingsError) as caught:- SettingsStore(Path(directory) / "config.json").save(raw)+ SettingsStore(Path(directory) / "settings.json").save(raw)self.assertIn(field, str(caught.exception))def test_every_crossing_effect_and_colour_pack_round_trips(self):@@ -230,7 +230,7 @@ class SettingsStoreTests(unittest.TestCase):pairs += [(style, colour) for style in ("glow", "beam") for colour in effects.PACK_IDS]pairs += list(zip(effects.EFFECT_IDS, effects.PACK_IDS))with tempfile.TemporaryDirectory() as directory:- store = SettingsStore(Path(directory) / "config.json")+ store = SettingsStore(Path(directory) / "settings.json")for style, colour in pairs:with self.subTest(style=style, colour=colour):raw = self.valid_raw()@@ -253,7 +253,7 @@ class SettingsStoreTests(unittest.TestCase):raw = self.valid_raw()raw["crossing"] = crossingwith self.assertRaises(SettingsError) as caught:- SettingsStore(Path(directory) / "config.json").save(raw)+ SettingsStore(Path(directory) / "settings.json").save(raw)self.assertIn(field, str(caught.exception))def test_rejects_unknown_trigger_style(self):@@ -261,11 +261,11 @@ class SettingsStoreTests(unittest.TestCase):raw = self.valid_raw()raw["trigger_style"] = "triple_tap"with self.assertRaises(SettingsError):- SettingsStore(Path(directory) / "config.json").save(raw)+ SettingsStore(Path(directory) / "settings.json").save(raw)def test_key_map_style_names_round_trip(self):with tempfile.TemporaryDirectory() as directory:- path = Path(directory) / "config.json"+ path = Path(directory) / "settings.json"raw = self.valid_raw()raw["key_map"] = "positional"loaded = SettingsStore(path).save(raw)@@ -298,16 +298,17 @@ class LegacyPortTests(unittest.TestCase):def test_the_old_default_port_is_moved_and_the_move_is_written_down(self):with tempfile.TemporaryDirectory() as directory:- path = Path(directory) / "config.json"+ path = Path(directory) / "settings.json"+ (Path(directory) / "config.json").write_text(json.dumps(self.raw(protocol.LEGACY_DEFAULT_PORT)), encoding="utf-8")store = SettingsStore(path)- store.save(self.raw(protocol.LEGACY_DEFAULT_PORT))self.assertEqual(store.load().port, protocol.DEFAULT_PORT)on_disk = json.loads(path.read_text(encoding="utf-8"))self.assertEqual(on_disk["port"], protocol.DEFAULT_PORT)+ self.assertEqual(on_disk["peers"][0]["port"], protocol.DEFAULT_PORT)def test_a_port_someone_chose_is_left_alone(self):with tempfile.TemporaryDirectory() as directory:- path = Path(directory) / "config.json"+ path = Path(directory) / "settings.json"store = SettingsStore(path)store.save(self.raw(9000))self.assertEqual(store.load().port, 9000)diff --git a/mac_app/tests/test_settings_sync_link.py b/mac_app/tests/test_settings_sync_link.pyindex e3cea4b..c163922 100644--- a/mac_app/tests/test_settings_sync_link.py+++ b/mac_app/tests/test_settings_sync_link.py@@ -1,132 +1,277 @@-"""Same on both machines over loopback: the real links of both apps, announcing on connect and-carrying each change, with two small ends holding each machine's state through settings_sync as-the apps' windows do (apply_same on the Mac, _on_settings on the PC)."""+"""Same on both machines over loopback: the Mac's real controller and responder against a PC end+made of core's own link and responder, announcing on connect and carrying each change, with two+small ends holding each machine's state through settings_sync as the apps' windows do (apply_same on+the Mac, _on_settings on the PC). The Mac's state travels over its own link and over the PC's."""-import unittest-from unittest import mockimport os+import shutil+import socketimport sys+import tempfile+import threading+import time+import unittest+from dataclasses import replace+from pathlib import Pathsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))-from two_machines import Duo, wait_for # first: it puts the PC's own modules on the path+_WIN = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "win_app")+if _WIN not in sys.path:+ sys.path.append(_WIN)import app_config # noqa: E402-from core import protocol # noqa: E402-from core import settings_sync # noqa: E402+from bridge import KVMController # noqa: E402+from bridge_fakes import PAIRED_TOKEN, FakeClipboard, FakeQuartz, quiet_logger # noqa: E402+from core import protocol, settings_sync # noqa: E402+from core.link import OutboundLink # noqa: E402+from core.tests import responder_harness as harness # noqa: E402from key_codes import KEY_NAME_TO_CODE # noqa: E402-from settings_store import config_to_raw # noqa: E402+from settings_store import SettingsStore, config_to_raw # noqa: E402+from windows_input import WindowsInput # noqa: E402++wait_for = harness.wait_for+PC_ID = harness.HERE+WITHOUT_SETTINGS = [cap for cap in harness.CAPS if cap != "settings"]+++def free_port():+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ return probe.getsockname()[1]class MacEnd:- def __init__(self, duo):- self.duo = duo- self.raw = config_to_raw(duo.mac.cfg)- self.raw["same_on_both"], self.raw["same_set_at"] = False, 0+ """The Mac's state as the app holds it, and what its apply_same does with a message."""++ def __init__(self, rig):+ self.rig = rig+ self.raw = config_to_raw(rig.controller.cfg)+ self.raw["same_on_both"], self.raw["same_set_at"], self.raw["same_by"] = False, 0, ""+ self.lock = threading.Lock()+ self.taken = []def state(self):return settings_sync.message_data(self.raw["same_on_both"], self.raw["same_set_at"],- settings_sync.mac_values(self.raw))+ settings_sync.mac_values(self.raw), by=self.raw["same_by"] or self.rig.mac_id_text)- def take(self, data):- taken = settings_sync.arrived(data, self.raw["same_set_at"], KEY_NAME_TO_CODE)- if taken is None:- return- on, set_at, values = taken- raw = settings_sync.apply_mac(self.raw, values) if on else dict(self.raw)- raw["same_on_both"], raw["same_set_at"] = on, set_at- self.raw = raw+ def take(self, data, peer=None):+ with self.lock:+ taken = settings_sync.arrived(data, self.raw["same_set_at"], KEY_NAME_TO_CODE, by_here=self.raw["same_by"])+ if taken is None:+ return+ on, set_at, values = taken+ raw = settings_sync.apply_mac(self.raw, values) if on else dict(self.raw)+ raw["same_on_both"], raw["same_set_at"], raw["same_by"] = on, set_at, data.get("by", "")+ self.raw = raw+ self.taken.append(data)+ self.send(data, source=peer)++ def send(self, data, source=None):+ self.rig.controller.send_settings(data, source=source)+ self.rig.input.send_settings(data, source=source)def set(self, on=None, at=0, **crossing):- if on is not None:- self.raw["same_on_both"] = on- self.raw["crossing"] = {**self.raw["crossing"], **crossing}- self.raw["same_set_at"] = at- data = self.state()- self.duo.mac.send_settings(data)- self.duo.mac_server.send_settings(data)+ with self.lock:+ if on is not None:+ self.raw["same_on_both"] = on+ self.raw["crossing"] = {**self.raw["crossing"], **crossing}+ self.raw["same_set_at"], self.raw["same_by"] = at, self.rig.mac_id_text+ self.send(self.state())class PCEnd:- def __init__(self, duo):- self.duo = duo- self.config = duo.pc_config+ """The PC's state, as the PC window holds it, and what its _on_settings does with a message."""++ def __init__(self, rig):+ self.rig = rig+ self.config = app_config.Config(host="127.0.0.1", port=rig.machine.port, auth_token=PAIRED_TOKEN, mac_return_edge="left")+ self.by = ""+ self.lock = threading.Lock()+ self.taken = []+ self.heard = []def state(self):return settings_sync.message_data(self.config.same_on_both, self.config.same_set_at,- settings_sync.pc_values(self.config))+ settings_sync.pc_values(self.config), by=self.by or protocol.id_text(PC_ID))- def take(self, data):- taken = settings_sync.arrived(data, self.config.same_set_at, app_config.TRIGGER_KEYS)- if taken is None:- return- on, set_at, values = taken- if on:- settings_sync.apply_pc(self.config, values)- self.config.same_on_both, self.config.same_set_at = on, set_at+ def take(self, data, peer=None):+ self.heard.append(data)+ with self.lock:+ taken = settings_sync.arrived(data, self.config.same_set_at, app_config.TRIGGER_KEYS, by_here=self.by)+ if taken is None:+ return+ on, set_at, values = taken+ if on:+ settings_sync.apply_pc(self.config, values)+ self.config.same_on_both, self.config.same_set_at, self.by = on, set_at, data.get("by", "")+ self.taken.append(data)def set(self, on=None, at=0, **fields):- if on is not None:- self.config.same_on_both = on- for name, value in fields.items():- setattr(self.config, name, value)- self.config.same_set_at = at+ with self.lock:+ if on is not None:+ self.config.same_on_both = on+ for name, value in fields.items():+ setattr(self.config, name, value)+ self.config.same_set_at, self.by = at, protocol.id_text(PC_ID)data = self.state()- self.duo.pc.send_settings(data)- self.duo.pc_server.send_settings(data)+ self.rig.pc_link.post(protocol.settings_msg(data))+ self.rig.machine.responder.send(self.rig.mac_id, protocol.settings_msg(data))-class SettingsOverLoopbackTests(unittest.TestCase):- def setUp(self):- self.duo = Duo(pc=dict(mac_return_edge="left"))- self.addCleanup(self.duo.close)- self.mac, self.pc = MacEnd(self.duo), PCEnd(self.duo)- for link in (self.duo.mac, self.duo.mac_server):- link.announce = lambda: [protocol.settings_msg(self.mac.state())]- self.duo.mac.on_settings = self.mac.take- self.duo.mac_server.settings_callback = self.mac.take- for link in (self.duo.pc, self.duo.pc_server):- link.announce = lambda: [protocol.settings_msg(self.pc.state())]- link.settings_callback = self.pc.take+class Announced(dict):+ """The PC's responder announcing its current state to whoever links in, not one frozen at build."""++ def __init__(self, rig):+ super().__init__()+ self.rig = rig++ def get(self, peer, default=None):+ return [protocol.settings_msg(self.rig.pc.state())]+++class Feed(list):+ def __init__(self, rig):+ super().__init__()+ self.rig = rig++ def append(self, item):+ super().append(item)+ self.rig.pc.take(item[1], protocol.id_text(item[0]))+++class Rig:+ """The Mac (controller, responder, settings.json) and a PC end, each linked to the other the way+ the apps do it: the Mac's controller dials the PC's responder, the PC's link dials the Mac's."""++ def __init__(self, test, pc_caps=harness.CAPS, side=None):+ folder = Path(tempfile.mkdtemp())+ test.addCleanup(shutil.rmtree, folder, True)+ self.store = SettingsStore(folder / "settings.json")+ cfg = self.store.load()+ self.mac_id_text = self.store.current()["machine_id"]+ self.mac_id = protocol.read_id(self.mac_id_text)+ self.mac_port = free_port()+ self.machine = harness.Machine(+ [harness.entry(self.mac_id_text, "Mac", token=PAIRED_TOKEN, platform="macos", host="127.0.0.1", port=self.mac_port)],+ caps=pc_caps,+ )+ self.machine.start()+ test.addCleanup(self.machine.stop)++ cfg = self.store.save({**config_to_raw(cfg), "host": "127.0.0.1", "port": self.machine.port,+ "auth_token": PAIRED_TOKEN, "pc_name": "PC"})+ settings = self.store.current()+ settings["peers"][0]["id"] = protocol.id_text(PC_ID)+ if side is not None:+ settings["peers"][0].update(side=side[0], side_set_at=side[1], side_by=self.mac_id_text)+ self.store.save_settings(settings)+ FakeQuartz.reset_cursor_spies()+ self.controller = KVMController(+ cfg, logger=quiet_logger(), quartz=FakeQuartz, clipboard=FakeClipboard(),+ book=self.store.book(), identity=self.identity, desktop_bounds=lambda: (0, 0, 1920, 1080),+ )+ test.addCleanup(self.controller.stop)+ self.input = WindowsInput(self.controller)+ self.input.server._injector = harness.FakeInjector()+ self.input.server._desktop = harness.FakeDesktop()+ self.input.server._clipboard = harness.FakeClipboard()+ test.addCleanup(self.input.stop)++ self.mac = MacEnd(self)+ self.pc = PCEnd(self)+ self.controller.announce = lambda: [protocol.settings_msg(self.mac.state())]+ self.controller.on_settings = self.mac.take+ self.input.settings_callback = self.mac.take+ self.machine.announcements = Announced(self)+ self.machine.settings_seen = Feed(self)++ self.pc_link = OutboundLink(+ PAIRED_TOKEN, self.machine.book, lambda: {"id": PC_ID, "name": "PC", "platform": "windows", "app": "1.5.0",+ "caps": list(pc_caps), "port": self.machine.port},+ up=self._pc_link_up, message=lambda link, message: self._pc_link_message(message), reconnect_seconds=0.05,+ )+ test.addCleanup(self.pc_link.stop)+ self.input.sync(replace(cfg, port=self.mac_port))++ def identity(self):+ return {"id": self.mac_id, "name": "This Mac", "platform": "macos", "app": "1.5.0", "caps": list(harness.CAPS), "port": self.mac_port}++ def _pc_link_up(self, link, fields):+ if "settings" in link.caps:+ link.post(protocol.settings_msg(self.pc.state()))++ def _pc_link_message(self, message):+ if message.get("type") == protocol.MSG_SETTINGS:+ self.pc.take(message["data"], protocol.id_text(self.mac_id))++ def link_mac_to_pc(self):+ """The Mac's own link to the PC, up before this returns."""+ self.controller.start()+ assert wait_for(lambda: self.controller.connected and self.controller._peers_up, 5.0), self.controller.connection_status+ return self++ def link_pc_to_mac(self):+ """The PC's link to the Mac, up before this returns."""+ self.pc_link.start()+ assert wait_for(lambda: self.pc_link.live() and self.input.server.links(), 5.0), self.pc_link.status+ return selfdef both_links(self):- self.duo.listen().link_mac_to_pc().link_pc_to_mac()+ return self.link_mac_to_pc().link_pc_to_mac()+++class SettingsOverLoopbackTests(unittest.TestCase):+ def setUp(self):+ self.rig = Rig(self)+ self.mac, self.pc = self.rig.mac, self.rig.pcdef test_turning_it_on_carries_this_machines_values_across(self):- self.both_links()- self.mac.set(on=True, at=100, glow_style="beam", corner="bottom_right", resistance_px=60)+ self.rig.both_links()+ self.mac.set(on=True, at=100, glow_style="beam", resistance_px=60)self.assertTrue(wait_for(lambda: self.pc.config.same_on_both))self.assertEqual((self.pc.config.glow_style, self.pc.config.crossing_resistance_px), ("beam", 60))- # The PC's Mac is on its left, so the Mac's bottom right is the PC's bottom left.- self.assertEqual(self.pc.config.crossing_corner, "bottom_left")self.assertEqual(self.pc.config.same_set_at, 100)+ self.assertEqual(self.pc.by, self.rig.mac_id_text)def test_a_change_on_either_machine_reaches_the_other_while_on(self):- self.both_links()+ self.rig.both_links()self.mac.set(on=True, at=100)self.assertTrue(wait_for(lambda: self.pc.config.same_on_both))- self.pc.set(at=101, effect_length="long", crossing_methods=["corner"])+ self.pc.set(at=101, effect_length="long", crossing_methods=["edge"])self.assertTrue(wait_for(lambda: self.mac.raw["crossing"]["effect_length"] == "long"))- # The notch is the Mac's own way in and stays.- self.assertEqual(self.mac.raw["crossing"]["methods"], ["corner", "notch"]- if "notch" in self.duo.mac.cfg.crossing["methods"] else ["corner"])+ # The shortcut went with the PC's; the notch is the Mac's own way in and stays.+ self.assertNotIn("shortcut", self.mac.raw["crossing"]["methods"])+ self.assertEqual("notch" in self.mac.raw["crossing"]["methods"], "notch" in self.rig.controller.cfg.crossing["methods"])+ self.assertEqual(self.mac.raw["same_by"], protocol.id_text(PC_ID))self.mac.set(at=102, glow_colour="ocean")self.assertTrue(wait_for(lambda: self.pc.config.glow_colour == "ocean"))def test_the_newer_end_wins_when_a_link_comes_up(self):# Changed on the PC while the Mac was away: the PC's is newer, and the Mac takes it the- # moment its own link connects, from the PC receiver's announcement.+ # moment its own link connects, from the PC responder's announcement.self.pc.config.same_on_both, self.pc.config.same_set_at = True, 500self.pc.config.glow_style = "beam"self.mac.raw["same_on_both"], self.mac.raw["same_set_at"] = True, 400- self.duo.listen().link_mac_to_pc()+ self.rig.link_mac_to_pc()self.assertTrue(wait_for(lambda: self.mac.raw["same_set_at"] == 500))self.assertEqual(self.mac.raw["crossing"]["glow_style"], "beam")# And the older end's own announcement changed nothing at the newer.self.assertEqual(self.pc.config.same_set_at, 500)+ def test_the_same_second_goes_to_the_larger_machine_id_at_both_ends(self):+ self.pc.config.same_on_both, self.pc.config.same_set_at, self.pc.by = True, 100, protocol.id_text(PC_ID)+ self.pc.config.glow_style = "beam"+ self.mac.raw["same_on_both"], self.mac.raw["same_set_at"], self.mac.raw["same_by"] = True, 100, self.rig.mac_id_text+ self.mac.raw["crossing"] = {**self.mac.raw["crossing"], "glow_style": "glow"}+ self.rig.both_links()+ winner = "beam" if PC_ID > self.rig.mac_id else "glow"+ self.assertTrue(wait_for(lambda: self.pc.config.glow_style == winner and self.mac.raw["crossing"]["glow_style"] == winner))+ time.sleep(0.2)+ self.assertEqual((self.pc.config.glow_style, self.mac.raw["crossing"]["glow_style"]), (winner, winner))+def test_turning_it_off_turns_it_off_at_both_and_leaves_the_values(self):- self.both_links()+ self.rig.both_links()self.mac.set(on=True, at=100, glow_style="beam")self.assertTrue(wait_for(lambda: self.pc.config.glow_style == "beam"))self.pc.set(on=False, at=200)@@ -135,33 +280,67 @@ class SettingsOverLoopbackTests(unittest.TestCase):self.mac.raw["crossing"]["glow_style"] = "glow"self.assertEqual(self.pc.config.glow_style, "beam")+ def test_a_state_is_not_sent_back_to_the_machine_it_came_from(self):+ self.rig.both_links()+ self.pc.set(on=True, at=300, glow_style="beam")+ self.assertTrue(wait_for(lambda: self.mac.raw["same_set_at"] == 300))+ time.sleep(0.3)+ self.assertEqual([data for data in self.pc.heard if data["set_at"] == 300], [])++ def test_a_state_goes_to_the_peer_once_when_both_links_are_up(self):+ # Counted by a stamp only this send carries: the announcements as each link comes up can+ # land after links() shows it, so a count of everything heard cannot tell them apart.+ self.rig.both_links()+ self.mac.set(at=700)+ ours = lambda: [data for data in self.pc.heard if data["set_at"] == 700]+ self.assertTrue(wait_for(lambda: len(ours()) == 1))+ time.sleep(0.3)+ self.assertEqual(len(ours()), 1)++ def test_a_state_goes_over_the_pcs_link_when_the_mac_has_none_of_its_own(self):+ # The Mac's server also announces its state on this link as it comes up, a moment after+ # links() shows it, so the PC's count of messages heard cannot say which one is ours:+ # a stamp only this send carries does.+ self.rig.link_pc_to_mac()+ self.mac.set(at=700)+ self.assertTrue(wait_for(lambda: any(data["set_at"] == 700 for data in self.pc.heard)))++ def test_a_state_made_by_a_real_machine_id_is_taken(self):+ data = settings_sync.message_data(True, 100, settings_sync.mac_values(self.mac.raw), by=protocol.id_text(PC_ID))+ taken = settings_sync.arrived(data, 0, KEY_NAME_TO_CODE)+ self.assertIsNotNone(taken)+def test_both_ends_know_a_peer_that_keeps_settings_in_step(self):- self.both_links()- self.assertTrue(wait_for(lambda: self.duo.mac_server.peer_settings is True))- self.assertTrue(self.duo.mac.peer_settings)- self.assertTrue(self.duo.pc.peer_settings)- self.assertTrue(wait_for(lambda: self.duo.pc_server.peer_settings is True))-- def test_an_older_peer_is_known_as_one_on_either_link(self):- # A Beamer before 1.5.0 sends a hello and a welcome with no settings flag.- older_hello, older_welcome = protocol.hello_msg, protocol.welcome_msg-- def strip(message):- message["data"].pop("settings", None)- return message-- with mock.patch.object(protocol, "hello_msg", lambda *a, **k: strip(older_hello(*a, **k))), \- mock.patch.object(protocol, "welcome_msg", lambda *a, **k: strip(older_welcome(*a, **k))):- self.both_links()- self.assertTrue(wait_for(lambda: self.duo.mac_server.peer_settings is False))- self.assertIs(self.duo.mac.peer_settings, False)- self.assertIs(self.duo.pc.peer_settings, False)+ self.rig.both_links()+ self.assertTrue(wait_for(lambda: self.rig.input.peer_settings is True))+ self.assertTrue(self.rig.controller.peer_settings)+ self.assertIn("settings", self.rig.pc_link.caps)+ self.assertTrue(wait_for(lambda: "settings" in (self.rig.machine.responder.caps_of(self.rig.mac_id) or ())))+++class AnOlderPeerTests(unittest.TestCase):+ def test_a_peer_without_the_settings_capability_is_known_as_one_on_either_link(self):+ rig = Rig(self, pc_caps=WITHOUT_SETTINGS)+ rig.both_links()+ self.assertTrue(wait_for(lambda: rig.input.peer_settings is False))+ self.assertIs(rig.controller.peer_settings, False)++ def test_nothing_is_sent_to_a_peer_that_does_not_keep_settings(self):+ rig = Rig(self, pc_caps=WITHOUT_SETTINGS)+ rig.both_links()+ self.assertTrue(wait_for(lambda: rig.input.peer_settings is False))+ data = rig.mac.state()+ self.assertFalse(rig.controller.send_settings(data))+ self.assertFalse(rig.input.send_settings(data))+ self.assertEqual(rig.pc.heard, [])++class AnnouncedOnLinkTests(unittest.TestCase):def test_the_arrangement_is_announced_when_a_link_comes_up(self):- # G1: a change made while nobody was connected reaches the other end on the next link.- self.duo.mac.announce = lambda: [protocol.arrangement_msg("top", 300), protocol.settings_msg(self.mac.state())]- self.duo.listen().link_mac_to_pc()- self.assertTrue(wait_for(lambda: ("top", 300) in self.duo.pc_arrangements))+ # A change made while nobody was connected reaches the other end on the next link.+ rig = Rig(self, side=("top", 300))+ rig.link_mac_to_pc()+ self.assertTrue(wait_for(lambda: any(read["edge"] == "top" and read["set_at"] == 300 for _, read in rig.machine.arrangements)))if __name__ == "__main__":diff --git a/mac_app/tests/test_settings_v6.py b/mac_app/tests/test_settings_v6.pynew file mode 100644index 0000000..1f787e5--- /dev/null+++ b/mac_app/tests/test_settings_v6.py@@ -0,0 +1,987 @@+"""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+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,+ "side": "left",+ "side_set_at": 1790000000,+ "side_by": machine_id,+ "paired_with": [],+ "paired_at": 0,+ "linked": False,+ "from_1_4": True,+ }])+ 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_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))+ self.assertEqual((first["side"], first["side_set_at"], first["side_by"]), ("bottom", 1790000500, after["machine_id"]))+ self.assertEqual((cfg.host, cfg.crossing["edge"]), ("192.0.2.99", "bottom"))++ def test_the_side_stamp_keeps_its_author_until_it_changes(self):+ settings = self.settings()+ settings["peers"][0].update(side_by=SECOND_ID)+ self.write_settings(settings)+ self.store.save(config_to_raw(self.cfg))+ self.assertEqual(self.settings()["peers"][0]["side_by"], SECOND_ID)+ raw = config_to_raw(self.cfg)+ raw["crossing"]["arrangement_set_at"] += 1+ self.store.save(raw)+ self.assertEqual(self.settings()["peers"][0]["side_by"], self.settings()["machine_id"])++ def test_an_arrangement_from_the_peer_is_stamped_with_the_peers_id_not_this_machines(self):+ raw = config_to_raw(self.cfg)+ raw["crossing"]["edge"] = "bottom"+ raw["crossing"]["arrangement_set_at"] = 1790000500+ self.store.save(raw, side_by=SECOND_ID)+ 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.settings()+ stamp = settings["peers"][0]["side_set_at"]+ settings["peers"][0].update(side_by=OTHER_ID_FOR_TIE)+ self.write_settings(settings)+ raw = config_to_raw(self.cfg)+ self.store.save(raw, side_by=SECOND_ID)+ self.assertEqual(self.settings()["peers"][0]["side_by"], SECOND_ID)+ self.assertEqual(self.settings()["peers"][0]["side_set_at"], stamp)++ 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["pc_name"] = "Renamed"+ self.store.save(raw)+ self.assertEqual(book.peers()[0]["name"], "Renamed")+ outcome, entry = book.admit(protocol.key_id(TOKEN), protocol.read_id(self.settings()["machine_id"]), protocol.read_id(PEER_ID), {"name": "Learnt"})+ self.assertEqual(self.settings()["peers"][0]["id"], PEER_ID)+ self.assertEqual(self.store.current()["peers"][0]["name"], "Learnt")++ def test_changing_the_methods_turns_zones_on_and_off(self):+ raw = config_to_raw(self.cfg)+ raw["crossing"]["methods"] = ["part", "notch"]+ raw["crossing"]["edge_parts"] = ["middle"]+ cfg = self.store.save(raw)+ settings = self.settings()+ self.assertFalse(settings["shortcut"])+ zones = {zone["kind"]: zone for zone in 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(cfg.crossing["methods"], ["part", "notch"])++ def test_the_corner_zones_edge_follows_the_corner_not_the_side(self):+ raw = config_to_raw(self.cfg)+ raw["crossing"]["edge"] = "top"+ raw["crossing"]["arrangement_set_at"] += 1+ self.store.save(raw)+ corner = [z for z in self.settings()["zones"] if z["kind"] == "corner"][0]+ self.assertEqual((corner["corner"], corner["edge"]), ("top_right", "right"))+ raw["crossing"]["corner"] = "bottom_left"+ self.store.save(raw)+ corner = [z for z in self.settings()["zones"] if z["kind"] == "corner"][0]+ self.assertEqual((corner["corner"], corner["edge"]), ("bottom_left", "left"))++ 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])+ self.assertEqual(after["zones"], [])+ 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"], [])++ 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)+ 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"], [])+++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_a_save_with_the_edge_and_the_thirds_on_turns_the_thirds_off(self):+ raw = config_to_raw(SettingsStore(self.path).load())+ raw["crossing"]["methods"] = ["edge", "part"]+ cfg = self.store.save(raw)+ self.assertEqual(cfg.crossing["methods"], ["edge"])+ zones = {z["kind"]: z for z in self.settings()["zones"]}+ self.assertTrue(zones["part"]["off"])+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_update_config_redirecting.py b/mac_app/tests/test_update_config_redirecting.pyindex 1d0d3bf..def9199 100644--- a/mac_app/tests/test_update_config_redirecting.py+++ b/mac_app/tests/test_update_config_redirecting.py@@ -1,3 +1,4 @@+import dataclassesimport unittestimport osimport sys@@ -5,7 +6,8 @@ import syssys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))from bridge import KVMController-from test_bridge import FakeClock, FakeQuartz, FakeSocket, crossing_config, link, quiet_logger+from bridge_fakes import PAIRED_TOKEN, FakeClock, FakeQuartz, crossing_config, quiet_logger+from fake_link import FakeLink, bring_upclass UpdateConfigWhileRedirectingTests(unittest.TestCase):@@ -16,20 +18,21 @@ class UpdateConfigWhileRedirectingTests(unittest.TestCase):def setUp(self):FakeQuartz.reset_cursor_spies()self.controller = KVMController(- crossing_config(),+ crossing_config(PAIRED_TOKEN),logger=quiet_logger(),quartz=FakeQuartz,clock=FakeClock(),+ link_factory=FakeLink,desktop_bounds=lambda: (0.0, 0.0, 1728.0, 1117.0),)- link(self.controller)+ self.link = bring_up(self.controller)def test_update_config_while_redirecting_restores_cursor_association(self):self.controller.set_redirecting(True)self.assertTrue(self.controller.redirecting)FakeQuartz.reset_cursor_spies()- self.controller.update_config(crossing_config())+ self.controller.update_config(crossing_config(PAIRED_TOKEN))self.assertFalse(self.controller.redirecting)self.assertIn(@@ -39,6 +42,18 @@ class UpdateConfigWhileRedirectingTests(unittest.TestCase):"when it forces redirecting False mid-redirect, same as set_redirecting(False) does",)+ def test_update_config_drops_a_link_dialled_to_an_address_that_is_no_longer_saved(self):+ cfg = self.controller.cfg+ self.link.dialled = (cfg.host, cfg.port)++ self.controller.update_config(dataclasses.replace(cfg))+ self.assertEqual(self.link.dropped, [])+ self.assertTrue(self.link.live())++ self.controller.update_config(dataclasses.replace(cfg, host="192.0.2.99"))+ self.assertEqual(self.link.dropped, ["Settings saved; reconnecting"])+ self.assertIs(self.controller._primary_link, self.link)+if __name__ == "__main__":unittest.main()diff --git a/mac_app/tests/test_wake.py b/mac_app/tests/test_wake.pyindex d7fe204..a4ff633 100644--- a/mac_app/tests/test_wake.py+++ b/mac_app/tests/test_wake.py@@ -1,7 +1,7 @@-import loggingimport threadingimport typesimport unittest+import unittest.mockimport osimport sys@@ -9,8 +9,10 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspaimport configimport wake-from test_bridge import FakeQuartz, quiet_logger-from wake import NOT_WOKEN_STATUS, WAKING_STATUS, WakingController, mac_from_arp_output, magic_packet, parse_mac+from bridge_fakes import PAIRED_TOKEN, FakeQuartz, quiet_logger+from core import protocol+from fake_link import FakeLink, bring_up+from wake import REFUSED_KINDS, WakingController, not_woken_status, waking_status, mac_from_arp_output, magic_packet, parse_macWINDOWS_ARP = """@@ -33,11 +35,14 @@ class FakeClock:return self.value+PEER = "192.0.2.10"++def make_config(mac="02:1A:2B:3C:0D:4E"):return config.Config(host="192.0.2.10",port=51820,- auth_token="synthetic-token",+ auth_token=PAIRED_TOKEN,reconnect_interval_s=0.1,mac_address=mac,)@@ -85,9 +90,6 @@ class WakingControllerTests(unittest.TestCase):self.sent = []self.learned = []- def socket_factory(address, timeout):- raise OSError("synthetic: host asleep")-self.controller = WakingController(make_config(),wake_sender=lambda mac, host: self.sent.append((mac, host)),@@ -95,8 +97,9 @@ class WakingControllerTests(unittest.TestCase):logger=quiet_logger(),quartz=FakeQuartz,clock=self.clock,- socket_factory=socket_factory,+ link_factory=FakeLink,)+ self.link = self.controller._primary_linkself.controller.WAKE_POLL_SECONDS = 0.01self.alerts = []self.controller.on_user_alert = lambda title, message: self.alerts.append(message)@@ -107,14 +110,24 @@ class WakingControllerTests(unittest.TestCase):if thread.name == "wake":thread.join(timeout=5)- def test_a_pc_that_refused_the_token_is_not_woken(self):- from bridge import AUTH_FAILED_STATUS+ def test_a_pc_that_answered_and_refused_is_not_woken(self):+ for kind in REFUSED_KINDS:+ with self.subTest(kind=kind):+ self.link.kind = kind+ self.assertFalse(self.controller.set_redirecting(True))+ self._wait_for_wake_thread()+ self.assertEqual(self.sent, [])+ self.assertFalse(self.controller.waking)- self.controller.connection_status = AUTH_FAILED_STATUS- self.assertFalse(self.controller.set_redirecting(True))- self._wait_for_wake_thread()- self.assertEqual(self.sent, [])- self.assertFalse(self.controller.waking)+ def test_a_pc_that_did_not_answer_is_woken_for_every_other_kind(self):+ self.controller.stop_event.set()+ for kind in ("unreachable", "timeout", "stopped", "closed", "failed"):+ with self.subTest(kind=kind):+ self.sent.clear()+ self.link.kind = kind+ self.assertFalse(self.controller.set_redirecting(True))+ self._wait_for_wake_thread()+ self.assertEqual(len(self.sent), 1)def test_switch_while_unreachable_sends_the_packet_and_shows_waking(self):# The wake thread must see the packet as sent before the window is checked.@@ -124,28 +137,28 @@ class WakingControllerTests(unittest.TestCase):self.assertEqual(self.sent, [("02:1A:2B:3C:0D:4E", "192.0.2.10")])self.assertFalse(self.controller.redirecting)self.assertTrue(self.controller.outbound.empty())- self.assertIn(WAKING_STATUS, self.alerts)+ self.assertIn(waking_status(PEER), self.alerts)def test_gives_up_after_the_window_with_nothing_queued(self):self.assertTrue(self.controller.wake())self.assertTrue(self.controller.waking)- self.assertEqual(self.controller.connection_status, WAKING_STATUS)+ self.assertEqual(self.controller.connection_status, waking_status(PEER))self.assertFalse(self.controller.wake(), "a second wake while one is in flight is refused")self.clock.value += wake.WAKE_WINDOW_SECONDSself._wait_for_wake_thread()self.assertFalse(self.controller.waking)- self.assertEqual(self.controller.connection_status, NOT_WOKEN_STATUS)- self.assertEqual(self.alerts[-1], NOT_WOKEN_STATUS)+ self.assertEqual(self.controller.connection_status, not_woken_status(PEER))+ self.assertEqual(self.alerts[-1], not_woken_status(PEER))self.assertEqual(len(self.sent), 1)self.assertTrue(self.controller.outbound.empty())def test_status_written_underneath_a_wake_shows_through_afterwards(self):self.controller.wake()self.controller.connection_status = "Windows is unreachable from this Mac"- self.assertEqual(self.controller.connection_status, WAKING_STATUS)+ self.assertEqual(self.controller.connection_status, waking_status(PEER))self.clock.value += wake.WAKE_WINDOW_SECONDSself._wait_for_wake_thread()- self.assertEqual(self.controller.connection_status, NOT_WOKEN_STATUS)+ self.assertEqual(self.controller.connection_status, not_woken_status(PEER))def test_without_a_hardware_address_the_switch_fails_as_before(self):controller = WakingController(@@ -154,6 +167,7 @@ class WakingControllerTests(unittest.TestCase):logger=quiet_logger(),quartz=FakeQuartz,clock=self.clock,+ link_factory=FakeLink,)controller.on_user_alert = lambda title, message: self.alerts.append(message)self.assertFalse(controller.set_redirecting(True))@@ -161,67 +175,112 @@ class WakingControllerTests(unittest.TestCase):self.assertFalse(controller.can_wake)self.assertTrue(self.alerts[0].startswith("Cannot switch"))- def test_successful_connection_learns_and_reports_a_new_address(self):- from test_bridge import FakeSocket, seed_receiver_reply- from core import protocol+ def test_a_slow_address_lookup_does_not_hold_the_link_up_callback(self):+ release = threading.Event()+ self.controller.mac_lookup = lambda host: release.wait(5) and None+ done = threading.Event()+ threading.Thread(target=lambda: (bring_up(self.controller), done.set()), daemon=True).start()+ try:+ self.assertTrue(done.wait(1.0), "the link's up callback waited for the address lookup")+ finally:+ release.set()++ def test_a_primary_link_up_cannot_overwrite_a_settings_change_made_meanwhile(self):+ newer = make_config()+ newer.reconnect_interval_s = 7.0+ import bridge as bridge_module++ def racing_replace(cfg, **changes):+ result = real(cfg, **changes)+ thread = threading.Thread(target=lambda: self.controller.apply_settings(newer))+ thread.start()+ thread.join(0.3)+ return result++ real = bridge_module.dataclasses.replace+ with unittest.mock.patch.object(bridge_module.dataclasses, "replace", racing_replace):+ with self.controller.book.lock:+ self.controller.book.data["peers"][0]["host"] = "192.0.2.88"+ bring_up(self.controller)+ self._wait_for_learning()+ self.assertIs(self.controller.cfg, newer)++ def _wait_for_learning(self):+ for thread in threading.enumerate():+ if thread.name == "Beamer-learn-mac":+ thread.join(timeout=5)- sock = FakeSocket()- seed_receiver_reply(sock, protocol.welcome_msg())- self.controller.socket_factory = lambda address, timeout: sock- self.assertTrue(self.controller._connect_once())+ def test_successful_connection_learns_and_reports_a_new_address(self):+ bring_up(self.controller)+ self._wait_for_learning()self.assertEqual(self.learned, ["AA:BB:CC:DD:EE:FF"])self.assertEqual(self.controller.cfg.mac_address, "AA:BB:CC:DD:EE:FF")+ self.assertTrue(self.controller.connected)self.assertFalse(self.controller.can_wake)+ def test_the_address_is_looked_up_at_the_host_the_link_dialled(self):+ asked = []+ self.controller.mac_lookup = lambda host: asked.append(host)+ with self.controller.book.lock:+ self.controller.book.data["peers"][0]["host"] = "192.0.2.99"+ bring_up(self.controller)+ self._wait_for_learning()+ self.assertEqual(asked, ["192.0.2.99"])++ def test_an_address_the_table_already_agrees_with_is_not_reported(self):+ self.controller.mac_lookup = lambda host: "02:1A:2B:3C:0D:4E"+ bring_up(self.controller)+ self._wait_for_learning()+ self.assertEqual(self.learned, [])+class ComingHomeThroughTheAppsControllerTests(unittest.TestCase):"""The app runs WakingController, so every way home the base class takes must pass through it."""def make(self):- def refuse(address, timeout):- raise OSError("unreachable")-controller = WakingController(make_config(), logger=quiet_logger(), quartz=FakeQuartz, clock=FakeClock(),- socket_factory=refuse)- controller.redirecting = True- return controller+ link_factory=FakeLink, desktop_bounds=lambda: (0, 0, 1920, 1080))+ link = bring_up(controller)+ self.assertTrue(controller.set_redirecting(True))+ return controller, linkdef test_the_pc_sending_input_home_returns_it(self):- controller = self.make()- controller._handle_switch({"target": "mac"})+ controller, link = self.make()+ link.arrives(controller, protocol.switch_v6(1, bytes(controller.identity()["id"])))self.assertFalse(controller.redirecting)def test_the_pc_taking_this_mac_over_ends_the_redirect(self):- controller = self.make()+ controller, _ = self.make()controller.set_receiving(True)self.assertFalse(controller.redirecting)self.assertTrue(controller.receiving)+ def test_a_dropped_link_returns_input_without_waking_anything(self):+ woken = []+ controller, link = self.make()+ controller.wake_sender = lambda mac, host: woken.append(mac)+ link.down(controller)+ self.assertFalse(controller.redirecting)+ self.assertEqual(woken, [])-class FollowingAMovedPcThroughTheAppsControllerTests(unittest.TestCase):- def test_the_app_controller_takes_the_new_address(self):- from test_bridge import FakeSocket, seed_receiver_reply- from core import protocol-- sock = FakeSocket()- seed_receiver_reply(sock, protocol.welcome_msg())-- def socket_factory(address, timeout):- if address[0] == "192.0.2.10":- raise ConnectionRefusedError("gone")- return sock+class FollowingAMovedPcThroughTheAppsControllerTests(unittest.TestCase):+ def test_the_app_controller_offers_the_beacons_and_takes_the_new_address(self):cfg = make_config()cfg.pc_name = "STUDIO-PC"controller = WakingController(cfg, logger=quiet_logger(), quartz=FakeQuartz, clock=FakeClock(),- socket_factory=socket_factory, mac_lookup=lambda host: None)- controller.discovery = types.SimpleNamespace(pcs=lambda: [- {"name": "STUDIO-PC", "address": "192.0.2.77", "port": cfg.port, "reply_port": 24821, "pair_id": None}])+ link_factory=FakeLink, mac_lookup=lambda host: None)+ beacons = [{"name": "STUDIO-PC", "address": "192.0.2.77", "port": cfg.port, "reply_port": 24821, "pair_id": None}]+ controller.discovery = types.SimpleNamespace(pcs=lambda: beacons)learned = []controller.on_host_learned = learned.append- self.assertFalse(controller._connect_once())- controller._follow_the_pc()+ controller._follow_the_peers()+ self.assertEqual(controller._primary_link.followed, [beacons])+ with controller.book.lock:+ controller.book.data["peers"][0]["host"] = "192.0.2.77"+ bring_up(controller)self.assertEqual(learned, ["192.0.2.77"])+ self.assertEqual(controller.cfg.host, "192.0.2.77")if __name__ == "__main__":diff --git a/mac_app/tests/test_way_home.py b/mac_app/tests/test_way_home.pyindex f027f83..92bfc73 100644--- a/mac_app/tests/test_way_home.py+++ b/mac_app/tests/test_way_home.py@@ -1,83 +1,231 @@+"""The way home for a machine driving this Mac: the zones this Mac's own settings carry, armed by+the responder while that machine's input is here. settings_store writes them from the Crossing+page's choices, core.receiver.zone_models turns them into the pointer models, and+WindowsInput.sync rebuilds them when a setting changes."""+import os+import socketimport sys-import threading+import tempfile+import timeimport unittest-from types import SimpleNamespace+from pathlib import Pathfrom unittest import mock-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__)))))-from core import return_edge+import settings_store+from bridge import KVMController+from bridge_fakes import PAIRED_TOKEN, FakeClipboard, FakeQuartz, quiet_logger+from core import protocol, receiver, return_edge+from core.tests import responder_harness as harnessfrom windows_input import WindowsInput+PEER = harness.B+PEER_TEXT = protocol.id_text(PEER)+NOTCH = (656.0, 856.0)+-def model(methods, parts=("middle",), corner="top_right", edge="right", notch_range=(656.0, 856.0)):+def zones(methods, parts=("middle",), corner="top_right"):crossing = {"methods": list(methods), "edge_parts": list(parts), "corner": corner}- owner = SimpleNamespace(_controller=SimpleNamespace(cfg=SimpleNamespace(crossing=crossing), notch_range=notch_range))- return WindowsInput._return_model(owner, edge, 120)+ return settings_store._apply_zones([], PEER_TEXT, crossing)+++def models(methods, parts=("middle",), corner="top_right", edge="right", notch=lambda: NOTCH, allowed=(PEER,)):+ peers = [{"id": PEER_TEXT, "side": edge}]+ return [model for _, model in receiver.zone_models(zones(methods, parts, corner), peers, set(allowed), 120, notch)]def crosses_at(armed, x):"""Whether a hard push up at `x` along the top of a 1512x982 display goes home."""display = [return_edge.Rect(0, 0, 1512, 982)]- return any(armed.feed(display, (x, 0), 0, -40).action == return_edge.CROSS for _ in range(20))+ return any(model.feed(display, (x, 0), 0, -40).action == return_edge.CROSS for model in armed for _ in range(20))class WayHomeFollowsThisMacTests(unittest.TestCase):"""The PC's pointer comes home through this Mac's edge as this Mac's own settings say."""def test_part_of_the_edge_arms_only_its_thirds(self):- armed = model(["part", "shortcut"], parts=("start",))- self.assertIsInstance(armed, return_edge.PartEdge)- self.assertEqual(armed.parts, frozenset({"start"}))+ armed = models(["part", "shortcut"], parts=("start",))+ self.assertEqual([type(model) for model in armed], [return_edge.PartEdge])+ self.assertEqual(armed[0].parts, frozenset({"start"}))+ self.assertEqual(armed[0].edge, "right")def test_the_whole_edge(self):- self.assertEqual(type(model(["edge"])), return_edge.ReturnEdge)+ armed = models(["edge"])+ self.assertEqual([type(model) for model in armed], [return_edge.ReturnEdge])+ self.assertEqual(armed[0].edge, "right")+ self.assertEqual(armed[0].resistance_px, 120)++ def test_the_whole_edge_stands_in_for_its_thirds(self):+ self.assertEqual([type(model) for model in models(["edge", "part"])], [return_edge.ReturnEdge])def test_the_notch_arms_only_the_notch(self):- # Toby, 28-09-2026: with only the notch and the shortcut on, the PC's pointer went home+ # Reported 28-09-2026: with only the notch and the shortcut on, the PC's pointer went home# anywhere along the Mac's top edge.- self.assertTrue(crosses_at(model(["notch", "shortcut"], edge="top"), 756))- self.assertFalse(crosses_at(model(["notch", "shortcut"], edge="top"), 200))- self.assertFalse(crosses_at(model(["notch", "shortcut"], edge="top"), 1300))- self.assertIsNone(model(["notch", "shortcut"], edge="right"))+ armed = models(["notch", "shortcut"], edge="top")+ self.assertEqual([type(model) for model in armed], [return_edge.SpanEdge])+ self.assertTrue(crosses_at(armed, 756))+ self.assertFalse(crosses_at(models(["notch", "shortcut"], edge="top"), 200))+ self.assertFalse(crosses_at(models(["notch", "shortcut"], edge="top"), 1300))++ def test_the_notch_crosses_the_top_edge_whichever_side_the_pc_is_on(self):+ # WIRE.md section 8: a notch zone is the Mac's notch and crosses the top edge. 1.4.x left+ # no way home by the pointer when the PC faced another edge.+ armed = models(["notch", "shortcut"], edge="right")+ self.assertEqual([(type(model), model.edge) for model in armed], [(return_edge.SpanEdge, "top")])++ def test_without_a_measured_notch_there_is_no_notch_zone(self):+ self.assertEqual(models(["notch", "shortcut"], edge="top", notch=None), [])def test_the_notch_is_read_at_each_push(self):# A focus that arrives before the first measurement, or across a display change, must not# leave the pointer without its way home for the rest of the session.- controller = SimpleNamespace(cfg=SimpleNamespace(crossing={"methods": ["notch", "shortcut"]}), notch_range=None)- armed = WindowsInput._return_model(SimpleNamespace(_controller=controller), "top", 120)+ held = {"span": None}+ armed = models(["notch", "shortcut"], edge="top", notch=lambda: held["span"])self.assertFalse(crosses_at(armed, 756))- controller.notch_range = (656.0, 856.0)+ held["span"] = NOTCHself.assertTrue(crosses_at(armed, 756))def test_the_whole_edge_still_wins_over_the_notch(self):- self.assertTrue(crosses_at(model(["edge", "notch"], edge="top"), 200))-- def test_a_corner_on_that_edge(self):- self.assertIsInstance(model(["corner"], corner="top_right"), return_edge.CornerPush)- self.assertIsNone(model(["corner"], corner="top_left"))+ armed = models(["edge", "notch"], edge="top")+ self.assertEqual([type(model) for model in armed], [return_edge.ReturnEdge, return_edge.SpanEdge])+ self.assertTrue(crosses_at(armed[:1], 200))++ def test_a_corner_is_the_corner_push_on_the_edge_it_touches(self):+ # 1.4.x armed a corner only when it sat on the edge facing the PC. A corner zone now names+ # its own edge (WIRE.md section 8: a Mac's crosses by the corner's own left or right edge,+ # whatever the side), so it is armed whichever side the PC is on.+ for corner, edge in (("top_right", "right"), ("top_left", "left"), ("bottom_right", "right")):+ with self.subTest(corner=corner):+ armed = models(["corner"], corner=corner, edge="right")+ self.assertEqual([type(model) for model in armed], [return_edge.CornerPush])+ self.assertEqual((armed[0].corner, armed[0].edge), (corner, edge))++ def test_a_corner_is_checked_before_the_edge_it_sits_in(self):+ armed = models(["corner", "edge"])+ self.assertEqual([type(model) for model in armed], [return_edge.CornerPush, return_edge.ReturnEdge])def test_the_shortcut_alone_leaves_no_way_home_by_the_pointer(self):- self.assertIsNone(model(["shortcut"]))---class CrossingChangesReachTheWayHomeTests(unittest.TestCase):- def test_a_change_to_the_ways_in_rebuilds_the_way_home_once(self):- # Toby, 28-09-2026: a change to Part of the edge applied only after crossing out and back.- owner = SimpleNamespace(server=mock.Mock(input_scale=None), _ways=None, _running_for=None, _lock=threading.RLock())- crossing = {"methods": ["part"], "edge_parts": ["start"], "corner": "top_right"}- cfg = SimpleNamespace(pointer_speed=1.0, scroll_speed=1.0, reverse_scroll=False,- allow_windows_to_drive=False, crossing=crossing)- WindowsInput.sync(owner, cfg)- WindowsInput.sync(owner, cfg)- self.assertEqual(owner.server.rearm_return.call_count, 1)- crossing["edge_parts"] = ["end"]- WindowsInput.sync(owner, cfg)- self.assertEqual(owner.server.rearm_return.call_count, 2)-+ self.assertEqual(models(["shortcut"]), [])++ def test_a_machine_that_is_not_driving_has_no_zones_armed(self):+ self.assertEqual(models(["edge", "part", "corner", "notch"], allowed=()), [])++ def test_a_peer_with_no_side_has_no_edge_or_thirds_but_keeps_its_corner_and_notch(self):+ armed = models(["edge", "corner", "notch"], edge="")+ self.assertEqual([type(model) for model in armed], [return_edge.CornerPush, return_edge.SpanEdge])+++class SyncRearmsTheZonesTests(unittest.TestCase):+ def test_a_sync_tells_the_responder_to_rebuild_the_zones_only_when_the_peers_or_zones_changed(self):+ controller = KVMController(+ settings_store.editable_default_config(), logger=quiet_logger(), quartz=FakeQuartz, clipboard=FakeClipboard(),+ desktop_bounds=lambda: (0, 0, 1920, 1080),+ )+ wire = WindowsInput(controller)+ self.addCleanup(wire.server.stop)+ wire.server = mock.Mock(input_scale=None, listening=True)+ cfg = controller.cfg+ wire.sync(cfg)+ wire.server.start.assert_called_once_with(cfg.port)+ wire.server.rearm.assert_not_called()+ wire.sync(cfg)+ wire.sync(cfg)+ wire.server.rearm.assert_not_called()+ with controller.book.lock:+ controller.book.data["zones"] = [{"peer": "", "kind": "edge"}]+ wire.sync(cfg)+ wire.sync(cfg)+ self.assertEqual(wire.server.rearm.call_count, 1)+ self.assertEqual(wire.server.peers_changed.call_count, 1)+++class ChangesReachTheArmedZonesTests(unittest.TestCase):+ """A real responder with a peer driving this Mac: the zones armed for it follow the settings."""++ def setUp(self):+ folder = Path(tempfile.mkdtemp())+ self.store = settings_store.SettingsStore(folder / "settings.json")+ cfg = self.store.load()+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ port = probe.getsockname()[1]+ self.cfg = self.store.save({**settings_store.config_to_raw(cfg), "host": "127.0.0.1", "port": port,+ "auth_token": PAIRED_TOKEN, "pc_name": "Driver"})+ self.set_crossing(["edge", "shortcut"], ("middle",))+ self.controller = KVMController(+ self.cfg, logger=quiet_logger(), quartz=FakeQuartz, clipboard=FakeClipboard(), book=self.store.book(),+ identity=lambda: {"id": protocol.read_id(self.store.current()["machine_id"]), "name": "This Mac",+ "platform": "macos", "app": "1.5.0", "caps": ["clipboard", "text", "settings"], "port": port},+ desktop_bounds=lambda: (0, 0, 1920, 1080),+ )+ self.wire = WindowsInput(self.controller)+ self.wire.server._injector = harness.FakeInjector()+ self.wire.server._desktop = harness.FakeDesktop()+ self.wire.server._clipboard = harness.FakeClipboard()+ self.wire.sync(self.cfg)+ self.addCleanup(self.wire.stop)+ self.addCleanup(self.controller.stop)+ def accepting():+ try:+ with socket.create_connection(("127.0.0.1", port), timeout=0.2):+ return True+ except OSError:+ return False++ self.assertTrue(harness.wait_for(accepting), "the Mac did not listen")+ self.driver = harness.Initiator(type("Far", (), {"port": port})(), peer=PEER, key=PAIRED_TOKEN)+ self.addCleanup(self.driver.close)+ self.mac_id = protocol.read_id(self.store.current()["machine_id"])+ self.driver.handshake(self.driver.hello(platform="windows"))+ self.driver.send(protocol.focus_v6(1, self.mac_id, resistance_px=120, reach=[]))+ self.assertEqual(self.driver.answer(1)[0], protocol.MSG_ACCEPT)+ self.assertTrue(harness.wait_for(lambda: self.controller.receiving))++ def set_crossing(self, methods, parts, corner="top_right"):+ settings = self.store.current()+ settings["peers"][0].update(id=PEER_TEXT, side="right", send=False)+ settings["zones"] = zones(methods, parts, corner)+ self.store.save_settings(settings)++ def armed(self):+ return [model for _, model in self.wire.server._armed]++ def test_the_zones_armed_are_the_ones_the_settings_carry(self):+ self.assertEqual([type(model) for model in self.armed()], [return_edge.ReturnEdge])++ def test_a_change_to_the_ways_applies_at_the_next_sync_while_the_peer_is_here(self):+ # Reported 28-09-2026: a change to Part of the edge applied only after crossing out and back.+ self.set_crossing(["part", "shortcut"], ("start",))+ self.wire.sync(self.cfg)+ armed = self.armed()+ self.assertEqual([type(model) for model in armed], [return_edge.PartEdge])+ self.assertEqual(armed[0].parts, frozenset({"start"}))+ self.set_crossing(["part", "shortcut"], ("end",))+ self.wire.sync(self.cfg)+ self.assertEqual(self.armed()[0].parts, frozenset({"end"}))++ def push_right(self, dx):+ self.wire.server._desktop.cursor = (1919, 540)+ self.driver.move(dx, 0)+ time.sleep(0.1)++ def sent_home(self):+ return self.driver.expect(protocol.MSG_SWITCH, timeout=0.5) is not None++ def test_two_pushes_that_add_up_to_the_resistance_cross(self):+ self.push_right(80)+ self.push_right(80)+ self.assertTrue(self.sent_home())++ def test_a_sync_between_two_pushes_does_not_lose_the_first(self):+ # The status tick calls sync every 0.4 s: a rebuilt model starts with no pressure, so a+ # push in progress would lose its travel at each tick.+ self.push_right(80)+ self.wire.sync(self.cfg)+ self.push_right(80)+ self.assertTrue(self.sent_home())if __name__ == "__main__":unittest.main()diff --git a/mac_app/tests/two_machines.py b/mac_app/tests/two_machines.pyindex 74d2e29..511f118 100644--- a/mac_app/tests/two_machines.py+++ b/mac_app/tests/two_machines.py@@ -1,45 +1,45 @@-"""Both apps' real link code against each other over loopback, for the crossing matrix.+"""The Mac's real code at both ends of a loopback pair, for the crossing matrix, the replay tests and the loopback tests.-The Mac is a real KVMController, driven through its event-tap callback with FakeQuartz; the PC is a-real MacSender, driven through its hook entry points. Each machine also runs the shared-ReceiverServer that the other one's link connects to, as it does in the apps. Only the platform-edges are faked: the pointer, the injector, the clipboard and the display geometry.+The Mac is a real KVMController, driven through its event-tap callback with FakeQuartz, over a real+core.link.OutboundLink to `pc_responder`, a core.receiver.LinkResponder on loopback with fakes for+its injector, desktop and clipboard (core/tests/responder_harness.Machine, platform "windows").+That is the Mac driving the PC.-win_app's modules are put on the path after this app's, so the PC's own (`sender`, `app_config`)-resolve to the PC's; what both share comes from core.-"""+The other direction is the Mac driven: windows_input.WindowsInput wires the Mac's real+LinkResponder to the controller, with the Mac's injector, desktop and clipboard swapped for fakes+(patched into windows_input's module names while it is built, so no product code differs), and+`pc` is a scripted version 6 initiator (responder_harness.Initiator) standing in for the PC's own+link. The PC is one machine with one pairing: both directions run under PAIRED_TOKEN and the+PC's one id. win_app is not involved: the PC's own half is step 5b's.+Settings live in a real SettingsStore in a temporary folder, so the controller's book and the+Mac's responder read what the app would."""++import copyimport osimport socketimport sys+import tempfileimport time--_APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))-_WIN = os.path.join(os.path.dirname(_APP), "win_app")-for _path in (_WIN, os.path.join(_WIN, "tests")):- if _path not in sys.path:- sys.path.append(_path)+import types+from pathlib import Path+from unittest import mocksys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+import windows_input+from bridge import KVMController+import bridge_fakes+from bridge_fakes import PAIRED_TOKEN, FakeClock, FakeQuartz, crossing_config, quiet_loggerfrom core import protocol-from core import receiverfrom core.return_edge import Rect+from core.tests.responder_harness import HERE, FakeDesktop, FakeInjector, Initiator, Machine, entry+from settings_store import SettingsStore-import app_config-import sender as pc_sender_module-from bridge import KVMController-from fakes import FakeClipboard, FakeDesktop, FakeInjector-from test_bridge import FakeClock, FakeQuartz, crossing_config, quiet_logger--TOKEN = "matrix-token"MAC_BOUNDS = (0, 0, 1728, 1117)PC_MONITORS = [Rect(0, 0, 1920, 1080)]---class NoUnlock:- def is_locked(self):- return None+OPPOSITE = {"left": "right", "right": "left", "top": "bottom", "bottom": "top"}+PC_TEXT = protocol.id_text(HERE)def free_port():@@ -54,128 +54,144 @@ def wait_for(predicate, timeout=5.0):if predicate():return Truetime.sleep(0.01)- return False+ return bool(predicate())class Duo:- """`crossing` is the Mac's crossing settings, `pc` the PC's Config fields. The two links are- started separately: `link_mac_to_pc()` is the Mac's own link to the PC, `link_pc_to_mac()` is- the PC's link to the Mac, and each can be left down."""-- def __init__(self, crossing=None, pc=None, mac_cfg=None, pc_monitors=None, mac_bounds=MAC_BOUNDS):+ """`crossing` is the Mac's crossing settings (its own engine); `side` the Mac edge that faces the+ PC as the Mac's book keeps it, which is the crossing's `edge` unless given; `mac_zones` the+ zones the Mac's responder arms for the PC while the PC drives it, and `pc_zones` the PC's for+ the Mac; `pc_side` the PC edge that faces the Mac. All default to the whole edge facing the+ other machine, and `side=""` is a Mac that has learnt no side for the PC. `allow_drive` is the+ Mac's setting for the PC driving it, `side_stamp` and `side_by` how the Mac's book dates its+ side. A zone's `peer` may be written "mac" or "pc" for the ids the store makes. Nothing starts until `listen()` and the `link_*` calls: the Mac's responder listens, the+ Mac's own link to the PC, and the PC's link to the Mac, each can be left down."""++ def __init__(self, crossing=None, mac_cfg=None, side=None, mac_zones=None, pc_zones=None, pc_side=None,+ mac_bounds=MAC_BOUNDS, pc_monitors=None, notch=None, pc_notch=None, allow_drive=True,+ side_stamp=0, side_by="", socket_factory=socket.create_connection):FakeQuartz.reset_cursor_spies()self.clock = FakeClock()self.feedback = []+ self.alerts = []+ self.mac_arrangements = []+ self.mac_arrivals = []self.mac_bounds = mac_boundsself.mac_port = free_port()- self.pc_port = free_port()- while self.pc_port == self.mac_port:- self.pc_port = free_port()+ self.dir = tempfile.TemporaryDirectory()+ self.store = SettingsStore(Path(self.dir.name) / "settings.json")+ self.mac_id = protocol.read_id(self.store.current()["machine_id"])+ self.mac_text = protocol.id_text(self.mac_id)- self.mac_desktop = FakeDesktop([Rect(*self._rect(mac_bounds))], cursor=(800, 500))- self.pc_desktop = FakeDesktop(pc_monitors or PC_MONITORS, cursor=(900, 500))- self.mac_injector = FakeInjector()- self.pc_injector = FakeInjector()- self.mac_peer = []- self.pc_peer = []- self.mac_arrangements = []- self.pc_arrangements = []-- cfg = mac_cfg or crossing_config(**(crossing or {}))- cfg.host, cfg.port, cfg.auth_token = "127.0.0.1", self.pc_port, TOKEN+ cfg = mac_cfg or crossing_config(PAIRED_TOKEN, **(crossing or {}))+ cfg.host, cfg.port, cfg.auth_token = "127.0.0.1", self.mac_port, PAIRED_TOKENcfg.reconnect_interval_s = 0.05+ self.side = cfg.crossing["edge"] if side is None else side+ self.pc_side = pc_side if pc_side is not None else OPPOSITE.get(self.side, "")++ self.pc_desktop = FakeDesktop(pc_monitors or PC_MONITORS, cursor=(900, 500))+ self.pc_responder = Machine(+ [entry(self.mac_id, "Mac", platform="macos", token=PAIRED_TOKEN, host="127.0.0.1", port=self.mac_port,+ side=self.pc_side)],+ self._named(pc_zones if pc_zones is not None else [{"peer": "mac", "kind": "edge"}]),+ desktop=self.pc_desktop, notch_span=(lambda: pc_notch) if pc_notch else None,+ ).start()+ self.pc_injector = self.pc_responder.injector++ settings = copy.deepcopy(self.store.current())+ settings["peers"] = [entry(HERE, "PC", platform="windows", token=PAIRED_TOKEN, host="127.0.0.1",+ port=self.pc_responder.port, side=self.side, side_set_at=side_stamp, side_by=side_by,+ allow_drive=allow_drive)]+ settings["zones"] = self._named(mac_zones if mac_zones is not None else [{"peer": "pc", "kind": "edge"}])+ self.store.save_settings(settings)++ # The one pasteboard the controller and the Mac's responder share, as on a real Mac.+ self.clipboard = bridge_fakes.FakeClipboard("on the Mac")self.mac = KVMController(- cfg, logger=quiet_logger(), quartz=FakeQuartz, clock=self.clock, desktop_bounds=lambda: self.mac_bounds+ cfg, logger=quiet_logger(), quartz=FakeQuartz, clock=self.clock, desktop_bounds=lambda: self.mac_bounds,+ book=self.store.book(), socket_factory=socket_factory, clipboard=self.clipboard,)self.mac.on_crossing = lambda kind, step: self.feedback.append((kind, step))- self.mac.on_user_alert = lambda title, message: None- self.mac_arrivals = []+ self.mac.on_user_alert = lambda title, message: self.alerts.append(message)+ self.mac.on_arrangement = lambda edge, set_at, by: self.mac_arrangements.append((edge, set_at, by))+ self.mac.notch_range = notch- pc_fields = dict(- host="127.0.0.1",- port=self.mac_port,- auth_token=TOKEN,- mac_host="127.0.0.1",- mac_return_edge="left",- crossing_resistance_px=40,- mac_resistance_px=40,- )- pc_fields.update(pc or {})- self.pc_config = app_config.Config(**pc_fields)- self.pc = pc_sender_module.MacSender(- desktop=self.pc_desktop, clipboard=FakeClipboard(), is_local=lambda host: False- )- self.pc_arrivals = []- self.pc._arrival_callback = lambda edge, x, y: self.pc_arrivals.append((edge, x, y))- self.pc._arrangement_callback = lambda edge, set_at: self.pc_arrangements.append((edge, set_at))- self.mac.on_arrangement = lambda edge, set_at: self.mac_arrangements.append((edge, set_at))- self.pc_pressure = []- self.pc._pressure_callback = lambda edge, pressure, crossed, part: self.pc_pressure.append((edge, crossed))-- # The PC's receiver: what the Mac's link connects to.- self.pc_server = receiver.ReceiverServer(- status_callback=lambda state, detail: None,- clipboard=FakeClipboard(),- unlock=NoUnlock(),- desktop=self.pc_desktop,- injector=self.pc_injector,- focus_callback=lambda target: self.pc.set_receiving(target == "windows"),- peer_callback=lambda *args: self.pc_peer.append(args),- arrangement_callback=lambda edge, set_at: self.pc_arrangements.append((edge, set_at)),- )- self.pc.send_peer_home = self.pc_server.send_home- # The Mac's receiver: what the PC's link connects to.- self.mac_server = receiver.ReceiverServer(- status_callback=lambda state, detail: None,- clipboard=FakeClipboard(),- unlock=NoUnlock(),- desktop=self.mac_desktop,- injector=self.mac_injector,- focus_callback=lambda target: self.mac.set_receiving(target == "mac"),- peer_callback=lambda *args: self.mac_peer.append(args),- arrangement_callback=lambda edge, set_at: self.mac_arrangements.append((edge, set_at)),- arrival_callback=lambda edge, x, y: self.mac_arrivals.append((edge, x, y)),- self_name="Mac",- peer_name="PC",- self_target="mac",- peer_target="windows",- )- self.mac.send_peer_home = self.mac_server.send_home+ left, top, right, bottom = mac_bounds+ self.mac_desktop = FakeDesktop([Rect(left, top, right - left, bottom - top)], cursor=(800, 500))+ self.mac_injector = FakeInjector()+ with mock.patch.multiple(+ windows_input, input_injector_mac=self.mac_injector, desktop_mac=self.mac_desktop, clipboard_mac=self.clipboard+ ):+ self.mac_input = windows_input.WindowsInput(+ self.mac, logger=quiet_logger(),+ arrangement_callback=lambda edge, set_at, by: self.mac_arrangements.append((edge, set_at, by)),+ arrival_callback=lambda edge, x, y: self.mac_arrivals.append((edge, x, y)),+ )+ self.mac_responder = self.mac_input.server+ self.pc = None+ self.cfg = cfgself._started = False+ self._closed = False- @staticmethod- def _rect(bounds):- left, top, right, bottom = bounds- return left, top, right - left, bottom - top+ def _named(self, zones):+ """Zones written with `"peer": "mac"` or `"pc"`, which are ids only once the store has made them."""+ names = {"mac": self.mac_text, "pc": PC_TEXT}+ return [{**zone, "peer": names.get(zone["peer"], zone["peer"])} for zone in zones]# -- links ---------------------------------------------------------------def listen(self):- """Both receivers, as they run whenever the app is open."""- self.pc_server.start(app_config.Config(host="127.0.0.1", port=self.pc_port, auth_token=TOKEN))- from config import Config as MacConfig-- self.mac_server.start(MacConfig(host="127.0.0.1", port=self.mac_port, auth_token=TOKEN))+ """The Mac's responder, as it runs whenever the app is open."""+ self.mac_input.sync(self.cfg)+ assert wait_for(lambda: self.mac_responder.listening), "the Mac's responder never listened"+ assert wait_for(self._accepting), "the Mac's responder never accepted"return self+ def _accepting(self):+ try:+ with socket.create_connection(("127.0.0.1", self.mac_port), timeout=0.2):+ return True+ except OSError:+ return False+def link_mac_to_pc(self):"""The Mac's own link to the PC, up before this returns."""if not self._started:self.mac.start()self._started = Trueassert wait_for(lambda: self.mac.connected), f"the Mac never connected: {self.mac.connection_status}"+ # `connected` is the link's handshake; the controller knows the peer a beat later.+ assert wait_for(lambda: PC_TEXT in self.mac._peers_up), "the controller never took the PC's link up"return self- def link_pc_to_mac(self):- self.pc.start(self.pc_config)- assert wait_for(lambda: self.pc.connected), f"the PC never connected: {self.pc.status}"+ def link_pc_to_mac(self, wrap=None):+ """The PC's own link to the Mac, handshaken: `pc` is the scripted initiator. `wrap` is given+ the connected socket before anything is sent and returns the one to use instead."""+ self.pc = Initiator(types.SimpleNamespace(port=self.mac_port), peer=HERE, key=PAIRED_TOKEN, preamble=wrap is None)+ if wrap is not None:+ self.pc.sock = wrap(self.pc.sock)+ self.pc.sock.sendall(self.pc.session.preamble())+ # Its hello says the port it listens on, which the Mac saves as the address to dial.+ self.pc.handshake(self.pc.hello(platform="windows", name="PC", port=self.pc_responder.port))+ assert wait_for(lambda: HERE in self.mac_responder.links()), "the Mac's responder never saw the PC's link"return selfdef close(self):- self.pc.stop()+ if self._closed:+ return+ self._closed = True+ if self.pc is not None:+ # Closing the descriptor does not end a recv another thread is blocked in, so the Mac+ # would hear nothing for its read timeout; a shutdown does.+ try:+ self.pc.sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+ self.pc.close()self.mac.stop()- self.pc_server.stop()- self.mac_server.stop()+ self.mac_responder.stop()+ self.pc_responder.stop()+ self.dir.cleanup()# -- the Mac's pointer ----------------------------------------------------@@ -195,12 +211,43 @@ class Duo:return Truereturn False- # -- the PC's pointer ------------------------------------------------------ def pc_push(self, x, y, dx, dy=0, times=12, until=lambda self: self.pc.redirecting):- self.pc_desktop.cursor = (x, y)+ def mac_lean(self, dx, dy=0, times=6, pace=0.02):+ """The Mac's forwarded pointer pushing on the PC's edge, one delta at a time with a breath+ between, until the input is home. The location is nothing the PC sees: a redirected+ pointer is pinned and only its deltas travel."""for _ in range(times):- self.pc.on_motion(dx, dy)- if until(self):+ self.mac_move(1727.0, 558.0, dx, dy)+ if not self.mac.redirecting:return True- return False+ wait_for(lambda: not self.mac.redirecting, pace)+ return wait_for(lambda: not self.mac.redirecting, 0.5)++ # -- the PC driving the Mac ---------------------------------------------------++ def pc_takes(self, edge=None, offset=None, resistance_px=40, reach=None, stay=False):+ """The scripted PC takes this Mac's input: a `focus` naming the Mac. Returns the route."""+ pc = self.pc+ pc.route += 1+ fields = {"edge": edge, "offset": offset, "resistance_px": resistance_px, "reach": [] if reach is None else reach}+ pc.send(protocol.focus_v6(pc.route, self.mac_id, stay=stay, **fields))+ return pc.route++ def pc_drives(self, edge=None, offset=None, **fields):+ """`pc_takes`, with the answer read and the Mac seen to be driven. Returns the route."""+ route = self.pc_takes(edge, offset, **fields)+ answer = self.pc.answer(route)+ assert answer == (protocol.MSG_ACCEPT, {"route": route}), f"the Mac answered {answer}"+ assert wait_for(lambda: self.mac.receiving), "the Mac never became driven"+ return route++ def pc_leans(self, cursor, dx, dy=0, times=1):+ """The PC's pointer, arriving as input, pushing at the Mac's edge from `cursor`. Each move+ is waited for, so what the Mac's zones did with it has been done when this returns."""+ self.mac_desktop.cursor = cursor+ for _ in range(times):+ seq = self.pc.move(dx, dy)+ assert self.pc.acked(seq) is not None, "the Mac never acknowledged the move"++ def pc_switch(self, timeout=2.0):+ """The `switch` the Mac's responder sent the PC, or None."""+ return self.pc.expect(protocol.MSG_SWITCH, timeout)diff --git a/mac_app/wake.py b/mac_app/wake.pyindex e0e5a18..4a70727 100644--- a/mac_app/wake.py+++ b/mac_app/wake.py@@ -6,22 +6,33 @@ from __future__ import annotationsimport threading-from bridge import AUTH_FAILED_STATUS, KVMController+from bridge import KVMControllerfrom core.wol import WAKE_WINDOW_SECONDS, lookup_mac, mac_from_arp_output, magic_packet, parse_mac, send_magic_packet__all__ = [- "NOT_WOKEN_STATUS", "WAKE_WINDOW_SECONDS", "WAKING_STATUS", "WakingController",+ "NOT_WOKEN_SUFFIX", "WAKE_WINDOW_SECONDS", "WakingController", "not_woken_status", "waking_status","lookup_mac", "mac_from_arp_output", "magic_packet", "parse_mac", "send_magic_packet",]-WAKING_STATUS = "Waking Windows…"-NOT_WOKEN_STATUS = "Windows did not wake"+# What the link says when the machine answered and would not have it: a different Beamer, an older+# or newer one, a pairing it holds under another machine, or a first frame it could not read.+REFUSED_KINDS = ("older", "newer", "different", "unauthenticated", "wrong_id", "unreadable")++NOT_WOKEN_SUFFIX = " did not wake"+++def waking_status(name):+ return f"Waking {name}…"+++def not_woken_status(name):+ return f"{name}{NOT_WOKEN_SUFFIX}"class WakingController(KVMController):"""KVMController plus wake-on-LAN. A switch attempted while the PC is unreachable sends the- magic packet and shows WAKING_STATUS until the connection worker gets through, the same- shape as the receiver's "Unlocking Windows…" -- and, like that path, nothing is queued: the+ magic packet and shows waking_status until the connection worker gets through, the same+ shape as the receiver's "Unlocking <name>…" -- and, like that path, nothing is queued: theswitch is refused, and the person switches again once the PC is up. Completing it for thema minute later, into whatever they had gone back to typing on the Mac, would be worse.@@ -40,12 +51,15 @@ class WakingController(KVMController):@propertydef connection_status(self):- return WAKING_STATUS if self._waking else self._connection_status+ return waking_status(self._wake_name()) if self._waking else KVMController.connection_status.fget(self)@connection_status.setterdef connection_status(self, value):self._connection_status = value+ def _wake_name(self):+ return self.peer_label or self.cfg.pc_name or self.cfg.host or "the other machine"+@propertydef waking(self) -> bool:return self._waking@@ -63,8 +77,7 @@ class WakingController(KVMController):def _refused(self) -> bool:"""A PC that answered and refused -- the token, or the protocol version -- is awake, andwaking 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+ return self.status_kind in REFUSED_KINDSdef wake(self) -> bool:"""Sends the packet and starts waiting, unless a wake is already in flight."""@@ -77,34 +90,36 @@ class WakingController(KVMController):def _wake_worker(self):started = self.clock()+ name = self._wake_name()try:self.wake_sender(self.cfg.mac_address, self.cfg.host)except (OSError, ValueError) as exc:self.logger.warning("wake-on-LAN packet not sent: %s", exc)self._waking = False- self.connection_status = NOT_WOKEN_STATUS+ self.connection_status = not_woken_status(name)self._alert("Beamer", "Could not send the wake-up packet")returnself.logger.info("sent wake-on-LAN to %s", self.cfg.host)- self._alert("Beamer", WAKING_STATUS)+ self._alert("Beamer", waking_status(name))while not self.stop_event.wait(self.WAKE_POLL_SECONDS):if self.connected:self._waking = False- self.logger.info("Windows woke and connected")- self._alert("Beamer", "Windows is awake — switch again to send input")+ self.logger.info("%s woke and connected", name)+ self._alert("Beamer", f"{name} is awake — switch again to send input")returnif self.clock() - started >= WAKE_WINDOW_SECONDS:breakself._waking = False- self.connection_status = NOT_WOKEN_STATUS- self.logger.warning("Windows did not answer within %.0fs of the wake-on-LAN packet", WAKE_WINDOW_SECONDS)- self._alert("Beamer", NOT_WOKEN_STATUS)+ self.connection_status = not_woken_status(name)+ self.logger.warning("%s did not answer within %.0fs of the wake-on-LAN packet", name, WAKE_WINDOW_SECONDS)+ self._alert("Beamer", not_woken_status(name))- def _connect_once(self, host=None):- connected = super()._connect_once(host=host)- if connected:- self._learn_mac(host or self.cfg.host)- return connected+ def _primary_up(self, link, fields):+ super()._primary_up(link, fields)+ # Off the link's thread: `arp` can take seconds, and the link's first read, which the peer+ # gives 2.5 seconds, waits behind this callback.+ host = (link.entry() or {}).get("host") or self.cfg.host+ threading.Thread(target=self._learn_mac, args=(host,), name="Beamer-learn-mac", daemon=True).start()def _learn_mac(self, host):try:@@ -112,9 +127,10 @@ class WakingController(KVMController):except Exception:self.logger.exception("hardware address lookup failed")return- if not mac or mac == self.cfg.mac_address:- return- self.cfg.mac_address = mac+ with self._cfg_lock:+ if not mac or mac == self.cfg.mac_address:+ return+ self.cfg.mac_address = macself.logger.info("learned the PC's hardware address from the ARP table")callback = self.on_mac_learnedif callback is not None:diff --git a/mac_app/widgets.py b/mac_app/widgets.pyindex 38dac0e..df2d348 100644--- a/mac_app/widgets.py+++ b/mac_app/widgets.py@@ -505,6 +505,20 @@ class _Target(AppKit.NSObject):self.callback(sender)+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 laysitself out in drawingRectForBounds too."""diff --git a/mac_app/windows_input.py b/mac_app/windows_input.pyindex 7d610df..879c0cf 100644--- a/mac_app/windows_input.py+++ b/mac_app/windows_input.py@@ -1,127 +1,126 @@-"""The other direction: the PC's keyboard and mouse arriving on this Mac.--A listener on the same port number this Mac reaches Windows on -- different-machines, so one number does for both -- running the same receiver.py the PC-runs, with this Mac's own injector, clipboard and display geometry handed to-it. Nothing about the protocol or the crossing is duplicated here; this module-is only the wiring that says which platform's modules to use and what to do-when input arrives.--The two directions never overlap. Every focus message is passed to the-controller, which stops its own tap from reading a pointer the PC is moving as-a push against this Mac's edge.+"""The other direction: other machines' keyboards and pointers arriving on this Mac.++A listener on this Mac's port running core.receiver.LinkResponder, the responder the other+desktops run, with this Mac's own injector, clipboard and display geometry handed to it. Nothing+about the protocol or the crossing is duplicated here; this module is only the wiring that says+which platform's modules to use and what to do when input arrives.++The two directions never overlap. The responder's `owner_callback` tells the controller when a+machine has taken this Mac or let it go, which stops the controller's own tap from reading a+pointer another machine is moving as a push against this Mac's edge, and the controller's owner+tells the responder whether this Mac's own input is away, which it refuses a take for."""+import jsonimport loggingimport threadingimport clipboard_mac+import crossingimport desktop_mac+import hardware_macimport input_injector_macimport no_unlock+from core import protocolfrom core import receiver-from core import return_edge-from core.receiver import ReceiverServer, ServerState+from core.receiver import LinkResponder, ServerStateLOGGER = logging.getLogger("Beamer")class WindowsInput:- """Owns the listener and keeps it in step with the settings. `sync` is- called from the status tick, so a token or port changed in the window- takes effect without anyone restarting Beamer."""+ """Owns the listener and keeps it in step with the settings. `sync` is called from the status+ tick, so a port, a pairing or a switch changed in the window takes effect without anyone+ restarting Beamer."""def __init__(self, controller, logger=None, arrangement_callback=None, pressure_callback=None, arrival_callback=None):self._controller = controllerself._logger = logger or LOGGER- # Windows can change the arrangement too, and it reaches this Mac over- # whichever of the two links is up: this one, or the Mac's own, which- # bridge.py handles. Both end at the same handler in the app.+ # A peer can change the arrangement too, and it reaches this Mac over whichever of the two+ # links is up: this one, or the Mac's own, which bridge.py handles. Both end at the same+ # handler in the app, called with (mac_edge, set_at, by).self._arrangement_callback = arrangement_callbackself._lock = threading.RLock()self._running_for = None- self._ways = None+ self._speeds = None+ self._armed_for = Noneself.state = ServerState.STOPPEDself.detail = "Not listening"- self.server = ReceiverServer(+ self.settings_callback = None+ self.paired_callback = None+ self.server = LinkResponder(+ controller.book,+ controller.identity,status_callback=self._on_status,+ injector=input_injector_mac,+ desktop=desktop_mac,clipboard=clipboard_mac,unlock=no_unlock,- desktop=desktop_mac,- injector=input_injector_mac,- focus_callback=self._on_focus,- arrangement_callback=self._on_arrangement,- # The crossing effects: the push home through the return edge, and the PC's pointer landing- # here. Both fire on the receiver's session thread; the app marshals them.+ hardware=hardware_mac.hardware_address_towards,+ away=lambda: controller.owner.away,+ zones=controller.book.zones,+ notch_span=lambda: controller.notch_range,+ owner_callback=self._on_owner,+ # The crossing effects: the push home through a zone, and a peer's pointer landing+ # here. Both fire on a link's thread; the app marshals them.pressure_callback=pressure_callback,arrival_callback=arrival_callback,- self_name="Mac",- peer_name="PC",- self_target="mac",- peer_target="windows",+ arrangement_callback=self._on_arrangement,+ settings_callback=self._on_settings,+ paired_callback=self._on_paired,+ notice_callback=controller._notify_user,+ announce=self._announce,)+ controller.responder = self.servercontroller.send_peer_home = self.server.send_home- # Pause crossing and the full-screen hold are about this screen: the PC's pointer does not- # go home through a held edge either.+ # Pause crossing and the full-screen hold are about this screen: a peer's pointer does not+ # go onward or home through a held edge either.self.server.edges_held = lambda: controller.crossing_paused or controller.full_screen_app is not None- self.server.return_model = self._return_model-- def _return_model(self, edge, resistance):- """The way home for the PC's pointer through `edge` of this Mac, from this Mac's own ways- in, as for its own pointer: only the chosen thirds, the whole edge, only the notch's own- stretch of the top edge, the corner when it sits on that edge, else none. On the receiver's- session thread."""- crossing_cfg = self._controller.cfg.crossing- methods = set(crossing_cfg["methods"])- if "part" in methods:- return return_edge.PartEdge(edge, crossing_cfg["edge_parts"], resistance)- if "edge" in methods:- return return_edge.ReturnEdge(edge, resistance)- # The same measured range the Mac's own pointer crosses by, read at each push: unmeasured,- # the notch is a wall, as it is for the Mac's own pointer.- if "notch" in methods and edge == "top":- return return_edge.SpanEdge(edge, lambda: self._controller.notch_range, resistance)- corner = crossing_cfg["corner"]- if "corner" in methods and edge in corner.split("_"):- return return_edge.CornerPush(corner, edge, resistance)- return None@propertydef 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()]+ 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()self._running_for = wanted+ self._armed_for = self._held()try:- self.server.start(cfg)+ self.server.start(wanted)except Exception:- self._logger.exception("The listener for the PC's input could not start")+ self._logger.exception("The listener for other machines' input could not start")++ def _held(self):+ """What the responder arms and answers from: the peers' ids, tokens, sides and switches, and the zones."""+ book = self._controller.book+ peers = tuple((p.get("id"), p.get("token"), p.get("side"), p.get("allow_drive")) for p in book.peers())+ return peers, json.dumps(book.zones(), sort_keys=True)def stop(self) -> None:with self._lock:@@ -131,25 +130,75 @@ class WindowsInput:try:input_injector_mac.release_all()except Exception:- self._logger.exception("Could not release the keys the PC was holding")+ self._logger.exception("Could not release the keys another machine 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 _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 _on_arrangement(self, mac_edge, set_at) -> None:+ def send_arrangement(self, mac_edge: str, set_at: int) -> bool:+ """Tell the primary peer which edge of this Mac faces it, over the link it opened to this+ Mac, when this Mac has none open to it (WIRE.md section 3, "Which link"). False when+ nobody is connected, which is not a failure worth reporting."""+ peers = self._controller.book.peers()+ ident = protocol.read_id(peers[0].get("id")) if peers else None+ if ident is None or self._outbound_up(ident):+ return False+ own = bytes(self._controller.identity()["id"])+ return self.server.send(ident, protocol.arrangement_v6(mac_edge, int(set_at), own))++ 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+ for peer in self.server.links():+ 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:+ 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))+ caps = self.server.caps_of(peer) or frozenset()+ if "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)+ self._arrangement_callback(crossing.OPPOSITE[read["edge"]], read["set_at"], protocol.id_text(read["by"]))++ def _on_settings(self, peer, data) -> None:+ if 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 = stateself.detail = detail- def _on_focus(self, target) -> None:- # The receiver itself releases whatever the PC was holding before- # this fires, on both machines alike.- self._controller.set_receiving(target == "mac")+ def _on_owner(self, peer) -> None:+ # The responder itself releases whatever the owner was holding before this fires.+ self._controller.driver = protocol.id_text(peer) if peer is not None else None+ self._controller.set_receiving(peer is not None)diff --git a/win_app/Beamer-Setup.iss b/win_app/Beamer-Setup.issindex b4738da..90c22aa 100644--- a/win_app/Beamer-Setup.iss+++ b/win_app/Beamer-Setup.iss@@ -62,4 +62,4 @@ Filename: "schtasks.exe"; Parameters: "/Create /RL HIGHEST /SC ONLOGON /TN Beame; The rules and the task were written elevated (by the app, or by the autostart step above), so; removing them needs elevation the per-user uninstaller does not have: one prompt, one command,; rather than three deletions that fail silently and leave them behind.-Filename: "cmd.exe"; Parameters: "/c netsh advfirewall firewall delete rule name=""Beamer Receiver (TCP-In)"" & netsh advfirewall firewall delete rule name=""Beamer Pairing (UDP-In)"" & schtasks /Delete /TN Beamer /F"; Flags: runhidden shellexec waituntilterminated; Verb: runas; RunOnceId: "BeamerCleanup"+Filename: "cmd.exe"; Parameters: "/c netsh advfirewall firewall delete rule name=""Beamer Receiver (TCP-In)"" & netsh advfirewall firewall delete rule name=""Beamer Pairing (UDP-In)"" & netsh advfirewall firewall delete rule name=""Beamer Pairing (TCP-In)"" & schtasks /Delete /TN Beamer /F"; Flags: runhidden shellexec waituntilterminated; Verb: runas; RunOnceId: "BeamerCleanup"diff --git a/win_app/Install-Beamer.ps1 b/win_app/Install-Beamer.ps1index 4c95f2a..9283f03 100644--- a/win_app/Install-Beamer.ps1+++ b/win_app/Install-Beamer.ps1@@ -71,7 +71,10 @@ if ($IsElevated) {# The pairing beacon answers the Mac on UDP 24821; without this the Mac never sees the PC.Get-NetFirewallRule -DisplayName 'Beamer Pairing (UDP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRuleNew-NetFirewallRule -DisplayName 'Beamer Pairing (UDP-In)' -Direction Inbound -Protocol UDP -LocalPort 24821 -Action Allow -Profile Private -Program $ExeDestination | Out-Null- Write-Host 'Private-network firewall rules installed (TCP 24820 receiver, UDP 24821 pairing).' -ForegroundColor Green+ # The pairing exchange itself runs over TCP on the same number while a code is on screen.+ Get-NetFirewallRule -DisplayName 'Beamer Pairing (TCP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRule+ New-NetFirewallRule -DisplayName 'Beamer Pairing (TCP-In)' -Direction Inbound -Protocol TCP -LocalPort 24821 -Action Allow -Profile Private -Program $ExeDestination | Out-Null+ Write-Host 'Private-network firewall rules installed (TCP 24820 receiver, UDP and TCP 24821 pairing).' -ForegroundColor Green} catch {Write-Host "Could not install the firewall rule: $_" -ForegroundColor Yellow}diff --git a/win_app/app_config.py b/win_app/app_config.pyindex c08a29c..687c749 100644--- a/win_app/app_config.py+++ b/win_app/app_config.py@@ -1,18 +1,34 @@-"""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. The app still works on one peer: `Config` is the flat view the window,+the sender and the receiver have always read, and `peers[0]` and the zones of that peer feed the+fields that used to be the Mac's (`mac_host`, `auth_token`, `send_to_mac`, `crossing_methods` and the+rest). 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+from dataclasses import dataclass, field, fields, replacefrom pathlib import Path-import capture_win+from platform_parts import capture as capture_winfrom core import effectsfrom core import ignoredfrom core import protocol+from core import receiverfrom core import return_edge+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.@@ -52,6 +68,11 @@ class ConfigError(Exception):pass+class SettingsFileError(ConfigError):+ """settings.json exists but this version cannot use it (another schema, a hand edit that broke+ it). Nothing is written over it."""++@dataclassclass Config:host: str@@ -82,6 +103,8 @@ class Config:# seconds of the last change to that or to a shared value; see settings_sync.same_on_both: bool = Falsesame_set_at: int = 0+ # The machine that made that last change, its id as base64: the larger id wins a tie.+ same_by: str = ""# How the Mac's pointer and scroll feel on this PC; see receiver.InputScale.pointer_speed: float = 1.0scroll_speed: float = 1.0@@ -126,6 +149,10 @@ class Config:# The window's own palette: follow Windows, or keep one. tokens.APPEARANCES is the home of# these three values.appearance: str = "system"+ # This machine's identity from settings.json (WIRE.md section 1), for the links and Same on all+ # machines; empty until a settings file has given it one. The id never changes once made.+ machine_id: str = ""+ name: str = ""def _stamp(value) -> int:@@ -153,8 +180,13 @@ def default_config() -> Config:def default_config_path() -> Path:base = os.environ.get("LOCALAPPDATA") or os.environ.get("XDG_CONFIG_HOME")if base:- return Path(base) / "Beamer" / "config.json"- return Path.home() / ".config" / "Beamer" / "config.json"+ return Path(base) / "Beamer" / "settings.json"+ return Path.home() / ".config" / "Beamer" / "settings.json"+++def legacy_config_path(path: Path) -> Path:+ """1.4.x's config.json, which sits beside settings.json and is only ever read."""+ return path.with_name("config.json")def validate_config(config: Config) -> None:@@ -166,8 +198,9 @@ def validate_config(config: Config) -> None:raise ConfigError("port must be an integer from 1 to 65535") from excif isinstance(config.port, bool) or not 1 <= port <= 65535:raise ConfigError("port must be an integer from 1 to 65535")- if not isinstance(config.auth_token, str) or not config.auth_token.strip():- raise ConfigError("auth_token must not be empty")+ # Empty is a machine with nothing paired: it still has settings of its own to keep.+ if not isinstance(config.auth_token, str):+ raise ConfigError("auth_token must be text")if config.auth_token == "CHANGE_ME":raise ConfigError("auth_token is still the placeholder")if config.trigger_key not in TRIGGER_KEYS:@@ -252,6 +285,10 @@ def validate_config(config: Config) -> None:raise ConfigError(str(exc)) from excif config.appearance not in tokens.APPEARANCES:raise ConfigError(f"appearance must be one of: {', '.join(tokens.APPEARANCES)}")+ if config.machine_id and not is_machine_id(config.machine_id):+ raise ConfigError("machine_id must be a machine id")+ if not isinstance(config.name, str):+ raise ConfigError("name must be text")def config_from_dict(raw: dict) -> Config:@@ -281,6 +318,7 @@ def config_from_dict(raw: dict) -> Config:hide_addresses=raw.get("hide_addresses", False),same_on_both=raw.get("same_on_both", False),same_set_at=_stamp(raw.get("same_set_at", 0)),+ same_by=raw.get("same_by", "") or "",pointer_speed=raw.get("pointer_speed", 1.0),scroll_speed=raw.get("scroll_speed", 1.0),reverse_scroll=raw.get("reverse_scroll", False),@@ -302,6 +340,8 @@ def config_from_dict(raw: dict) -> Config:mac_resistance_px=int(raw.get("mac_resistance_px", 120)),ignored_inputs=raw.get("ignored_inputs", []),appearance=raw.get("appearance") if raw.get("appearance") in tokens.APPEARANCES else "system",+ machine_id=raw.get("machine_id", "") or "",+ name=raw.get("name", "") or "",)except (TypeError, ValueError) as exc:raise ConfigError(f"config.json contains an invalid value: {exc}") from exc@@ -309,25 +349,19 @@ def config_from_dict(raw: dict) -> Config:return config-def load_config(path: Path) -> Config:- if not path.exists():- raise ConfigError(f"config file not found: {path}")+def load_config(path: Path, unpaired_ok: bool = False) -> Config:+ """The flat config from settings.json at `path`, migrating 1.4.x's config.json first when there+ is no settings file yet. A machine with no peer is unpaired, which raises ConfigError as a missing+ config always did, unless `unpaired_ok`: the window then gets this machine's own settings, with no+ token, to show and keep."""try:- with path.open("r", encoding="utf-8") as handle:- raw = json.load(handle)- except (UnicodeDecodeError, json.JSONDecodeError) as exc:- raise ConfigError(f"config file contains invalid JSON: {exc}") from exc+ settings = load_settings(path)except OSError as exc:- raise ConfigError(f"config file could not be read: {exc}") from exc- config = config_from_dict(raw)- if config.port != int(raw["port"]):- try:- save_config(path, config)- except (ConfigError, OSError):- # The port in hand is what matters; a config file that cannot be written must- # not stop Beamer listening on it.- pass- return config+ raise ConfigError(f"settings could not be read or written: {exc}") from exc+ if not settings["peers"] and not unpaired_ok:+ raise ConfigError("nothing is paired yet")+ config = config_from_dict(_flat_from_settings(settings))+ return replace(config, host=_own_address(config.mac_host))def config_to_dict(config: Config) -> dict:@@ -349,6 +383,7 @@ def config_to_dict(config: Config) -> dict:"hide_addresses": config.hide_addresses,"same_on_both": config.same_on_both,"same_set_at": int(config.same_set_at),+ "same_by": config.same_by,"pointer_speed": config.pointer_speed,"scroll_speed": config.scroll_speed,"reverse_scroll": config.reverse_scroll,@@ -370,11 +405,190 @@ def config_to_dict(config: Config) -> dict:"mac_resistance_px": int(config.mac_resistance_px),"ignored_inputs": list(config.ignored_inputs),"appearance": config.appearance,+ "machine_id": config.machine_id,+ "name": config.name,}-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),+ "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)+ 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:@@ -396,3 +610,303 @@ def save_config(path: Path, config: Config) -> None: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 _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", "")+ if legacy is not None and remigrate(settings, legacy):+ _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+ 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+ 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, leaving every other+ peer, zone and field as it was. 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 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"]:+ entry = _peer_entry(flat, flat["auth_token"], flat["port"], own_id)+ if peers:+ for zone in settings["zones"]:+ if zone.get("peer") == peers[0].get("id"):+ zone["peer"] = ""+ peers[0] = entry+ else:+ peers.insert(0, entry)+ peer = peers[0]+ if (peer.get("side"), peer.get("side_set_at")) != (flat["mac_return_edge"], flat["arrangement_set_at"]):+ peer["side_by"] = own_id if flat["arrangement_set_at"] else ""+ peer.update(+ name=flat["paired_with"], host=flat["mac_host"], hw=flat["mac_hardware_address"], send=flat["send_to_mac"],+ allow_drive=flat["allow_mac_to_drive"], side=flat["mac_return_edge"], side_set_at=flat["arrangement_set_at"],+ )+ if flat["port"] != old_port and peer.get("port") == old_port:+ peer["port"] = flat["port"]+ _apply_zones(settings, peer.get("id", ""), flat)+++def _apply_zones(settings: dict, peer_id: str, flat: dict) -> None:+ """One zone of each kind for the peer, on or off as `crossing_methods` says, keeping the zone a+ user had and its other fields."""+ methods, corner, parts = _zone_fields(flat)+ mine = _zones_of(settings, peer_id)+ rest = {"edge": {}, "part": {"parts": list(parts)},+ "corner": {"corner": corner, "edge": _corner_edge(corner, flat["mac_return_edge"])}}+ for kind in KINDS:+ zone = mine.get(kind)+ if zone is None:+ zone = {"peer": peer_id, "kind": kind}+ settings["zones"].append(zone)+ zone.update(rest[kind])+ if kind in methods:+ zone.pop("off", None)+ else:+ zone["off"] = True+++# 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)+ _apply_flat(settings, payload)+ _write_json(path, settings)+++def write_settings(path: Path, settings: dict) -> None:+ """The settings as the link changed them (an id learnt, an address, `linked`), written atomically."""+ _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 address, hardware+ address and name, and the side and the stamp that settled it."""+ 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, arrangements and a fold write into the first peer or its zones, in the flat view's names.+LEARNED = (+ "auth_token", "mac_host", "mac_hardware_address", "paired_with", "mac_return_edge", "arrangement_set_at",+ "send_to_mac", "allow_mac_to_drive", "crossing_methods", "crossing_edge_parts", "crossing_corner",+)+# 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:+ return False+ entry["hw"] = address+ _write_json(path, settings)+ return True+++def _side_order(entry: dict):+ by = _unb64(entry.get("side_by"), 16) if entry.get("side_by") else b""+ return int(entry.get("side_set_at") or 0), by or b""+++def apply_arrangement(path: Path, peer: str, edge: str, set_at: int, by: str):+ """A peer's `arrangement` (WIRE.md section 8): `edge` is the edge of the peer that faces this PC, so+ this PC's side for it is the opposite. Taken when it is newer than the side held (a higher stamp, or+ the same stamp and the larger `by` as bytes). A side that would make two zones in use cover one+ stretch is applied and turns this peer's clashing zones off. Returns (changed, notices): whether+ the file was written, and a sentence for each zone turned off."""+ with SETTINGS_LOCK:+ settings = load_settings(path)+ entry = next((item for item in settings["peers"] if item.get("id") == peer), None)+ by_bytes = _unb64(by, 16)+ if entry is None or edge not in EDGES or by_bytes is None or (int(set_at), by_bytes) <= _side_order(entry):+ return False, []+ entry.update(side=return_edge.OPPOSITE[edge], side_set_at=int(set_at), side_by=by)+ notices = _clear_overlaps(settings, entry)+ _write_json(path, settings)+ return True, notices+++def _clear_overlaps(settings: dict, entry: dict) -> list:+ sides = {item.get("id", ""): item.get("side", "") for item in settings["peers"]}+ names = {item.get("id", ""): item.get("name") or "another machine" for item in 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 receiver.zone_stretch(zone, sides):+ covered.setdefault(stretch, zone.get("peer"))+ notices = []+ for zone in mine:+ stretch = receiver.zone_stretch(zone, sides)+ clash = next((covered[item] for item in stretch if item in covered), None)+ if clash is not None:+ zone["off"] = True+ notices.append(f"{names.get(clash)} and {names.get(entry.get('id'))} now lead from the same part of this PC's screen, so {names.get(entry.get('id'))}'s {zone.get('kind')} zone is off.")+ else:+ for item in stretch:+ covered.setdefault(item, entry.get("id"))+ return noticesdiff --git a/win_app/build.spec b/win_app/build.specindex 4ad0e9f..deb2b7e 100644--- a/win_app/build.spec+++ b/win_app/build.spec@@ -2,6 +2,10 @@ from pathlib import Pathsource_dir = Path(SPECPATH)+# Every module of the app's folder and of core/, by name: the same set the import probe loads from+# the built exe, so a module the analysis misses fails the probe and is never left out by drift here.+app_modules = sorted(path.stem for path in source_dir.glob("*.py") if path.stem != "kvm_bridge_win")+core_modules = sorted(f"core.{path.stem}" for path in (source_dir.parent / "core").glob("*.py") if path.stem != "__init__")analysis = Analysis([str(source_dir / "kvm_bridge_win.py")],@@ -9,8 +13,9 @@ analysis = Analysis(pathex=[str(source_dir), str(source_dir.parent)],binaries=[],datas=[(str(source_dir / "Beamer.ico"), "."), (str(source_dir / "assets"), "assets"), (str(source_dir.parent / "VERSION"), ".")],- # core/effects.py imports its fx_* modules by name, which PyInstaller's analysis cannot see.- hiddenimports=["nacl", "_cffi_backend"] + sorted(f"core.{path.stem}" for path in (source_dir.parent / "core").glob("fx_*.py")),+ # core/effects.py imports its fx_* modules by name, which PyInstaller's analysis cannot see; they are+ # among core_modules. segno is imported inside a try in qr_code.py, so it is named here as well.+ hiddenimports=["nacl", "_cffi_backend", "segno"] + app_modules + core_modules,hookspath=[],hooksconfig={},runtime_hooks=[],diff --git a/win_app/capture_win.py b/win_app/capture_win.pyindex 04d89c3..b17e158 100644--- a/win_app/capture_win.py+++ b/win_app/capture_win.py@@ -117,6 +117,21 @@ def button_of(message: int, mouse_data: int) -> Optional[Tuple[str, bool]]:return None+def mouse_event(message: int, mouse_data: int):+ """What a low-level mouse message says, in the sender's neutral terms: ("button", name, down),+ ("wheel", dy, dx) in notches, ("move",), or None for a message the Mac has no name for."""+ button = button_of(message, mouse_data)+ if button is not None:+ return ("button",) + button+ if message == WM_MOUSEWHEEL:+ return ("wheel", wheel_notches(mouse_data), 0.0)+ if message == WM_MOUSEHWHEEL:+ return ("wheel", 0.0, wheel_notches(mouse_data))+ if message == WM_MOUSEMOVE:+ return ("move",)+ return None++# What the Keyboard page calls a recorded key, in Windows' own words.VK_TITLES: Dict[int, str] = {0x08: "Backspace", 0x09: "Tab", 0x0D: "Enter", 0x13: "Pause", 0x14: "Caps Lock", 0x1B: "Esc",diff --git a/win_app/clipboard_win.py b/win_app/clipboard_win.pyindex 473d1d1..92a1e77 100644--- a/win_app/clipboard_win.py+++ b/win_app/clipboard_win.py@@ -339,6 +339,11 @@ def changed_contents() -> Tuple[Optional[str], Optional[bytes]]:return text, png+def change_stamp() -> Optional[int]:+ """A number that changes whenever the clipboard does, or None off Windows."""+ return user32.GetClipboardSequenceNumber() if _IS_WINDOWS else None++def forget_sync() -> None:"""A new link: the Mac may have lost what it was sent, so the next switch sends again."""global _synced_sequencediff --git a/win_app/edge_glow.py b/win_app/edge_glow.pyindex 3e72e55..dc742b6 100644--- a/win_app/edge_glow.py+++ b/win_app/edge_glow.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport copyimport ctypes+import sysimport timefrom PySide6.QtCore import QRect, QRectF, Qt, QTimer@@ -117,6 +118,8 @@ class GlowState:def system_dark() -> bool:"""Apps in dark mode. The overlay cannot see the wallpaper, so this is the best it has."""+ if sys.platform != "win32":+ return theme.system_dark()try:import winreg@@ -157,6 +160,8 @@ def keep_on_top(widget: QWidget) -> None:"""Puts `widget`'s window back at the top of the topmost windows. The taskbar is topmost too andraises itself whenever it is hovered or clicked, and a push into a corner or along its edge isright over it, so the topmost flag Qt sets once at creation leaves the light under it."""+ if sys.platform != "win32":+ returntry:ctypes.windll.user32.SetWindowPos(int(widget.winId()), HWND_TOPMOST, 0, 0, 0, 0,SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER)diff --git a/win_app/effect_overlay.py b/win_app/effect_overlay.pyindex 2d56585..84d4511 100644--- a/win_app/effect_overlay.py+++ b/win_app/effect_overlay.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport ctypesimport loggingimport math+import sysimport timefrom PySide6.QtCore import QPointF, QRect, QRectF, Qt, QTimer@@ -178,6 +179,8 @@ def union_bounds(pens, pad: float = 0.0):def system_reduced_motion() -> bool:"""Windows' "Show animations in Windows" switched off."""+ if sys.platform != "win32":+ return FalseSPI_GETCLIENTAREAANIMATION = 0x1042value = ctypes.c_int(1)try:diff --git a/win_app/firewall_win.py b/win_app/firewall_win.pyindex 25cfc49..9522262 100644--- a/win_app/firewall_win.py+++ b/win_app/firewall_win.py@@ -27,6 +27,9 @@ RULE_NAME = "Beamer Receiver (TCP-In)"# not the second, so reporting only the TCP rule tells that user everything is fine.PAIRING_RULE_NAME = "Beamer Pairing (UDP-In)"PAIRING_PORT = protocol.PAIRING_PORT+# Pairing version 3 also hosts the pairing exchange over TCP on the same number while a code is+# on screen. Judged on its own: without it a Mac still finds this PC, then fails to finish pairing.+PAIRING_TCP_RULE_NAME = "Beamer Pairing (TCP-In)"_IS_WINDOWS = sys.platform == "win32"@@ -44,6 +47,15 @@ class FirewallStatus:# Whether the pairing beacon's UDP rule is present. Defaults True so a status built before# pairing existed does not claim a missing rule it knows nothing about.pairing_allowed: bool = True+ pairing_tcp_allowed: bool = True+++def missing_rule(status: "FirewallStatus") -> bool:+ """Whether a rule this app needs is absent and nothing blocks it, so an elevated run may write the+ rules without asking: the receiver's, or either pairing rule."""+ return not status.error and not status.blocked and not (+ status.allowed and getattr(status, "pairing_allowed", True) and getattr(status, "pairing_tcp_allowed", True)+ )@dataclass(frozen=True)@@ -143,11 +155,12 @@ def interpret(payload: dict, exe: str, port: int, elevated: bool = True) -> Fireblocked = any(touches(p, active or ("Domain", "Private", "Public")) for p in block_profiles)covered = all(any(touches(p, (name,)) for p in allow_profiles) for name in lan_profiles) and bool(allow_profiles)public = tuple((int(n.get("index", 0)), str(n.get("alias", ""))) for n in lan if str(n.get("category", "")) == "Public")- pairing_rules = [- rule for rule in payload.get("rules", [])- if _rule_applies(rule, exe, PAIRING_PORT, "udp")- and str(rule.get("action", "")).lower() == "allow"- ]+ def pairing_allowed(protocol: str) -> bool:+ return any(+ _rule_applies(rule, exe, PAIRING_PORT, protocol) and str(rule.get("action", "")).lower() == "allow"+ for rule in payload.get("rules", [])+ )+return FirewallStatus(port=port,allowed=bool(allow_profiles),@@ -158,7 +171,8 @@ def interpret(payload: dict, exe: str, port: int, elevated: bool = True) -> Firepublic_interfaces=public,elevated=elevated,error="",- pairing_allowed=bool(pairing_rules),+ pairing_allowed=pairing_allowed("udp"),+ pairing_tcp_allowed=pairing_allowed("tcp"),)@@ -204,12 +218,23 @@ def advise(status: FirewallStatus) -> Advice:"repair",rule_profiles,)- elif not status.pairing_allowed:+ elif not status.pairing_allowed or not status.pairing_tcp_allowed:+ missing = []+ if not status.pairing_allowed:+ missing.append((+ f"the pairing beacon on UDP {PAIRING_PORT}",+ "a Mac that has not been set up by hand will never see this PC in its list",+ ))+ if not status.pairing_tcp_allowed:+ missing.append((+ f"the pairing exchange on TCP {PAIRING_PORT}",+ "a Mac that finds this PC cannot finish pairing with it",+ ))advice = Advice(- f"Windows Firewall lets your Mac reach Beamer on port {port}, but there is no rule for the "- f"pairing beacon on UDP {PAIRING_PORT}, so a Mac that has not been set up by hand will never "- "see this PC in its list. Installs made before pairing existed are missing it. Fixing it adds "- "the missing rule and leaves the working one alone.",+ f"Windows Firewall lets your Mac reach Beamer on port {port}, but there is no rule for "+ f"{' or for '.join(rule for rule, _ in missing)}, so {' and '.join(effect for _, effect in missing)}. "+ "Installs made before these rules existed are missing them. Fixing it adds what is missing "+ "and leaves the working rules alone.","Fix the firewall","repair",rule_profiles,@@ -297,14 +322,27 @@ $networks = @(Get-NetConnectionProfile | ForEach-Object {{[pscustomobject]@{{ rules = @($rules); networks = $networks }} | ConvertTo-Json -Depth 4 -Compress"""-_REPAIR_SCRIPT = _PREAMBLE + """+# The same rule is reached more than once (by its program and again by its display name), and a+# second removal of a rule already gone raises "The requested object could not be found". Each rule+# is therefore removed once, by name, and that one error is the state removal wants, not a failure.+_REMOVE_SCRIPT = _PREAMBLE + """$exe = {exe}$stale = @($({filters}) | Get-NetFirewallRule | Where-Object {{ [string]$_.Direction -eq 'Inbound' }})$stale += @(Get-NetFirewallRule -DisplayName {name} -ErrorAction SilentlyContinue)$stale += @(Get-NetFirewallRule -DisplayName {pairing_name} -ErrorAction SilentlyContinue)-if ($stale.Count -gt 0) {{ $stale | Remove-NetFirewallRule }}+$stale += @(Get-NetFirewallRule -DisplayName {pairing_tcp_name} -ErrorAction SilentlyContinue)+$stale = @($stale | Sort-Object Name -Unique)+foreach ($rule in $stale) {{+ try {{ Remove-NetFirewallRule -Name $rule.Name }}+ catch {{ if ($_.Exception.Message -notmatch 'could not be found') {{ throw }} }}+}}+"""++_ADD_SCRIPT = _PREAMBLE + """+$exe = {exe}New-NetFirewallRule -DisplayName {name} -Direction Inbound -Protocol TCP -LocalPort {port} -Action Allow -Profile {profiles} -Program $exe | Out-NullNew-NetFirewallRule -DisplayName {pairing_name} -Direction Inbound -Protocol UDP -LocalPort {pairing_port} -Action Allow -Profile {profiles} -Program $exe | Out-Null+New-NetFirewallRule -DisplayName {pairing_tcp_name} -Direction Inbound -Protocol TCP -LocalPort {pairing_port} -Action Allow -Profile {profiles} -Program $exe | Out-Null"""_TRUST_SCRIPT = _PREAMBLE + """@@ -339,17 +377,21 @@ def repair(exe: str, port: int, profiles: Sequence[str] = ("Private",)) -> None:the installer would have. Never Public: that opens the port on every untrusted network themachine ever joins, which is the wrong trade for a KVM; trust_network() is the fix for that."""wanted = [p for p in profiles if p in ("Private", "Domain")] or ["Private"]- _powershell(- _REPAIR_SCRIPT.format(- exe=_quote(exe),- filters=_RULES_FOR_LEAF,- name=_quote(RULE_NAME),- port=int(port),- pairing_name=_quote(PAIRING_RULE_NAME),- pairing_port=PAIRING_PORT,- profiles=",".join(wanted),- )+ names = dict(+ exe=_quote(exe),+ name=_quote(RULE_NAME),+ pairing_name=_quote(PAIRING_RULE_NAME),+ pairing_tcp_name=_quote(PAIRING_TCP_RULE_NAME),)+ try:+ _powershell(_REMOVE_SCRIPT.format(filters=_RULES_FOR_LEAF, **names))+ except RuntimeError as exc:+ # Belt and braces for the script's own tolerance: a rule that is already absent must never+ # stop the new ones being written, or the PC is left with none.+ if "could not be found" not in str(exc):+ raise+ LOGGER.info("A firewall rule was already gone while repairing: %s", exc)+ _powershell(_ADD_SCRIPT.format(port=int(port), pairing_port=PAIRING_PORT, profiles=",".join(wanted), **names))def trust_network(interface_indexes: Sequence[int]) -> None:diff --git a/win_app/hardware_win.py b/win_app/hardware_win.pynew file mode 100644index 0000000..38d6617--- /dev/null+++ b/win_app/hardware_win.py@@ -0,0 +1,115 @@+"""This PC's hardware address, for the handshake's `hw` field (WIRE.md section 2).++A peer sends wake-on-LAN to it, so it must be the adapter this link leaves from, not the first one+the system lists. No subprocess and no PowerShell: Beamer is a windowless app and either would+flash a console. ctypes types only, no ctypes.wintypes, so the module imports on every OS."""++import ctypes+import sys++from core import pairing++AF_INET = 2+GAA_FLAG_SKIP_ANYCAST = 0x2+GAA_FLAG_SKIP_MULTICAST = 0x4+GAA_FLAG_SKIP_DNS_SERVER = 0x8+ERROR_SUCCESS = 0+ERROR_BUFFER_OVERFLOW = 111+++class SockaddrIn(ctypes.Structure):+ _fields_ = [("family", ctypes.c_uint16), ("port", ctypes.c_uint16), ("addr", ctypes.c_ubyte * 4)]+++class SocketAddress(ctypes.Structure):+ _fields_ = [("sockaddr", ctypes.c_void_p), ("length", ctypes.c_int)]+++class UnicastAddress(ctypes.Structure):+ pass+++UnicastAddress._fields_ = [+ ("length", ctypes.c_uint32),+ ("flags", ctypes.c_uint32),+ ("next", ctypes.POINTER(UnicastAddress)),+ ("address", SocketAddress),+]+++class AdapterAddresses(ctypes.Structure):+ """IP_ADAPTER_ADDRESSES_LH up to PhysicalAddressLength. ctypes' natural alignment matches the+ 64-bit Windows header: Length and IfIndex fill the leading ULONGLONG union, every pointer is+ 8-aligned. Only ever read through a pointer into the API's own buffer, so no tail is needed."""+++AdapterAddresses._fields_ = [+ ("length", ctypes.c_uint32),+ ("if_index", ctypes.c_uint32),+ ("next", ctypes.POINTER(AdapterAddresses)),+ ("adapter_name", ctypes.c_void_p),+ ("first_unicast", ctypes.POINTER(UnicastAddress)),+ ("first_anycast", ctypes.c_void_p),+ ("first_multicast", ctypes.c_void_p),+ ("first_dns_server", ctypes.c_void_p),+ ("dns_suffix", ctypes.c_void_p),+ ("description", ctypes.c_void_p),+ ("friendly_name", ctypes.c_void_p),+ ("physical_address", ctypes.c_ubyte * 8),+ ("physical_address_length", ctypes.c_uint32),+]+++def format_mac(raw: bytes) -> str:+ """Six bytes as `aa:bb:cc:dd:ee:ff`; anything else, and all zeros, is unknown ('')."""+ if len(raw) != 6 or not any(raw):+ return ""+ return ":".join(f"{b:02x}" for b in raw)+++def _adapter_table() -> list:+ """(IPv4 text, physical address bytes) for every unicast address on every adapter."""+ lib = ctypes.WinDLL("iphlpapi")+ flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER+ size = ctypes.c_uint32(16384)+ # The adapter list can grow between the sizing call and the real one, hence the retry.+ for _ in range(4):+ buffer = ctypes.create_string_buffer(size.value)+ status = lib.GetAdaptersAddresses(AF_INET, flags, None, buffer, ctypes.byref(size))+ if status != ERROR_BUFFER_OVERFLOW:+ break+ if status != ERROR_SUCCESS:+ raise OSError(f"GetAdaptersAddresses returned {status}")++ table = []+ adapter = ctypes.cast(buffer, ctypes.POINTER(AdapterAddresses))+ while adapter:+ entry = adapter.contents+ raw = bytes(entry.physical_address[:min(entry.physical_address_length, 8)])+ unicast = entry.first_unicast+ while unicast:+ sockaddr = unicast.contents.address.sockaddr+ if sockaddr:+ parsed = ctypes.cast(sockaddr, ctypes.POINTER(SockaddrIn)).contents+ if parsed.family == AF_INET:+ table.append((".".join(str(b) for b in parsed.addr), raw))+ unicast = unicast.contents.next+ adapter = entry.next+ return table+++def hardware_address_towards(host: str) -> str:+ """The MAC of the adapter that would reach `host` (an IPv4 string), or '' when unknown.+ Never raises: the field is optional on the wire, so a failure only costs the peer its wake."""+ if sys.platform != "win32" or not host:+ return ""+ try:+ local = pairing.local_address_towards(host)+ for address, raw in _adapter_table():+ if address == local:+ mac = format_mac(raw)+ if mac:+ return mac+ except Exception:+ return ""+ return ""diff --git a/win_app/input_injector.py b/win_app/input_injector.pyindex 22c124d..1ef9cbc 100644--- a/win_app/input_injector.py+++ b/win_app/input_injector.py@@ -399,6 +399,26 @@ def inject_key(name: str, down: bool, us: Optional[str] = None) -> None:_send_input(*(_keybd_input(vk, scan, flags) for vk, scan, flags in plan))+def plan_text_inputs(text: str) -> List[Tuple[int, int, int]]:+ """(vk, scan, flags) for typing `text` as characters: a Unicode down and up for each UTF-16 code+ unit, so a character outside the Basic Multilingual Plane goes as its surrogate pair."""+ plan = []+ data = text.encode("utf-16-le")+ for index in range(0, len(data), 2):+ unit = int.from_bytes(data[index:index + 2], "little")+ plan.append((0, unit, KEYEVENTF_UNICODE))+ plan.append((0, unit, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP))+ return plan+++@_locked+def inject_text(text: str) -> None:+ """Types `text` as it stands (WIRE.md section 10): the layout and any modifier held play no part."""+ plan = plan_text_inputs(text)+ if plan:+ _send_input(*(_keybd_input(vk, scan, flags) for vk, scan, flags in plan))++def _mouse_input(dx: int, dy: int, data: int, flags: int) -> INPUT:mouse_input = MOUSEINPUT(dx=dx, dy=dy, mouseData=data, dwFlags=flags, time=0, dwExtraInfo=INJECTED_MARK)return INPUT(type=INPUT_MOUSE, union=_INPUTUNION(mi=mouse_input))diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.pyindex 3d20ba6..c348746 100644--- a/win_app/kvm_bridge_win.py+++ b/win_app/kvm_bridge_win.py@@ -1,6 +1,7 @@import argparseimport ctypesfrom dataclasses import replace+import functoolsimport loggingfrom logging.handlers import RotatingFileHandlerimport os@@ -40,6 +41,7 @@ import app_configfrom app_config import (Config,ConfigError,+ SettingsFileError,TRIGGER_KEYS,TRIGGER_VKS,UNRECORDABLE_TRIGGER_VKS,@@ -48,27 +50,28 @@ from app_config import (load_config,save_config,)-import autostart_win-import capture_win-import desktop_winfrom core import effectsfrom diagram import ArrangementDiagram, PushStripfrom edge_glow import EdgeGlow, PreviewLoopfrom effect_overlay import EffectOverlay, logical_pointfrom effect_previews import EffectStill, SwitchStill, TileHover-import firewall_winfrom core import ignoredimport motionfrom core import pairing-from core.pairing import PAIRING_PORT, Announcer, local_address_towards+from core import peerlist+from core.pairing import PAIRING_PORT, PairingService, local_address_towards+import machines_winimport pages_win+import hardware_win+import peers_view+import platform_parts+import qr_codefrom core import protocolfrom core import receiver-from core.receiver import ReceiverServer, ServerState+from core.receiver import LinkResponder, ServerStatefrom core import return_edge-import senderfrom core import settings_sync-from sender import MacSender+from sender import LinkSenderimport themeimport tokensfrom core import updates@@ -85,13 +88,10 @@ except OSError:HOME_PAGE = "https://kalkmancode.co.uk/beamer"HOME_PAGE_TEXT = "Beamer's website"-IDLE_CODE = "––– –––"-PAIR_HINT = "Type this code into Beamer on the Mac."-STATUS_TITLES = {ServerState.STOPPED: "Receiver stopped",- ServerState.WAITING: "Waiting for your Mac",- ServerState.CONNECTED: "Mac connected",+ ServerState.WAITING: "Waiting for a machine",+ ServerState.CONNECTED: "Machine connected",ServerState.ERROR: "Receiver needs attention",}@@ -141,6 +141,13 @@ def asset_path(name: str) -> Path:ICON_PATH = asset_path("Beamer.ico")+# The OS parts keep their Windows names so the code and its tests read as before; on Linux they are+# linux_stand_ins' (platform_parts).+autostart_win = platform_parts.autostart+capture_win = platform_parts.capture+desktop_win = platform_parts.desktop+firewall_win = platform_parts.firewall+# Where configure_logging put the log, for the tray's Open log folder.LOG_PATH: Optional[Path] = None@@ -199,18 +206,25 @@ class StatusBridge(QObject):# (method, edge, x, y): the pointer landed on this PC at desktop pixel (x, y).arrived = Signal(str, str, float, float)firewall = Signal(object)- paired = Signal(str, str, str)+ # A pairing this PC hosted finished and was stored: the new peer entry.+ paired = Signal(object)+ # A pairing this PC requested ended: (the entry stored or None, the error or None).+ pair_finished = Signal(object, object)# The other direction: this PC's own input going to the Mac.sending = Signal(bool, str)redirecting = Signal(bool)- focus = Signal(str)- learned = Signal(str, object, object)- # Either link, telling us the two machines' arrangement changed at the other end.- arrangement = Signal(str, int)- # Either link, carrying the Mac's Same on both machines state.- settings = Signal(object)+ # A peer began or stopped driving this PC: its id as base64, "" when none does.+ owner = Signal(str)+ # A link learnt something about a peer and saved it, or came up or went down.+ peers_changed = Signal()+ # Either link, telling us a peer's side of the arrangement changed at its end: (peer id, the+ # peer's edge that faces this PC, stamp, the machine that made the change).+ arrangement = Signal(str, str, int, str)+ # Either link, carrying a peer's Same on all machines state: (peer id, data).+ settings = Signal(str, object)alert = Signal(str, str)- mac_learned = Signal(str)+ # A sentence for the user from the link layer: a first link, a folded pairing.+ notice = Signal(str)# (version, url) when a newer Beamer is out, else None.update = Signal(object)# The firewall rules are in place (or could not be), so the sockets may open.@@ -234,21 +248,27 @@ class WindowsApplication(QWidget):self.bridge.arrived.connect(self._on_arrival)self.bridge.firewall.connect(self._on_firewall)self.bridge.paired.connect(self._on_paired)+ self.bridge.pair_finished.connect(self._on_pair_finished)self.bridge.sending.connect(self._on_sending)self.bridge.redirecting.connect(self._on_redirecting)- self.bridge.focus.connect(self._on_focus)- self.bridge.learned.connect(self._on_learned)+ self.bridge.owner.connect(self._on_owner)+ self.bridge.peers_changed.connect(self._on_peers_changed)self.bridge.arrangement.connect(self._on_arrangement)self.bridge.settings.connect(self._on_settings)+ self.bridge.notice.connect(self._on_alert_text)self.bridge.update.connect(self._on_update)self.bridge.rules_ready.connect(self._listen)self._update = Noneself._effects_failed = False- # Announces this PC from launch, configured or not: pairing is how a fresh install- # gets its token, so it cannot wait for the receiver to be listening.- self.announcer = Announcer(self._announced_port, self.bridge.paired.emit, logger=LOGGER)self._code_shown = False- self._code_addresses: list = []+ self._code_address = ""+ self._qr_cache = (None, None)+ self._pairing_open = False+ self._pairing_machine = None+ self._pairing_target = ""+ self._peer_entries: list = []+ self._labels_by_id: dict = {}+ self._peers_tick = 0self._firewall_advice: Optional[firewall_win.Advice] = Noneself._firewall_status: Optional[firewall_win.FirewallStatus] = Noneself._firewall_tone: Optional[str] = None@@ -257,64 +277,112 @@ class WindowsApplication(QWidget):self._firewall_auto_repaired = Falseself._host = default_config().hostself._last_seen_state: Optional[ServerState] = None+ self._receiver_port: Optional[int] = Noneself.glow: Optional[EdgeGlow] = Noneself.effects: Optional[EffectOverlay] = None- self.server = ReceiverServer(- self._set_status,+ # The peers as the link layer reads and writes them, over settings.json and its lock.+ self.book = app_config.ReadFallbackPeerBook(+ lambda: app_config.load_settings(self.config_path),+ lambda settings: app_config.write_settings(self.config_path, settings),+ app_config.SETTINGS_LOCK,+ )+ self.server = LinkResponder(+ self.book,+ self._identity,+ status_callback=self._set_status,pressure_callback=lambda edge, pressure, crossed, part=None: self.bridge.pressure.emit(edge, pressure, crossed, part),# The Mac's notch crossing lands on this PC's bottom edge, and that is the only- # arrival an effect draws differently. No edge is the Mac's shortcut or menu.+ # arrival an effect draws differently. No edge is a peer's shortcut or menu.arrival_callback=lambda edge, x, y: self.bridge.arrived.emit("switch" if edge is None else "notch" if edge == "bottom" else "edge", edge or "", float(x), float(y)),- focus_callback=self.bridge.focus.emit,- peer_callback=self.bridge.learned.emit,- arrangement_callback=self.bridge.arrangement.emit,+ owner_callback=lambda peer: self.bridge.owner.emit(protocol.id_text(peer) if peer else ""),+ arrangement_callback=lambda peer, read: self.bridge.arrangement.emit(+ protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"])+ ),+ settings_callback=lambda peer, data: self.bridge.settings.emit(protocol.id_text(peer), data),+ paired_callback=self._store_paired,+ notice_callback=self.bridge.notice.emit,+ link_callback=lambda peer, up: self.bridge.peers_changed.emit(),+ announce=self._announce,+ away=lambda: self.sender.redirecting,+ zones=self._zones,+ clipboard=platform_parts.clipboard,+ unlock=platform_parts.unlock,+ hardware=hardware_win.hardware_address_towards,+ desktop=platform_parts.desktop,+ injector=platform_parts.injector,)- # The second link, outwards: this PC's keyboard and mouse on the Mac.- self.sender = MacSender(+ # The links outwards: this PC's keyboard and mouse on its peers.+ self.sender = LinkSender(+ self.book,+ self._identity,+ hardware=hardware_win.hardware_address_towards,+ zones=self._zones,status_callback=self.bridge.sending.emit,redirect_callback=self.bridge.redirecting.emit,pressure_callback=self.bridge.pressure.emit,- arrangement_callback=self.bridge.arrangement.emit,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- # Same on both machines, over either link: applied on the GUI thread, and announced with- # this PC's own arrangement the moment either link comes up.- for link in (self.server, self.sender):- link.settings_callback = self.bridge.settings.emit- link.announce = self._announce+ # 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"])+ )+ self.sender.link_callback = lambda peer, up: self.bridge.peers_changed.emit()+ self.sender.notice_callback = self.bridge.notice.emit+ self.sender.paired_callback = self._store_paired+ self.sender.hw_learned = self._learn_peer_hardware+ self.sender.announce = self._announceself.scope_labels: dict = {}self.own_notes: list = []self._same_seen = None- # Pause crossing and the full-screen hold are about this screen: the Mac's pointer does+ # 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)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)+ self._paired = Falsetry:- self._config = load_config(config_path)+ # With nothing paired the window still has this PC's own settings to show and keep.+ self._config = load_config(config_path, unpaired_ok=True)self._same_seen = self._same_fields()self._apply_input_scale(self._config)self._host = self._config.host- self._status = ServerState.WAITING- self._status_detail = f"Ready on TCP port {self._config.port}"+ self._paired = bool(self.book.peers())+ if self._paired:+ self._status = ServerState.WAITING+ self._status_detail = f"Ready on TCP port {self._config.port}"+ else:+ self._status = ServerState.ERROR+ self._status_detail = "Not paired yet: press Pair a machine on Overview"except ConfigError as exc:LOGGER.info("Configuration is not ready: %s", exc)self._status = ServerState.ERROR- self._status_detail = "Not paired yet: press Pair a Mac on Overview"+ self._status_detail = (+ "Settings could not be read: see the log" if isinstance(exc, SettingsFileError)+ else "Not paired yet: press Pair a machine on Overview"+ )++ # Announces this PC from launch, configured or not: pairing is how a fresh install gets its+ # first peer, so it cannot wait for the receiver to be listening. Without a readable+ # settings file there is no machine id to pair under, and so no service.+ self._settings_port, self._kept_hide = self._read_kept()+ self.pairing = self._make_pairing()+ self.sender.machines = self.pairing.machines if self.pairing is not None else (lambda: [])# Before any widget is built: every control takes its colours from the palette in use.appearance = self._config.appearance if self._config is not None else "system"@@ -439,18 +507,23 @@ class WindowsApplication(QWidget):# -- Overview ---------------------------------------------------------------------------def _overview_page(self, layout, current) -> None:- # Pairing leads until there is a Mac, since nothing else here works without one; once- # paired it moves down beside the other once-only settings (_place_pairing).- self.overview_layout = layout+ self.machines = machines_win.MachinesModule(+ self._set_peer_send, self._set_peer_allow, self._remove_peer, self._toggle_pairing_sheet+ )+ layout.addWidget(self.machines)+ self.sheet = machines_win.PairingSheet(+ self._show_code, self._cancel_code, self._pair_clicked, self._pick_machine+ )+ self.sheet.setVisible(False)+ layout.addWidget(self.sheet)self.link_module = self._link_module()layout.addWidget(self.link_module)layout.addWidget(self._input_module())- layout.addWidget(self._directions_module(current))layout.addWidget(self._same_module(current))self.sign_in_module = self._sign_in_module()layout.addWidget(self.sign_in_module)layout.addWidget(self._updates_module(current))- self._pairing_block(layout, current)+ self._refresh_peers()def _updates_module(self, current: Config) -> QWidget:module = widgets.Module("Updates")@@ -509,8 +582,6 @@ class WindowsApplication(QWidget):module.body.addLayout(heading_row)self.status_detail = widgets.label("", "note", wrap=True)module.body.addWidget(self.status_detail)- self.outward_line = widgets.label("", "note", wrap=True)- module.body.addWidget(self.outward_line)where_row = QHBoxLayout()where_row.setSpacing(6)where_row.addWidget(widgets.label("Input:", "note"))@@ -531,19 +602,22 @@ class WindowsApplication(QWidget):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 to your Mac")+ self.redirect_button = QPushButton("Send input across")self.redirect_button.setProperty("vernier", "primary")self.redirect_button.setCursor(Qt.CursorShape.PointingHandCursor)self.redirect_button.clicked.connect(self.toggle_redirect)module.body.addWidget(self.redirect_button)# Why the button above is dimmed, while it is.- self.redirect_note = widgets.label("Switch on This PC drives your Mac, below, to send input from here.",+ self.redirect_note = widgets.label("Switch on This PC drives it for a machine above to send input from here.","note", wrap=True)self.redirect_note.setVisible(False)module.body.addWidget(self.redirect_note)+ self.send_hint = widgets.label("", "note", wrap=True)+ self.send_hint.setVisible(False)+ module.body.addWidget(self.send_hint)self.pause_button = QPushButton("Pause crossing")self.pause_button.setCursor(Qt.CursorShape.PointingHandCursor)self.pause_button.clicked.connect(self.toggle_pause)@@ -558,10 +632,14 @@ class WindowsApplication(QWidget):module.body.addWidget(self.hold_switch)module.body.addWidget(self._own_note())module.body.addWidget(widgets.label(- "Off, your pointer can leave a full-screen game or video, and the Mac's pointer can come home "- "through this PC's edge. Useful if your keyboard has no key for the shortcut.", "note", wrap=True))+ "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))return module+ def _redirect_text(self) -> str:+ sendable = [entry for entry in self._peer_entries if entry.get("send")]+ 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()@@ -570,14 +648,18 @@ class WindowsApplication(QWidget):self._refresh_window()def _crossing_state_args(self) -> tuple:- config = self._config- methods = set(config.crossing_methods) if config is not None else set()+ entries = self._peer_entries+ methods = set(self._config.crossing_methods) if self._config is not None else set()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(methods & {"edge", "part", "corner"}),+ self.sender.crossing_paused, self.sender.full_screen_app, self._machines_name(),)+ def _machines_name(self) -> str:+ entries = 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())@@ -598,32 +680,8 @@ class WindowsApplication(QWidget):QApplication.beep()self.tray.showMessage(title, self._shown(message), QIcon(str(ICON_PATH)), 4000)- def _on_mac_learned(self, address: str) -> None:- if self._config is None or self._config.mac_hardware_address == address:- return- self._config.mac_hardware_address = address- self._persist()-- 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)- if self._config is None:- self.allow_switch.setEnabled(False)- self.send_switch.setEnabled(False)- return module+ def _on_alert_text(self, message: str) -> None:+ self._on_alert("Beamer", message)def _same_module(self, current: Config) -> QWidget:module = widgets.Module("Settings")@@ -634,7 +692,7 @@ class WindowsApplication(QWidget):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:+ if self._config is None or not self._paired:self.same_switch.setEnabled(False)return module@@ -645,27 +703,21 @@ class WindowsApplication(QWidget):self.own_notes.append(note)return note- def _peer_too_old(self) -> bool:- """Whether a link is up to a Mac whose Beamer does not keep settings in step."""- with self._status_lock:- receiving = self._status == ServerState.CONNECTED- links = ((receiving, self.server.peer_settings), (self.sender.connected, self.sender.peer_settings))- return any(up and known is False for up, known in links)-def _show_same(self) -> None:if self._config is None:return- old = self._peer_too_old()- on = self._config.same_on_both and not old+ old = False+ on = self._config.same_on_bothif self.same_switch.isChecked() != on:self.same_switch.blockSignals(True)self.same_switch.setChecked(on)self.same_switch.blockSignals(False)- self.same_switch.setEnabled(not old)- self.same_note.setText(settings_sync.switch_note("Mac", self._config.same_on_both, old))+ 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()])+ self.same_note.setText(settings_sync.switch_note(who, self._config.same_on_both, old))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, "Mac", on, pages_win.SCOPE.get(key))+ 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:@@ -673,30 +725,78 @@ class WindowsApplication(QWidget):motion.set_shown(note, on)def _same_fields(self) -> tuple:- return tuple(getattr(self._config, field) if not isinstance(getattr(self._config, field), list)- else tuple(getattr(self._config, field)) for field in settings_sync.PC_FIELDS.values())+ return tuple(settings_sync.pc_values(self._config).values())def _same_state(self) -> dict:config = self._config- return settings_sync.message_data(config.same_on_both, config.same_set_at, settings_sync.pc_values(config))-- def _send_same(self) -> None:- data = self._same_state()- self.sender.send_settings(data)- self.server.send_settings(data)+ return settings_sync.message_data(+ config.same_on_both, config.same_set_at, settings_sync.pc_values(config), by=config.same_by+ )- def _announce(self) -> list:- """What this PC tells the Mac on every new link: its arrangement, only once chosen here- (one a hello filled in is the Mac's to name), and its settings state. On the link's thread."""+ 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."""+ 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++ 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._configif 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 = []- if config.mac_return_edge in return_edge.OPPOSITE and config.arrangement_set_at:- messages.append(protocol.arrangement_msg(return_edge.OPPOSITE[config.mac_return_edge], config.arrangement_set_at))- messages.append(protocol.settings_msg(self._same_state()))+ 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:+ messages.append(protocol.arrangement_v6(entry["side"], entry["side_set_at"], author))+ if entry.get("send"):+ others = [protocol.read_id(item.get("id")) for item in peers if 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, ()):+ messages.append(protocol.settings_msg(self._same_state()))return messages+ 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": "windows",+ "app": VERSION[:32] if VERSION.isascii() and VERSION.isprintable() else "dev",+ "caps": ["clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings"],+ "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 ithas. Either way the Mac follows, now if a link is up, else when one next comes up."""@@ -704,17 +804,20 @@ class WindowsApplication(QWidget):returnself._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_idself._persist()self._send_same()self._show_same()- def _on_settings(self, data) -> None:- """The Mac'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."""+ 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:return- held = (self._config.same_on_both, settings_sync.pc_values(self._config))- taken = settings_sync.arrived(data, self._config.same_set_at, TRIGGER_KEYS, held)+ taken = settings_sync.arrived(+ data, self._config.same_set_at, TRIGGER_KEYS, by_here=self._config.same_by+ )if taken is None:returnon, set_at, values = taken@@ -722,22 +825,24 @@ class WindowsApplication(QWidget):crossing_edge_parts=list(self._config.crossing_edge_parts))config.same_on_both = onconfig.same_set_at = set_at+ config.same_by = data.get("by", "") if isinstance(data.get("by"), str) else ""if on:settings_sync.apply_pc(config, values)try:app_config.validate_config(config)except ConfigError:- LOGGER.exception("Settings from the Mac could not be applied")+ LOGGER.exception("Settings from a peer could not be applied")returnself._config = configself._same_seen = self._same_fields()if not self._persist():return- LOGGER.info("Settings from the Mac applied (same on both machines %s)", "on" if on else "off")+ 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()+ self._send_same(source=protocol.read_id(peer), data=data)def _sign_in_module(self) -> QWidget:module = widgets.Module("At sign-in")@@ -759,22 +864,6 @@ class WindowsApplication(QWidget):module.body.addWidget(self.logon_hint)return module- def _set_allow_drive(self, enabled: bool) -> None:- """Starts or stops the receiver. There is no separate Start/Stop button: this switch is- what persists."""- if self._config is None:- return- self._config.allow_mac_to_drive = bool(enabled)- self._persist()- try:- if enabled:- self.server.start(self._config)- else:- self.server.stop()- except Exception as exc:- LOGGER.exception("Receiver action failed")- self._set_status(ServerState.ERROR, f"Receiver failed: {exc}")-def _set_start_at_logon(self, enabled: bool) -> None:exe = autostart_win.installed_exe()if exe is None:@@ -790,21 +879,6 @@ class WindowsApplication(QWidget):returnself.logon_hint.setText("In the tray, with no window.")- def _toggle_sending(self, enabled: bool) -> None:- """Takes effect at once: it decides whether this PC's own keyboard is being- watched, which is not something to leave a person guessing about."""- if self._config is None:- return- self._config.send_to_mac = bool(enabled)- self._persist()- if enabled:- self._start_sending(self._config)- else:- # Input comes home by this switch and shows where the pointer is, as any switch does;- # stopping would bring it home too, silently, as it does for a reload or quitting.- self.sender.set_redirecting(False)- self._stop_sending()-# -- Crossing -----------------------------------------------------------------------------def _crossing_page(self, layout, current: Config) -> None:@@ -899,16 +973,6 @@ class WindowsApplication(QWidget):for key in ("edge", "parts", "corner", "dragging"):module.body.addWidget(self.crossing_rows[key])- 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 moduledef _ways_changed(self, way: str, on: bool) -> None:@@ -973,11 +1037,12 @@ class WindowsApplication(QWidget):if self._config is None or pc_edge == self._config.mac_return_edge:returnself._config.mac_return_edge = pc_edge- self._config.arrangement_set_at = int(time.time())+ self._config.arrangement_set_at = settings_sync.next_stamp(self._config.arrangement_set_at, time.time())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)+ peer = self._first_peer()+ own = protocol.read_id(self._config.machine_id)+ if peer is not None and own is not None:+ self._send_to(peer, protocol.arrangement_v6(pc_edge, self._config.arrangement_set_at, own))self.sender.update_config(self._config)self._reflect_look()self._reflect_ways()@@ -1004,23 +1069,46 @@ class WindowsApplication(QWidget):self.sender.update_config(self._config)self._reflect_ways()- def _on_arrangement(self, mac_edge: str, set_at: int) -> None:- """The Mac changed the arrangement, over either link. `mac_edge` is always the edge of- the MAC that leads here; an arrival older than what this end already holds is ignored."""+ def _first_peer(self) -> Optional[bytes]:+ """The peer the window shows (`peers[0]`), once it has an id."""+ try:+ peers = self.book.peers()+ except Exception:+ return None+ return protocol.read_id(peers[0].get("id")) if peers else None++ def _on_arrangement(self, peer: str, edge: str, set_at: int, by: str) -> None:+ """A peer changed the arrangement, over either link. `edge` is the edge of the PEER that+ faces this PC; one older than what this end holds, by stamp and then by id, is ignored. A+ side that makes two zones cover one stretch turns the peer's clashing zones off."""if self._config is None:return- pc_edge = return_edge.OPPOSITE.get(mac_edge)- if pc_edge is None or pc_edge == self._config.mac_return_edge:- # One change on the Mac reaches this PC over both links, so the second copy finds it applied.+ try:+ changed, notices = app_config.apply_arrangement(self.config_path, peer, edge, set_at, by)+ except (ConfigError, OSError):+ LOGGER.exception("An arrangement could not be saved")return- if self._config.arrangement_set_at and not protocol.arrangement_wins(set_at, self._config.arrangement_set_at):- LOGGER.info("Ignoring an arrangement from the Mac that is no newer than this PC's (%s vs %s)", set_at, self._config.arrangement_set_at)+ if not changed:return- self._config.mac_return_edge = pc_edge- self._config.arrangement_set_at = int(set_at)- self._persist()+ for notice in notices:+ self._on_alert("Beamer", notice)+ self._pull_peer_fields()+ self.sender.refresh()+ self.server.peers_changed()++ def _pull_peer_fields(self) -> None:+ """What links and arrangements wrote into the first peer, into the window's flat view."""+ if self._config is None:+ return+ try:+ learned = app_config.learned_fields(self.config_path)+ except (ConfigError, OSError):+ LOGGER.exception("The peers could not be read")+ return+ for name, value in learned.items():+ setattr(self._config, name, value)self.sender.update_config(self._config)- self.edge_choice.set_value(pc_edge)+ self.edge_choice.set_value(self._config.mac_return_edge)self._reflect_look()self._reflect_ways()@@ -1574,11 +1662,22 @@ class WindowsApplication(QWidget):self._same_seen = fieldsif shared:self._config.same_set_at = settings_sync.next_stamp(self._config.same_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:self._send_same()return True@@ -1586,188 +1685,349 @@ class WindowsApplication(QWidget):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, "windows", 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: a link may have learnt the migrated entry's+ # id or linked it since, or it may be gone (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)}"+ items.append((entry, labels[token], state, where))+ return items++ def _refresh_peers(self) -> None:+ try:+ peers = self.book.peers()+ except (ConfigError, OSError):+ LOGGER.exception("The peers could not be read")+ peers = []+ self._peer_entries = peers+ self.machines.set_peers(self._peer_items(peers))++ 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("send") and protocol.is_paired_token(entry.get("token")) for entry in self._peer_entries)++ def _label_of(self, peer: Optional[bytes]) -> str:+ return self._labels_by_id.get(peer, "the other 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_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"]:+ 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}"),+ ):+ 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 _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)+ removed = peerlist.remove_peer(settings, token)+ if removed is None:+ return+ 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()+ 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.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.")):- return [address]- return pairing._local_ipv4_addresses()+ return address+ return pairing.pairing_address() or ""def _refresh_pairing(self) -> None:- code = self.announcer.code+ service = self.pairing+ if service is None:+ return+ if self._pairing_open:+ self.sheet.set_machines(service.machines())+ code = service.codeif code is not None:- seconds = self.announcer.seconds_left- 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)}")- widgets.set_role(self.code_label, "code")- self.count_label.setText(f"{seconds // 60}:{seconds % 60:02d}")- widgets.set_role(self.count_label, "count")- self.drain.set_remaining(seconds)- self.pair_button.setText("Cancel")- if not self._code_shown:- self._code_addresses = self._pairing_addresses()- self.address_note.setVisible(bool(self._code_addresses))- motion.set_shown(self.code_module, True)- # Every tick, so switching Hide addresses while a code is up applies at once.- note = self._shown(- f"Not listed on the Mac? Type this PC's address there: {', '.join(self._code_addresses)}"- ) if self._code_addresses else ""- if self.address_note.text() != note:- self.address_note.setText(note)+ hide = self._hide_addresses()+ address = getattr(self, "_code_address", "") if self._code_shown else self._pairing_address()+ self._code_address = address+ rows, note = None, ""+ if hide:+ note = "The QR holds this PC's address, so it is not shown while Hide addresses is on."+ else:+ text = service.qr_text(address) if address else None+ if text is not None:+ if self._qr_cache[0] != text:+ self._qr_cache = (text, qr_code.modules(text))+ rows = self._qr_cache[1]+ where = f"This PC's address: {address} · port {service.tcp_port}" if address else ""+ self.sheet.show_code(code, service.seconds_left, self._shown(where), rows, note)self._code_shown = Truereturnif not self._code_shown:returnself._code_shown = False- motion.set_shown(self.code_module, False)- self.code_label.setAccessibleName("Pairing code")- self.drain.set_remaining(0)- self._show_paired(self._config.paired_with if self._config is not None else "")- outcome = self.announcer.outcome- if outcome == "refused":- self._say_pairing("A wrong code was entered, so that code is cancelled. Pair again for a fresh one.", "note-fault")- elif outcome == "version":- self._say_pairing("The Mac runs a different version of Beamer. Update Beamer on both machines, then pair again.", "note-fault")- elif outcome == "expired":- self._say_pairing("The code expired. Pair again for a fresh one.", "note-amber")- elif outcome is None:- self._say_pairing("Pairing cancelled.", "note")-- def _say_pairing(self, text: str, tone: str) -> None:- if text != self.pair_note.text():- self.pair_note.setText(text)- self.pair_note.setVisible(bool(text))- widgets.set_role(self.pair_note, tone)-- def _on_paired(self, token: str, mac_name: str, mac_address: str) -> None:- current = self._config or default_config()- host = self.host_entry.text().strip() or self._host- if not host:- # A fresh install knows no address of its own; the one facing the Mac is the one- # to show.+ self.sheet.hide_code()+ outcome = service.outcome+ if outcome == "paired":+ return+ text = self._shown(peerlist.host_outcome_text(outcome, service.known))+ self.sheet.say_host(text, "note-amber" if outcome == "expired" else "note-fault")++ def _pick_machine(self, machine: Optional[dict]) -> None:+ self._pairing_machine = machine+ if machine is not None and machine.get("pairing") != pairing.PAIRING_V3:+ self.sheet.say_pair(peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_VERSION), machine["name"]), "note-fault")+ else:+ self.sheet.say_pair("", "note")++ def _pair_clicked(self, machine: Optional[dict], address: str, code: str) -> None:+ service = self.pairing+ if service is None:+ self.sheet.say_pair("Pairing is not available: this PC's settings could not be read.", "note-fault")+ return+ self._pairing_target = machine["name"] if machine is not None else address+ self.sheet.say_pair("", "note")+ self.sheet.busy(True)++ def work() -> None:try:- host = local_address_towards(mac_address)- except OSError:- pass- try:- candidate = replace(- current,- host=host,- port=int(self.port_entry.text().strip() or current.port),- auth_token=token,- paired_with=mac_name,- )- save_config(self.config_path, candidate)- self._apply_config(candidate)- except (ConfigError, TypeError, ValueError, OSError) as exc:- LOGGER.exception("Paired token could not be saved")- self._say_pairing(f"Paired, but the token could not be saved: {exc}", "note-fault")- return- self._host = candidate.host- self.host_entry.setText(candidate.host)- self.token_entry.setText(token)- self._refresh_pairing()- who = mac_name or "your Mac"- self._show_paired(candidate.paired_with)- self._say_pairing("Paired. The receiver restarted with the new token.", "note-live")- LOGGER.info("Paired with %s", who)+ entry = service.pair(machine, code) if machine is not None else service.pair_by_address(address, code)+ except Exception as exc:+ if not isinstance(exc, pairing.PairingError):+ LOGGER.exception("Pairing failed")+ self.bridge.pair_finished.emit(None, exc)+ return+ self.bridge.pair_finished.emit(entry, None)++ threading.Thread(target=work, name="Beamer-pair", daemon=True).start()++ def _on_pair_finished(self, entry, error) -> None:+ if self._closing:+ return+ self.sheet.busy(False)+ if error is not None:+ self.sheet.say_pair(self._shown(peerlist.pairing_error_text(error, self._pairing_target or "That machine")), "note-fault")+ return+ self.sheet.clear_code()+ self.sheet.say_pair(self._shown(f"Paired with {entry['name']}."), "note-live")+ LOGGER.info("Paired with %s", entry["name"])+ self._after_peers_edit()++ def _on_paired(self, entry) -> None:+ """A machine paired with the code this PC was showing, and its entry is stored."""+ if self._closing:+ return+ self.sheet.say_host(self._shown(peerlist.host_outcome_text("paired", entry)), "note-live")+ self._after_peers_edit()# -- Connection -------------------------------------------------------------------------@@ -1776,7 +2036,7 @@ class WindowsApplication(QWidget):privacy = widgets.Module("Addresses")self.hide_switch = widgets.Switch("Hide addresses")self.hide_switch.setFont(theme.font(theme.TYPE["body"]))- self.hide_switch.setChecked(current.hide_addresses)+ self.hide_switch.setChecked(self._hide_addresses())self.hide_switch.toggled.connect(self._set_hide_addresses)privacy.body.addWidget(self.hide_switch)privacy.body.addWidget(widgets.label(@@ -1800,33 +2060,17 @@ class WindowsApplication(QWidget):fields.addWidget(key, row, 0)fields.addWidget(entry, row, 1, 1, span)- # 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)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.save_message = widgets.label("", "note", wrap=True)self.save_message.setVisible(False)module.body.addWidget(self.save_message)@@ -1839,74 +2083,72 @@ class WindowsApplication(QWidget):def _shown(self, text: str) -> str:"""`text` as the window may show it: with Hide addresses on, no address in it."""- return pages_win.redact(text, bool(self._config is not None and self._config.hide_addresses))+ return pages_win.redact(text, self._hide_addresses())def _set_hide_addresses(self, enabled: bool) -> None:if self._config is None:- return- self._config.hide_addresses = bool(enabled)- self._persist()- self._show_host_entry()- self.mac_host_readout.setText(self._shown(self._config.mac_host) or "Not learned yet")+ self._kept_hide = bool(enabled)+ try:+ app_config.set_own(self.config_path, hide_addresses=self._kept_hide)+ except (ConfigError, OSError):+ LOGGER.exception("Hide addresses could not be saved")+ else:+ self._config.hide_addresses = bool(enabled)+ self._persist()+ self.host_readout.setText(self._shown(self._host) or "Not known yet")+ self._refresh_peers()self._refresh_pairing()self._refresh_window()self.tray.setToolTip(self._title())self.status_action.setText(self._title())- def _show_host_entry(self) -> None:- """The address field as dots while addresses are hidden, still editable."""- hide = bool(self._config is not None and self._config.hide_addresses)- self.host_entry.setEchoMode(QLineEdit.EchoMode.Password if hide else QLineEdit.EchoMode.Normal)-- def _update_token_visibility(self, checked: bool) -> None:- self.token_entry.setEchoMode(QLineEdit.EchoMode.Normal if checked else QLineEdit.EchoMode.Password)- self.show_token.setText("Hide" if checked else "Show")- self.show_token.setAccessibleName("Hide the shared token" if checked else "Show the shared token")-def save(self) -> None:- current = self._config or default_config()+ """The Connection page's one setting is this PC's own port. It never touches a peer's entry, whose+ port is that machine's own, and it works with nothing paired."""try:- candidate = replace(- current,- host=self.host_entry.text().strip() or self._host,- port=int(self.port_entry.text().strip()),- auth_token=self.token_entry.text(),- )- save_config(self.config_path, candidate)- self._apply_config(candidate)- except (ConfigError, TypeError, ValueError) as exc:- self.save_message.setText(str(exc))+ port = int(self.port_entry.text().strip())+ if not 1 <= port <= 65535:+ raise ValueError+ app_config.set_own(self.config_path, port=port)+ except (TypeError, ValueError):+ self.save_message.setText("port must be an integer from 1 to 65535")self.save_message.setVisible(True)widgets.set_role(self.save_message, "note-fault")return- except OSError as exc:+ except (ConfigError, OSError) as exc:LOGGER.exception("Configuration could not be saved")QMessageBox.critical(self, "Save failed", str(exc))return+ self._settings_port = port+ if self._config is not None:+ config = replace(self._config, port=port)+ if self._paired:+ self._apply_config(config)+ else:+ self._config = configself.save_message.setText("Saved.")self.save_message.setVisible(True)widgets.set_role(self.save_message, "note-live")def _apply_config(self, config: Config) -> None:- if self.server.listening:- self.server.stop()self._config = config+ self._settings_port = config.portself._same_seen = self._same_fields()self._apply_input_scale(config)if not config.edge_glow:self._hide_crossing()- self.allow_switch.setEnabled(True)- self.allow_switch.setChecked(config.allow_mac_to_drive)- if config.allow_mac_to_drive:- self.server.start(config)- self.send_switch.setEnabled(True)- self.send_switch.setChecked(config.send_to_mac)- if config.send_to_mac:- self.sender.update_config(config)+ self.same_switch.setEnabled(self._paired)+ if self._paired:+ self._start_receiver(config)+ self.server.peers_changed()+ self._send_paired()+ self.sender.update_config(config)+ self._refresh_peers()+ if self._any_send():self._start_sending(config)else:self._stop_sending()- self.mac_host_readout.setText(self._shown(config.mac_host) or "Not learned yet")+ self.host_readout.setText(self._shown(config.host) or "Not known yet")# -- Firewall, on Connection --------------------------------------------------------------@@ -2012,8 +2254,7 @@ class WindowsApplication(QWidget):if (advice.action == "repair"and status.elevated- and not status.allowed- and not status.blocked+ and firewall_win.missing_rule(status)and not self._firewall_auto_repaired):self._firewall_auto_repaired = True@@ -2071,23 +2312,19 @@ class WindowsApplication(QWidget):self.open_action.triggered.connect(self.show_window)self.status_action = menu.addAction(self._title())self.status_action.setEnabled(False)- self.redirect_action = menu.addAction("Send input to your Mac")+ self.redirect_action = menu.addAction("Send input across")self.redirect_action.triggered.connect(self.toggle_redirect)self.pause_action = menu.addAction("Pause crossing")self.pause_action.triggered.connect(self.toggle_pause)menu.addSeparator()# One tick per direction, each the same switch the Overview page shows, so either# direction can be turned off while the other keeps working and the two never disagree.- self.drive_action = menu.addAction("Your Mac drives this PC")+ self.drive_action = menu.addAction("Machines drive this PC")self.drive_action.setCheckable(True)- self.drive_action.toggled.connect(self.allow_switch.setChecked)- self.allow_switch.toggled.connect(self.drive_action.setChecked)- self.send_action = menu.addAction("This PC drives your Mac")+ self.drive_action.triggered.connect(lambda on: self._set_every_peer("allow_drive", on))+ self.send_action = menu.addAction("This PC drives machines")self.send_action.setCheckable(True)- self.send_action.toggled.connect(self.send_switch.setChecked)- self.send_switch.toggled.connect(self.send_action.setChecked)- self.drive_action.setChecked(self.allow_switch.isChecked())- self.send_action.setChecked(self.send_switch.isChecked())+ self.send_action.triggered.connect(lambda on: self._set_every_peer("send", on))menu.addSeparator()menu.addAction("Reload configuration").triggered.connect(self.reload_config)menu.addAction("Open log folder").triggered.connect(self.open_log_folder)@@ -2101,14 +2338,15 @@ class WindowsApplication(QWidget):self.tray.show()def reload_config(self) -> None:- """Re-reads config.json, for the times it was edited outside the window, and shows it."""+ """Re-reads settings.json, for the times it was edited outside the window, and shows it."""try:- config = load_config(self.config_path)+ config = load_config(self.config_path, unpaired_ok=True)except (ConfigError, OSError) as exc:LOGGER.warning("Configuration not reloaded: %s", exc)self._on_alert("Beamer", f"Could not reload the configuration: {exc}")returnself._host = config.host+ self._paired = bool(self.book.peers())self._apply_config(config)self._configure_trigger(config)self._reflect_config(config)@@ -2164,18 +2402,20 @@ class WindowsApplication(QWidget):switch.blockSignals(True)switch.setChecked(value)switch.blockSignals(False)- self.host_entry.setText(config.host)- # The switch above was set with its signal blocked, so its handler never ran.- self._show_host_entry()+ self.host_readout.setText(self._shown(config.host) or "Not known yet")self.port_entry.setText(str(config.port))- self.token_entry.setText(config.auth_token)- self._show_paired(config.paired_with)+ self._refresh_peers()def _on_tray_activated(self, reason) -> None:if reason in (QSystemTrayIcon.ActivationReason.Trigger, QSystemTrayIcon.ActivationReason.DoubleClick):self.show_window()def start(self) -> None:+ if platform_parts.NOT_YET:+ # Nothing listens, announces or checks for updates: the parts behind them are not built.+ self._set_status(ServerState.STOPPED, platform_parts.NOT_YET)+ self._on_firewall(platform_parts.firewall.status("", self._config.port if self._config else protocol.DEFAULT_PORT))+ returnself.update_checker.start()if getattr(sys, "frozen", False) and firewall_win.is_elevated():# Beamer's own rules before any socket opens: a listener Windows has no rule for makes@@ -2189,7 +2429,7 @@ class WindowsApplication(QWidget):try:exe, port = self._firewall_target()status = firewall_win.status(exe, port)- if not status.error and not status.allowed and not status.blocked:+ if firewall_win.missing_rule(status):LOGGER.info("Adding this PC's firewall rules before listening")firewall_win.repair(exe, port, ("Private",))except Exception:@@ -2199,9 +2439,10 @@ class WindowsApplication(QWidget):def _listen(self) -> None:if self._closing:return- self.announcer.start()- if self._config is not None:- self.server.start(self._config)+ if self.pairing is not None:+ self.pairing.start()+ if self._config is not None and self._paired:+ self._start_receiver(self._config)self._start_sending(self._config)# After the rules, so the firewall module reads what start() just wrote, and with no config# the receiver never starts, so nothing else would ever read it.@@ -2210,12 +2451,20 @@ class WindowsApplication(QWidget):def _configure_trigger(self, config: Config) -> None:self._trigger.configure(config.trigger_key, config.trigger_style, config.double_tap_ms)+ def _start_receiver(self, config: Config) -> None:+ if platform_parts.NOT_YET:+ return+ if self.server.listening and self._receiver_port != config.port:+ self.server.stop()+ self._receiver_port = config.port+ self.server.start(config.port)+def _start_sending(self, config: Config) -> None:"""The outward link and the hooks that feed it. The hooks go in onlywhen sending is on: they are the one part of Beamer that can take thisPC's own keyboard away, so an install that never sends never installsthem."""- if not config.send_to_mac:+ if not self._any_send() or platform_parts.NOT_YET:returnself._configure_trigger(config)try:@@ -2226,6 +2475,18 @@ class WindowsApplication(QWidget):returnself.sender.start(config)+ def _on_hook_mouse(self, message: int, x: int, y: int, mouse_data: int) -> bool:+ """Every mouse message, on the hook thread: what Windows said becomes the sender's neutral+ call. True when the event belongs to a peer and Windows must not see it."""+ event = capture_win.mouse_event(message, mouse_data)+ if event is None:+ return False+ if event[0] == "button":+ return self.sender.on_button(event[1], event[2])+ if event[0] == "wheel":+ return self.sender.on_wheel(event[1], event[2])+ return self.sender.on_pointer_move()+def _on_hook_key(self, name: str, down: bool, vk: Optional[int] = None, us: Optional[str] = None) -> bool:"""Every key, on the hook thread. The trigger is swallowed as itswitches; everything else goes to the Mac only while the Mac has@@ -2245,62 +2506,58 @@ class WindowsApplication(QWidget):return Truereturn self.sender.on_key(name, down, vk, us)- def _on_focus(self, target: str) -> None:- """The Mac took input on this PC, or gave it back. Either way the- outward edge follows: one of the two links owns the keyboard at a- time, never both."""- self.sender.set_receiving(target == "windows")+ def _store_paired(self, peer: bytes, ids: list) -> None:+ """The machines a peer says it is paired with, for the Crossing page, on the link's thread."""+ try:+ self.book.store_paired(protocol.id_text(peer), [protocol.id_text(item) for item in ids])+ except (ConfigError, OSError):+ LOGGER.exception("The peers a peer is paired with could not be saved")- def _on_learned(self, host, edge, resistance) -> None:- """The Mac's address and the way home it named in its hello. Saved, so- this PC can open its own link to the Mac before the Mac has crossed --- or at all, if the Mac is asleep when Beamer starts here."""- if self._config is None:+ def _send_paired(self) -> None:+ """Every peer this PC may send to is told the others it has, when the list changes."""+ try:+ peers = self.book.peers()+ except Exception:return- if sender.is_this_machine(host):- # The Mac reached this PC through the macOS 27 localhost tunnel,- # so its "address" is this PC's own. Saving it would point the- # outward link at this PC's own receiver.- LOGGER.info("Ignoring %s as the Mac's address: that is this PC", host)- host = None- changed = False- if host and host != self._config.mac_host and self._config.mac_hardware_address:- # A different Mac: the old one's hardware address would wake the wrong machine.- self._config.mac_hardware_address = ""- changed = True- # The hello's way home only fills an edge this PC does not hold yet: one chosen here, or- # one the Mac's stamped arrangement set, stands, and the Mac announces its arrangement on- # every new link anyway.- if self._config.mac_return_edge:- edge = None- for name, value in (("mac_host", host), ("mac_return_edge", edge or ""), ("mac_resistance_px", resistance)):- if value in (None, "") or getattr(self._config, name) == value:- continue- setattr(self._config, name, value)- changed = True- if not changed:+ ids = [protocol.read_id(item.get("id")) for item in peers]+ for item, peer in zip(peers, ids):+ if peer is not None and item.get("send"):+ self._send_to(peer, protocol.paired_msg([other for other in ids if other not in (None, peer)][: protocol.MAX_PEERS]))++ def _learn_peer_hardware(self, peer: bytes, address: str) -> None:+ """A peer's hardware address from the ARP table, off the GUI thread."""+ try:+ changed = app_config.set_peer_hardware_address(self.config_path, protocol.id_text(peer), address)+ except (ConfigError, OSError):+ LOGGER.exception("A hardware address could not be saved")return- LOGGER.info("Learned the Mac at %s, coming home through the %s edge", self._config.mac_host, self._config.mac_return_edge)- if not self._persist():+ if changed:+ self.bridge.peers_changed.emit()++ def _on_owner(self, peer: str) -> None:+ """A peer took input on this PC, or gave it back. Either way the outward edge follows:+ this PC's input is never here and elsewhere at once."""+ self.sender.set_receiving(bool(peer))++ def _on_peers_changed(self) -> None:+ """A link learnt something about a peer (an address, an id, a name, a hardware address) and+ saved it, or came up or went down: the window's flat view follows, and so do the links."""+ if self._config is None or self._closing:return- self.sender.update_config(self._config)- self._start_sending(self._config)- shown = pages_win.redact(self._config.mac_host, self._config.hide_addresses)- self.mac_host_readout.setText(shown or "Not learned yet")- self.edge_choice.set_value(self._config.mac_return_edge)- self._reflect_look()- self._reflect_ways()+ self._pull_peer_fields()+ self.sender.refresh()+ self._refresh_peers()def _on_sending(self, connected: bool, detail: str) -> None:self._sending_detail = detaildef _on_redirecting(self, redirecting: bool) -> None:self._sending_detail = (- "This PC's keyboard and mouse are on the Mac" if redirecting else self.sender.status+ f"This PC's keyboard and mouse are on {self._label_of(self.sender.owner)}" if redirecting else self.sender.status)def _announced_port(self) -> int:- return self._config.port if self._config is not None else default_config().port+ return self._settings_portdef show_window(self) -> None:self.showNormal()@@ -2347,7 +2604,8 @@ class WindowsApplication(QWidget):self._closing = Trueself.refresh_timer.stop()self.update_checker.stop()- self.announcer.stop()+ if self.pairing is not None:+ self.pairing.stop()self.server.stop()self._stop_sending()self._hide_crossing()@@ -2435,24 +2693,6 @@ class WindowsApplication(QWidget):return Nonereturn self.effects- def _return_model(self, edge: str, resistance: int):- """The way home for the Mac's pointer through `edge` of this screen, from this PC's own- ways in, as for this PC's own mouse: only the chosen thirds, the whole edge, the corner- when it sits on that edge, else none (the Mac's shortcut still switches). On the- receiver's session thread."""- config = self._config- if config is None:- return return_edge.ReturnEdge(edge, resistance)- methods = set(config.crossing_methods)- if "part" in methods:- return return_edge.PartEdge(edge, config.crossing_edge_parts, resistance)- if "edge" in methods:- return return_edge.ReturnEdge(edge, resistance)- corner = config.crossing_corner- if "corner" in methods and edge in corner.split("_"):- return return_edge.CornerPush(corner, edge, resistance)- return None-def _on_effects_failed(self) -> None:"""The overlay turned the effects off for the run; the Design page says so."""self._effects_failed = True@@ -2495,11 +2735,8 @@ class WindowsApplication(QWidget):detail = self._status_detailtone = theme.state_tone(state.value.lower())self.led.set_tone(tone)- # The Mac's name goes in the detail, not the heading: a long name wrapped the heading onto+ # The machines' names go in the detail, not the heading: a long name wrapped the heading onto# two lines at 640 wide and made the window scroll.- if state is ServerState.CONNECTED and detail.startswith("Connected to "):- who = (self._config.paired_with if self._config is not None else "") or "Your Mac"- detail = f"{who} at {detail[len('Connected to '):]}"detail = self._shown(detail)heading = STATUS_TITLES[state]if heading != self.status_heading.text():@@ -2512,7 +2749,7 @@ class WindowsApplication(QWidget):if detail != self.status_detail.text():self.status_detail.setText(detail)widgets.set_role(self.status_detail, "note-fault" if state is ServerState.ERROR else "note")- location = "On your Mac" if self.sender.redirecting else "On this PC"+ location = f"On {self._label_of(self.sender.owner)}" if self.sender.redirecting else "On this PC"if location != self.location_readout.text():self.location_readout.setText(location)trip = self.sender.round_trip_ms@@ -2520,14 +2757,14 @@ class WindowsApplication(QWidget):if trip_text != self.round_trip_readout.text():self.round_trip_readout.setText(trip_text)self.round_trip_row.setVisible(trip is not None)- redirect_text = "Bring input back to this PC" if self.sender.redirecting else "Send input to your Mac"+ redirect_text = "Bring input back to this PC" if self.sender.redirecting else self._redirect_text()if redirect_text != self.redirect_button.text():self.redirect_button.setText(redirect_text)self.redirect_action.setText(redirect_text)- sending = self._config is not None and self._config.send_to_mac+ sending = self._config is not None and self._any_send()self.redirect_button.setEnabled(sending)self.redirect_action.setEnabled(sending)- self.redirect_note.setVisible(not sending and self._config is not None)+ self.redirect_note.setVisible(not sending and self._paired)pause_text = "Resume crossing" if self.sender.crossing_paused else "Pause crossing"if pause_text != self.pause_button.text():self.pause_button.setText(pause_text)@@ -2542,30 +2779,24 @@ class WindowsApplication(QWidget):armed = args[4]self.pause_button.setVisible(armed)motion.set_shown(self.pause_row, armed or pages_win.crossing_state_blocked(*args[:4]))- outward = pages_win.outward_link_line(self.sender.connected)- if outward != self.outward_line.text():- shot = motion.snapshot(self.outward_line)- self.outward_line.setText(outward)- motion.fade_from(self.outward_line, shot)- # "On your Mac" above already says this while redirecting; the hint is for the rest --+ # "On <machine>" above already says this while redirecting; the hint is for the rest --# not connected, or the hooks failing to install -- and stays quiet in the boring case.send_hint = "" if self.sender.redirecting or self._sending_detail in (- "Off", "Not connected to the Mac"+ "Off", "Not connected") else self._shown(self._sending_detail)if send_hint != self.send_hint.text():self.send_hint.setText(send_hint)# Hidden while empty, or its spacing leaves a gap between the two switches.self.send_hint.setVisible(bool(send_hint))self.sidebar.set_link(tone, SIDEBAR_LINK_WORDS.get(state, "Unknown"))- self.sidebar.set_dots(pages_win.dots(self._config is None, self._firewall_tone))+ self.sidebar.set_dots(pages_win.dots(self._config is None or not self._paired, self._firewall_tone))+ self._peers_tick += 1+ if self._peers_tick % 4 == 0:+ self._refresh_peers()+ else:+ self._refresh_peer_states()+ self._refresh_tray_directions()self._refresh_pairing()- edge = self.server.return_edge- resistance = self.server.return_resistance- known = bool(edge) and resistance is not None- text = f"{edge} edge · {resistance} px" if known else ""- if text != self.return_readout.text():- self.return_readout.setText(text)- motion.set_shown(self.return_row, known)def _title(self) -> str:with self._status_lock:@@ -2574,43 +2805,64 @@ class WindowsApplication(QWidget):def parse_args() -> argparse.Namespace:parser = argparse.ArgumentParser(description="Beamer Windows receiver")- parser.add_argument("--config", type=Path, default=default_config_path(), help="path to config.json")+ parser.add_argument("--config", type=Path, default=default_config_path(), help="path to settings.json")parser.add_argument("--hidden", action="store_true", help="start in the tray without showing the window")return parser.parse_args()-def main() -> None:- if sys.platform != "win32":- raise SystemExit("Beamer Windows receiver must run on Windows")- # use_last_error, then ctypes.get_last_error(): a plain GetLastError() call- # through windll can read an error ctypes' own marshalling set in between,- # and 183 (already exists) is the whole single-instance check.[email protected]_cache(maxsize=None)+def _windows_kernel32():kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)kernel32.CreateMutexW.restype = ctypes.c_void_pkernel32.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_wchar_p]kernel32.CloseHandle.argtypes = [ctypes.c_void_p]- mutex = kernel32.CreateMutexW(None, False, "Local\\Beamer.Receiver")- already_running = ctypes.get_last_error() == 183- if not mutex:- raise OSError("Beamer could not create its single-instance lock")- if already_running:- kernel32.CloseHandle(mutex)+ kernel32.GetCurrentProcess.restype = ctypes.c_void_p+ kernel32.SetPriorityClass.argtypes = [ctypes.c_void_p, ctypes.c_ulong]+ return kernel32+++def _claim_instance():+ """The single-instance lock: the function that gives it back, or None when another Beamer+ already holds it."""+ if sys.platform == "win32":+ # use_last_error, then ctypes.get_last_error(): a plain GetLastError() call+ # through windll can read an error ctypes' own marshalling set in between,+ # and 183 (already exists) is the whole single-instance check.+ kernel32 = _windows_kernel32()+ mutex = kernel32.CreateMutexW(None, False, "Local\\Beamer.Receiver")+ already_running = ctypes.get_last_error() == 183+ if not mutex:+ raise OSError("Beamer could not create its single-instance lock")+ if already_running:+ kernel32.CloseHandle(mutex)+ return None+ return lambda: kernel32.CloseHandle(mutex)+ from PySide6.QtCore import QLockFile++ lock = QLockFile(str(Path(tempfile.gettempdir()) / f"Beamer.Receiver.{os.getuid()}.lock"))+ lock.setStaleLockTime(0)+ return lock.unlock if lock.tryLock(0) else None+++def main() -> None:+ release = _claim_instance()+ if release is None:returnarguments = parse_args()log_path = configure_logging()LOGGER.info("Starting Beamer Windows receiver")if log_path is not None:LOGGER.info("Logging to %s", log_path)- # Above normal, so a busy machine cannot starve the hooks: Windows removes a- # low-level hook whose callback misses its timeout, silently and for good,- # and every Beamer thread must win the CPU for the hook thread to get the- # GIL. Beamer idles near 0%, so the class costs the rest of the machine- # nothing (for example, a video pipeline holding half the CPU once left- # the PC's mouse stranded on the Mac).- kernel32.GetCurrentProcess.restype = ctypes.c_void_p- kernel32.SetPriorityClass.argtypes = [ctypes.c_void_p, ctypes.c_ulong]- if not kernel32.SetPriorityClass(kernel32.GetCurrentProcess(), 0x8000): # ABOVE_NORMAL_PRIORITY_CLASS- LOGGER.warning("Could not raise Beamer's priority: %s", ctypes.WinError(ctypes.get_last_error()))+ if sys.platform == "win32":+ # Above normal, so a busy machine cannot starve the hooks: Windows removes a+ # low-level hook whose callback misses its timeout, silently and for good,+ # and every Beamer thread must win the CPU for the hook thread to get the+ # GIL. Beamer idles near 0%, so the class costs the rest of the machine+ # nothing (for example, a video pipeline holding half the CPU once left+ # the PC's mouse stranded on the Mac).+ kernel32 = _windows_kernel32()+ if not kernel32.SetPriorityClass(kernel32.GetCurrentProcess(), 0x8000): # ABOVE_NORMAL_PRIORITY_CLASS+ LOGGER.warning("Could not raise Beamer's priority: %s", ctypes.WinError(ctypes.get_last_error()))try:app = QApplication(sys.argv)app.setApplicationName("Beamer")@@ -2623,7 +2875,7 @@ def main() -> None:application.start()sys.exit(app.exec())finally:- kernel32.CloseHandle(mutex)+ release()def import_probe(out_path: str, names: list) -> int:diff --git a/win_app/linux_stand_ins.py b/win_app/linux_stand_ins.pynew file mode 100644index 0000000..6de412f--- /dev/null+++ b/win_app/linux_stand_ins.py@@ -0,0 +1,125 @@+"""The OS parts on Linux until their back ends land: each answers as a machine that has nothing,+says once in the log that it is not built yet, and does nothing. They let the shell start and show+its window and tray; nothing listens, pairs or captures.++Each mirrors only the names the shell reaches through platform_parts, with the Windows module's+signatures, so a real back end replaces one by name without touching a caller."""++import logging+from dataclasses import dataclass+from types import SimpleNamespace+from typing import Optional++LOGGER = logging.getLogger("Beamer")++NOT_YET = "Linux support is not built yet: Beamer cannot pair, capture or be driven here"++_said: set = set()+++def _say(part: str) -> None:+ if part not in _said:+ _said.add(part)+ LOGGER.info("%s is not yet on Linux", part)+++# Wire names come from a per-OS key table. Until Linux has one, the default trigger alone is in it+# (evdev's KEY_RIGHTCTRL, 97), so a saved config still validates.+_KEY_RIGHTCTRL = 97+++class _Hooks:+ def __init__(self, on_key, on_mouse, on_motion) -> None:+ pass++ def start(self) -> None:+ _say("Keyboard and mouse capture")++ def stop(self) -> None:+ pass+++class _Trigger:+ def configure(self, key: str, style: str, window_ms: int) -> None:+ pass++ def feed(self, name: str, down: bool, now: float) -> Optional[str]:+ return None++ def claims(self, name: str, down: bool, redirecting: bool) -> bool:+ return False+++capture = SimpleNamespace(+ Hooks=_Hooks,+ Trigger=_Trigger,+ TOGGLE="toggle",+ REDIRECT="redirect",+ RETURN="return",+ VK_TO_NAME={_KEY_RIGHTCTRL: "cmd_r"},+ VK_TITLES={_KEY_RIGHTCTRL: "Right Ctrl"},+ hook_vk=lambda vk, scan: vk,+ input_title=lambda entry: entry,+)++desktop = SimpleNamespace(+ monitors=lambda: [],+ cursor_position=lambda: (0, 0),+ set_cursor_position=lambda x, y: None,+ full_screen_app=lambda: None,+ button_down=lambda name: False,+)++clipboard = SimpleNamespace(+ get_contents=lambda: (None, None),+ changed_contents=lambda: (None, None),+ forget_sync=lambda: None,+ set_contents=lambda text, png: False,+)++autostart = SimpleNamespace(+ installed_exe=lambda: None,+ is_enabled=lambda: False,+ set_enabled=lambda enabled, exe: None,+)++unlock = SimpleNamespace(+ is_locked=lambda: None,+ signal_unlock=lambda: False,+ ensure_unlocked=lambda *args, **kwargs: False,+)++injector = SimpleNamespace(release_all=lambda: None)+++@dataclass(frozen=True)+class FirewallStatus:+ port: int+ allowed: bool = False+ blocked: bool = False+ active_profiles: tuple = ()+ lan_profiles: tuple = ()+ covered: bool = False+ public_interfaces: tuple = ()+ elevated: bool = False+ error: str = ""+ pairing_allowed: bool = True+++@dataclass(frozen=True)+class Advice:+ sentence: str+ button: str+ action: Optional[str]+ rule_profiles: tuple = ("Private",)+++firewall = SimpleNamespace(+ FirewallStatus=FirewallStatus,+ Advice=Advice,+ status=lambda exe, port: FirewallStatus(port),+ advise=lambda status: Advice("Beamer's firewall check is not yet on Linux.", "Check again", None),+ repair=lambda exe, port, profiles: None,+ trust_network=lambda indexes: None,+ is_elevated=lambda: False,+)diff --git a/win_app/machines_win.py b/win_app/machines_win.pynew file mode 100644index 0000000..4b2b89a--- /dev/null+++ b/win_app/machines_win.py@@ -0,0 +1,431 @@+"""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.QtWidgets import (+ QButtonGroup,+ QHBoxLayout,+ QLineEdit,+ QPushButton,+ QSizePolicy,+ QVBoxLayout,+ QWidget,+)++import peers_view+import theme+import widgets+from core import pairing++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+++def _plain() -> QWidget:+ item = QWidget()+ item.setProperty("vernier", "plain")+ return item+++def _button(text: str, role: str = "") -> QPushButton:+ button = QPushButton(text)+ if role:+ button.setProperty("vernier", role)+ button.setCursor(Qt.CursorShape.PointingHandCursor)+ return button+++class PeerRow(QWidget):+ """One paired machine: its name and state, one sentence, the two direction switches and Remove."""++ def __init__(self, token: str, on_send: Callable, on_allow: Callable, on_remove: Callable) -> None:+ super().__init__()+ self.setProperty("vernier", "plain")+ self.token = token+ 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.setSpacing(10)+ self.led = widgets.Led()+ head.addWidget(self.led, 0, Qt.AlignmentFlag.AlignVCenter)+ self.name = widgets.label("", "tile-name", wrap=True)+ head.addWidget(self.name, 1)+ self.word = widgets.label("", "readout")+ head.addWidget(self.word, 0, Qt.AlignmentFlag.AlignRight)+ 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.send = widgets.Switch("This PC drives it")+ self.allow = widgets.Switch("It drives this PC")+ 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.setSpacing(16)+ switches = QVBoxLayout()+ switches.setSpacing(2)+ switches.addWidget(self.send)+ switches.addWidget(self.allow)+ for switch in (self.send, self.allow):+ switch.setMaximumWidth(300)+ controls.addLayout(switches)+ controls.addStretch(1)+ controls.addWidget(self.remove_button, 0, Qt.AlignmentFlag.AlignBottom)+ self.controls = controls+ column.addLayout(controls)+ self.confirm = _plain()+ sure = QVBoxLayout(self.confirm)+ 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 _ask(self, asking: bool) -> None:+ self.confirm.setVisible(asking)+ self.remove_button.setVisible(not asking)+ self.send.setVisible(not asking)+ self.allow.setVisible(not asking)++ def refresh(self, entry: dict, label: str, state, where: str) -> None:+ 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.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}")+++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_remove: Callable, on_pair: Callable) -> None:+ super().__init__("Machines")+ self._callbacks = (on_send, on_allow, 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)++ 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.setFont(theme.mono_font(theme.PAIRING_CODE))+ 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))+ 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)+ 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.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.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))+ 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) -> 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."""+ listed = [item for item in machines if item.get("pair_id") or item.get("pairing") != pairing.PAIRING_V3]+ key = tuple((item["address"], item["name"], item.get("platform"), item.get("pairing"), item.get("pair_id")) for item in listed)+ 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 in listed:+ version = item.get("pairing") == pairing.PAIRING_V3+ text = f"{item['name']} · {peers_view.platform_name(item)} · " + ("showing a code" if version else OLDER)+ button = _button(text, "choice")+ 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 --git a/win_app/pages_win.py b/win_app/pages_win.pyindex fc2c8c7..634e3fe 100644--- a/win_app/pages_win.py+++ b/win_app/pages_win.py@@ -12,8 +12,8 @@ from core import effects# (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."),@@ -176,19 +176,19 @@ def toggle_part(parts, part, on) -> list:NOT_LEARNED_EDGE = "Not learned yet: your Mac tells this PC when it first connects, or choose a side."-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="your Mac") -> 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."@@ -207,14 +207,6 @@ def crossing_state_blocked(paired, mac_heard, sending, connected) -> bool:return not (paired and mac_heard and sending and connected)-def outward_link_line(connected) -> str:- """The Overview's line for this PC's own link to the Mac, which its edges need and the receiver's- status above it does not say."""- if connected:- return "This PC to your Mac: Linked"- return "This PC to your Mac: not connected, so pushing an edge does nothing"--def crossing_rows(methods) -> frozenset:"""Which of the Crossing page's rows the chosen ways use; the rest are hidden."""methods = set(methods)diff --git a/win_app/peers_view.py b/win_app/peers_view.pynew file mode 100644index 0000000..61d49e8--- /dev/null+++ b/win_app/peers_view.py@@ -0,0 +1,70 @@+"""What each paired machine's row on Overview says: a tone, a state word and one sentence.++Pure, so every state a link can be in is tested against a word. The booleans decide the broad+state; the link's own `kind` picks the flavour of a fault, and its status sentence (which already+names the machine, WIRE.md section 2) is the detail. The words are the Mac's, row for row.+"""++from __future__ import annotations++from dataclasses import dataclass++from core import protocol++PLATFORM_NAMES = {"macos": "Mac", "windows": "Windows", "linux": "Linux", "ios": "iPhone", "android": "Android"}++REFUSED_KINDS = ("unauthenticated", "wrong_id", "different", "unreadable")+VERSION_KINDS = ("older", "newer", "not_beamer")+UNREACHABLE_KINDS = ("unreachable", "timeout")+QUIET_KINDS = ("connected", "removed", "off")+++@dataclass(frozen=True)+class PeerState:+ tone: str+ word: str+ detail: str+++def platform_name(entry: dict) -> str:+ return PLATFORM_NAMES.get(entry.get("platform"), "Other")+++def address_line(entry: dict, hide: bool) -> str:+ host, port = entry.get("host") or "", entry.get("port")+ if not host or not isinstance(port, int) or isinstance(port, bool) or port <= 0:+ return "No address"+ return f"{'•••' if hide else host} · port {port}"+++def describe(entry: dict, label: str, *, up: bool, driving: bool, input_there: bool, kind: str, status: str,+ waking: bool) -> PeerState:+ """`up`: a link to this machine is live, either way round. `driving`: its input is on this PC.+ `input_there`: this PC's input is on it. `kind` and `status`: what the link this PC dials to it+ last reported."""+ if driving:+ return PeerState("signal", "Driving this PC",+ f"{label}'s keyboard and pointer are on this PC. Push the pointer back through the edge it arrived by to send them home.")+ if input_there:+ return PeerState("signal", "Input here",+ f"This PC's keyboard and pointer are on {label}. Do the same again to bring them home.")+ if not protocol.is_paired_token(entry.get("token")):+ return PeerState("amber", "Pair again",+ f"{label} was paired in 1.4.x with a typed token, which 1.5.0 does not use. Remove it and pair it again.")+ if up:+ return PeerState("signal", "Linked", f"Connected to {label}.")+ if waking:+ return PeerState("amber", "Waiting", f"Waking {label}…")+ if not entry.get("send"):+ return PeerState("amber", "Waiting", f"Waiting for {label} to connect.")+ if not status or kind in QUIET_KINDS:+ return PeerState("amber", "Waiting", f"Looking for {label}. It connects on its own once Beamer is open there.")+ if kind in REFUSED_KINDS:+ return PeerState("fault", "Refused", status)+ if kind in VERSION_KINDS or (kind == "closed" and status.startswith("Update Beamer on")):+ return PeerState("fault", "Version", status)+ if kind in UNREACHABLE_KINDS:+ return PeerState("fault", "Unreachable", status)+ if kind == "refused":+ return PeerState("fault", "Not listening", status)+ return PeerState("fault", "Dropped", f"{status.rstrip('.')}. Beamer keeps trying to reconnect.")diff --git a/win_app/platform_parts.py b/win_app/platform_parts.pynew file mode 100644index 0000000..230a578--- /dev/null+++ b/win_app/platform_parts.py@@ -0,0 +1,45 @@+"""The one switch between the OS parts the shell drives: capture, injection, clipboard, desktop+geometry, autostart, firewall and unlock, which also carry the touchpad injector and GameInputSvc+(input_injector and desktop_win reach them). Chosen once, at import.++Linux gets linux_stand_ins, and no Windows module is imported there. Every other platform keeps+the Windows modules, including the Mac, where the win_app tests import them on purpose. The+callers keep their old names (`capture_win` and so on) bound to these, so a test that patches+`kvm_bridge_win.firewall_win` still patches the part in use."""++import sys+from types import SimpleNamespace++PARTS = ("capture", "desktop", "clipboard", "autostart", "firewall", "unlock", "injector")+++def load(platform: str) -> SimpleNamespace:+ # Plain imports, not importlib: PyInstaller finds modules by reading import statements.+ if platform.startswith("linux"):+ import linux_stand_ins++ return SimpleNamespace(not_yet=linux_stand_ins.NOT_YET, **{name: getattr(linux_stand_ins, name) for name in PARTS})+ import autostart_win+ import capture_win+ import clipboard_win+ import desktop_win+ import firewall_win+ import input_injector+ import unlock_win++ return SimpleNamespace(+ not_yet=None, capture=capture_win, desktop=desktop_win, clipboard=clipboard_win, autostart=autostart_win,+ firewall=firewall_win, unlock=unlock_win, injector=input_injector,+ )+++_parts = load(sys.platform)++NOT_YET = _parts.not_yet+capture = _parts.capture+desktop = _parts.desktop+clipboard = _parts.clipboard+autostart = _parts.autostart+firewall = _parts.firewall+unlock = _parts.unlock+injector = _parts.injectordiff --git a/win_app/qr_code.py b/win_app/qr_code.pynew file mode 100644index 0000000..1e690b5--- /dev/null+++ b/win_app/qr_code.py@@ -0,0 +1,27 @@+"""The pairing QR as a grid of dark and light modules, for the window to paint.++The text is the one WIRE.md section 6 specifies (`core.pairing.qr_text`); segno is pure Python, so the+built app needs nothing beside it. Level M: a phone camera reads it off a screen at that, and every+level above it only makes the code denser.+"""++from __future__ import annotations++from typing import Optional++try:+ import segno+except ImportError: # the sheet shows the code and the address alone+ segno = None++QUIET = 4+++def modules(text: str) -> Optional[list]:+ """Rows of booleans, True for a dark module, with the four-module quiet zone the QR standard+ asks of the reader's surround; None when segno is not installed."""+ if segno is None:+ return None+ rows = [list(map(bool, row)) for row in segno.make(text, error="m", micro=False, boost_error=False).matrix]+ edge = len(rows[0]) + 2 * QUIET+ return [[False] * edge] * QUIET + [[False] * QUIET + row + [False] * QUIET for row in rows] + [[False] * edge] * QUIETdiff --git a/win_app/requirements-win.txt b/win_app/requirements-win.txtindex a2f58ec..17ffc2b 100644--- a/win_app/requirements-win.txt+++ b/win_app/requirements-win.txt@@ -2,3 +2,4 @@ PySide6-Essentials>=6.11.1pyinstaller>=6.0pyinstaller-hooks-contrib>=2024.1PyNaCl>=1.6+segno>=1.6diff --git a/win_app/sender.py b/win_app/sender.pyindex a3b4390..050591f 100644--- a/win_app/sender.py+++ b/win_app/sender.py@@ -1,116 +1,86 @@-"""Sending this PC's own keyboard and mouse to the Mac: the mirror of-mac_app/bridge.py's link half, talking to the same receiver.py the Mac's-sender talks to, over a second connection this PC opens outwards.--Two links, not one bidirectional socket. The existing Mac-to-Windows link is-the one used every day, and its sequence, acknowledgement and watchdog-bookkeeping is all sender-shaped; threading a second ownership state through-it would put that link at risk for nothing. This one is opened by this PC, to-the Mac's own listener on the same port number, so it needs no inbound-firewall rule here.--Nothing about the crossing is configured on this side. The Mac names the way-home on its own link -- the Windows edge input comes back through -- and that-is the same physical border this PC pushes out across, so the edge, its-resistance and the Mac's address are all learned rather than typed.--Which way input is flowing is one state across both links: the outbound edge-is armed only while the Mac is not driving this PC, so a pointer the Mac is-moving cannot push itself back out through the border it just came in by.+"""This PC's own keyboard and mouse going to its peers: the Windows half of WIRE.md sections 3 to 5.++One outbound link per peer with `send` on (core/link.py), and the owner state machine+(core/owner.py) deciding where each input event goes: here, or to one peer. This module is the glue+between the two and the platform: it feeds the owner the events the hooks capture, carries out what+the owner answers (messages on links, the clipboard, the pointer landing, the pin that holds the+pointer still while input is elsewhere), and arms this PC's own zones (WIRE.md section 8) so a push+through one takes the peer beyond it.++No platform name is imported here: the desktop, the clipboard and the way a hook says what happened+(`on_button`, `on_wheel`, `on_pointer_move`, `on_motion`, `on_key`) are handed in, so the Linux+shell reaches the same code. Keys arrive with the names Windows capture gives them, the Windows+key as "ctrl" and Ctrl as "cmd", and leave as the physical key (`PHYSICAL`) before core/keytable.py+names them for each peer.++Which peer a shortcut, the tray or a menu picks is the first one the UI shows (`peers[0]`); a push+through a zone picks that zone's peer."""import collectionsimport ipaddressimport loggingimport queue-import socket-import structimport threadingimport timefrom typing import Callable, Optionalfrom core import ignored+from core import keytable+from core import owner as owner_module+from core import peerlistfrom core import protocol+from core import receiverfrom core import return_edgefrom core import wolLOGGER = logging.getLogger(__name__)-ACK_TIMEOUT_SECONDS = 2.0-CONNECT_TIMEOUT_SECONDS = 1.0-AUTH_TIMEOUT_SECONDS = 2.0-SOCKET_IO_TIMEOUT_SECONDS = 0.5-PING_INTERVAL_SECONDS = 1.0-OUTBOUND_QUEUE_SIZE = 2048+SEND_QUEUE_SIZE = 4096MONITORS_MAX_AGE_SECONDS = 1.0--CONTROL_MESSAGE_TYPES = frozenset({protocol.MSG_FOCUS, protocol.MSG_CLIPBOARD})-_LOCAL_CLIPBOARD_SENTINEL_TYPE = "_local_clipboard"-_GATE_EXEMPT_TYPES = CONTROL_MESSAGE_TYPES | {_LOCAL_CLIPBOARD_SENTINEL_TYPE}-# A key-up owed to the Mac for a key that went down there, queued as input-# comes home. Local to the queue: _process_outbound rebuilds the message from-# its type and data, so the mark never reaches the wire.-_RELEASE_MARK = "_release"--ROUND_TRIP_SAMPLES = 8+TICK_SECONDS = 0.1ROUND_TRIP_MAX_AGE_SECONDS = 5.0WAKE_POLL_SECONDS = 0.5-WAKING_STATUS = "Waking your Mac…"-NOT_WOKEN_STATUS = "Your Mac did not wake"--# The capture names this PC's Ctrl "cmd" and its Windows key "ctrl", the Semantic style, so Ctrl+C-# is Cmd+C on the Mac. Positional swaps them back.-POSITIONAL_SWAP = {"cmd": "ctrl", "cmd_r": "ctrl_r", "ctrl": "cmd", "ctrl_r": "cmd_r"}--OLD_RECEIVER_STATUS ="The Mac did not answer the handshake — it is probably running an older Beamer; update it"-AUTH_FAILED_STATUS = "The Mac could not be authenticated — check the shared token matches on both sides"---class HandshakeError(protocol.ProtocolError):- def __init__(self, status):- super().__init__(status)- self.status = status---class FrameDecoder:- """Reassembles and opens frames from the raw chunks the reader thread- receives. One per connection, like the session it opens frames with."""-- def __init__(self, session):- self.session = session- self.buffer = bytearray()-- def feed(self, chunk):- self.buffer.extend(chunk)- messages = []- while len(self.buffer) >= protocol.HEADER_SIZE:- length = struct.unpack_from(">I", self.buffer)[0]- if length < 1 or length > protocol.MAX_FRAME_BYTES:- raise protocol.ProtocolError(f"invalid message length: {length}")- frame_length = protocol.HEADER_SIZE + length- if len(self.buffer) < frame_length:- break- body = bytes(self.buffer[protocol.HEADER_SIZE:frame_length])- del self.buffer[:frame_length]- messages.append(self.session.open(body))- return messages+# How long a machine that is being driven waits for its driver to let go before it gives up on+# the move it was asked for: the responder's own forced end is one second.+LET_GO_WAIT_SECONDS = 1.5+WAKING_STATUS = "Waking {name}…"+NOT_WOKEN_STATUS = "{name} did not wake"+NOT_CONNECTED_STATUS = "Not connected"++# The capture names this PC's Ctrl "cmd" and its Windows key "ctrl", the Semantic style; the key+# table takes the physical key, so the two are swapped back here.+PHYSICAL = {"cmd": "ctrl", "cmd_r": "ctrl_r", "ctrl": "cmd", "ctrl_r": "cmd_r"}+MEDIA_KEYS = frozenset(+ {"volume_mute", "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause"}+)+OWN_PLATFORM = "windows"+INPUT_TYPES = protocol.INPUT_TYPES++# What the owner's reasons for bringing input home say, naming the machine (WIRE.md section 5).+HOME_REASONS = {+ "owned": "{name} is being driven from another machine",+ "not_allowed": "{name} does not accept input from this one",+ "busy": "{name} is driving another machine",+ "sent_home": "{name} sent the input back",+ "link_lost": "Lost the link to {name}",+ "no_answer": "{name} did not answer",+ "refused": "{name} would not take the input",+ "malformed": "{name} would not take the input",+}def is_this_machine(host: str, local_addresses=None, address_towards=None) -> bool:- """Whether `host` is this PC rather than the Mac. Worth a guard of its- own: the Mac's address is learned from the peer address of its own link,- and when the Mac connects through the macOS 27 SSH tunnel that address is- 127.0.0.1 -- this PC's. Connecting there would reach this PC's own- receiver, authenticate with the shared token, and the receiver's preempt- rule would close the real Mac's session. The daily link would drop and- reconnect for as long as both were running.-- Two answers are consulted, because the first one fails silently: the- hostname-based address list is empty on a PC whose name does not- resolve, and an empty list would have said "not this machine" for this- machine's own address. The route probe asks the stack which local- address would reach `host`; for this PC's own address that is the- address itself."""+ """Whether `host` is this PC rather than a peer. Worth a guard of its own: a peer's address is+ learned from the peer address of its own link, and when the Mac connects through the macOS 27+ SSH tunnel that address is 127.0.0.1 -- this PC's. Connecting there would reach this PC's own+ receiver, authenticate with the pair's token, and the responder would take it for the peer's+ second link and close the real one.++ Two answers are consulted, because the first one fails silently: the hostname-based address+ list is empty on a PC whose name does not resolve, and an empty list would have said "not this+ machine" for this machine's own address. The route probe asks the stack which local address+ would reach `host`; for this PC's own address that is the address itself."""if not host:return Truetry:@@ -133,146 +103,156 @@ def is_this_machine(host: str, local_addresses=None, address_towards=None) -> boreturn False-def _default_socket_factory(address, timeout):- return socket.create_connection(address, timeout=timeout)---class MacSender:- """One link to the Mac, plus the decision -- taken on the hook thread --- of whether each local input event belongs to this PC or to the Mac.+class LinkSender:+ """The links to every peer this PC may send to, and the decision -- taken on the hook thread --+ of whether each local input event belongs to this PC or to one of them.- `status_callback(connected, detail)` and `redirect_callback(redirecting)`- are called from worker threads; a GUI marshals them. `desktop` and- `clipboard` default to the real Win32 modules and are handed in by tests.- """+ `book` is a `receiver.PeerBook` over the app's settings and `zones()` gives this PC's zones as+ settings.json keeps them. `identity()` is this machine as a `hello` says it. Callbacks, each+ from a worker thread (a GUI marshals them): `status_callback(connected, detail)` for the first+ peer, `redirect_callback(redirecting)`, `pressure_callback(edge, pressure, crossed, part)` and+ `arrival_callback(edge, x, y)`. `driven()` says whether a peer's input is on this PC, and+ `send_peer_home()` sends it home, both the responder's, handed in by the app that owns both+ halves. `desktop` and `clipboard` are the platform's modules. `hardware(host)` is this PC's+ hardware address on the interface that reaches `host`, which each link sends in its own `hello`."""def __init__(self,+ book: receiver.PeerBook,+ identity: Callable[[], dict],+ *,+ zones: Callable[[], list] = lambda: [],status_callback: Callable[[bool, str], None] = None,redirect_callback: Callable[[bool], None] = None,pressure_callback: Callable[[str, float, bool, Optional[str]], None] = None,- arrangement_callback: Callable[[str, int], None] = None,+ arrival_callback: Callable[[str, int, int], None] = None,desktop=None,clipboard=None,- socket_factory=_default_socket_factory,+ links=None,is_local=is_this_machine,clock=time.monotonic,wake_sender=wol.send_magic_packet,mac_lookup=wol.lookup_mac,- arrival_callback: Callable[[str, int, int], None] = None,+ hardware: Callable[[str], str] = None,) -> None:+ self._book = book+ self._identity = identity+ self._hardware = hardware+ self._zones = zonesself._status_callback = status_callbackself._redirect_callback = redirect_callbackself._pressure_callback = pressure_callback- self._arrangement_callback = arrangement_callback- # Same on both machines, as the receiver's: `settings_callback(data)` for each settings- # message from the Mac, `announce()` for what to send the moment the link is up,- # `peer_settings` whether the Mac's welcome said it keeps settings in step.- self.settings_callback: Optional[Callable[[dict], None]] = None- self.announce: Callable[[], list] = lambda: []- self.peer_settings: Optional[bool] = None- # `arrival_callback(edge, x, y)`, as the shared receiver's: the pointer came home through the- # Mac's return edge and was placed at desktop pixel (x, y) on `edge` of this PC, or, with- # edge None, input came home by a switch and the pointer is at (x, y) where it was left.self._arrival_callback = arrival_callbackself._desktop = desktopself._clipboard = clipboard- self._socket_factory = socket_factoryself._is_local = is_localself._clock = clock+ self._wake_sender = wake_sender+ self._mac_lookup = mac_lookupself._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 useself._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+ 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._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 = Falseself._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.+ # (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+ # 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.notice_callback: Optional[Callable[[str], None]] = 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 ------------------------------------------------@property- def connected(self) -> bool:- with self._socket_lock:- return self._sock is not None+ def redirecting(self) -> bool:+ owner = self._owner+ return owner is not None and owner.away@property- def status(self) -> str:- return self._status+ def owner(self) -> Optional[bytes]:+ """The peer this PC's input is on, or None at home."""+ owner = self._owner+ return owner.on if owner is not None else None++ def expects_clipboard(self, link, began) -> bool:+ """For a link's `large` hook: whether a frame its peer began sending at `began` could be the+ clipboard of a let-go."""+ owner, peer = self._owner, protocol.read_id(link.peer_id)+ return owner is not None and peer is not None and owner.expects_clipboard(peer, began)@property- def edge(self) -> Optional[str]:- return self._edge+ def connected(self) -> bool:+ peer = self._primary()+ return peer is not None and self.links.up(peer)++ @property+ def status(self) -> str:+ peer = self._primary_key()+ return self._statuses.get(peer) or NOT_CONNECTED_STATUS@propertydef waking(self) -> bool:- return self._waking+ return bool(self._waking)++ def is_waking(self, peer: bytes) -> bool:+ return peer in self._waking@propertydef round_trip_ms(self) -> Optional[int]:- """The Mac's figure, measured the same way: the upper median of the last few trips from- an input event's send to the ACK naming it, or None while input is not on the Mac, the- link is down, or nothing fresh has been acknowledged for a few seconds."""- if not self.redirecting or not self.connected:- return None- with self._sequence_lock:- trips = sorted(self._round_trips)- measured_at = self._round_trip_at- if not trips or self._clock() - measured_at > ROUND_TRIP_MAX_AGE_SECONDS:- return None- return int(round(trips[len(trips) // 2] * 1000))+ """The upper median of the last few trips from an input event's send to the ACK naming it,+ less the time the peer held that ACK, on the link the input is on; None while input is+ here or nothing fresh has been acknowledged."""+ peer = self.owner+ return self.links.round_trip_ms(peer) if peer is not None else None@propertydef full_screen_app(self):@@ -290,17 +270,11 @@ class MacSender:def edges_held(self) -> bool:return self.crossing_paused or self.full_screen_app is not None- def set_receiving(self, receiving: bool) -> None:- """Called when the Mac takes input on this PC, and again when it gives- it back. While it is True nothing here arms, sends or crosses."""- receiving = bool(receiving)- if receiving == self._receiving:- return- self._receiving = receiving- if receiving and self.redirecting:- self.set_redirecting(False, came_home=False)- self._last_point = None- self._rearm_edge()+ @property+ def shortcut_armed(self) -> bool:+ """Whether the double-tap may move input. The app asks before acting on the trigger, so+ turning the shortcut off here turns it off everywhere."""+ return "shortcut" in set(self._setting("crossing_methods", ("edge", "shortcut")) or ())# -- lifecycle ----------------------------------------------------------@@ -309,210 +283,197 @@ class MacSender:if self._threads:returnself._stop_event.clear()- for name, target in (- ("Beamer-mac-link", self._connection_worker),- ("Beamer-mac-out", self._outbound_worker),- ("Beamer-mac-in", self._reader_worker),- ("Beamer-mac-watchdog", self._watchdog_worker),- ):+ for name, target in (("Beamer-links-out", self._outbound_worker), ("Beamer-links-tick", self._tick_worker)):thread = threading.Thread(target=target, name=name, daemon=True)thread.start()self._threads.append(thread)+ self.links.start()def stop(self) -> None:- self._stop_event.set()self._buttons_held.clear()- self.set_redirecting(False, came_home=False)- self._drop_connection()+ self.set_redirecting(False)+ # The let-go and the releases ahead of it are sent before anything stops.+ deadline = self._clock() + 1.0+ while self._threads and (not self._outbound.empty() or self._clip_wait) and self._clock() < deadline:+ time.sleep(0.01)+ self._stop_event.set()+ self.links.stop()for thread in self._threads:thread.join(timeout=2.0)self._threads = []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:- return False- last = max(self._last_ack_at, self._connected_at)- return (self._clock() - last) <= ACK_TIMEOUT_SECONDS+ 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._feed(lambda o: o.link_down(peer))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)- return True- if not self._link_live():- self._force_local("the link to the Mac went quiet")- return False- if vk is not None and self._ignore_gate.keeps(ignored.key(vk), down):+ """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+ return self._input({"type": protocol.MSG_KEYDOWN if down else protocol.MSG_KEYUP, "data": dict(data)})- 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+ 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))- def _send_mouse(self, capture_win, message, mouse_data) -> bool:- button = capture_win.button_of(message, mouse_data)- if button is not None:- name, down = button- if self._ignore_gate.keeps(ignored.button(name), down):- return False- self._enqueue(- {"type": protocol.MSG_MOUSEDOWN if down else protocol.MSG_MOUSEUP, "data": {"button": name}}- )- return True- if message == capture_win.WM_MOUSEWHEEL:- self._enqueue(protocol.scroll_msg(capture_win.wheel_notches(mouse_data), 0.0, "line"))- return True- if message == capture_win.WM_MOUSEHWHEEL:- self._enqueue(protocol.scroll_msg(0.0, capture_win.wheel_notches(mouse_data), "line"))- return True- # Anything else the Mac has no name for: left to Windows rather than- # dropped.- return False+ def _input(self, message: dict) -> bool:+ """Gives the owner one input event and carries out what it answers; True when this PC+ must not act on the event."""+ with self._lock:+ actions = self._owner.input(message)+ self._queue(actions)+ self._report(actions)+ return not any(action is owner_module.LOCAL for action in actions)def _press_edge(self, dx, dy) -> None:- """One raw movement while input is still this PC's. Feeds the same- return-edge model the Mac's receiver uses, so the border behaves- identically whichever side of it the pointer starts on.-- Nothing is held here, unlike the receiver's side of the same model:- Windows has already stopped the cursor at the edge of the desktop, so- the hold is the screen's own. Only the pressure is ours to measure,- and only a breakthrough acts.-- It runs while the Mac is driving this PC too. Every move the Mac makes- here carries INJECTED_MARK and never arrives, so what does is this- PC's own mouse, and its push out means the pointer is going back to- the Mac with this mouse behind it (ignoring this once left only the- Mac's trackpad able to take the pointer back)."""- if not self.connected or self.edges_held:+ """One raw movement while input is still this PC's. Feeds the zone models, the same ones+ the responder uses for a driven pointer, so the border behaves identically whichever side+ of it the pointer starts on.++ Nothing is held here, unlike the responder's side of the same models: Windows has already+ stopped the cursor at the edge of the desktop, so the hold is the screen's own. Only the+ pressure is ours to measure, and only a breakthrough acts.++ It runs while a peer is driving this PC too. Every move a peer makes here carries+ INJECTED_MARK and never arrives, so what does is this PC's own mouse, and its push out+ means the pointer is going on with this mouse behind it."""+ if not self._models or self.edges_held or self._owner is None:returnif self._buttons_held and self._setting("block_while_dragging", True) and self._still_dragging():# A drag that reaches the edge is dragging, not leaving: the push so far is dropped,# as the Mac drops it, so letting go at the edge does not finish a crossing.- for candidate in (self._corner_model, self._edge_model):- if candidate is not None:- candidate.reset()+ for _peer, model in self._models:+ model.reset()returntry: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+ 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:returnexcept Exception:- LOGGER.exception("The way out to the Mac failed; crossing out is off until the next reconnect")- self._edge_model = self._corner_model = None+ LOGGER.exception("The way out failed; crossing out is off until the next change")+ self._models = []returnpart = Noneif isinstance(model, return_edge.PartEdge):@@ -522,19 +483,10 @@ class MacSender:part = model.cornerself._notify_pressure(model.edge, outcome.pressure, outcome.action == return_edge.CROSS, part)if outcome.action == return_edge.CROSS:- if self._receiving:- # The Mac's input goes home first, over its own link; its- # focus back to the Mac clears receiving here too, later, and- # finds it already cleared.- send_home = self.send_peer_home- if send_home is None or not send_home():- LOGGER.warning("cannot cross: the Mac is driving this PC and cannot be reached")- self._alert("Cannot switch — the Mac is driving this PC and cannot be reached")- return- self._receiving = False- # The model names the edge on the far side, not the one just left:- # it is the same border, read from the other end.- self.set_redirecting(True, arrival_edge=outcome.edge, offset=outcome.offset)+ offset = receiver.corner_offset(model.corner, model.edge) if isinstance(model, return_edge.CornerPush) else outcome.offset+ # The model names the edge on the far side, not the one just left: it is the same+ # border, read from the other end.+ self._go(target, outcome.edge, offset)def _still_dragging(self) -> bool:"""A release the hook never saw -- let go over the secure desktop or an elevated window --@@ -550,582 +502,544 @@ class MacSender:# -- switching ----------------------------------------------------------- def set_redirecting(self, value, arrival_edge=None, offset=None, came_home=True) -> bool:- """`arrival_edge` is the Mac edge the pointer arrives at and `offset`- the fraction along it -- the same fraction it left this PC at, which- is what makes one border out of two screens. Both are absent when the- shortcut moved input rather than a crossing.-- Input coming home this way is a switch -- the shortcut, the tray, the- direction switch or the Mac sending it back -- and is reported to the- arrival callback with edge None, for the arrival that shows where the- pointer is. `came_home` is False for the two ways back that show their- own: a crossing that lands here, and the Mac taking this PC over."""- value = bool(value)- if value == self.redirecting:- return False+ def set_redirecting(self, value, came_home=True) -> bool:+ """Moves this PC's input to the first peer, or home, as the shortcut, the tray and the+ direction switch do. False when nothing moved."""if value:- if not self.connected:- LOGGER.warning("cannot redirect: the Mac is not connected")- if not self.wake():- self._alert(f"Cannot switch — {self._status}")+ if self.redirecting:return False- if self._receiving:- # The Mac is driving this PC over the other link, so switching- # to the Mac means sending its input home, the way back that- # does not depend on the Mac's own return edge.- send_home = self.send_peer_home- if send_home is not None and send_home():- return True- LOGGER.warning("cannot redirect: the Mac is driving this PC and cannot be reached")- self._alert("Cannot switch — the Mac is driving this PC and cannot be reached")+ peer = self._primary()+ if peer is None:+ self._alert(f"Cannot switch — {self.status}")return False- self.redirecting = True- self._pin_point = self._desktop_module().cursor_position()- arrival = arrival_edge if arrival_edge in return_edge.EDGES else None- self._enqueue_control({"type": _LOCAL_CLIPBOARD_SENTINEL_TYPE, "data": {}})- self._enqueue_control(- protocol.focus_msg(- "mac",- edge=arrival,- offset=offset,- return_edge=arrival or self._mac_arrival_edge(),- resistance_px=int(self._resistance()),- )- )- LOGGER.info("redirecting input to the Mac")- else:- # The flag first, so the hook thread stops adding keys; then- # whatever is still down on the Mac is released there before the- # focus goes home, marked to pass the gate that has just closed.- # The entries stay, so the physical releases here are swallowed.- self.redirecting = False- self._ignore_gate.reset()- for data in list(self._keys_down.values()):- self._enqueue_control({"type": protocol.MSG_KEYUP, "data": data, _RELEASE_MARK: True})- self._pin_point = None- self._last_point = None- # A fresh model, not a reset one: the old one disarmed itself at- # breakthrough so a burst of deltas still in flight could not- # cross twice, and nothing else re-arms it.- self._rearm_edge()- self._enqueue_control(protocol.focus_msg("windows"))- LOGGER.info("input returned to this PC")- if came_home:- self._report_switch_home()- if self._redirect_callback is not None:- try:- self._redirect_callback(value)- except Exception:- LOGGER.exception("Redirect callback failed")+ return self._go(peer)+ if not self.redirecting:+ return False+ with self._lock:+ actions = self._owner.go(None)+ self._queue(actions)+ self._report(actions)return True- def _report_switch_home(self) -> None:- if self._arrival_callback is None:- return- try:- x, y = self._desktop_module().cursor_position()- self._arrival_callback(None, x, y)- except Exception:- LOGGER.exception("Arrival callback for a switch failed")-def toggle(self) -> None:- """The shortcut's way across and back, for when the pointer is not at- an edge -- or the edge is off."""+ """The shortcut's way across and back, for when the pointer is not at an edge -- or the+ edge is off."""self.set_redirecting(not self.redirecting)- def _handle_switch(self, data) -> None:- """The Mac pushed the pointer back through its return edge. Stop- sending, then land the pointer on the edge of this PC it comes back- to."""- if not isinstance(data, dict) or data.get("target") != "windows":+ def go(self, peer: bytes, edge: Optional[str] = None, offset: Optional[float] = None) -> bool:+ return self._go(peer, edge, offset)++ def _go(self, peer: bytes, edge=None, offset=None) -> bool:+ owner = self._owner+ if owner is None:+ return False+ if self.driven():+ # A machine that is driven does not drive (section 4): its driver goes home first, then+ # the move goes ahead. Waiting happens off this thread, which may be the hook's.+ threading.Thread(target=self._after_let_go, args=(peer, edge, offset), name="Beamer-links-home", daemon=True).start()+ return True+ with self._lock:+ self._note_clipboard()+ actions = owner.go(peer, edge, offset)+ self._queue(actions)+ self._report(actions)+ if owner.away and self.driven():+ # A take here won as this one was sent (section 4's busy rule): both stay at home.+ with self._lock:+ actions = owner.go(None)+ self._queue(actions)+ self._report(actions)+ return owner.away++ def _after_let_go(self, peer, edge, offset) -> None:+ if not self.send_peer_home() and self.driven():+ self._alert(f"Cannot switch — {self._name(peer)} could not be reached while this PC is being driven")return- edge = data.get("edge")- offset = data.get("offset")- crossed = edge in return_edge.EDGES and isinstance(offset, (int, float)) and not isinstance(offset, bool)- # Without an edge the Mac sent this PC's input home by its own switch: that is a switch- # arriving here, and shows where the pointer is.- self.set_redirecting(False, came_home=not crossed)- if crossed:- 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- if self._arrival_callback is not None:+ deadline = self._clock() + LET_GO_WAIT_SECONDS+ while self.driven() and self._clock() < deadline and not self._stop_event.is_set():+ time.sleep(0.02)+ if not self.driven() and not self.redirecting:+ self._go(peer, edge, offset)++ def set_receiving(self, receiving: bool) -> None:+ """A peer took this PC's input, or gave it back. Input cannot be here and elsewhere at+ once (section 4): if it was on a peer, it comes home."""+ if receiving and self.redirecting:+ self.set_redirecting(False)++ # -- inbound messages ---------------------------------------------------++ def on_link(self, peer: bytes, up: bool, accepts: bool = False) -> None:+ """A link came up (its handshake done) or went down, from its own thread."""+ with self._lock:+ if up:+ self._accepts[peer] = accepts+ else:+ self._accepts.pop(peer, None)+ actions = self._owner.link_up(peer, accepts) if up else self._owner.link_down(peer)+ self._queue(actions)+ self._report(actions)+ self.refresh()+ self._report_status()+ if up and self.hw_learned is not None:+ threading.Thread(target=self._learn_hardware, args=(peer,), name="Beamer-links-hw", daemon=True).start()+ callback = self.link_callback+ if callback is not None:+ self._call(callback, peer, up)++ def on_message(self, peer: bytes, message: dict, began_at: Optional[float] = None) -> None:+ """What a peer sent back on the link this PC opened to it, from that link's thread."""+ kind = message.get("type")+ data = message.get("data") or {}+ if kind == protocol.MSG_SWITCH:+ read = protocol.read_switch(message)+ if read is not None:+ with self._lock:+ self._note_clipboard()+ actions = self._owner.switch(peer, read)+ self._queue(actions)+ self._report(actions)+ elif kind == protocol.MSG_ACCEPT:+ read = protocol.read_accept(message)+ if read is not None:+ with self._lock:+ self._note_clipboard()+ actions = self._owner.accept(peer, read)+ self._queue(actions)+ self._report(actions)+ elif kind == protocol.MSG_REFUSE:+ read = protocol.read_refuse(message)+ if read is not None:+ with self._lock:+ actions = self._owner.refuse(peer, read)+ self._queue(actions)+ self._report(actions)+ elif kind == protocol.MSG_ACCEPTS:+ read = protocol.read_accepts(message)+ if read is not None:+ with self._lock:+ self._accepts[peer] = read["accepts"]+ actions = self._owner.accepts(peer, read["accepts"])+ self._queue(actions)+ self._report(actions)+ elif kind == protocol.MSG_CLIPBOARD:+ 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"])+ with self._lock:+ actions = self._owner.clipboard_arrived(peer, began_at if began_at is not None else self._clock(), clean)+ self._queue(actions)+ self._report(actions)+ elif kind == protocol.MSG_ARRANGEMENT:+ read = protocol.read_arrangement_v6(message, time.time())+ if read is not None and self.arrangement_callback is not None:+ self._call(self.arrangement_callback, peer, read)+ elif kind == protocol.MSG_SETTINGS:+ if isinstance(data, dict) and self.settings_callback is not None and "settings" in self.links.caps(peer):+ self._call(self.settings_callback, peer, data)+ elif kind == protocol.MSG_PAIRED:+ read = protocol.read_paired(message)+ if read is not None and self.paired_callback is not None:+ self._call(self.paired_callback, peer, read)++ def on_status(self, key, up: bool, detail: str) -> None:+ """A link's status text, for the peer the UI shows."""+ self._statuses[key] = detail+ self._report_status()++ def _report_status(self) -> None:+ if self._status_callback is not None:+ self._call(self._status_callback, self.connected, self.status)++ # -- sending ------------------------------------------------------------++ def send_to(self, peer: bytes, message: dict) -> bool:+ """A message of this machine's own (`arrangement`, `settings`, `paired`) on the link it+ opened to `peer`; False when there is none, and the app then tries the peer's own link."""+ return self.links.up(peer) and self.links.post(peer, message)++ def send_arrangement(self, peer: bytes, edge: str, set_at: int) -> bool:+ """Tells a peer which of this PC's edges faces it, when the change was made here."""+ return self.send_to(peer, protocol.arrangement_v6(edge, set_at, self._own_id))++ def peers_up(self) -> list:+ return [peer for peer in self._peers if self.links.up(peer)]++ def _queue(self, actions) -> None:+ """Hands what the owner answered to the outbound worker, in order. Called with the lock still+ held, in the same step as the decision, so two threads' decisions cannot reach the worker the+ other way round (a release behind the press it releases would leave the key down)."""+ for action in actions:+ if isinstance(action, (owner_module.Send, owner_module.SendClipboard, owner_module.SetClipboard)):try:- self._arrival_callback(edge, x, y)- except Exception:- LOGGER.exception("Arrival callback failed")+ self._outbound.put_nowait(action)+ except queue.Full:+ LOGGER.error("the outbound queue filled up; input returns to this PC")+ self._overflowed = True+ return- # -- the link -----------------------------------------------------------+ def _report(self, actions) -> None:+ """What the owner reported that is not a message: where the input is now, a move that did not+ happen. Never under the lock, since it calls the app."""+ if self._overflowed:+ self._overflowed = False+ self._lost()+ for action in actions:+ if isinstance(action, owner_module.Moved):+ self._moved(action)+ elif isinstance(action, owner_module.Unreachable):+ self._unreachable(action)- def _connection_worker(self) -> None:+ def _outbound_worker(self) -> None:while not self._stop_event.is_set():- config = self._ready_config()- if config is None or self.connected:- self._stop_event.wait(0.5)+ try:+ action = self._outbound.get(timeout=0.2)+ except queue.Empty:continue- if not self._connect_once(config):- self._stop_event.wait(max(0.5, float(getattr(config, "reconnect_interval_s", 2.0))))+ try:+ self._deliver(action)+ except Exception:+ # One bad message must not end the only thread that drains this queue: nothing+ # restarts it, and the hooks would keep swallowing input into a queue nobody reads.+ LOGGER.exception("outbound worker recovered")+ self._lost()+ finally:+ self._outbound.task_done()++ 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."""+ if isinstance(action, owner_module.SetClipboard):+ self._set_clipboard(action.message)+ return+ peer = action.peer+ 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):+ self._clip_wait[peer] = collections.deque()+ threading.Thread(target=self._clipboard_then_rest, args=(peer,), name="Beamer-links-clipboard", daemon=True).start()+ return+ self._send(peer, action.message)- def _connect_once(self, config) -> bool:- host, port = self._address(config)- sock = None- self._set_status(f"Connecting to the Mac at {host}:{port}")+ def _clipboard_then_rest(self, peer: bytes) -> None:try:- sock = self._socket_factory((host, port), CONNECT_TIMEOUT_SECONDS)- sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)- sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)- session = protocol.SecureSession(config.auth_token)- sock.sendall(session.preamble())- sock.settimeout(AUTH_TIMEOUT_SECONDS)+ self._send_clipboard(peer)+ except Exception:+ LOGGER.exception("The clipboard could not be sent")+ while True:+ with self._clip_lock:+ waiting = self._clip_wait[peer]+ if not waiting:+ del self._clip_wait[peer]+ return+ action = waiting.popleft()try:- protocol.recv_preamble(sock, session)- except socket.timeout:- raise HandshakeError(OLD_RECEIVER_STATUS) from None- except protocol.VersionMismatch as exc:- raise HandshakeError(- f"The Mac speaks Beamer protocol v{exc.peer_version}, this PC v{protocol.PROTOCOL_VERSION} — update both apps"- ) from None- protocol.send_msg(- sock,- session,- protocol.hello_msg(- return_edge=self._mac_arrival_edge(), resistance_px=int(self._resistance())- ),+ if isinstance(action, owner_module.SendClipboard):+ self._send_clipboard(peer)+ else:+ self._send(peer, action.message)+ except Exception:+ LOGGER.exception("A message held behind the clipboard could not be sent")++ 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):+ message = self._key_message(peer, message)+ 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) -> 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:+ # 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:- reply = protocol.recv_msg(sock, session)- except (protocol.ConnectionClosed, protocol.AuthenticationError):- # The receiver closes without a word when a frame fails to authenticate.- raise HandshakeError(AUTH_FAILED_STATUS) from None- if reply.get("type") != protocol.MSG_WELCOME:- raise protocol.ProtocolError("the Mac did not confirm authentication")- data = reply.get("data")- if not isinstance(data, dict):- raise protocol.ProtocolError("welcome message missing data")- if data.get("error") or data.get("version") != protocol.PROTOCOL_VERSION:- raise HandshakeError(OLD_RECEIVER_STATUS)- self.peer_settings = protocol.keeps_settings(data)- sock.settimeout(SOCKET_IO_TIMEOUT_SECONDS)- except HandshakeError as exc:- self._close(sock)- self._set_status(exc.status)- LOGGER.warning("connection to the Mac failed: %s", exc.status)- return False- except (OSError, protocol.ProtocolError) as exc:- self._close(sock)- self._set_status(f"The Mac is not reachable on {host}:{port}")- LOGGER.debug("connection to the Mac failed: %s", exc)- return False- with self._socket_lock:- if self._stop_event.is_set() or self._sock is not None:- self._close(sock)- return False- self._sock = sock- self._session = session- self._clipboard_module().forget_sync()- now = self._clock()- with self._sequence_lock:- self._last_sent_seq = 0- self._last_ack_seq = -1- self._last_ack_at = now- self._unacked_sent_at.clear()- self._round_trips.clear()- self._round_trip_at = 0.0- self._connected_at = now- self._last_send_at = now- self._set_status(f"Connected to the Mac at {host}")- LOGGER.info("connected to the Mac at %s:%s", host, port)- self._learn_mac_address(host)+ name = keytable.wire_name(physical, OWN_PLATFORM, entry.get("platform", "macos"), 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._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) -> None:try:- announcements = list(self.announce())+ text, image = self._clipboard_module().get_contents()except Exception:- LOGGER.exception("announce failed")- announcements = []- for announcement in announcements:- self._send_raw(announcement)- return True+ LOGGER.exception("Failed to read the local clipboard for %s", self._name(peer))+ 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 ("clipboard_image" not in caps or len(image) > protocol.CLIPBOARD_IMAGE_MAX_BYTES):+ image = None+ if not text and image is None:+ return+ self.links.post(peer, protocol.clipboard_msg(text or None, image))- def _learn_mac_address(self, host) -> None:- """Read the Mac's hardware address from the ARP table while the entry is fresh, for the- wake-up a later switch may need."""+ 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):+ returntry:- address = self._mac_lookup(host)+ self._clipboard_module().set_contents(read["text"], read["image"])except Exception:- LOGGER.exception("hardware address lookup failed")+ LOGGER.exception("Failed to set the local clipboard")return- if not address or address == self._setting("mac_hardware_address", ""):+ 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:+ if self._pin_point is None:+ self._pin_point = self._desktop_module().cursor_position()+ LOGGER.info("input is on %s", self._name(moved.to))+ self._report_redirecting(True)return- # Not written here: the config is the app's own object, which the app saves.- LOGGER.info("learned the Mac's hardware address from the ARP table")- if self.on_mac_learned is not None:- try:- self.on_mac_learned(address)- except Exception:- LOGGER.exception("on_mac_learned callback failed")-- def wake(self) -> bool:- """Send the Mac a wake-on-LAN packet and wait up to a minute for the link, as the Mac- does for the PC. Nothing is queued: the person switches again once the Mac is up. False- when there is no address to wake or a wake is already in flight."""- address = self._setting("mac_hardware_address", "")- if not address or self.connected or self._status in (AUTH_FAILED_STATUS, OLD_RECEIVER_STATUS) \- or "protocol v" in self._status:- # A Mac that answered and refused is awake; waking it would hide why.- return False- with self._wake_lock:- if self._waking:- return True- self._waking = True- threading.Thread(target=self._wake_worker, args=(address,), name="Beamer-wake-mac", daemon=True).start()- return True+ 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)", moved.why)+ 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:+ reason = HOME_REASONS.get(moved.why, "{name} returned the input")+ self._alert(reason.format(name=self._name(moved.left)))- def _wake_worker(self, address) -> None:- started = self._clock()+ 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:- self._wake_sender(address, self._setting("mac_host", "") or None)- except (OSError, ValueError) as exc:- LOGGER.warning("wake-on-LAN packet not sent: %s", exc)- self._waking = False- self._alert("Could not send the wake-up packet")- return- LOGGER.info("sent wake-on-LAN to the Mac")- self._alert(WAKING_STATUS)- while not self._stop_event.wait(WAKE_POLL_SECONDS):- if self.connected:- self._waking = False- LOGGER.info("the Mac woke and connected")- self._alert("Your Mac is awake — switch again to send input")- return- if self._clock() - started >= wol.WAKE_WINDOW_SECONDS:- break- self._waking = False- if self._stop_event.is_set():+ 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- LOGGER.warning("the Mac did not answer within %.0fs of the wake-on-LAN packet", wol.WAKE_WINDOW_SECONDS)- self._alert(NOT_WOKEN_STATUS)+ self._report_arrival(edge, x, y)- def _alert(self, message: str) -> None:- if self.on_alert is None:+ def _report_arrival(self, edge, x=None, y=None) -> None:+ if self._arrival_callback is None:returntry:- self.on_alert("Beamer", message)+ if x is None:+ x, y = self._desktop_module().cursor_position()+ self._arrival_callback(edge, x, y)except Exception:- LOGGER.exception("Alert callback failed")+ LOGGER.exception("Arrival callback failed")- def _outbound_worker(self) -> None:- while not self._stop_event.is_set():- try:- message = self._outbound.get(timeout=0.2)- except queue.Empty:- continue- try:- self._process_outbound(message)- except Exception:- # One bad message must not end the only thread that drains- # this queue: nothing restarts it, and the hooks would keep- # swallowing input into a queue nobody reads.- LOGGER.exception("outbound worker recovered")- self._force_local(f"outbound message {message.get('type')!r} failed")- finally:- self._outbound.task_done()+ 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 _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 _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 message_type == _LOCAL_CLIPBOARD_SENTINEL_TYPE:- self._send_local_clipboard()+ if action.why == "unreachable" and self._accepts.get(action.peer) is False:+ self._alert("Cannot switch — " + HOME_REASONS["not_allowed"].format(name=name))return- if message_type in CONTROL_MESSAGE_TYPES:- self._send_raw(message)+ self._alert(f"Cannot switch — {name} could not be reached")++ 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"):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_settings(self, data: dict) -> bool:- """Tell the Mac this PC's settings state."""- return self._send_raw(protocol.settings_msg(data))-- def _send_local_clipboard(self) -> None:try:- text, image = self._clipboard_module().changed_contents()+ address = self._mac_lookup(entry["host"])except Exception:- LOGGER.exception("Failed to read the local clipboard for the Mac")- return- if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:- LOGGER.warning("Local clipboard text too large; skipping the text")- 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")- image = None- if not text and image is None:+ LOGGER.exception("hardware address lookup failed")return- self._send_raw(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()+ 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._primary()+ 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):+ return False+ with self._wake_lock:+ if peer in self._waking:return True- except (OSError, protocol.ProtocolError) as exc:- self._connection_failed(f"Sending to the Mac failed: {exc}", expected_socket=sock)- return False+ self._waking.add(peer)+ threading.Thread(target=self._wake_worker, args=(peer, address, entry), name="Beamer-wake", daemon=True).start()+ return True- 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+ def _wake_worker(self, peer, address, entry) -> None:+ name = self._name(peer)+ started = self._clock()+ try: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)- return- if message_type == protocol.MSG_CLIPBOARD:- self._apply_inbound_clipboard(message.get("data", {}))- return- if message_type == protocol.MSG_SWITCH:- self._handle_switch(message.get("data", {}))- 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")- return- if message_type == protocol.MSG_SETTINGS:- data = message.get("data")- if isinstance(data, dict) and self.settings_callback is not None:- try:- self.settings_callback(data)- except Exception:- LOGGER.exception("Settings callback failed")- return+ 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 ------------------------------------------------------------ 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):+ def _tick_worker(self) -> None:+ while not self._stop_event.wait(TICK_SECONDS):+ self.tick()++ def tick(self) -> None:+ """What happens as time passes: the owner's waits and left-out peers, the zones following who+ can be reached, and following a peer's beacon to a new address."""+ owner = self._owner+ if owner is None: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:+ with self._lock:+ actions = owner.tick()+ self._queue(actions)+ if frozenset(owner.reach_for(None)) != self._armed_for:+ # A peer began to accept this PC's input, or one left out after a failed hand-over+ # has had its three seconds: the zones that lead to it are live or dead now.+ self._arm_locked()+ self._report(actions)+ now = self._clock()+ if now - self._followed_at >= 1.0:+ self._followed_at = now+ self.links.follow(self.machines())++ def _arm_locked(self) -> None:+ """A fresh set of zone models, for the peers this PC can send to now (never the one its input+ is on: that peer's own zones lead on from there)."""+ owner = self._owner+ if owner is None:+ self._models = []return+ allowed = set(owner.reach_for(None))+ self._armed_for = frozenset(allowed)try:- self._clipboard_module().set_contents(text, image)+ self._models = receiver.zone_models(+ self._zone_list, self._entries, allowed, self._resistance(), None,+ )except Exception:- LOGGER.exception("Failed to set the local clipboard from the Mac")-- def _watchdog_worker(self) -> None:- while not self._stop_event.wait(0.1):- self._watchdog_tick()-- def _watchdog_tick(self) -> bool:- if not self.connected:- 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+ LOGGER.exception("Could not arm the zones")+ self._models = []++ def _primary_key(self):+ """The first peer the UI shows that this PC dials: by id once it has one, else by its token's+ key id, which is all a migrated entry has until its first link."""+ for entry in self._entries:+ if entry.get("send") and entry.get("host") and entry.get("port"):+ return self.links.key_of(entry)+ return None- # -- plumbing -----------------------------------------------------------+ def _primary(self) -> Optional[bytes]:+ for entry in self._entries:+ peer = protocol.read_id(entry.get("id"))+ if peer is not None and entry.get("send") and entry.get("host") and entry.get("port"):+ return peer+ return None- def _enqueue(self, message) -> None:- try:- self._outbound.put_nowait(message)- except queue.Full:- self._force_local("the outbound queue to the Mac filled up")+ def _status_of(self, peer) -> str:+ entry = self._peers.get(peer) or {}+ return self._statuses.get(self.links.key_of(entry)) or NOT_CONNECTED_STATUS- def _enqueue_control(self, message) -> None:- try:- self._outbound.put_nowait(message)- except queue.Full:- LOGGER.error("outbound queue full; dropped control message %r", message.get("type"))+ def _name(self, peer) -> str:+ """What this PC's statuses and alerts call a machine: its label, so two of one name are told apart."""+ return peerlist.label_for(self._entries, peer_id=protocol.id_text(peer)) or "The other machine"- def _force_local(self, reason) -> None:- if self.redirecting:- LOGGER.error("%s; input forced back to this PC", reason)- self._alert("Input returned to this PC")- self.redirecting = False- self._pin_point = None- # The model that crossed disarmed itself; without a fresh one the edge never crosses again.- self._rearm_edge()- if self._redirect_callback is not None:- try:- self._redirect_callback(False)- except Exception:- LOGGER.exception("Redirect callback failed")-- def _connection_failed(self, reason, expected_socket=None) -> None:- with self._socket_lock:- stale = expected_socket is not None and self._sock is not expected_socket- if stale:- # A deliberate stop or a reconnect already dropped this socket --- # closing it out from under a worker mid-recv/-send raises an- # OSError of its own, which is not a connection failure.+ def _alert(self, message: str) -> None:+ if self.on_alert is None:return- self._force_local(reason)- self._set_status(reason)- self._drop_connection(expected_socket)-- def _drop_connection(self, expected_socket=None) -> None:- with self._socket_lock:- if expected_socket is not None and self._sock is not expected_socket:- return- sock = self._sock- self._sock = None- self._session = None- self._close(sock)+ try:+ self.on_alert("Beamer", message)+ except Exception:+ LOGGER.exception("Alert callback failed")@staticmethod- def _close(sock) -> None:- if sock is None:- return+ def _call(callback, *args) -> None:try:- sock.shutdown(socket.SHUT_RDWR)- except OSError:- pass- try:- sock.close()- except OSError:- pass-- def _mac_arrival_edge(self) -> Optional[str]:- """The Mac edge input arrives at, which is also the Mac's way home:- the far side of this PC's own outward edge. Sent in the hello as well- as on every switch, so the Mac is armed to push back before it has- ever been pushed into."""- return return_edge.OPPOSITE.get(self._edge) if self._edge else None-- def _rearm_edge(self) -> None:- """A fresh pair of models. Not a reset: a model disarms itself at- breakthrough so a burst of deltas still in flight cannot cross twice,- and nothing else re-arms it."""- methods = self._methods()- resistance = int(self._resistance())- if self._edge is None:- self._edge_model = self._corner_model = None- return- if "edge" in methods:- self._edge_model = return_edge.ReturnEdge(self._edge, resistance)- elif "part" in methods:- parts = self._setting("crossing_edge_parts", ("middle",))- self._edge_model = return_edge.PartEdge(self._edge, parts, resistance)- else:- self._edge_model = None- corner = self._setting("crossing_corner", "top_left")- if "corner" in methods and corner in return_edge.CORNERS:- self._corner_model = return_edge.CornerPush(corner, self._edge, resistance)- else:- self._corner_model = None-- def _methods(self):- return set(self._setting("crossing_methods", ("edge", "shortcut")) or ())-- @property- def shortcut_armed(self) -> bool:- """Whether the double-tap may move input. The app asks before acting on- the trigger, so turning the shortcut off here turns it off everywhere."""- return "shortcut" in self._methods()+ callback(*args)+ except Exception:+ LOGGER.exception("A callback failed")def _setting(self, name, fallback):with self._config_lock:@@ -1136,23 +1050,21 @@ class MacSender:return fallback if value is None else valuedef _resistance(self) -> int:- """How hard this PC's own way out pushes back, which is this PC's- setting -- and also what the Mac is asked to use at its return edge, so- one number governs the whole round trip in this direction."""+ """How hard this PC's own way out pushes back: this PC's setting, and what every peer is+ told to use at its zones while this PC's input is on it."""return int(self._setting("crossing_resistance_px", return_edge.DEFAULT_RESISTANCE_PX))def _warp_to_pin(self) -> None:- """Put the pointer back where it was when input left. Measured: SetCursorPos- produces no raw input at all -- a deliberate 137-pixel warp in a quiet- window produced no WM_INPUT -- so the pin cannot feed itself back to- the Mac as movement nobody made."""+ """Put the pointer back where it was when input left. Measured: SetCursorPos produces no raw+ input at all -- a deliberate 137-pixel warp in a quiet window produced no WM_INPUT -- so the+ pin cannot feed itself back as movement nobody made."""pin = self._pin_pointif pin is None:returntry:self._desktop_module().set_cursor_position(*pin)except Exception:- LOGGER.exception("Could not hold the pointer while the Mac has input")+ LOGGER.exception("Could not hold the pointer while a peer has input")def _cached_monitors(self):now = self._clock()@@ -1164,14 +1076,16 @@ class MacSender:def _desktop_module(self):if self._desktop is not None:return self._desktop- import desktop_win- return desktop_win+ import platform_parts++ return platform_parts.desktopdef _clipboard_module(self):if self._clipboard is not None:return self._clipboard- import clipboard_win- return clipboard_win+ import platform_parts++ return platform_parts.clipboarddef _notify_pressure(self, edge, pressure, crossed, part=None) -> None:if self._pressure_callback is None:@@ -1181,11 +1095,188 @@ class MacSender: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 (all a+ migrated entry has until its first link says who it is) 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.is_paired_token(entry.get("token")) 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, notice=self._notice, **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) -> None:+ link = self._link(peer)+ if link is not None:+ link.drop("The link went quiet")++ 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 _notice(self, text) -> None:+ callback = self._sender.notice_callback+ if callback is not None:+ self._sender._call(callback, text)+++def _outbound_link():+ from core import link++ return link.OutboundLink+++def _default_links(sender):+ return LinkSet(sender, sender._is_local)diff --git a/win_app/tests/fakes.py b/win_app/tests/fakes.pydeleted file mode 100644index d0a5883..0000000--- a/win_app/tests/fakes.py+++ /dev/null@@ -1,160 +0,0 @@-"""Shared test doubles and helpers for the Windows receiver test suite.--receiver.py normally injects real input via input_injector, which only works-on Windows. These helpers let the receiver's connection-handling logic (auth,-versioning, preemption, timeouts, message dispatch) be exercised on any-platform, including this Mac, without touching a real desktop.-"""--import socket-import time-from typing import List, Optional, Tuple-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--from core import protocol---class FakeInjector:- """A drop-in replacement for input_injector, passed to- receiver.handle_message(message, injector=...) so tests never need a real- Windows desktop (or even ctypes.windll) to run. Records every call so- tests can assert on what would have been injected."""-- def __init__(self):- self.calls: List[Tuple[str, tuple]] = []-- def inject_key(self, key, down, us=None):- self.calls.append(("key", (key, down)))-- def inject_mouse_move(self, dx, dy):- self.calls.append(("mouse_move", (dx, dy)))-- def inject_mouse_button(self, button, down):- self.calls.append(("mouse_button", (button, down)))-- def inject_scroll(self, dy, dx=0.0, mode="line"):- self.calls.append(("scroll", (dy, dx, mode)))-- def inject_gesture(self, name):- self.calls.append(("gesture", (name,)))---class FakeClipboard:- """A drop-in replacement for clipboard_win, passed to- ReceiverServer(status_callback, clipboard=...) so tests never need a real- Windows desktop (or even ctypes.windll) to run."""-- def __init__(self, text=None, image=None):- self.text = text- self.image = image- self.set_calls: List[Tuple[Optional[str], Optional[bytes]]] = []-- def get_contents(self):- return self.text, self.image-- def changed_contents(self):- return self.text, self.image-- def forget_sync(self):- pass-- def set_contents(self, text, image):- self.set_calls.append((text, image))- return True---class FakeDesktop:- """A drop-in replacement for desktop_win, passed to- ReceiverServer(status_callback, desktop=...). Monitors are crossing.Rect- values in virtual-desktop pixels, so a negative-origin arrangement is one- list away."""-- def __init__(self, monitors, cursor=(0, 0)):- self._monitors = list(monitors)- self.cursor = cursor- self.set_calls: List[Tuple[int, int]] = []-- def monitors(self):- return list(self._monitors)-- def cursor_position(self):- return self.cursor-- def set_cursor_position(self, x, y):- self.cursor = (x, y)- self.set_calls.append((x, y))---class SecureClient:- """The Mac's half of a connection, driven from a test over a real- socket: sends its preamble at once and reads the receiver's on first use,- so it can be built before the session thread that answers it has started.- Frames are sealed and opened with the real cipher, never mocked away."""-- def __init__(self, sock, token="shared-token"):- self.sock = sock- self.session = protocol.SecureSession(token)- sock.sendall(self.session.preamble())-- def _preamble(self):- # Both keys need the receiver's prefix, so neither side of a test can seal or open without it.- if self.session.peer_prefix is None:- protocol.recv_preamble(self.sock, self.session)-- def send(self, message):- self._preamble()- protocol.send_msg(self.sock, self.session, message)-- def recv(self):- self._preamble()- return protocol.recv_msg(self.sock, self.session)-- def settimeout(self, value):- self.sock.settimeout(value)-- def close(self):- self.sock.close()---def connected_socket_pair(token="shared-token"):- """Return (client, server_socket, client_address) for a loopback TCP- connection, mirroring what ReceiverServer._serve would hand to a session- thread after accept(). `client` is a SecureClient holding `token`; its raw- socket is `client.sock` for tests that need to misbehave on purpose."""- listener = socket.socket()- listener.bind(("127.0.0.1", 0))- listener.listen(1)- client = socket.create_connection(listener.getsockname())- server, address = listener.accept()- listener.close()- return SecureClient(client, token), server, address---def wait_for_status(statuses, state, timeout=1.0):- """Poll a (state, detail) list appended to by a status callback until an- entry matching `state` shows up. Status callbacks fire from a background- session thread, so tests must not assume they've landed the instant a- socket operation on the other end of the connection completes."""- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- for entry in list(statuses):- if entry[0] == state:- return entry- time.sleep(0.01)- raise AssertionError(f"status {state!r} not observed within {timeout}s; got {statuses!r}")---def wait_for_calls(calls, minimum=1, timeout=1.0):- """Poll a list a background session thread appends to (e.g.- FakeClipboard.set_calls) until it has at least `minimum` entries. Needed- for effects with no reply on the wire to synchronize on, unlike- wait_for_status which polls status-callback entries instead."""- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- if len(calls) >= minimum:- return- time.sleep(0.01)- raise AssertionError(f"expected at least {minimum} call(s) within {timeout}s; got {calls!r}")diff --git a/win_app/tests/fixtures/app_config_1_4_3.py b/win_app/tests/fixtures/app_config_1_4_3.pynew file mode 100644index 0000000..f870d04--- /dev/null+++ b/win_app/tests/fixtures/app_config_1_4_3.py@@ -0,0 +1,381 @@+"""A copy of win_app/app_config.py from release-1.4.x (1.4.3, 60a3b70), its imports pointed at core/ and+platform_parts and nothing else changed. test_settings_migration loads the config.json 1.5.0 leaves+behind through it: a downgrade must still find its pairing.++Configuration loading and saving for the Windows tray application."""++import json+import os+import tempfile+from dataclasses import dataclass, field+from pathlib import Path++from platform_parts import capture as capture_win+from core import effects+from core import ignored+from core import protocol+from core import return_edge+import tokens+++# 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+EDGES = ("left", "right", "top", "bottom")+CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")+METHODS = ("edge", "part", "corner", "shortcut")+TRIGGER_STYLES = ("double_tap", "hold")+# Any named key that is not a character can be the trigger, recorded by pressing it, as on the+# Mac: a modifier, a function key, a navigation key. Stored as its wire name, which is Mac-shaped --+# "cmd_r" is the right Ctrl key on this keyboard -- so every trigger saved before the recorder+# (eight fixed keys, 1.2 to 1.3.1) is still one. Media and browser keys are left out: they are+# what the stays-on-this-PC list is for. The undifferentiated 0x10-0x12 never reach the hook.+_NOT_TRIGGERS = {0x10, 0x11, 0x12} | set(range(0xA6, 0xB4))+TRIGGER_VKS = {+ name: vk for vk, name in capture_win.VK_TO_NAME.items() if vk not in _NOT_TRIGGERS+}+TRIGGER_KEYS = {name: capture_win.VK_TITLES[vk] for name, vk in TRIGGER_VKS.items()}+# Loaded if a config names them, never offered by the recorder, as on the Mac: Backspace, Tab,+# Enter, Esc and Space are typing keys a double-tap or a hold would take from every app, and+# Windows gives a window no key-down for Print Screen, so it cannot be recorded at all.+UNRECORDABLE_TRIGGER_VKS = {0x08, 0x09, 0x0D, 0x1B, 0x20, 0x2C}+MODIFIER_STYLES = ("semantic", "positional")+++def palette_colours(colour: str) -> tuple:+ """The colours of a `glow_colour` id: one of today's palettes, else a crossing effect's pack.+ An unknown id is Signal's, as today's glow always drew it."""+ if colour in tokens.PALETTES:+ return tuple(tokens.PALETTES[colour])+ found = effects.pack(colour) if colour in effects.PACK_IDS else None+ return tuple(found[1]) if found else tuple(tokens.PALETTES["signal"])+++class ConfigError(Exception):+ pass+++@dataclass+class Config:+ host: str+ port: int+ auth_token: str+ reconnect_interval_s: float = 2.0+ # The crossing settings that live here are how this PC's own edge looks: the+ # Mac configures the rest and tells this PC the return edge on every switch.+ edge_glow: bool = True+ glow_style: str = "glow"+ glow_colour: str = "signal"+ # 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.+ shortcut_arrival_style: str = "match"+ # How long an effect takes to play through once the pointer crosses: see effects.LENGTHS.+ effect_length: str = "normal"+ # The Mac's name from the last pairing, for the window to say who this PC is paired with.+ paired_with: str = ""+ # Whether each machine may take the other's input. Two plain switches: the+ # receiver, and the outward link.+ allow_mac_to_drive: bool = True+ # Ask GitHub once a day whether a newer release is out; see updates.py.+ check_updates: bool = True+ # Every address the window shows is hidden.+ hide_addresses: bool = False+ # How the Mac's pointer and scroll feel on this PC; see receiver.InputScale.+ pointer_speed: float = 1.0+ scroll_speed: float = 1.0+ reverse_scroll: bool = False+ send_to_mac: bool = True+ # How input leaves this PC. Any combination of the methods can be on, and+ # none of them means the PC can only be driven, never drive.+ crossing_methods: list = field(default_factory=lambda: ["edge", "shortcut"])+ crossing_corner: str = "top_left"+ # "Part of the edge": the thirds of the edge to the Mac that cross, as return_edge.PARTS names them.+ crossing_edge_parts: list = field(default_factory=lambda: ["middle"])+ crossing_resistance_px: int = 120+ trigger_key: str = "cmd_r"+ trigger_style: str = "double_tap"+ double_tap_ms: int = 300+ # How this PC's Ctrl and Windows keys arrive on the Mac, the Mac's own two styles: Semantic+ # makes Ctrl+C Cmd+C there, Positional keeps each key where it sits.+ modifier_style: str = "semantic"+ # A push against the edge with a button held is a drag, not a crossing, as on the Mac.+ block_while_dragging: bool = True+ # The Mac's address is learned, never typed: it is the peer address the+ # Mac's own link arrives from.+ mac_host: str = ""+ # The edge of THIS PC that leads to the Mac, which is both the way home+ # and the way out -- one border, walked either way. It can be set at+ # either machine and is synced over the link, so `arrangement_set_at`+ # (unix seconds) says how recently this end changed it and settles which+ # of two ends that disagree is the newer.+ mac_return_edge: str = ""+ arrangement_set_at: int = 0+ # What the Mac asks for at the return edge. The PC's own push out has its+ # own number, above: one slider for each direction, because the hand does+ # not feel a trackpad and a mouse the same way.+ mac_resistance_px: int = 120+ # The Mac's hardware address, read from this PC's ARP table whenever the link comes up, so a+ # switch that finds the Mac asleep can send it a wake-on-LAN packet. Never typed.+ mac_hardware_address: str = ""+ # Keys and buttons that stay on this PC while its input is on the Mac; see ignored.py.+ ignored_inputs: list = field(default_factory=list)+ # The window's own palette: follow Windows, or keep one. tokens.APPEARANCES is the home of+ # these three values.+ appearance: str = "system"+++def migrated_port(value) -> int:+ """The port to use for a config that still carries the old default.++ 51820 sits inside the 49152-65535 range Windows hands out for itself, so it was never a+ port anyone could rely on keeping. Nobody chose it -- it was what the app shipped with --+ so it moves; a port a user actually typed is theirs and is left exactly as it is.+ """+ port = int(value)+ return protocol.DEFAULT_PORT if port == protocol.LEGACY_DEFAULT_PORT else port+++def default_config() -> Config:+ # `host` is the address this PC shows the Mac; pairing fills it in with the+ # address that faces the Mac, so a fresh install carries none.+ return Config(host="", port=protocol.DEFAULT_PORT, auth_token="")+++def default_config_path() -> Path:+ base = os.environ.get("LOCALAPPDATA") or os.environ.get("XDG_CONFIG_HOME")+ if base:+ return Path(base) / "Beamer" / "config.json"+ return Path.home() / ".config" / "Beamer" / "config.json"+++def validate_config(config: Config) -> None:+ if not isinstance(config.host, str):+ raise ConfigError("host must be text")+ try:+ port = int(config.port)+ except (TypeError, ValueError) as exc:+ raise ConfigError("port must be an integer from 1 to 65535") from exc+ if isinstance(config.port, bool) or not 1 <= port <= 65535:+ raise ConfigError("port must be an integer from 1 to 65535")+ if not isinstance(config.auth_token, str) or not config.auth_token.strip():+ raise ConfigError("auth_token must not be empty")+ if config.auth_token == "CHANGE_ME":+ raise ConfigError("auth_token is still the placeholder")+ if config.trigger_key not in TRIGGER_KEYS:+ raise ConfigError(f"trigger_key must be one of: {', '.join(TRIGGER_KEYS)}")+ if config.trigger_style not in TRIGGER_STYLES:+ raise ConfigError(f"trigger_style must be one of: {', '.join(TRIGGER_STYLES)}")+ try:+ double_tap_ms = int(config.double_tap_ms)+ except (TypeError, ValueError) as exc:+ raise ConfigError("double_tap_ms must be greater than zero") from exc+ if isinstance(config.double_tap_ms, bool) or not 50 <= double_tap_ms <= 2000:+ raise ConfigError("double_tap_ms must be between 50 and 2000")+ if config.modifier_style not in MODIFIER_STYLES:+ raise ConfigError(f"modifier_style must be one of: {', '.join(MODIFIER_STYLES)}")+ if not isinstance(config.block_while_dragging, bool):+ raise ConfigError("block_while_dragging must be true or false")+ if not isinstance(config.mac_hardware_address, str):+ raise ConfigError("mac_hardware_address must be text")+ if not isinstance(config.crossing_methods, list) or any(+ method not in METHODS for method in config.crossing_methods+ ):+ raise ConfigError(f"crossing_methods must be a list of: {', '.join(METHODS)}")+ if config.crossing_corner not in CORNERS:+ raise ConfigError(f"crossing_corner must be one of: {', '.join(CORNERS)}")+ parts = config.crossing_edge_parts+ if not isinstance(parts, list) or not parts or not all(part in return_edge.PARTS for part in parts):+ raise ConfigError(f"crossing_edge_parts must be one or more of: {', '.join(return_edge.PARTS)}")+ for name in ("crossing_resistance_px", "mac_resistance_px"):+ value = getattr(config, name)+ try:+ resistance = int(value)+ except (TypeError, ValueError) as exc:+ raise ConfigError(f"{name} must be a whole number of pixels from 0 to 500") from exc+ if isinstance(value, bool) or not 0 <= resistance <= 500:+ raise ConfigError(f"{name} must be a whole number of pixels from 0 to 500")+ if not isinstance(config.allow_mac_to_drive, bool):+ raise ConfigError("allow_mac_to_drive must be true or false")+ if not isinstance(config.check_updates, bool):+ raise ConfigError("check_updates must be true or false")+ if not isinstance(config.hide_addresses, bool):+ raise ConfigError("hide_addresses must be true or false")+ for name in ("pointer_speed", "scroll_speed"):+ value = getattr(config, name)+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not 0.25 <= value <= 4.0:+ raise ConfigError(f"{name} must be a number from 0.25 to 4")+ if not isinstance(config.reverse_scroll, bool):+ raise ConfigError("reverse_scroll must be true or false")+ try:+ reconnect_interval_s = float(config.reconnect_interval_s)+ except (TypeError, ValueError) as exc:+ raise ConfigError("reconnect_interval_s must be greater than zero") from exc+ if isinstance(config.reconnect_interval_s, bool) or reconnect_interval_s <= 0:+ raise ConfigError("reconnect_interval_s must be greater than zero")+ if not isinstance(config.edge_glow, bool):+ raise ConfigError("edge_glow must be true or false")+ if config.glow_style not in GLOW_STYLES:+ raise ConfigError(f"glow_style must be one of: {', '.join(GLOW_STYLES)}")+ if config.glow_colour not in GLOW_COLOURS:+ raise ConfigError(f"glow_colour must be one of: {', '.join(GLOW_COLOURS)}")+ if not isinstance(config.shortcut_arrival, bool):+ raise ConfigError("shortcut_arrival must be true or false")+ if config.shortcut_arrival_style not in effects.SWITCH_STYLES:+ raise ConfigError(f"shortcut_arrival_style must be one of: {', '.join(effects.SWITCH_STYLES)}")+ lengths = tuple(value for value, _name in effects.LENGTHS)+ if config.effect_length not in lengths:+ raise ConfigError(f"effect_length must be one of: {', '.join(lengths)}")+ if not isinstance(config.paired_with, str):+ raise ConfigError("paired_with must be text")+ if not isinstance(config.send_to_mac, bool):+ raise ConfigError("send_to_mac must be true or false")+ if not isinstance(config.mac_host, str):+ raise ConfigError("mac_host must be text")+ if config.mac_return_edge not in ("",) + EDGES:+ raise ConfigError("mac_return_edge must be an edge name, or empty")+ try:+ ignored.validate(config.ignored_inputs)+ except ValueError as exc:+ raise ConfigError(str(exc)) from exc+ if config.appearance not in tokens.APPEARANCES:+ raise ConfigError(f"appearance must be one of: {', '.join(tokens.APPEARANCES)}")+++def config_from_dict(raw: dict) -> Config:+ if not isinstance(raw, dict):+ raise ConfigError("config.json must contain a JSON object")+ missing = [key for key in ("host", "port", "auth_token") if key not in raw]+ if missing:+ raise ConfigError(f"config.json is missing required field(s): {', '.join(missing)}")+ trigger_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"))+ config = Config(+ host=raw["host"],+ port=migrated_port(raw["port"]),+ auth_token=raw["auth_token"],+ reconnect_interval_s=float(raw.get("reconnect_interval_s", 2.0)),+ edge_glow=raw.get("edge_glow", True),+ glow_style=glow_style,+ glow_colour=glow_colour,+ shortcut_arrival=raw.get("shortcut_arrival", True),+ shortcut_arrival_style=switch_style,+ effect_length=raw.get("effect_length", "normal"),+ paired_with=raw.get("paired_with", "") or "",+ allow_mac_to_drive=raw.get("allow_mac_to_drive", True),+ check_updates=raw.get("check_updates", True),+ hide_addresses=raw.get("hide_addresses", False),+ pointer_speed=raw.get("pointer_speed", 1.0),+ scroll_speed=raw.get("scroll_speed", 1.0),+ reverse_scroll=raw.get("reverse_scroll", False),+ send_to_mac=raw.get("send_to_mac", True),+ crossing_methods=list(raw.get("crossing_methods", ["edge", "shortcut"])),+ crossing_corner=raw.get("crossing_corner", "top_left"),+ crossing_edge_parts=raw.get("crossing_edge_parts", ["middle"]),+ crossing_resistance_px=int(raw.get("crossing_resistance_px", 120)),+ trigger_key=trigger_key,+ trigger_style=raw.get("trigger_style", "double_tap"),+ double_tap_ms=int(raw.get("double_tap_ms", 300)),+ modifier_style=raw.get("modifier_style", "semantic"),+ block_while_dragging=raw.get("block_while_dragging", True),+ mac_hardware_address=raw.get("mac_hardware_address", "") or "",+ mac_host=raw.get("mac_host", "") or "",+ mac_return_edge=raw.get("mac_return_edge", "") or "",+ arrangement_set_at=int(raw.get("arrangement_set_at", 0)),+ mac_resistance_px=int(raw.get("mac_resistance_px", 120)),+ ignored_inputs=raw.get("ignored_inputs", []),+ appearance=raw.get("appearance") if raw.get("appearance") in tokens.APPEARANCES else "system",+ )+ except (TypeError, ValueError) as exc:+ raise ConfigError(f"config.json contains an invalid value: {exc}") from exc+ validate_config(config)+ return config+++def load_config(path: Path) -> Config:+ if not path.exists():+ raise ConfigError(f"config file not found: {path}")+ try:+ with path.open("r", encoding="utf-8") as handle:+ raw = json.load(handle)+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise ConfigError(f"config file contains invalid JSON: {exc}") from exc+ except OSError as exc:+ raise ConfigError(f"config file could not be read: {exc}") from exc+ config = config_from_dict(raw)+ if config.port != int(raw["port"]):+ try:+ save_config(path, config)+ except (ConfigError, OSError):+ # The port in hand is what matters; a config file that cannot be written must+ # not stop Beamer listening on it.+ pass+ return config+++def config_to_dict(config: Config) -> dict:+ validate_config(config)+ return {+ "host": config.host.strip(),+ "port": int(config.port),+ "auth_token": config.auth_token,+ "reconnect_interval_s": float(config.reconnect_interval_s),+ "edge_glow": config.edge_glow,+ "glow_style": config.glow_style,+ "glow_colour": config.glow_colour,+ "shortcut_arrival": config.shortcut_arrival,+ "shortcut_arrival_style": config.shortcut_arrival_style,+ "effect_length": config.effect_length,+ "paired_with": config.paired_with,+ "allow_mac_to_drive": config.allow_mac_to_drive,+ "check_updates": config.check_updates,+ "hide_addresses": config.hide_addresses,+ "pointer_speed": config.pointer_speed,+ "scroll_speed": config.scroll_speed,+ "reverse_scroll": config.reverse_scroll,+ "send_to_mac": config.send_to_mac,+ "crossing_methods": list(config.crossing_methods),+ "crossing_corner": config.crossing_corner,+ "crossing_edge_parts": list(config.crossing_edge_parts),+ "crossing_resistance_px": int(config.crossing_resistance_px),+ "trigger_key": config.trigger_key,+ "trigger_style": config.trigger_style,+ "double_tap_ms": int(config.double_tap_ms),+ "modifier_style": config.modifier_style,+ "block_while_dragging": config.block_while_dragging,+ "mac_hardware_address": config.mac_hardware_address,+ "mac_host": config.mac_host,+ "mac_return_edge": config.mac_return_edge,+ "arrangement_set_at": int(config.arrangement_set_at),+ "mac_resistance_px": int(config.mac_resistance_px),+ "ignored_inputs": list(config.ignored_inputs),+ "appearance": config.appearance,+ }+++def save_config(path: Path, config: Config) -> None:+ payload = config_to_dict(config)+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary_path = None+ try:+ with tempfile.NamedTemporaryFile(+ mode="w",+ encoding="utf-8",+ dir=path.parent,+ prefix=f".{path.name}.",+ suffix=".tmp",+ delete=False,+ ) as handle:+ temporary_path = Path(handle.name)+ json.dump(payload, handle, indent=2)+ handle.write("\n")+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(temporary_path, path)+ temporary_path = None+ finally:+ if temporary_path is not None:+ temporary_path.unlink(missing_ok=True)diff --git a/win_app/tests/fixtures/config_1_4_3.json b/win_app/tests/fixtures/config_1_4_3.jsonnew file mode 100644index 0000000..1346743--- /dev/null+++ b/win_app/tests/fixtures/config_1_4_3.json@@ -0,0 +1,44 @@+{+ "host": "192.0.2.20",+ "port": 24820,+ "auth_token": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",+ "reconnect_interval_s": 2.0,+ "edge_glow": true,+ "glow_style": "beam",+ "glow_colour": "sunset",+ "shortcut_arrival": true,+ "shortcut_arrival_style": "match",+ "effect_length": "normal",+ "paired_with": "MacBook Pro",+ "allow_mac_to_drive": true,+ "check_updates": true,+ "hide_addresses": false,+ "pointer_speed": 1.5,+ "scroll_speed": 1.0,+ "reverse_scroll": false,+ "send_to_mac": true,+ "crossing_methods": [+ "edge",+ "corner",+ "shortcut"+ ],+ "crossing_corner": "top_right",+ "crossing_edge_parts": [+ "start",+ "end"+ ],+ "crossing_resistance_px": 150,+ "trigger_key": "cmd_r",+ "trigger_style": "double_tap",+ "double_tap_ms": 300,+ "modifier_style": "positional",+ "mac_hardware_address": "aa:bb:cc:dd:ee:ff",+ "mac_host": "192.0.2.10",+ "mac_return_edge": "left",+ "arrangement_set_at": 1790000000,+ "mac_resistance_px": 90,+ "ignored_inputs": [+ "button:back"+ ],+ "appearance": "dark"+}diff --git a/win_app/tests/links_rig.py b/win_app/tests/links_rig.pynew file mode 100644index 0000000..de2a06d--- /dev/null+++ b/win_app/tests/links_rig.py@@ -0,0 +1,170 @@+"""A LinkSender with no sockets: the links are a fake that records what is sent to each peer, the+settings are the shared harness's, and the outbound worker is run by hand (`flush`), so a test reads+what one event did and in what order."""++import os+import sys+import time++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from app_config import Config+from core import protocol, receiver+from core.return_edge import Rect+from core.tests import responder_harness as harness+import sender++HERE, B, C = harness.HERE, harness.B, harness.C+MONITORS = [Rect(0, 0, 1920, 1080)]+CAPS = frozenset({"clipboard", "clipboard_image", "settings", "media_keys"})+++def make_config(**overrides):+ values = dict(+ host="", port=24820, auth_token="", machine_id=protocol.id_text(HERE), name="This PC",+ crossing_resistance_px=40,+ )+ values.update(overrides)+ return Config(**values)+++def edge_zone(peer, **fields):+ return dict({"peer": protocol.id_text(peer), "kind": "edge"}, **fields)+++class FakeLinks:+ """core.link's side of the seam: what the sender asks of its links and what each answers."""++ def __init__(self, owner) -> None:+ self.owner = owner+ self.up_set = set()+ self.refusing = set()+ self.caps_of = {}+ self.sent = [] # (peer, message), input and control in the order they were given+ self.input = []+ self.closed = []+ self.synced = []+ self.fail_input = False+ self.trip = None++ def start(self):+ pass++ def stop(self):+ pass++ def sync(self, entries):+ self.synced.append(list(entries))++ def key_of(self, entry):+ return entry.get("id") or entry.get("token")++ def up(self, peer):+ return peer in self.up_set++ live = up++ def refused(self, peer):+ return peer in self.refusing++ def caps(self, peer):+ return self.caps_of.get(peer, CAPS)++ def post(self, peer, message):+ if peer not in self.up_set:+ return False+ self.sent.append((peer, message))+ return True++ def send_input(self, peer, message):+ if peer not in self.up_set or self.fail_input:+ return False+ self.input.append((peer, message))+ self.sent.append((peer, message))+ return True++ def close(self, peer):+ self.closed.append(peer)+ self.up_set.discard(peer)++ def round_trip_ms(self, peer):+ return self.trip++ def follow(self, machines):+ pass+++class Rig:+ def __init__(self, cursor=(0, 500), monitors=MONITORS, entries=None, zones=None, up=(B,), **config):+ self.desktop = harness.FakeDesktop(monitors, cursor)+ self.clipboard = harness.FakeClipboard("here")+ self.settings = harness.Settings(+ entries if entries is not None else [harness.entry(B, "Mac", side="left")],+ zones if zones is not None else [edge_zone(B)],+ )+ self.book = receiver.PeerBook(self.settings.load, self.settings.save)+ self.alerts, self.arrivals, self.pressure, self.redirects, self.statuses = [], [], [], [], []+ self.driven = False+ self.sent_home = []+ self.sender = sender.LinkSender(+ self.book,+ lambda: {},+ zones=lambda: self.settings.data["zones"],+ desktop=self.desktop,+ clipboard=self.clipboard,+ links=FakeLinks,+ is_local=lambda host: False,+ status_callback=lambda connected, detail: self.statuses.append((connected, detail)),+ redirect_callback=self.redirects.append,+ pressure_callback=lambda edge, pressure, crossed, part: self.pressure.append((edge, pressure, crossed, part)),+ arrival_callback=lambda edge, x, y: self.arrivals.append((edge, x, y)),+ )+ self.sender.on_alert = lambda title, message: self.alerts.append(message)+ self.sender.driven = lambda: self.driven+ self.sender.send_peer_home = lambda: self.sent_home.append(True) or True+ self.links = self.sender.links+ self.sender.update_config(make_config(**config))+ for peer in up:+ self.bring_up(peer)++ def bring_up(self, peer, accepts=True):+ self.links.up_set.add(peer)+ self.sender.on_link(peer, True, accepts)+ self.flush()++ def drop(self, peer):+ self.links.up_set.discard(peer)+ self.sender.on_link(peer, False)+ self.flush()++ def flush(self):+ """What the outbound worker would have done with everything queued so far."""+ deadline = time.monotonic() + 3+ while time.monotonic() < deadline:+ while not self.sender._outbound.empty():+ self.sender._deliver(self.sender._outbound.get_nowait())+ if not self.sender._clip_wait:+ return+ time.sleep(0.002)++ def sent(self, peer=None, kind=None):+ self.flush()+ return [+ message for target, message in self.links.sent+ if (peer is None or target == peer) and (kind is None or message["type"] == kind)+ ]++ def inbound(self, peer, message):+ self.sender.on_message(peer, message)+ self.flush()++ def push(self, times=4, dx=-20, dy=0):+ """The hand still moving with the cursor already stopped at the edge: the position never+ changes, which is why the movement comes from raw input rather than from the hook."""+ for _ in range(times):+ self.sender.on_motion(dx, dy)+ self.flush()++ def accept_take(self, peer=B):+ route = self.sender._owner.route+ self.inbound(peer, protocol.accept_msg(route))diff --git a/win_app/tests/test_app_config.py b/win_app/tests/test_app_config.pyindex b535273..c36bd29 100644--- a/win_app/tests/test_app_config.py+++ b/win_app/tests/test_app_config.py@@ -148,24 +148,6 @@ if __name__ == "__main__":unittest.main()-class ArrangementTests(unittest.TestCase):- """Which end's arrangement stands when the two disagree."""-- def test_the_newer_stamp_wins(self):- self.assertTrue(protocol.arrangement_wins(200, 100))- self.assertFalse(protocol.arrangement_wins(100, 200))-- def test_an_equal_stamp_changes_nothing(self):- self.assertFalse(protocol.arrangement_wins(100, 100))-- def test_a_peer_with_no_stamp_never_beats_a_change_made_here(self):- self.assertFalse(protocol.arrangement_wins(0, 100))- self.assertFalse(protocol.arrangement_wins(None, 100))-- def test_two_ends_that_never_changed_it_agree(self):- self.assertFalse(protocol.arrangement_wins(0, 0))--class LegacyTriggerTests(unittest.TestCase):def test_right_alt_is_a_choice_and_is_kept(self):# "alt_r" was once rewritten to "cmd_r" as a dead default, but it is a live entry in@@ -203,16 +185,61 @@ class LegacyPortTests(unittest.TestCase):def test_a_new_config_starts_on_the_new_port(self):self.assertEqual(default_config().port, protocol.DEFAULT_PORT)- def test_loading_a_config_on_the_old_port_writes_the_move_down(self):+ def test_migrating_a_config_on_the_old_port_writes_the_move_down(self):with tempfile.TemporaryDirectory() as directory:- path = Path(directory) / "config.json"- path.write_text(+ (Path(directory) / "config.json").write_text(json.dumps({"host": "192.168.1.3", "port": protocol.LEGACY_DEFAULT_PORT, "auth_token": "t"}),encoding="utf-8",)+ path = Path(directory) / "settings.json"self.assertEqual(app_config.load_config(path).port, protocol.DEFAULT_PORT)on_disk = json.loads(path.read_text(encoding="utf-8"))self.assertEqual(on_disk["port"], protocol.DEFAULT_PORT)++class ReadFallbackPeerBookTests(unittest.TestCase):+ """A read that fails (a scanner holding settings.json) gives the link's read-only calls the last+ good copy, but never a copy that a save could write back over what the window has since changed."""++ def setUp(self):+ self.disk = {"peers": [{"id": "a", "token": "t", "paired_with": []}], "zones": [{"peer": "a"}]}+ self.broken = False+ self.saved = []++ def load():+ if self.broken:+ raise OSError("locked by a scanner")+ return json.loads(json.dumps(self.disk))++ self.book = app_config.ReadFallbackPeerBook(load, self.saved.append)++ def test_the_read_only_calls_use_the_last_good_copy_when_a_read_fails(self):+ self.book.peers()+ self.broken = True+ self.assertEqual([peer["id"] for peer in self.book.peers()], ["a"])+ self.assertEqual(self.book.zones(), [{"peer": "a"}])++ def test_with_no_good_copy_yet_a_failed_read_raises(self):+ self.broken = True+ with self.assertRaises(OSError):+ self.book.peers()++ def test_a_save_after_a_failed_read_raises_rather_than_write_the_stale_copy(self):+ self.book.peers()+ self.disk["peers"][0]["send"] = False+ self.broken = True+ with self.assertRaises(OSError):+ self.book.store_paired("a", ["b"])+ with self.assertRaises(OSError):+ self.book.admit(b"\x00" * 32, b"\x01" * 16, b"\x02" * 16, {})+ self.assertEqual(self.saved, [])++ def test_a_removed_machine_does_not_come_back_through_a_pairing_message(self):+ self.book.peers()+ self.disk["peers"] = []+ self.broken = True+ with self.assertRaises(OSError):+ self.book.store_paired("a", ["b"])+ self.assertEqual(self.saved, [])diff --git a/win_app/tests/test_arrangement.py b/win_app/tests/test_arrangement.pynew file mode 100644index 0000000..743146f--- /dev/null+++ b/win_app/tests/test_arrangement.py@@ -0,0 +1,107 @@+"""A peer's `arrangement` and what the links write into the first peer, as the settings keep them+(WIRE.md sections 1 and 8)."""++import json+import os+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import app_config+from core import protocol+from core.tests import responder_harness as harness++B, C = harness.B, harness.C+BT, CT = protocol.id_text(B), protocol.id_text(C)+LOW, HIGH = protocol.id_text(bytes([1]) * 16), protocol.id_text(bytes([200]) * 16)+++class Folder(unittest.TestCase):+ def setUp(self):+ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ self.path = Path(directory.name) / "settings.json"+ settings = app_config.migrate(None, machine_id=protocol.id_text(harness.HERE))+ settings["peers"] = [+ harness.entry(B, "Mac", side="left", side_set_at=100, side_by=LOW),+ harness.entry(C, "Other", platform="windows", side="top"),+ ]+ settings["zones"] = [+ {"peer": BT, "kind": "edge"},+ {"peer": BT, "kind": "corner", "corner": "top_left", "edge": "left", "off": True},+ {"peer": CT, "kind": "edge"},+ ]+ app_config.write_settings(self.path, settings)++ def saved(self):+ return json.loads(self.path.read_text(encoding="utf-8"))++ def peer(self, ident):+ return next(item for item in self.saved()["peers"] if item["id"] == ident)+++class ArrangementTests(Folder):+ def test_a_newer_stamp_sets_the_opposite_side_and_the_stamp_and_author(self):+ changed, notices = app_config.apply_arrangement(self.path, BT, "left", 200, HIGH)+ self.assertTrue(changed)+ entry = self.peer(BT)+ self.assertEqual((entry["side"], entry["side_set_at"], entry["side_by"]), ("right", 200, HIGH))+ self.assertEqual(notices, [])++ def test_an_older_or_equal_stamp_changes_nothing(self):+ for set_at, by in ((99, HIGH), (100, LOW)):+ self.assertEqual(app_config.apply_arrangement(self.path, BT, "left", set_at, by), (False, []))+ self.assertEqual(self.peer(BT)["side"], "left")++ def test_the_same_second_goes_to_the_larger_id(self):+ self.assertTrue(app_config.apply_arrangement(self.path, BT, "left", 100, HIGH)[0])+ self.assertEqual(self.peer(BT)["side"], "right")++ def test_a_peer_that_is_not_in_the_list_or_an_edge_that_is_not_one_is_ignored(self):+ self.assertEqual(app_config.apply_arrangement(self.path, protocol.id_text(harness.D), "left", 200, HIGH), (False, []))+ self.assertEqual(app_config.apply_arrangement(self.path, BT, "up", 200, HIGH), (False, []))+ self.assertEqual(app_config.apply_arrangement(self.path, BT, "left", 200, "not an id"), (False, []))++ def test_a_side_that_clashes_with_another_peers_zone_turns_the_senders_zone_off_and_says_so(self):+ changed, notices = app_config.apply_arrangement(self.path, BT, "bottom", 200, HIGH)+ self.assertTrue(changed)+ self.assertEqual(self.peer(BT)["side"], "top")+ zones = [zone for zone in self.saved()["zones"] if zone["peer"] == BT and zone["kind"] == "edge"]+ self.assertTrue(zones[0]["off"])+ self.assertTrue(notices and "Mac" in notices[0] and "Other" in notices[0])+ other = [zone for zone in self.saved()["zones"] if zone["peer"] == CT][0]+ self.assertNotIn("off", other)+++class LearnedTests(Folder):+ def test_what_the_links_write_comes_back_in_the_flat_names(self):+ settings = self.saved()+ settings["peers"][0].update(host="192.168.77.9", hw="aa:bb:cc:dd:ee:ff", name="Studio")+ app_config.write_settings(self.path, settings)+ learned = app_config.learned_fields(self.path)+ self.assertEqual(learned["mac_host"], "192.168.77.9")+ self.assertEqual(learned["mac_hardware_address"], "aa:bb:cc:dd:ee:ff")+ self.assertEqual(learned["paired_with"], "Studio")+ self.assertEqual((learned["mac_return_edge"], learned["arrangement_set_at"]), ("left", 100))++ def test_the_token_and_the_ways_come_back_too_so_a_fold_cannot_be_undone_by_a_save(self):+ settings = self.saved()+ settings["peers"] = settings["peers"][1:]+ app_config.write_settings(self.path, settings)+ learned = app_config.learned_fields(self.path)+ self.assertEqual(learned["auth_token"], harness.entry(C, "Other")["token"])+ self.assertEqual(learned["mac_return_edge"], "top")+ self.assertIn("edge", learned["crossing_methods"])++ def test_the_stamps_author_for_same_on_all_machines_is_kept(self):+ config = app_config.load_config(self.path)+ self.assertEqual(config.same_by, "")+ app_config.save_config(self.path, app_config.replace(config, same_by=HIGH, same_set_at=5))+ self.assertEqual(app_config.load_config(self.path).same_by, HIGH)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_clipboard_win.py b/win_app/tests/test_clipboard_win.pyindex e35327e..55b8256 100644--- a/win_app/tests/test_clipboard_win.py+++ b/win_app/tests/test_clipboard_win.py@@ -3,6 +3,7 @@ the clipboard message's image payload, and the read/write orchestrationover fake user32/kernel32 backed by real ctypes buffers. The Qt PNG codec isreplaced with a marker encoding so nothing here needs PySide6 or Windows."""+import base64import ctypesimport structimport sys@@ -113,8 +114,9 @@ class ClipboardMessageTests(unittest.TestCase):self.assertIsNone(protocol.clipboard_image(protocol.clipboard_msg("hello")["data"]))def test_image_round_trips_through_the_sealed_wire(self):- sender = protocol.SecureSession("shared-token")- receiver = protocol.SecureSession("shared-token")+ token = base64.urlsafe_b64encode(bytes(range(32))).decode("ascii").rstrip("=")+ sender = protocol.LinkSession(token, protocol.ROLE_INITIATOR)+ receiver = protocol.LinkSession(token, protocol.ROLE_RESPONDER)receiver.accept_preamble(sender.preamble())sender.accept_preamble(receiver.preamble())frame = sender.seal(protocol.clipboard_msg("shot.png", PNG))@@ -287,6 +289,13 @@ class ClipboardOrchestrationTests(unittest.TestCase):self.assertEqual(clipboard_win.get_contents(), (None, None))self.assertFalse(clipboard_win.set_contents("x", PNG))+ def test_the_change_stamp_is_the_sequence_number(self):+ # Wire version 6's responder compares it across a visit (core.receiver.LinkResponder).+ if sys.platform == "win32":+ self.assertEqual(clipboard_win.change_stamp(), clipboard_win.user32.GetClipboardSequenceNumber())+ else:+ self.assertIsNone(clipboard_win.change_stamp())+if __name__ == "__main__":unittest.main()diff --git a/win_app/tests/test_crossing_matrix.py b/win_app/tests/test_crossing_matrix.pyindex a43158c..bcaf577 100644--- a/win_app/tests/test_crossing_matrix.py+++ b/win_app/tests/test_crossing_matrix.py@@ -1,10 +1,11 @@"""This PC's ways in on each arrangement, and the arrangement as both machines hold it. The two--machine cases, which need the Mac's code too, are in mac_app/tests/test_crossing_matrix.py; what-each row proves is written up in docs/crossing-matrix-28-09-2026.md."""+machine cases, which need the Mac's code too, are in mac_app/tests/test_crossing_matrix.py. Since 1.5.0 a way in is a zone+of the peer's (WIRE.md section 8): an edge zone is the peer's whole side, a part zone some thirds+of it, a corner zone names its corner and the edge it crosses, whatever the side is."""import itertools+import jsonimport logging-import timeimport typesimport unittestimport os@@ -12,13 +13,14 @@ import syssys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))-from core import return_edge-import sender-from app_config import Config, default_config-from fakes import FakeClipboard, FakeDesktop-from core.return_edge import CORNERS, EDGES, OPPOSITE, Rect+import app_config+from app_config import default_config+from core import protocol+from core.receiver import corner_offset+from core.return_edge import CORNERS, EDGES, OPPOSITE+from core.tests import responder_harness as harness+from links_rig import B, Rig, edge_zone, make_config-MONITORS = [Rect(0, 0, 1920, 1080)]THIRDS = {"start": 0.17, "middle": 0.5, "end": 0.83}LAST_X, LAST_Y = 1919, 1079@@ -62,58 +64,62 @@ def third_at_corner(corner, side):return "start" if horizontal == "left" else "end"-def make_sender(methods, edge, corner="top_left", parts=("middle",), **more):+def corner_edges(corner):+ return corner.split("_")+++def zones_for(methods, corner, corner_edge, parts):+ zones = []+ if "edge" in methods:+ zones.append(edge_zone(B))+ if "part" in methods:+ zones.append({"peer": protocol.id_text(B), "kind": "part", "parts": list(parts)})+ if "corner" in methods:+ zones.append({"peer": protocol.id_text(B), "kind": "corner", "corner": corner, "edge": corner_edge})+ return zones+++def make_rig(methods, side, corner="top_left", corner_edge="left", parts=("middle",), **more):more.setdefault("crossing_resistance_px", 40)- desktop = FakeDesktop(MONITORS)- link = sender.MacSender(desktop=desktop, clipboard=FakeClipboard(), is_local=lambda host: False)- link.update_config(- Config(- host="127.0.0.1",- port=1,- auth_token="matrix-token",- mac_host="127.0.0.1",- mac_return_edge=edge,- crossing_methods=list(methods),- crossing_corner=corner,- crossing_edge_parts=list(parts),- **more,- )+ return Rig(+ entries=[harness.entry(B, "Mac", side=side)],+ zones=zones_for(methods, corner, corner_edge, parts),+ crossing_methods=sorted(methods),+ **more,)- link._sock = object()- link._connected_at = link._last_ack_at = time.monotonic()- return link, desktop-def push(methods, edge, probe, corner="top_left", parts=("middle",)):+def push(methods, side, probe, corner="top_left", corner_edge="left", parts=("middle",)):"""The focus message a push sends, or None when the push never crosses."""- link, desktop = make_sender(methods, edge, corner, parts)+ rig = make_rig(methods, side, corner, corner_edge, parts)_, x, y, dx, dy = probe[:5]- desktop.cursor = (x, y)+ rig.desktop.cursor = (x, y)for _ in range(12):- link.on_motion(dx, dy)- if link.redirecting:+ rig.sender.on_motion(dx, dy)+ if rig.sender.redirecting:break- if not link.redirecting:+ if not rig.sender.redirecting:return None- return [m for m in list(link._outbound.queue) if m["type"] == "focus"][-1]["data"]+ return rig.sent(B, "focus")[-1]["data"]-def expected(methods, edge, corner, parts, probe):- """The Mac edge a push arrives at. Edge is the whole arrangement side and Part of the edge its- thirds; Corner is one corner, any of the four, and always arrives by the arrangement side."""+def expected(methods, side, corner, corner_edge, parts, probe):+ """The edge of the peer a push arrives at. An edge zone is the whole side the peer is on and a+ part zone its thirds; a corner zone is one corner of any of the four and crosses the edge it+ names, whatever side the peer is on."""_, _, _, _, _, kind, where, third = probe- def by_edge(side, part):- if side != edge:+ def by_edge(edge, part):+ if edge != side:return None- return OPPOSITE[edge] if "edge" in methods or ("part" in methods and part in parts) else None+ return OPPOSITE[side] if "edge" in methods or ("part" in methods and part in parts) else Noneif kind == "edge":return by_edge(where, third)vertical, horizontal = where.split("_")if kind == "diagonal":if "corner" in methods and where == corner:- return OPPOSITE[edge]+ return OPPOSITE[corner_edge]return by_edge(horizontal, third_at_corner(where, horizontal)) or by_edge(vertical, third_at_corner(where, vertical))return by_edge(third, third_at_corner(where, third))@@ -125,67 +131,96 @@ def method_sets():yield frozenset(methods)+def corner_choices(methods):+ if "corner" not in methods:+ return [("top_left", "left")]+ return [(corner, edge) for corner in CORNERS for edge in corner_edges(corner)]+++def parts_choices(methods):+ if "part" not in methods:+ return [("middle",)]+ return [("middle",), ("start", "end"), ("start", "middle", "end")]++class PcWaysOutTests(unittest.TestCase):def test_every_way_crosses_where_it_says_and_nowhere_else(self):for methods in method_sets():- for edge in EDGES:- for corner in CORNERS:- for parts in (("middle",), ("start", "end"), ("start", "middle", "end")):+ for side in EDGES + ("",):+ for corner, corner_edge in corner_choices(methods):+ for parts in parts_choices(methods):for probe in probes():- focus = push(methods, edge, probe, corner, parts)+ focus = push(methods, side, probe, corner, corner_edge, parts)arrived = None if focus is None else focus.get("edge")- with self.subTest(methods=sorted(methods), mac_is=edge, corner=corner, parts=parts, probe=probe[0]):- self.assertEqual(arrived, expected(methods, edge, corner, parts, probe))+ with self.subTest(methods=sorted(methods), mac_is=side, corner=corner, corner_edge=corner_edge, parts=parts, probe=probe[0]):+ self.assertEqual(arrived, expected(methods, side, corner, corner_edge, parts, probe))def test_the_shortcut_alone_leaves_every_edge_a_wall(self):- for edge in EDGES:+ for side in EDGES:for probe in probes():- self.assertIsNone(push(("shortcut",), edge, probe), probe[0])+ self.assertIsNone(push(("shortcut",), side, probe), probe[0])- def test_the_mac_lands_at_the_same_fraction_along_the_far_edge(self):- for edge in EDGES:+ def test_the_peer_lands_at_the_same_fraction_along_the_far_edge(self):+ for side in EDGES:for third, fraction in THIRDS.items():- probe = (f"{edge}/{third}", *side_point(edge, third), *outward(edge))- focus = push(("edge",), edge, probe)- self.assertEqual(focus["edge"], OPPOSITE[edge])+ probe = (f"{side}/{third}", *side_point(side, third), *outward(side))+ focus = push(("edge",), side, probe)+ self.assertEqual(focus["edge"], OPPOSITE[side])self.assertAlmostEqual(focus["offset"], fraction, places=2)- def test_a_corner_arrives_at_its_position_along_the_arrangement_side_not_along_its_own(self):- probe = ("top_left diagonal", 0, 0, -30, -30)- self.assertEqual(push(("corner",), "right", probe, corner="top_left")["offset"], 0.0)- probe = ("bottom_left diagonal", 0, LAST_Y, -30, 30)- self.assertAlmostEqual(push(("corner",), "right", probe, corner="bottom_left")["offset"], 1.0, places=2)- probe = ("top_left diagonal", 0, 0, -30, -30)- self.assertEqual(push(("corner",), "bottom", probe, corner="top_left")["offset"], 0.0)- probe = ("top_right diagonal", LAST_X, 0, 30, -30)- self.assertAlmostEqual(push(("corner",), "bottom", probe, corner="top_right")["offset"], 1.0, places=2)-- def test_a_pc_that_holds_no_edge_has_no_way_out(self):+ def test_a_corner_arrives_at_the_end_of_its_crossing_edge_nearest_it(self):+ cases = [+ ("top_left", "left", "right", 0.0), ("bottom_left", "left", "right", 1.0),+ ("top_left", "top", "bottom", 0.0), ("top_right", "top", "bottom", 1.0),+ ("bottom_right", "right", "left", 1.0), ("bottom_left", "bottom", "top", 0.0),+ ]+ for corner, edge, arrives, offset in cases:+ vertical, horizontal = corner.split("_")+ x, y = corner_point(corner)+ probe = (corner, x, y, outward(horizontal)[0], outward(vertical)[1])+ for side in EDGES + ("",):+ focus = push(("corner",), side, probe, corner=corner, corner_edge=edge)+ with self.subTest(corner=corner, edge=edge, side=side):+ self.assertEqual(focus["edge"], arrives)+ self.assertAlmostEqual(focus["offset"], offset, places=2)+ self.assertEqual(focus["offset"], corner_offset(corner, edge))++ def test_a_pc_that_holds_no_side_has_no_edge_or_part_way_out_but_its_corner_still_crosses(self):for methods in method_sets():for probe in probes():- self.assertIsNone(push(methods, "", probe), (methods, probe[0]))---class PcWayHomeNamedToTheMacTests(unittest.TestCase):- def test_the_hello_and_a_shortcut_switch_name_the_mac_edge_opposite_the_pcs(self):- for edge in EDGES:- link, _ = make_sender(("shortcut",), edge)- self.assertEqual(link._mac_arrival_edge(), OPPOSITE[edge])-- def test_a_crossing_names_the_edge_it_arrived_by(self):- for edge in EDGES:- probe = ("push", *side_point(edge, "middle"), *outward(edge))- focus = push(("edge",), edge, probe)- self.assertEqual(focus["return_edge"], focus["edge"])+ focus = push(methods, "", probe)+ if "corner" in methods and probe[0] == "top_left diagonal":+ self.assertEqual(focus["edge"], "right", (methods, probe[0]))+ else:+ self.assertIsNone(focus, (methods, probe[0]))+++class PcWayOutNamedToThePeerTests(unittest.TestCase):+ def test_a_crossing_names_the_edge_of_the_peer_it_arrives_by_and_the_pcs_resistance(self):+ for side in EDGES:+ probe = ("push", *side_point(side, "middle"), *outward(side))+ focus = push(("edge",), side, probe)+ self.assertEqual(focus["edge"], OPPOSITE[side])self.assertEqual(focus["resistance_px"], 40)-- def test_the_pcs_resistance_is_what_it_asks_the_mac_for_never_the_macs_own(self):- link, _ = make_sender(("edge",), "right", crossing_resistance_px=40)- link._config.crossing_resistance_px = 200- link.update_config(link._config)- self.assertEqual(link._resistance(), 200)- link._config.mac_resistance_px = 5- self.assertEqual(link._resistance(), 200, "the resistance the Mac reported is never read")+ self.assertNotIn("return_edge", focus)++ def test_the_pcs_resistance_is_what_it_asks_the_peer_for_never_the_peers_own(self):+ rig = make_rig(("edge",), "left", crossing_resistance_px=40)+ rig.sender.update_config(make_config(crossing_resistance_px=200))+ self.assertEqual(rig.sender._resistance(), 200)+ rig.desktop.cursor = (0, 500)+ rig.push(4)+ self.assertFalse(rig.sender.redirecting, "80 pixels is under the new 200 of resistance")+ rig.push(8)+ self.assertTrue(rig.sender.redirecting)+ self.assertEqual(rig.sent(B, "focus")[-1]["data"]["resistance_px"], 200)++ def test_a_resistance_the_peer_reported_is_never_read(self):+ rig = make_rig(("edge",), "left", crossing_resistance_px=40, mac_resistance_px=5)+ self.assertEqual(rig.sender._resistance(), 40)+ rig.desktop.cursor = (0, 500)+ rig.push(1)+ self.assertFalse(rig.sender.redirecting)class WhatIsSharedTests(unittest.TestCase):@@ -205,90 +240,74 @@ except ImportError: # PySide6 is only in the Windows venv@unittest.skipIf(kvm_bridge_win is None, "needs PySide6")class ArrangementHeldByBothTests(unittest.TestCase):- """`_on_arrangement` and `_on_learned` are the two ways a Mac's idea of where the machines are- reaches this PC: a stamped message over either link, and the unstamped way home the hello- carries."""-- def page(self, edge="right", stamp=0):- config = default_config()- config.mac_return_edge = edge- config.arrangement_set_at = stamp- saved = []- page = types.SimpleNamespace(- _config=config,- _persist=lambda: saved.append((config.mac_return_edge, config.arrangement_set_at)) or True,- _start_sending=lambda config: None,- sender=types.SimpleNamespace(update_config=lambda config: None),- edge_choice=types.SimpleNamespace(set_value=lambda value: None),- mac_host_readout=types.SimpleNamespace(setText=lambda text: None),- _reflect_look=lambda: None,- _reflect_ways=lambda: None,+ """`_on_arrangement` is how a peer's idea of where the machines are reaches this PC: a stamped+ message over either link, settled by stamp and then by id (section 8)."""++ def setUp(self):+ import tempfile+ from pathlib import Path++ from core import protocol+ from core.tests import responder_harness as harness++ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ self.path = Path(directory.name) / "settings.json"+ self.peer = protocol.id_text(harness.B)+ self.own = protocol.id_text(harness.HERE)+ settings = app_config.migrate(None, machine_id=self.own)+ settings["peers"] = [harness.entry(harness.B, "Mac", side="right", side_set_at=100, side_by=self.own)]+ app_config.write_settings(self.path, settings)+ self.refreshed = []+ self.page = types.SimpleNamespace(+ _config=default_config(), config_path=self.path, _on_alert=lambda title, message: None,+ _pull_peer_fields=lambda: self.refreshed.append("pulled"),+ sender=types.SimpleNamespace(refresh=lambda: self.refreshed.append("sender")),+ server=types.SimpleNamespace(peers_changed=lambda: self.refreshed.append("server")),)- return page, saved- def arrive(self, page, mac_edge, stamp):- kvm_bridge_win.WindowsApplication._on_arrangement(page, mac_edge, stamp)+ def arrive(self, edge, stamp, by=None):+ kvm_bridge_win.WindowsApplication._on_arrangement(self.page, self.peer, edge, stamp, by or self.peer)- def learn(self, page, edge, host="192.168.1.10"):- real = kvm_bridge_win.sender.is_this_machine- kvm_bridge_win.sender.is_this_machine = lambda h: False- try:- kvm_bridge_win.WindowsApplication._on_learned(page, host, edge, 40)- finally:- kvm_bridge_win.sender.is_this_machine = real+ def side(self):+ return json.loads(self.path.read_text(encoding="utf-8"))["peers"][0]["side"]- def test_a_newer_arrangement_from_the_mac_is_applied_as_this_pcs_opposite_edge_with_its_stamp(self):- page, saved = self.page("right", stamp=100)- self.arrive(page, "top", 200)- self.assertEqual((page._config.mac_return_edge, page._config.arrangement_set_at), ("bottom", 200))-- def test_the_same_edge_with_a_newer_stamp_leaves_the_stored_stamp_as_the_mac_does(self):- page, saved = self.page("left", stamp=100)- self.arrive(page, "right", 200)- self.assertEqual((page._config.mac_return_edge, page._config.arrangement_set_at), ("left", 100))+ def test_a_newer_arrangement_is_applied_as_this_pcs_opposite_edge(self):+ self.arrive("top", 200)+ self.assertEqual(self.side(), "bottom")+ self.assertEqual(self.refreshed, ["pulled", "sender", "server"])def test_an_older_arrangement_is_ignored(self):- page, saved = self.page("right", stamp=200)- self.arrive(page, "top", 100)- self.assertEqual(page._config.mac_return_edge, "right")- self.assertEqual(saved, [])+ self.arrive("top", 50)+ self.assertEqual(self.side(), "right")+ self.assertEqual(self.refreshed, [])def test_the_same_arrangement_over_the_second_link_changes_nothing_and_logs_nothing(self):- # One change on the Mac reaches this PC over both links, so the second copy carries the- # stamp the first already stored.- page, saved = self.page("left", stamp=300)+ self.arrive("top", 200)+ self.refreshed.clear()with self.assertNoLogs(kvm_bridge_win.LOGGER, logging.INFO):- self.arrive(page, "right", 300)- self.assertEqual(saved, [])+ self.arrive("top", 200)+ self.assertEqual(self.refreshed, [])- def test_the_macs_hello_names_the_edge_of_a_pc_that_has_none(self):- page, saved = self.page("", stamp=0)- self.learn(page, "left")- self.assertEqual(page._config.mac_return_edge, "left")+ def test_a_change_made_here_is_stamped_and_sent_to_the_first_peer(self):+ from core import protocol+ from core.tests import responder_harness as harness- def test_a_change_made_here_with_no_link_is_stored_and_told_to_nobody(self):- page, saved = self.page("right", stamp=0)+ config = default_config()+ config.mac_return_edge, config.machine_id = "right", self.owntold = []- page.sender = types.SimpleNamespace(send_arrangement=lambda *a: told.append(("pc-to-mac", a)) or False, update_config=lambda c: None)- page.server = types.SimpleNamespace(send_arrangement=lambda *a: told.append(("mac-to-pc", a)) or False)+ page = types.SimpleNamespace(+ _config=config, _persist=lambda: True, _first_peer=lambda: harness.B,+ _send_to=lambda peer, message: told.append((peer, message)) or False,+ sender=types.SimpleNamespace(update_config=lambda config: None),+ _reflect_look=lambda: None, _reflect_ways=lambda: None,+ )kvm_bridge_win.WindowsApplication._set_arrangement(page, "top")- self.assertEqual(page._config.mac_return_edge, "top")- self.assertGreater(page._config.arrangement_set_at, 0)- self.assertEqual([who for who, _ in told], ["pc-to-mac", "mac-to-pc"])- self.assertEqual(told[0][1][0], "bottom")-- def test_the_macs_hello_leaves_an_edge_set_here(self):- # G1 in the report, fixed: a PC set up before pairing keeps the side chosen here, and the- # Mac's first hello only fills an edge the PC does not hold.- page, saved = self.page("top", stamp=5000)- self.learn(page, "left")- self.assertEqual((page._config.mac_return_edge, page._config.arrangement_set_at), ("top", 5000))-- def test_the_macs_hello_leaves_an_edge_even_a_hello_filled(self):- # The Mac's announced arrangement, not its next hello, is what moves it after that.- page, saved = self.page("left", stamp=0)- self.learn(page, "bottom")- self.assertEqual(page._config.mac_return_edge, "left")+ self.assertEqual(config.mac_return_edge, "top")+ self.assertGreater(config.arrangement_set_at, 0)+ peer, message = told[0]+ self.assertEqual(peer, harness.B)+ self.assertEqual(message["data"], {"edge": "top", "set_at": config.arrangement_set_at, "by": self.own})def test_a_fresh_config_holds_no_edge_though_the_crossing_page_offers_right(self):# Pinned known gap (G3 in the report).diff --git a/win_app/tests/test_effect_fires.py b/win_app/tests/test_effect_fires.pyindex ead6595..ca26c19 100644--- a/win_app/tests/test_effect_fires.py+++ b/win_app/tests/test_effect_fires.py@@ -2,9 +2,9 @@callbacks to the call that actually reaches EffectOverlay or EdgeGlow, at the one hop that has notest today: kvm_bridge_win.py's WindowsApplication._on_pressure / _on_arrival.-sender.py's MacSender._notify_pressure(edge, pressure, crossed, part) and its arrival_callback --+sender.py's LinkSender._notify_pressure(edge, pressure, crossed, part) and its arrival_callback --an edge push, a Part-of-the-edge push, a corner push, a crossing, a switch home -- are already-proven by test_sender.py's PushTests, CornerCrossingTests and ArrivalTests. receiver.py's+proven by test_links.py's EdgeTests, CornerTests, TakingTests and OnwardTests. receiver.py'spressure_callback and arrival_callback (the return-edge push and its arrival) are proven bytest_receiver.py's tests around line 716. Neither is repeated here: these tests start from the(edge, pressure, crossed, part) / (method, edge, x, y) values those callbacks already produce and@@ -92,7 +92,7 @@ class PressureRoutingTest(unittest.TestCase):owner.glow.set_pressure.assert_called_once_with("right", 0.5, False, "end")def test_a_corner_push_reaches_the_overlay_with_its_corner(self):- """sender.py names the corner in `part` (test_sender.py's CornerTests), and the overlay+ """sender.py names the corner in `part` (test_links.py's CornerTests), and the overlayplays the corner form from it."""owner = _owner(glow_style="rupture")overlay = mock.Mock()@@ -132,10 +132,10 @@ class PressureRoutingTest(unittest.TestCase):@unittest.skipIf(kvm_bridge_win is None, "needs PySide6")class ArrivalRoutingTest(unittest.TestCase):"""`method` is decided before _on_arrival ever runs, by the inline lambdas that wire- receiver.py's and sender.py's arrival_callback in WindowsApplication.__init__+ the responder's and sender.py's arrival_callback in WindowsApplication.__init__(kvm_bridge_win.py: "notch" if edge == "bottom" else "edge", or "switch" if edge is None, for- the receiver around line 240; "switch" if edge is None else "edge" for the sender around line- 253 -- the sender has no notch of its own, since only the Mac has one). Neither lambda is a+ the responder around line 286; "switch" if edge is None else "edge" for the sender around line+ 312 -- the sender has no notch of its own, since only the Mac has one). Neither lambda is aseparately callable unit, so it is not unit-tested on its own; these tests start from themethod it would have produced and check where _on_arrival sends it."""diff --git a/win_app/tests/test_firewall_win.py b/win_app/tests/test_firewall_win.pyindex 2a5b1c8..f78c4fc 100644--- a/win_app/tests/test_firewall_win.py+++ b/win_app/tests/test_firewall_win.py@@ -7,6 +7,7 @@ the status script emits, so the decisions run on the Mac with no Windows at all.import unittestimport osimport sys+from unittest import mocksys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))@@ -34,6 +35,15 @@ def pairing_rule(action="Allow", profile="Private", program=EXE, enabled="True")}+def pairing_tcp_rule(action="Allow", profile="Private", program=EXE, enabled="True"):+ """The TCP rule for the pairing exchange, hosted while a pairing code is on screen."""+ return {+ "name": "{z}", "display": "Beamer Pairing (TCP-In)", "enabled": enabled, "action": action,+ "direction": "Inbound", "profile": profile, "program": program, "protocol": "TCP",+ "localPort": [str(firewall_win.PAIRING_PORT)],+ }++def network(category="Private", alias="Wi-Fi", index=5, ipv4="Internet", ipv6="NoTraffic"):return {"alias": alias, "index": index, "category": category, "ipv4": ipv4, "ipv6": ipv6}@@ -52,7 +62,7 @@ class InterpretTests(unittest.TestCase):self.assertEqual(advise(status).action, "repair")def test_correct_rule_on_private_lan(self):- status = interpret(payload([rule(), pairing_rule()]), EXE, PORT)+ status = interpret(payload([rule(), pairing_rule(), pairing_tcp_rule()]), EXE, PORT)self.assertTrue(status.allowed)self.assertTrue(status.covered)self.assertTrue(status.pairing_allowed)@@ -91,7 +101,7 @@ class InterpretTests(unittest.TestCase):self.assertIn("blocking", advice.sentence)def test_block_rule_on_an_inactive_profile_is_harmless(self):- status = interpret(payload([rule(), pairing_rule(), rule(action="Block", profile="Public", port="Any")]), EXE, PORT)+ status = interpret(payload([rule(), pairing_rule(), pairing_tcp_rule(), rule(action="Block", profile="Public", port="Any")]), EXE, PORT)self.assertFalse(status.blocked)self.assertEqual(advise(status).action, "check")@@ -116,7 +126,7 @@ class InterpretTests(unittest.TestCase):self.assertFalse(interpret(payload([rule(direction="Outbound")]), EXE, PORT).allowed)def test_any_profile_rule_covers_everything(self):- status = interpret(payload([rule(profile="Any"), pairing_rule(profile="Any")], [network("Public")]), EXE, PORT)+ status = interpret(payload([rule(profile="Any"), pairing_rule(profile="Any"), pairing_tcp_rule(profile="Any")], [network("Public")]), EXE, PORT)self.assertTrue(status.covered)self.assertEqual(status.public_interfaces, ((5, "Wi-Fi"),))self.assertEqual(advise(status).action, "check")@@ -128,7 +138,7 @@ class InterpretTests(unittest.TestCase):def test_public_hyper_v_switch_beside_private_wifi_is_not_the_lan(self):# A common setup: Wi-Fi Private with Internet, a vEthernet switch Public with none.networks = [network(), network("Public", alias="vEthernet (Hyper-V Switch)", index=31, ipv4="NoTraffic")]- status = interpret(payload([rule(), pairing_rule()], networks), EXE, PORT)+ status = interpret(payload([rule(), pairing_rule(), pairing_tcp_rule()], networks), EXE, PORT)self.assertEqual(status.active_profiles, ("Private", "Public"))self.assertEqual(status.lan_profiles, ("Private",))self.assertTrue(status.covered)@@ -162,25 +172,85 @@ class InterpretTests(unittest.TestCase):class RepairScriptTests(unittest.TestCase):def test_repair_never_opens_the_port_on_public(self):- rendered = firewall_win._REPAIR_SCRIPT.format(- exe=firewall_win._quote(EXE), filters=firewall_win._RULES_FOR_LEAF,+ rendered = firewall_win._ADD_SCRIPT.format(+ exe=firewall_win._quote(EXE),name=firewall_win._quote(firewall_win.RULE_NAME), port=PORT,pairing_name=firewall_win._quote(firewall_win.PAIRING_RULE_NAME), pairing_port=firewall_win.PAIRING_PORT,+ pairing_tcp_name=firewall_win._quote(firewall_win.PAIRING_TCP_RULE_NAME),profiles="Private",)self.assertIn("-Profile Private ", rendered)self.assertNotIn("Public", rendered)self.assertIn(f"-Protocol TCP -LocalPort {PORT} ", rendered)self.assertIn(f"-Protocol UDP -LocalPort {firewall_win.PAIRING_PORT} ", rendered)- self.assertEqual(rendered.count("-Profile Private "), 2)+ self.assertIn(f"-DisplayName 'Beamer Pairing (TCP-In)' -Direction Inbound -Protocol TCP -LocalPort {firewall_win.PAIRING_PORT} ", rendered)+ self.assertEqual(rendered.count("-Profile Private "), 3)++ def test_the_removal_never_runs_bare(self):# A bare Remove-NetFirewallRule deletes every rule on the machine.+ rendered = firewall_win._REMOVE_SCRIPT.format(+ exe=firewall_win._quote(EXE), filters=firewall_win._RULES_FOR_LEAF,+ name=firewall_win._quote(firewall_win.RULE_NAME),+ pairing_name=firewall_win._quote(firewall_win.PAIRING_RULE_NAME),+ pairing_tcp_name=firewall_win._quote(firewall_win.PAIRING_TCP_RULE_NAME),+ )self.assertNotIn("\nRemove-NetFirewallRule", rendered)- self.assertIn("if ($stale.Count -gt 0)", rendered)+ self.assertIn("foreach ($rule in $stale)", rendered)def test_quote_doubles_single_quotes(self):self.assertEqual(firewall_win._quote("it's"), "'it''s'")+NOT_FOUND = "Remove-NetFirewallRule : The requested object could not be found."+++class RepairToleratesAbsentRulesTests(unittest.TestCase):+ """1.5.0-beta.2, fresh install on the rig (01-10-2026): a rule enumerated twice (once by its+ program, once by its display name) is removed once and then "not found", which aborted repair+ before any rule was written. A rule that is already gone is the state removal wants."""++ def run_repair(self, remove_error=None):+ calls = []++ def fake(script, timeout=60.0):+ calls.append(script)+ if "Remove-NetFirewallRule" in script and remove_error is not None:+ raise RuntimeError(remove_error)+ return ""++ with mock.patch.object(firewall_win, "_powershell", side_effect=fake):+ firewall_win.repair(EXE, PORT)+ return calls++ def test_a_rule_already_gone_does_not_stop_the_new_rules_being_written(self):+ calls = self.run_repair(NOT_FOUND)+ self.assertEqual(sum("New-NetFirewallRule" in call for call in calls), 1)+ self.assertEqual(calls[-1].count("New-NetFirewallRule"), 3)++ def test_any_other_removal_failure_still_fails_and_writes_nothing(self):+ calls = []++ def fake(script, timeout=60.0):+ calls.append(script)+ raise RuntimeError("Access is denied.")++ with mock.patch.object(firewall_win, "_powershell", side_effect=fake):+ with self.assertRaisesRegex(RuntimeError, "Access is denied"):+ firewall_win.repair(EXE, PORT)+ self.assertFalse(any("New-NetFirewallRule" in call for call in calls))++ def test_the_removal_script_removes_each_rule_once_and_tolerates_not_found(self):+ removal = firewall_win._REMOVE_SCRIPT.format(+ exe=firewall_win._quote(EXE), filters=firewall_win._RULES_FOR_LEAF,+ name=firewall_win._quote(firewall_win.RULE_NAME),+ pairing_name=firewall_win._quote(firewall_win.PAIRING_RULE_NAME),+ pairing_tcp_name=firewall_win._quote(firewall_win.PAIRING_TCP_RULE_NAME),+ )+ self.assertIn("Sort-Object Name -Unique", removal)+ self.assertIn("could not be found", removal)+ self.assertNotIn("$stale | Remove-NetFirewallRule", removal)++if __name__ == "__main__":unittest.main()@@ -197,8 +267,18 @@ class PairingRuleTests(unittest.TestCase):self.assertEqual(advice.action, "repair")self.assertIn("pairing beacon", advice.sentence)- def test_both_rules_present_is_all_clear(self):+ def test_a_missing_pairing_rule_is_one_this_app_may_add_by_itself(self):+ # An upgrade from 1.4.x has the receiver and the UDP rule and no TCP one: the first code shown+ # would otherwise make Windows ask, and a click on Allow writes rules for public networks too.status = interpret(payload([rule(), pairing_rule()]), EXE, PORT)+ self.assertTrue(firewall_win.missing_rule(status))+ whole = interpret(payload([rule(), pairing_rule(), pairing_tcp_rule()]), EXE, PORT)+ self.assertFalse(firewall_win.missing_rule(whole))+ blocked = interpret(payload([rule(action="Block")]), EXE, PORT)+ self.assertFalse(firewall_win.missing_rule(blocked))++ def test_both_rules_present_is_all_clear(self):+ status = interpret(payload([rule(), pairing_rule(), pairing_tcp_rule()]), EXE, PORT)self.assertTrue(status.pairing_allowed)advice = advise(status)self.assertEqual(advice.action, "check")@@ -213,6 +293,30 @@ class PairingRuleTests(unittest.TestCase):status = interpret(payload([rule(), wrong]), EXE, PORT)self.assertFalse(status.pairing_allowed)+ def test_pairing_rules_without_the_tcp_one_is_reported_and_repairable(self):+ # Installs from before pairing version 3 have the UDP beacon rule and not the TCP exchange.+ status = interpret(payload([rule(), pairing_rule()]), EXE, PORT)+ self.assertTrue(status.pairing_allowed)+ self.assertFalse(status.pairing_tcp_allowed)+ advice = advise(status)+ self.assertEqual(advice.action, "repair")+ self.assertIn(f"TCP {firewall_win.PAIRING_PORT}", advice.sentence)+ self.assertNotIn("UDP", advice.sentence)++ def test_both_pairing_rules_missing_names_both(self):+ advice = advise(interpret(payload([rule()]), EXE, PORT))+ self.assertIn(f"UDP {firewall_win.PAIRING_PORT}", advice.sentence)+ self.assertIn(f"TCP {firewall_win.PAIRING_PORT}", advice.sentence)++ def test_a_disabled_or_udp_pairing_tcp_rule_does_not_count(self):+ for wrong in (pairing_tcp_rule(enabled="False"), {**pairing_tcp_rule(), "protocol": "UDP"}):+ status = interpret(payload([rule(), pairing_rule(), wrong]), EXE, PORT)+ self.assertFalse(status.pairing_tcp_allowed)++ def test_a_pairing_tcp_block_is_not_an_allow(self):+ status = interpret(payload([rule(), pairing_rule(), pairing_tcp_rule(action="Block")]), EXE, PORT)+ self.assertFalse(status.pairing_tcp_allowed)+def test_a_missing_tcp_rule_is_reported_before_the_pairing_rule(self):# Input not arriving at all is the bigger problem; one button fixes both.status = interpret(payload([pairing_rule()]), EXE, PORT)diff --git a/win_app/tests/test_hardware_win.py b/win_app/tests/test_hardware_win.pynew file mode 100644index 0000000..df77172--- /dev/null+++ b/win_app/tests/test_hardware_win.py@@ -0,0 +1,77 @@+"""This PC's hardware address for the handshake's `hw` field. The Win32 lookup runs only on Windows."""++import os+import re+import sys+import unittest+from unittest import mock++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import hardware_win+from core import pairing++MAC_FORM = re.compile(r"^([0-9a-f]{2}:){5}[0-9a-f]{2}$")+++class FormatMacTest(unittest.TestCase):+ def test_six_bytes_become_lower_case_colon_groups(self):+ self.assertEqual(hardware_win.format_mac(b"\xaa\xbb\xcc\x0d\xee\xff"), "aa:bb:cc:0d:ee:ff")++ def test_wrong_length_is_unknown(self):+ self.assertEqual(hardware_win.format_mac(b"\xaa\xbb\xcc\xdd\xee"), "")+ self.assertEqual(hardware_win.format_mac(b"\xaa\xbb\xcc\xdd\xee\xff\x00\x01"), "")+ self.assertEqual(hardware_win.format_mac(b""), "")++ def test_all_zero_is_unknown(self):+ self.assertEqual(hardware_win.format_mac(bytes(6)), "")+++class HardwareAddressTowardsTest(unittest.TestCase):+ def test_off_windows_is_unknown_without_touching_the_network(self):+ with mock.patch.object(hardware_win.sys, "platform", "darwin"), \+ mock.patch.object(pairing, "local_address_towards") as route:+ self.assertEqual(hardware_win.hardware_address_towards("192.168.77.5"), "")+ route.assert_not_called()++ def test_garbage_host_is_unknown(self):+ self.assertEqual(hardware_win.hardware_address_towards("not a host"), "")+ self.assertEqual(hardware_win.hardware_address_towards(""), "")++ def test_a_failing_lookup_never_raises(self):+ with mock.patch.object(hardware_win.sys, "platform", "win32"), \+ mock.patch.object(pairing, "local_address_towards", side_effect=OSError("no route")):+ self.assertEqual(hardware_win.hardware_address_towards("192.168.77.5"), "")++ def test_a_failing_adapter_walk_never_raises(self):+ with mock.patch.object(hardware_win.sys, "platform", "win32"), \+ mock.patch.object(pairing, "local_address_towards", return_value="192.168.77.3"), \+ mock.patch.object(hardware_win, "_adapter_table", side_effect=OSError("boom")):+ self.assertEqual(hardware_win.hardware_address_towards("192.168.77.5"), "")++ def test_the_adapter_that_owns_the_routed_address_wins(self):+ table = [("10.1.0.9", b"\x02\x00\x00\x00\x00\x01"), ("192.168.77.3", b"\xaa\xbb\xcc\xdd\xee\xff")]+ with mock.patch.object(hardware_win.sys, "platform", "win32"), \+ mock.patch.object(pairing, "local_address_towards", return_value="192.168.77.3"), \+ mock.patch.object(hardware_win, "_adapter_table", return_value=table):+ self.assertEqual(hardware_win.hardware_address_towards("192.168.77.5"), "aa:bb:cc:dd:ee:ff")++ def test_an_all_zero_adapter_is_skipped(self):+ table = [("192.168.77.3", bytes(6))]+ with mock.patch.object(hardware_win.sys, "platform", "win32"), \+ mock.patch.object(pairing, "local_address_towards", return_value="192.168.77.3"), \+ mock.patch.object(hardware_win, "_adapter_table", return_value=table):+ self.assertEqual(hardware_win.hardware_address_towards("192.168.77.5"), "")++[email protected](sys.platform == "win32", "GetAdaptersAddresses exists only on Windows")+class RealAdapterTest(unittest.TestCase):+ def test_result_is_unknown_or_well_formed(self):+ for host in ("192.0.2.1", "192.168.77.5"):+ got = hardware_win.hardware_address_towards(host)+ self.assertTrue(got == "" or MAC_FORM.match(got), got)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_hide_addresses_win.py b/win_app/tests/test_hide_addresses_win.pyindex 00819f2..8d25a95 100644--- a/win_app/tests/test_hide_addresses_win.py+++ b/win_app/tests/test_hide_addresses_win.py@@ -1,4 +1,4 @@-"""Hide addresses in the real window, built offscreen as tools/readme_shots_win.py builds it, which+"""Hide addresses in the real window, built offscreen as the README's screenshots build it, whichstarts no receiver, hooks or announcer."""import json@@ -8,7 +8,7 @@ import unittestfrom pathlib import Pathtry:- from PySide6.QtWidgets import QApplication, QLineEdit+ from PySide6.QtWidgets import QApplicationimport kvm_bridge_winimport theme@@ -22,28 +22,33 @@ class HideAddressesWindowTest(unittest.TestCase):os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")self.app = QApplication.instance() or QApplication([])theme.init_fonts()- self.config = Path(tempfile.mkdtemp()) / "config.json"+ folder = Path(tempfile.mkdtemp())+ self.config = folder / "settings.json"self.raw = {"host": "192.0.2.20", "port": 24820, "auth_token": "synthetic", "paired_with": "MacBook Pro","mac_host": "192.0.2.10", "mac_return_edge": "left"}- self.config.write_text(json.dumps(self.raw))+ (folder / "config.json").write_text(json.dumps(self.raw))self.window = kvm_bridge_win.WindowsApplication(self.config)def tearDown(self):self.window.deleteLater()- def test_a_reload_that_turns_it_on_hides_this_pcs_address(self):+ def edit_settings(self, **changes):+ self.config.write_text(json.dumps({**json.loads(self.config.read_text()), **changes}))++ def test_a_reload_that_turns_it_on_hides_this_pcs_and_each_machines_address(self):# The final bug pass, 28-09-2026: the tray's Reload configuration set the switch on but left- # the address field readable, as the switch's handler never ran.- self.assertEqual(self.window.host_entry.echoMode(), QLineEdit.EchoMode.Normal)- self.config.write_text(json.dumps(dict(self.raw, hide_addresses=True)))+ # the address readable, as the switch's handler never ran.+ self.edit_settings(hide_addresses=True)self.window.reload_config()self.assertTrue(self.window.hide_switch.isChecked())- self.assertEqual(self.window.host_entry.echoMode(), QLineEdit.EchoMode.Password)+ self.assertNotIn("192.0.2", self.window.host_readout.text())+ row = next(iter(self.window.machines.rows.values()))+ self.assertNotIn("192.0.2.10", row.where.text())def test_the_directions_note_hides_the_macs_address(self):- # The feature shoot, 29-09-2026: with it on, the note under Send input to your Mac still+ # The feature shoot, 29-09-2026: with it on, the note under Send input across still# read "Connected to the Mac at" and its address.- self.config.write_text(json.dumps(dict(self.raw, hide_addresses=True)))+ self.edit_settings(hide_addresses=True)self.window.reload_config()self.window._sending_detail = "Connected to the Mac at 192.0.2.10"self.window._refresh_window()@@ -52,7 +57,7 @@ class HideAddressesWindowTest(unittest.TestCase):def test_a_tray_alert_hides_the_macs_address(self):# "Cannot switch — <status>" carries the sender's status, which can name the Mac's address.- self.config.write_text(json.dumps(dict(self.raw, hide_addresses=True)))+ self.edit_settings(hide_addresses=True)self.window.reload_config()shown = []self.window.tray.showMessage = lambda title, message, *rest: shown.append(message)diff --git a/win_app/tests/test_hook_key_repeat.py b/win_app/tests/test_hook_key_repeat.pyindex 8753085..498ba82 100644--- a/win_app/tests/test_hook_key_repeat.py+++ b/win_app/tests/test_hook_key_repeat.py@@ -1,7 +1,7 @@-"""kvm_bridge_win.py:1056-1071 (`_on_hook_key`) cannot be imported here (it+"""kvm_bridge_win.py:2351 (`_on_hook_key`) cannot be imported here (itneeds PySide6, Windows-only), so this drives its exact dispatch by handagainst the two pure-Python pieces it calls: `capture_win.Trigger.feed` and-`sender.MacSender.on_key`. The dispatch replicated below is copied verbatim+`sender.LinkSender.on_key`. The dispatch replicated below is copied verbatimfrom `_on_hook_key`'s body."""import time@@ -13,100 +13,94 @@ sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(import capture_winfrom core import protocol-import senderfrom capture_win import Trigger-from fakes import FakeDesktop-from sender import MacSender+from links_rig import B, Rig, make_config-def dispatch(trigger, mac_sender, 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 Trueif action == capture_win.TOGGLE:- mac_sender.toggle()+ link_sender.toggle()else:- mac_sender.set_redirecting(action == capture_win.REDIRECT)+ link_sender.set_redirecting(action == capture_win.REDIRECT)return True- if trigger.claims(name, down, mac_sender.redirecting):+ if trigger.claims(name, down, link_sender.redirecting):return True- return mac_sender.on_key(name, down)+ return link_sender.on_key(name, down, vk, us)class HeldTriggerRepeatTests(unittest.TestCase):def setUp(self):self.trigger = Trigger("alt_r", "hold", 300)- self.mac_sender = MacSender(desktop=FakeDesktop([]))- # Make the link look live without a real socket or connection- # thread, exactly as `_link_live`/`connected` require.- self.mac_sender._sock = object()- self.mac_sender._connected_at = time.monotonic()+ self.rig = Rig()+ self.link_sender = self.rig.sender- def test_held_trigger_key_repeat_is_not_forwarded_to_mac(self):+ def keys(self, kind):+ return self.rig.sent(B, kind)++ def test_held_trigger_key_repeat_is_not_forwarded_to_the_peer(self):# Physical press: the trigger claims it, redirecting turns on.- self.assertTrue(dispatch(self.trigger, self.mac_sender, "alt_r", True))- self.assertTrue(self.mac_sender.redirecting)+ self.assertTrue(dispatch(self.trigger, self.link_sender, "alt_r", True))+ self.assertTrue(self.link_sender.redirecting)# Windows autorepeats WM_KEYDOWN for as long as the key stays down.# The trigger's own comment says a repeat "never reaches an app";- # it must not be forwarded to the Mac as a live keystroke.- dispatch(self.trigger, self.mac_sender, "alt_r", True)-- forwarded = [- message- for message in list(self.mac_sender._outbound.queue)- if message.get("type") == protocol.MSG_KEYDOWN- and message.get("data", {}).get("key") == "alt_r"- ]+ # it must not be forwarded to the peer as a live keystroke. Any key+ # at all is checked, not one name: the key table renames keys per peer.+ dispatch(self.trigger, self.link_sender, "alt_r", True)+self.assertEqual(- forwarded,+ self.keys(protocol.MSG_KEYDOWN),[],- "an autorepeat of the held trigger key was forwarded to the Mac "+ "an autorepeat of the held trigger key was forwarded to the peer ""as MSG_KEYDOWN",)def test_a_lone_tap_at_home_under_double_tap_is_an_ordinary_key(self):trigger = Trigger("cmd_r", "double_tap", 300)- 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_the_trigger_is_swallowed_while_input_is_away_under_double_tap(self):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))- forwarded = [m for m in list(self.mac_sender._outbound.queue) if m.get("data", {}).get("key") == "cmd_r"]- self.assertEqual(forwarded, [])+ 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.assertEqual(self.keys(protocol.MSG_KEYDOWN) + self.keys(protocol.MSG_KEYUP), [])def test_the_second_taps_release_is_swallowed_after_coming_home(self):# 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"), [])if __name__ == "__main__":diff --git a/win_app/tests/test_ignored_inputs.py b/win_app/tests/test_ignored_inputs.pyindex 6efac39..0741679 100644--- a/win_app/tests/test_ignored_inputs.py+++ b/win_app/tests/test_ignored_inputs.py@@ -1,9 +1,8 @@"""Keys and buttons that stay on this PC while its input is on the Mac: the sender's decision on-the hook thread, the side buttons now crossing, and the setting's round trip through config.json."""+the hook thread, the side buttons now crossing, and the setting's round trip through settings.json."""import jsonimport tempfile-import timeimport unittestfrom pathlib import Pathimport os@@ -15,9 +14,7 @@ import app_configimport capture_winfrom core import ignoredfrom core import protocol-import sender-from fakes import FakeClipboard, FakeDesktop-from core.return_edge import Rect+from links_rig import B, Rig, make_config as rig_configVK_F13 = 0x7CVK_A = 0x41@@ -37,57 +34,46 @@ def make_config(**overrides):return app_config.Config(**values)-def x_button(message, number):- return message, number << 16--class SenderTests(unittest.TestCase):def setUp(self):- self.sender = sender.MacSender(- desktop=FakeDesktop([Rect(0, 0, 1920, 1080)], cursor=(900, 500)),- clipboard=FakeClipboard(),- is_local=lambda host: False,- )- self.configure([ignored.key(VK_F13), ignored.button("back")])- self.sender._sock = object()- self.sender._connected_at = time.monotonic()- self.sender._last_ack_at = time.monotonic()+ self.rig = Rig(cursor=(900, 500), ignored_inputs=[ignored.key(VK_F13), ignored.button("back")])+ self.sender = self.rig.senderself.sender.set_redirecting(True)- self.drain()-- def tearDown(self):- self.sender._sock = None+ self.rig.accept_take()def configure(self, entries):- self.sender.update_config(make_config(ignored_inputs=list(entries)))+ self.sender.update_config(rig_config(ignored_inputs=list(entries)))- def drain(self):- messages = []- while not self.sender._outbound.empty():- messages.append(self.sender._outbound.get_nowait())- return [(m["type"], m["data"]) for m in messages if m["type"] in (+ def sent(self):+ return [(m["type"], m["data"]) for m in self.rig.sent(B) if m["type"] in (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_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"}),])- def test_a_key_ignored_while_held_on_the_mac_is_still_released_there(self):+ def test_a_key_ignored_while_held_on_the_peer_is_still_released_there(self):self.configure([])self.assertTrue(self.sender.on_key("f13", True, VK_F13))self.configure([ignored.key(VK_F13)])self.assertTrue(self.sender.on_key("f13", False, VK_F13))- self.assertEqual(self.drain(), [+ self.assertEqual(self.sent(), [(protocol.MSG_KEYDOWN, {"key": "f13"}),(protocol.MSG_KEYUP, {"key": "f13"}),])@@ -95,20 +81,17 @@ class SenderTests(unittest.TestCase):def test_the_side_buttons_cross_as_back_and_forward(self):self.configure([])for message in (capture_win.WM_XBUTTONDOWN, capture_win.WM_XBUTTONUP):- message, data = x_button(message, 2)- self.assertTrue(self.sender.on_mouse(message, 0, 0, data))- self.assertEqual(self.drain(), [+ self.assertTrue(self.mouse(message, 2 << 16))+ self.assertEqual(self.sent(), [(protocol.MSG_MOUSEDOWN, {"button": "forward"}),(protocol.MSG_MOUSEUP, {"button": "forward"}),])def test_an_ignored_button_stays_on_this_pc(self):- message, data = x_button(capture_win.WM_XBUTTONDOWN, 1)- self.assertFalse(self.sender.on_mouse(message, 0, 0, data))- message, data = x_button(capture_win.WM_XBUTTONUP, 1)- self.assertFalse(self.sender.on_mouse(message, 0, 0, data))- self.assertTrue(self.sender.on_mouse(capture_win.WM_MBUTTONDOWN, 0, 0, 0))- self.assertEqual(self.drain(), [(protocol.MSG_MOUSEDOWN, {"button": "middle"})])+ self.assertFalse(self.mouse(capture_win.WM_XBUTTONDOWN, 1 << 16))+ self.assertFalse(self.mouse(capture_win.WM_XBUTTONUP, 1 << 16))+ self.assertTrue(self.mouse(capture_win.WM_MBUTTONDOWN))+ self.assertEqual(self.sent(), [(protocol.MSG_MOUSEDOWN, {"button": "middle"})])class CaptureTests(unittest.TestCase):@@ -153,7 +136,7 @@ class CaptureTests(unittest.TestCase):class ConfigTests(unittest.TestCase):def test_the_list_survives_a_save_and_a_load(self):with tempfile.TemporaryDirectory() as directory:- path = Path(directory) / "config.json"+ path = Path(directory) / "settings.json"entries = [ignored.key(VK_F13), ignored.button("back")]app_config.save_config(path, make_config(port=24820, ignored_inputs=entries))self.assertEqual(json.loads(path.read_text())["ignored_inputs"], entries)diff --git a/win_app/tests/test_input_injector.py b/win_app/tests/test_input_injector.pyindex c3c3113..dd17545 100644--- a/win_app/tests/test_input_injector.py+++ b/win_app/tests/test_input_injector.py@@ -468,3 +468,28 @@ class InjectedMarkTests(unittest.TestCase):def test_a_key_input_is_stamped(self):item = input_injector._keybd_input(0x41, 0x1E, 0)self.assertEqual(item.union.ki.dwExtraInfo, input_injector.INJECTED_MARK)+++class InjectTextTests(unittest.TestCase):+ """WIRE.md section 10: a `text` message is typed as characters, never as keys."""++ def test_each_character_is_a_unicode_down_and_up_pair(self):+ plan = input_injector.plan_text_inputs("aé")+ down, up = KEYEVENTF_UNICODE, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP+ self.assertEqual(plan, [(0, ord("a"), down), (0, ord("a"), up), (0, ord("é"), down), (0, ord("é"), up)])++ def test_a_character_outside_the_bmp_goes_as_its_surrogate_pair(self):+ plan = input_injector.plan_text_inputs("\U0001F600")+ self.assertEqual([scan for _vk, scan, _flags in plan], [0xD83D, 0xD83D, 0xDE00, 0xDE00])++ def test_injecting_text_sends_one_batch_stamped_with_the_mark(self):+ sent = []+ with mock.patch.object(input_injector, "_send_input", lambda *items: sent.extend(items)):+ input_injector.inject_text("hi")+ self.assertEqual(len(sent), 4)+ self.assertTrue(all(item.union.ki.dwExtraInfo == input_injector.INJECTED_MARK for item in sent))+ self.assertEqual([item.union.ki.wScan for item in sent], [ord("h"), ord("h"), ord("i"), ord("i")])++ def test_empty_text_sends_nothing(self):+ with mock.patch.object(input_injector, "_send_input", lambda *items: self.fail("nothing to send")):+ input_injector.inject_text("")diff --git a/win_app/tests/test_key_up_after_switch_back.py b/win_app/tests/test_key_up_after_switch_back.pyindex 60aa7dd..c9e5068 100644--- a/win_app/tests/test_key_up_after_switch_back.py+++ b/win_app/tests/test_key_up_after_switch_back.py@@ -1,62 +1,29 @@-"""Reproduces win-sender-3: a key held down while redirecting, released after-switching back to Windows, never reaches the Mac as a key-up -- because-on_key's gate reads the live `redirecting` flag rather than whether the-key-down was actually forwarded."""+"""Reproduces win-sender-3: a key held down while input is on a peer, released after it has come+home, must still reach the peer as a key-up, because on_key's gate reads where input is now rather+than whether the key-down was actually forwarded. The owner (core/owner.py) now answers for it: it+releases what it pressed on a peer when input leaves, and swallows the physical release."""-import time-import unittestimport osimport sys+import unittestsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from links_rig import B, Rigfrom core import protocol-import sender-from fakes import FakeClipboard, FakeDesktop-from core.return_edge import Rect--MONITORS = [Rect(0, 0, 1920, 1080)]---def make_config(**overrides):- from app_config import Config-- values = dict(- host="127.0.0.1",- port=0,- auth_token="shared-token",- mac_host="127.0.0.1",- mac_return_edge="left",- mac_resistance_px=40,- crossing_resistance_px=40,- )- values.update(overrides)- return Config(**values)class KeyUpAfterSwitchBackTest(unittest.TestCase):def setUp(self):- self.desktop = FakeDesktop(MONITORS, cursor=(0, 500))- self.sender = sender.MacSender(desktop=self.desktop, clipboard=FakeClipboard(), is_local=lambda host: False)- self.sender.update_config(make_config())- self.sender._sock = object()- self.sender._connected_at = time.monotonic()- self.sender._last_ack_at = time.monotonic()-- def tearDown(self):- self.sender._sock = None+ self.rig = Rig(cursor=(0, 500))+ self.sender = self.rig.sender+ self.sender.set_redirecting(True)+ self.rig.accept_take()- def _drain_keys(self):- keys = []- while not self.sender._outbound.empty():- message = self.sender._outbound.get_nowait()- if message.get("type") in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP):- keys.append(message)- return keys+ def keys(self):+ return [m["type"] for m in self.rig.sent(B) if m["type"] in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP)]def test_key_released_after_switch_back_is_dropped(self):- self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)-sent_down = self.sender.on_key("a", True)self.assertTrue(sent_down, "the key-down while redirecting should have been forwarded")@@ -64,11 +31,10 @@ class KeyUpAfterSwitchBackTest(unittest.TestCase):sent_up = self.sender.on_key("a", False)- keys = self._drain_keys()self.assertEqual(- [k["type"] for k in keys],+ self.keys(),[protocol.MSG_KEYDOWN, protocol.MSG_KEYUP],- "a key-down forwarded to the Mac owes it the matching key-up, "+ "a key-down forwarded to the peer owes it the matching key-up, ""even after redirecting has already been switched back off",)self.assertTrue(@@ -77,32 +43,20 @@ class KeyUpAfterSwitchBackTest(unittest.TestCase):)def test_a_held_keys_autorepeat_at_home_is_swallowed_until_its_release(self):- self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)self.sender.on_key("a", True)self.sender.set_redirecting(False)- self.assertTrue(self.sender.on_key("a", True), "an autorepeat of a key the Mac holds")+ self.assertTrue(self.sender.on_key("a", True), "an autorepeat of a key the peer holds")self.assertTrue(self.sender.on_key("a", False), "the release Windows never saw the down for")self.assertFalse(self.sender.on_key("a", True), "a fresh press is Windows' own again")- def test_a_release_still_queued_when_input_comes_home_is_sent(self):- sent = []- self.sender._send_raw = lambda message: sent.append(message) or True-- def drain():- while not self.sender._outbound.empty():- self.sender._process_outbound(self.sender._outbound.get_nowait())-- self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)+ def test_a_release_still_queued_when_input_comes_home_is_sent_once(self):self.sender.on_key("a", True)- drain()- # The release is queued but not yet sent when input comes home.+ self.rig.flush()+ # The release is queued but not yet sent when input comes home: the owner must not add a+ # second one of its own.self.sender.on_key("a", False)self.sender.set_redirecting(False)- drain()- self.assertEqual(- [m["type"] for m in sent if m["type"] in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP)],- [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP],- )+ self.assertEqual(self.keys(), [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP])if __name__ == "__main__":diff --git a/win_app/tests/test_link_set.py b/win_app/tests/test_link_set.pynew file mode 100644index 0000000..b10ee2c--- /dev/null+++ b/win_app/tests/test_link_set.py@@ -0,0 +1,151 @@+"""LinkSet keeps one link per paired entry; a removed machine's link must not hold the window's thread."""++import os+import sys+import unittest+from types import SimpleNamespace++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import sender+from core import protocol++TOKEN = protocol.id_text(bytes(range(32)))+++class FakeLink:+ stops = []+ peer_id = ""++ def __init__(self, token, book, identity, **callbacks):+ self.token = token+ self.callbacks = callbacks++ def start(self):+ pass++ def stop(self, wait=True):+ FakeLink.stops.append(wait)+++class LinkSetTest(unittest.TestCase):+ def test_a_removed_machines_link_stops_without_waiting(self):+ FakeLink.stops = []+ links = sender.LinkSet(SimpleNamespace(_book=None, _identity=None, _hardware=None, _peers={}), is_local=lambda host: False, link_class=FakeLink)+ links.start()+ links.sync([{"token": TOKEN, "host": "192.0.2.10"}])+ links.sync([])+ self.assertEqual(FakeLink.stops, [False])++ def test_a_removed_machine_that_was_linked_goes_down_in_the_owner(self):+ peer = bytes(range(1, 17))+ told = []++ class Linked(FakeLink):+ peer_id = protocol.id_text(peer)++ owner = SimpleNamespace(+ _book=None, _identity=None, _hardware=None, _peers={},+ on_link=lambda who, up, accepts=False: told.append((who, up)),+ announce=lambda who: [],+ )+ links = sender.LinkSet(owner, is_local=lambda host: False, link_class=Linked)+ links.start()+ links.sync([{"token": TOKEN, "host": "192.0.2.10"}])+ link = links._links[TOKEN]+ links._up(link, {"id": peer, "accepts": True})+ told.clear()+ links.sync([])+ self.assertEqual(told, [(peer, False)])+ self.assertIsNone(links._link(peer))++ def test_a_link_that_comes_up_after_its_machine_was_removed_is_not_registered(self):+ peer = bytes(range(1, 17))+ told = []+ owner = SimpleNamespace(+ _book=None, _identity=None, _hardware=None, _peers={},+ on_link=lambda who, up, accepts=False: told.append((who, up)),+ announce=lambda who: [],+ )+ links = sender.LinkSet(owner, is_local=lambda host: False, link_class=FakeLink)+ links.start()+ links.sync([{"token": TOKEN, "host": "192.0.2.10"}])+ link = links._links[TOKEN]+ links.sync([])+ links._up(link, {"id": peer, "accepts": True})+ self.assertEqual(told, [])+ self.assertIsNone(links._link(peer))++ def test_a_machine_removed_while_it_is_being_told_up_ends_down_in_the_owner(self):+ peer = bytes(range(1, 17))+ told = []+ holder = {}++ def on_link(who, up, accepts=False):+ # The True is recorded after the removal's False, as when sync runs in the gap between+ # _up's lock and its call.+ if up and "sync" in holder:+ holder.pop("sync")()+ told.append((who, up))++ owner = SimpleNamespace(+ _book=None, _identity=None, _hardware=None, _peers={},+ on_link=on_link, announce=lambda who: [],+ )++ class Linked(FakeLink):+ peer_id = protocol.id_text(peer)++ links = sender.LinkSet(owner, is_local=lambda host: False, link_class=Linked)+ links.start()+ links.sync([{"token": TOKEN, "host": "192.0.2.10"}])+ link = links._links[TOKEN]+ holder["sync"] = lambda: links.sync([])+ links._up(link, {"id": peer, "accepts": True})+ self.assertEqual(told, [(peer, False), (peer, True), (peer, False)])+ self.assertIsNone(links._link(peer))++ def test_each_link_is_given_the_senders_hardware_hook(self):+ hook = lambda host: "aa:bb:cc:dd:ee:ff"+ made = []++ class Recording(FakeLink):+ def __init__(self, *args, **callbacks):+ super().__init__(*args, **callbacks)+ made.append(self)++ links = sender.LinkSet(SimpleNamespace(_book=None, _identity=None, _hardware=hook, _peers={}), is_local=lambda host: False, link_class=Recording)+ links.sync([{"token": TOKEN, "host": "192.0.2.10"}])+ self.assertIs(made[0].callbacks["hardware"], hook)++ def test_each_link_reads_a_large_frame_only_while_the_sender_expects_its_clipboard(self):+ made = []++ class Recording(FakeLink):+ def __init__(self, *args, **callbacks):+ super().__init__(*args, **callbacks)+ made.append(self)++ expected = []+ owner = SimpleNamespace(_book=None, _identity=None, _hardware=None, _peers={}, expects_clipboard=lambda link, began: expected.append((link, began)) or True)+ links = sender.LinkSet(owner, is_local=lambda host: False, link_class=Recording)+ links.sync([{"token": TOKEN, "host": "192.0.2.10"}])+ self.assertTrue(made[0].callbacks["large"](made[0], 5.0))+ self.assertEqual(expected, [(made[0], 5.0)])++ def test_no_hook_leaves_the_link_without_one(self):+ made = []++ class Recording(FakeLink):+ def __init__(self, *args, **callbacks):+ super().__init__(*args, **callbacks)+ made.append(self)++ links = sender.LinkSet(SimpleNamespace(_book=None, _identity=None, _hardware=None, _peers={}), is_local=lambda host: False, link_class=Recording)+ links.sync([{"token": TOKEN, "host": "192.0.2.10"}])+ self.assertNotIn("hardware", made[0].callbacks)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_links.py b/win_app/tests/test_links.pynew file mode 100644index 0000000..09c679c--- /dev/null+++ b/win_app/tests/test_links.py@@ -0,0 +1,700 @@+"""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 unittest++from links_rig import B, C, CAPS, HERE, Rig, edge_zone, make_config++import capture_win+import sender+from core import protocol+from core.return_edge import Rect+from core.tests import responder_harness as harness+++def target_of(message):+ return protocol.read_id(message["data"]["target"])+++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_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_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, ["Mac is driving another machine"])+ self.assertEqual(self.rig.redirects, [True, False])+ self.assertEqual(self.rig.arrivals, [])++ 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_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_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_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], "Cannot switch — Other could not be reached")+++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_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_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_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_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]+ self.assertEqual(message["data"], {"edge": "left", "set_at": 1790000001, "by": protocol.id_text(HERE)})++ 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 --git a/win_app/tests/test_links_loopback.py b/win_app/tests/test_links_loopback.pynew file mode 100644index 0000000..b84a575--- /dev/null+++ b/win_app/tests/test_links_loopback.py@@ -0,0 +1,116 @@+"""LinkSender over real links: this PC's input to a LinkResponder on loopback, which is what the+other machine runs, so the two halves are proved against each other rather than against a mock."""++import unittest++from links_rig import make_config++import sender+from core import protocol, receiver+from core.return_edge import Rect+from core.tests import responder_harness as harness+from core.tests.responder_harness import B, HERE, TOKENS, Machine, entry, wait_for++MONITORS = [Rect(0, 0, 1920, 1080)]+++class Loopback(unittest.TestCase):+ """This PC is machine B; machine HERE (a responder) is the peer it dials."""++ def setUp(self):+ self.far = Machine([entry(B, "Near", platform="windows")]).start()+ self.addCleanup(self.far.stop)+ peer = entry(HERE, "Far", token=TOKENS[B], host="127.0.0.1", port=self.far.port, side="left", linked=False)+ self.settings = harness.Settings([peer], [{"peer": protocol.id_text(HERE), "kind": "edge"}])+ self.settings.data["machine_id"] = protocol.id_text(B)+ self.book = receiver.PeerBook(self.settings.load, self.settings.save)+ self.desktop = harness.FakeDesktop(MONITORS, (0, 500))+ self.clipboard = harness.FakeClipboard("from near")+ self.alerts, self.arrivals, self.statuses = [], [], []+ self.sender = sender.LinkSender(+ self.book,+ lambda: {"id": B, "name": "Near", "platform": "windows", "app": "1.5.0", "caps": list(harness.CAPS), "port": 24820},+ zones=lambda: self.settings.data["zones"],+ desktop=self.desktop,+ clipboard=self.clipboard,+ is_local=lambda host: False,+ arrival_callback=lambda edge, x, y: self.arrivals.append((edge, x, y)),+ status_callback=lambda connected, detail: self.statuses.append((connected, detail)),+ )+ self.sender.on_alert = lambda title, message: self.alerts.append(message)+ self.sender.start(make_config(machine_id=protocol.id_text(B), crossing_resistance_px=40))+ self.addCleanup(self.sender.stop)+ self.assertTrue(wait_for(lambda: self.sender.connected, 5), self.sender.status)++ def take(self):+ self.assertTrue(self.sender.set_redirecting(True))+ self.assertTrue(wait_for(lambda: self.far.owners and self.far.owners[-1] == B))++ def test_the_first_link_learns_the_peers_id_and_says_so(self):+ self.assertTrue(self.settings.data["peers"][0]["linked"])+ self.assertEqual(self.sender.peers_up(), [HERE])++ def test_keys_and_the_pointer_reach_the_peers_injector_while_input_is_there(self):+ self.take()+ 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.sender.on_motion(5, -3)+ self.assertTrue(wait_for(lambda: ("move", 5, -3) in self.far.injected()))+ keys = [call for call in self.far.injected() if call[0] == "key"]+ # The peer's welcome said it is a Windows machine, so every key goes as itself.+ self.assertEqual(keys, [("key", "ctrl", True), ("key", "c", True), ("key", "c", False), ("key", "ctrl", False)])++ def test_the_clipboard_arrives_before_any_input(self):+ self.take()+ self.sender.on_key("a", True, 0x41, "a")+ self.assertTrue(wait_for(lambda: ("key", "a", True) in self.far.injected()))+ sets = [event for event in self.far.events if event[0] in ("set",)]+ self.assertEqual(sets[0], ("set", "from near"))+ self.assertLess(self.far.events.index(sets[0]), len(self.far.events))++ def test_a_push_through_the_zone_takes_the_peer_at_the_matching_edge(self):+ for _ in range(4):+ self.sender.on_motion(-20, 0)+ self.assertTrue(wait_for(lambda: self.far.arrivals))+ edge, x, _y = self.far.arrivals[-1]+ self.assertEqual((edge, x), ("right", 1919))++ def test_the_peer_sending_the_input_home_brings_it_back_here(self):+ self.take()+ self.assertTrue(self.far.responder.send_home())+ self.assertTrue(wait_for(lambda: not self.sender.redirecting))+ self.assertEqual(self.arrivals[-1][0], None)++ def test_letting_go_releases_what_was_held_on_the_peer(self):+ self.take()+ self.sender.on_key("a", True, 0x41, "a")+ self.sender.on_button("left", True)+ self.assertTrue(wait_for(lambda: ("button", "left", True) in self.far.injected()))+ self.sender.set_redirecting(False)+ self.assertTrue(wait_for(lambda: ("key", "a", False) in self.far.injected() and ("button", "left", False) in self.far.injected()))+ self.assertTrue(wait_for(lambda: self.far.owners[-1] is None))++ def test_the_link_dropping_brings_input_home_and_says_so(self):+ self.take()+ self.far.stop()+ self.assertTrue(wait_for(lambda: not self.sender.redirecting, 5))+ self.assertIn("Lost the link to Here", self.alerts)++ def test_a_peer_that_does_not_allow_driving_refuses_and_input_comes_home(self):+ self.far.settings.peer(TOKENS[B])["allow_drive"] = False+ self.far.responder.peers_changed()+ self.assertTrue(wait_for(lambda: self.alerts == [] and self.sender._accepts.get(HERE) is False))+ self.assertFalse(self.sender.set_redirecting(True))+ self.assertEqual(self.alerts, ["Cannot switch — Here does not accept input from this one"])++ def test_the_round_trip_is_measured_while_input_is_there(self):+ self.take()+ for _ in range(5):+ self.sender.on_motion(1, 0)+ self.assertTrue(wait_for(lambda: self.sender.round_trip_ms is not None, 5))+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_linux_start.py b/win_app/tests/test_linux_start.pynew file mode 100644index 0000000..842f621--- /dev/null+++ b/win_app/tests/test_linux_start.py@@ -0,0 +1,98 @@+"""The shell starts as it would on Linux: sys.platform is faked in a child process (PySide6 and the+stdlib are already loaded by then), the window is built offscreen and main() runs to a clean exit.+Nothing Windows-only may be imported, and nothing may listen. Skipped on Windows, where a faked+platform would break the stdlib; the rig proves the other half, that Windows is unchanged."""++import json+import os+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++WINDOWS_ONLY = (+ "capture_win", "desktop_win", "clipboard_win", "autostart_win", "firewall_win", "unlock_win",+ "input_injector", "touchpad_injector", "winreg", "msvcrt",+)+PORT = 24993+++def child(mode: str, config: Path) -> None:+ import socket+ import tempfile # noqa: F401 (loaded before the platform changes)++ from PySide6.QtCore import QTimer+ from PySide6.QtWidgets import QApplication++ here = Path(__file__).resolve().parent.parent+ sys.path[:0] = [str(here), str(here.parent)]+ sys.platform = "linux"++ import kvm_bridge_win+ from core.receiver import ServerState++ if mode == "window":+ app = QApplication([])+ window = kvm_bridge_win.WindowsApplication(config)+ window.start()+ assert window.windowTitle() == "Beamer"+ assert window._status is ServerState.STOPPED, window._status+ assert "not built yet" in window._status_detail, window._status_detail+ assert "not yet on Linux" in window.firewall_note.text(), window.firewall_note.text()+ assert not window.logon_switch.isEnabled()+ window.reload_config()+ assert window.server._listener is None and not window.sender.connected+ try:+ socket.create_connection(("127.0.0.1", PORT), timeout=0.5).close()+ except OSError:+ pass+ else:+ raise AssertionError("something is listening")+ window.quit()+ window.deleteLater()+ else:+ original = kvm_bridge_win.WindowsApplication.start++ def start_then_quit(self):+ original(self)+ QTimer.singleShot(200, QApplication.quit)++ kvm_bridge_win.WindowsApplication.start = start_then_quit+ sys.argv = ["beamer", "--config", str(config), "--hidden"]+ try:+ kvm_bridge_win.main()+ except SystemExit as exit_:+ assert exit_.code in (0, None), exit_.code+ loaded = [name for name in WINDOWS_ONLY if name in sys.modules]+ assert not loaded, f"Windows-only modules imported: {loaded}"+ print("ok")+++class LinuxStartTest(unittest.TestCase):+ @unittest.skipIf(sys.platform == "win32", "a faked platform breaks the Windows stdlib")+ def test_the_shell_starts_builds_its_window_and_quits_with_no_windows_module(self):+ try:+ import PySide6 # noqa: F401+ except ImportError:+ self.skipTest("needs PySide6")+ with tempfile.TemporaryDirectory() as directory:+ config = Path(directory) / "settings.json"+ (Path(directory) / "config.json").write_text(json.dumps({+ "host": "192.0.2.20", "port": PORT, "auth_token": "synthetic", "paired_with": "MacBook Pro",+ "mac_host": "192.0.2.10", "mac_return_edge": "left",+ "allow_mac_to_drive": True, "send_to_mac": True,+ }))+ env = dict(os.environ, QT_QPA_PLATFORM="offscreen", XDG_CONFIG_HOME=directory)+ env.pop("LOCALAPPDATA", None)+ for mode in ("window", "main"):+ done = subprocess.run(+ [sys.executable, str(Path(__file__).resolve()), mode, str(config)],+ env=env, capture_output=True, text=True, timeout=120,+ )+ self.assertEqual(done.returncode, 0, mode + done.stdout + done.stderr)+ self.assertIn("ok", done.stdout)+++if __name__ == "__main__":+ child(sys.argv[1], Path(sys.argv[2]))diff --git a/win_app/tests/test_pages_win.py b/win_app/tests/test_pages_win.pyindex 6170d19..2efe96d 100644--- a/win_app/tests/test_pages_win.py+++ b/win_app/tests/test_pages_win.py@@ -366,28 +366,13 @@ class CrossingPageTest(unittest.TestCase):self.reflect(self.page)self.assertEqual([buttons[p].text() for p in ("start", "middle", "end")], ["Left", "Middle", "Right"])- def test_an_edge_learned_from_the_mac_renames_the_chips(self):- import kvm_bridge_win-+ def test_an_edge_learned_from_a_peer_renames_the_chips(self):page = self.pagepage._config.crossing_methods = ["part"]page._config.mac_return_edge = "right"self.reflect(page)- page._persist = lambda: True- page._start_sending = lambda config: None- page._reflect_look = lambda: None- page._reflect_ways = lambda: self.reflect(page)- page.sender = SimpleNamespace(update_config=lambda config: None)- page.mac_host_readout = widgets.label("", "readout")- page.edge_choice = SimpleNamespace(set_value=lambda value: None)- # A hello fills only an edge the PC does not hold yet (G1).- page._config.mac_return_edge = ""- real = kvm_bridge_win.sender.is_this_machine- kvm_bridge_win.sender.is_this_machine = lambda host: False- try:- kvm_bridge_win.WindowsApplication._on_learned(page, "192.168.1.10", "top", 120)- finally:- kvm_bridge_win.sender.is_this_machine = real+ page._config.mac_return_edge = "top"+ self.reflect(page)buttons = page.part_buttonsself.assertEqual([buttons[p].text() for p in ("start", "middle", "end")], ["Left", "Middle", "Right"])self.assertIn("top edge", page.parts_note.text())@@ -410,13 +395,20 @@ class CrossingPageTest(unittest.TestCase):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, False, False, True, False, None).startswith("This PC does not drive your Mac"))self.assertTrue(line(True, True, True, False, True, False, None).startswith("Not connected to your Mac"))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.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))@@ -424,11 +416,6 @@ class CrossingPageTest(unittest.TestCase):self.assertTrue(pages_win.crossing_state_blocked(True, True, True, False))self.assertFalse(pages_win.crossing_state_blocked(True, True, True, True))- def test_the_overview_says_whether_this_pcs_own_link_is_up(self):- self.assertEqual(pages_win.outward_link_line(True), "This PC to your Mac: Linked")- self.assertEqual(pages_win.outward_link_line(False),- "This PC to your Mac: not connected, so pushing an edge does nothing")-def test_no_learned_edge_is_not_described_as_the_right_edge(self):summary = pages_win.ways_summary(["edge"], "", ["middle"], "top_right", "Right Ctrl", "double_tap")self.assertNotIn("right edge", summary)diff --git a/win_app/tests/test_pairing_window.py b/win_app/tests/test_pairing_window.pyindex 03f4bea..9e436fd 100644--- a/win_app/tests/test_pairing_window.py+++ b/win_app/tests/test_pairing_window.py@@ -1,61 +1,425 @@-"""What the PC's window says when a code ends, in the real window built offscreen as-tools/readme_shots_win.py builds it, which starts no receiver, hooks or announcer."""+"""Overview's machines and the pairing sheet in the real window, built offscreen as+the README's screenshots build it, which starts no receiver, hooks or announcer."""import jsonimport os+import socket+import sysimport tempfileimport unittestfrom pathlib import Path-import sys+from types import SimpleNamespacesys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))-from core import pairing+from core import pairing, peerlist, protocoltry:from PySide6.QtWidgets import QApplication+ import app_configimport kvm_bridge_winimport themeexcept ImportError: # PySide6 is only in the Windows venvkvm_bridge_win = None+TOKEN_A = protocol.id_text(bytes(range(32)))+TOKEN_B = protocol.id_text(bytes(range(1, 33)))+ID_A = b"\x0a" * 15 + b"\x01"+ID_B = b"\x0b" * 15 + b"\x02"+++def peer(identity, name, token, host, platform="macos", paired_at=1_780_000_000):+ return pairing.peer_entry(identity, name, platform, 24820, token, host, paired_at)+@unittest.skipIf(kvm_bridge_win is None, "needs PySide6")-class PairingOutcomeWindowTest(unittest.TestCase):+class MachinesWindowTest(unittest.TestCase):def setUp(self):os.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 = Nonedef tearDown(self):+ if self.window is not None:+ self.window.deleteLater()++ def open(self, *entries, **top):+ settings = app_config.load_settings(self.path)+ settings["peers"] = list(entries)+ 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_a_typed_token_from_1_4_x_asks_to_pair_again(self):+ (self.folder / "config.json").write_text(json.dumps({+ "host": "192.0.2.20", "port": 24820, "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)+ row = next(iter(self.window.machines.rows.values()))+ self.assertEqual(row.word.text(), "Pair again")++ 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_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": 24820, "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])++[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.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_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"))- 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_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):+ 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 --git a/win_app/tests/test_parity.py b/win_app/tests/test_parity.pyindex e734995..8922239 100644--- a/win_app/tests/test_parity.py+++ b/win_app/tests/test_parity.py@@ -12,12 +12,18 @@ sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(import app_configimport capture_win-from core import protocolfrom app_config import ConfigError, config_from_dict, config_to_dict, default_config-import sender as sender_module-import test_sender-from test_sender import MONITORS, MacSenderWithLink, make_config, wait_for-from fakes import FakeClipboard, FakeDesktop, wait_for_calls+from core.tests import responder_harness as harness+from links_rig import B, Rig, make_config+++def wait_for(predicate, timeout=5.0):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return True+ time.sleep(0.02)+ return Falsedef raw(**values):@@ -104,16 +110,11 @@ class ConfigRangeTests(unittest.TestCase):class HeldEdgeTests(unittest.TestCase):def setUp(self):- self.desktop = FakeDesktop(MONITORS, cursor=(0, 500))- self.link = MacSenderWithLink(desktop=self.desktop)- self.sender = self.link.sender-- def tearDown(self):- self.link.close()+ self.rig = Rig(cursor=(0, 500))+ self.sender = self.rig.senderdef push(self, times=10):- for _ in range(times):- self.sender.on_motion(-20, 0)+ self.rig.push(times)def test_pause_holds_the_edge_and_leaves_the_shortcut(self):self.sender.crossing_paused = True@@ -138,102 +139,101 @@ class HeldEdgeTests(unittest.TestCase):self.assertTrue(self.sender.redirecting)def test_a_drag_against_the_edge_does_not_cross(self):- self.sender.on_mouse(capture_win.WM_LBUTTONDOWN, 0, 500, 0)+ self.sender.on_button("left", True)self.push()self.assertFalse(self.sender.redirecting)- self.sender.on_mouse(capture_win.WM_LBUTTONUP, 0, 500, 0)+ self.sender.on_button("left", False)self.push()self.assertTrue(self.sender.redirecting)def test_a_button_whose_release_was_never_seen_does_not_hold_the_edge_for_ever(self):# Let go over the secure desktop: the hook never saw the release, Windows says it is up.- self.desktop.button_down = lambda name: False- self.sender.on_mouse(capture_win.WM_MBUTTONDOWN, 0, 500, 0)+ self.rig.desktop.button_down = lambda name: False+ self.sender.on_button("middle", True)self.push()self.assertTrue(self.sender.redirecting)def test_a_drag_crosses_when_the_setting_is_off(self):self.sender.update_config(make_config(block_while_dragging=False))- self.sender.on_mouse(capture_win.WM_LBUTTONDOWN, 0, 500, 0)+ self.sender.on_button("left", True)self.push()self.assertTrue(self.sender.redirecting)class AlertAndWakeTests(unittest.TestCase):def setUp(self):- self.alerts = []self.packets = []- self.sender = sender_module.MacSender(- desktop=FakeDesktop(MONITORS, cursor=(900, 500)),- clipboard=FakeClipboard(),- is_local=lambda host: False,- wake_sender=lambda mac, host: self.packets.append((mac, host)),- mac_lookup=lambda host: None,- )- self.sender.on_alert = lambda title, message: self.alerts.append(message)++ def rig(self, **fields):+ rig = Rig(entries=[harness.entry(B, "Mac", side="left", **fields)], up=())+ rig.sender._wake_sender = lambda address, host=None: self.packets.append((address, host))+ return rigdef test_a_switch_with_no_link_and_no_address_says_why(self):- self.sender.update_config(make_config())- self.assertFalse(self.sender.set_redirecting(True))- self.assertTrue(self.alerts and self.alerts[0].startswith("Cannot switch"))+ rig = self.rig()+ self.assertFalse(rig.sender.set_redirecting(True))+ self.assertTrue(rig.alerts and rig.alerts[0].startswith("Cannot switch"))self.assertEqual(self.packets, [])def test_a_switch_with_no_link_wakes_a_mac_whose_address_is_known(self):- self.sender.update_config(make_config(mac_hardware_address="02:1A:2B:3C:0D:4E"))- self.assertFalse(self.sender.set_redirecting(True))+ rig = self.rig(hw="02:1A:2B:3C:0D:4E")+ self.assertFalse(rig.sender.set_redirecting(True))self.assertTrue(wait_for(lambda: self.packets))- self.assertEqual(self.packets[0], ("02:1A:2B:3C:0D:4E", "127.0.0.1"))- self.assertTrue(wait_for(lambda: "Waking your Mac…" in self.alerts))- self.sender._stop_event.set()+ self.assertEqual(self.packets[0], ("02:1A:2B:3C:0D:4E", "192.168.77.9"))+ self.assertTrue(wait_for(lambda: "Waking Mac…" in rig.alerts))+ rig.sender._stop_event.set()def test_a_mac_that_refused_the_token_is_not_woken(self):- self.sender.update_config(make_config(mac_hardware_address="02:1A:2B:3C:0D:4E"))- self.sender._status = sender_module.AUTH_FAILED_STATUS- self.assertFalse(self.sender.set_redirecting(True))+ rig = self.rig(hw="02:1A:2B:3C:0D:4E")+ rig.links.refusing.add(B)+ rig.sender.on_status(rig.links.key_of(rig.settings.data["peers"][0]), False, "Mac refused the pairing")+ self.assertFalse(rig.sender.set_redirecting(True))self.assertEqual(self.packets, [])- self.assertTrue(self.alerts[0].endswith(sender_module.AUTH_FAILED_STATUS))+ self.assertTrue(rig.alerts[0].endswith("Mac refused the pairing"))def test_a_dead_link_sending_input_home_says_so(self):- self.sender.redirecting = True- self.sender._force_local("the link went quiet")- self.assertEqual(self.alerts, ["Input returned to this PC"])+ rig = Rig()+ rig.sender.set_redirecting(True)+ rig.accept_take()+ rig.links.up_set.discard(B)+ rig.sender.on_key("a", True, 0x41, "a")+ self.assertFalse(rig.sender.redirecting)+ self.assertEqual(rig.alerts, ["Lost the link to Mac"])++class ModifierStyleTests(unittest.TestCase):+ def setUp(self):+ self.rig = Rig()+ self.sender = self.rig.sender+ self.sender.set_redirecting(True)+ self.rig.accept_take()-class ModifierAndRoundTripTests(test_sender.LinkTests):- """Over the real loopback link to the Mac's receiver, reusing LinkTests' set-up; its own- tests are proved in test_sender and not run twice."""+ def keys(self):+ return [(m["type"], m["data"]["key"]) for m in self.rig.sent(B) if m["type"] in ("keydown", "keyup")]def test_positional_sends_ctrl_as_control(self):- self.sender.update_config(make_config(port=self.port, modifier_style="positional"))- self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)+ self.sender.update_config(make_config(modifier_style="positional"))+ self.sender.on_key("cmd", True)+ self.assertEqual(self.keys(), [("keydown", "ctrl")])++ # LinkSender._key_message applies the style when the outbound worker delivers a key, and+ # `_keys_down` holds only the physical name, so a release after a style change leaves under+ # the new style's name: the Mac gets ctrl down and cmd up. The press goes out within+ # milliseconds, hence the flush between the two calls.+ def test_the_style_changing_while_a_key_is_held_still_releases_it_under_its_press_name(self):+ self.sender.update_config(make_config(modifier_style="positional"))self.sender.on_key("cmd", True)- # The style changes while the key is held: its release still matches its press.- self.sender.update_config(make_config(port=self.port))+ self.rig.flush()+ self.sender.update_config(make_config())self.sender.on_key("cmd", False)- wait_for_calls(self.injector.calls, 2)- self.assertEqual(self.injector.calls, [("key", ("ctrl", True)), ("key", ("ctrl", False))])+ self.assertEqual(self.keys(), [("keydown", "ctrl"), ("keyup", "ctrl")])def test_shift_let_go_first_still_releases_the_capital(self):- self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)self.sender.on_key("A", True, 0x41)self.sender.on_key("a", False, 0x41)- wait_for_calls(self.injector.calls, 2)- self.assertEqual(self.injector.calls, [("key", ("A", True)), ("key", ("A", False))])+ self.assertEqual(self.keys(), [("keydown", "A"), ("keyup", "A")])self.assertEqual(self.sender._keys_down, {})- def test_the_round_trip_is_measured_while_input_is_on_the_mac(self):- self.assertIsNone(self.sender.round_trip_ms)- self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)- for _ in range(5):- self.sender.on_motion(3, 0)- time.sleep(0.05)- self.assertTrue(wait_for(lambda: self.sender.round_trip_ms is not None), "no round trip measured")- self.assertGreaterEqual(self.sender.round_trip_ms, 0)---for _name in [n for n in dir(test_sender.LinkTests) if n.startswith("test_")]:- setattr(ModifierAndRoundTripTests, _name, None)-if __name__ == "__main__":unittest.main()diff --git a/win_app/tests/test_peers_view.py b/win_app/tests/test_peers_view.pynew file mode 100644index 0000000..0baedaf--- /dev/null+++ b/win_app/tests/test_peers_view.py@@ -0,0 +1,101 @@+"""What each machine's row on Overview says, from what the link layer knows of it. Pure."""++import os+import sys+import unittest++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import peers_view+from core import protocol++GOOD = protocol.id_text(bytes(range(32)))+PEER_ID = protocol.id_text(b"\x01" * 16)+++def entry(**fields):+ base = {"id": PEER_ID, "name": "Studio Mac", "platform": "macos", "token": GOOD, "host": "192.168.77.5",+ "port": 24820, "send": True, "allow_drive": True, "linked": True}+ base.update(fields)+ return base+++def state(peer=None, **link):+ args = dict(up=False, driving=False, input_there=False, kind="failed", status="", waking=False)+ args.update(link)+ return peers_view.describe(peer or entry(), "Studio Mac", **args)+++class DescribeTest(unittest.TestCase):+ def test_a_peer_whose_input_is_on_this_pc_is_driving_it(self):+ found = state(up=True, driving=True)+ self.assertEqual((found.word, found.tone), ("Driving this PC", "signal"))+ self.assertIn("Studio Mac", found.detail)++ def test_the_machine_holding_this_pcs_input_says_input_is_there(self):+ found = state(up=True, input_there=True)+ self.assertEqual((found.word, found.tone), ("Input here", "signal"))+ self.assertIn("Studio Mac", found.detail)++ def test_a_live_link_is_linked(self):+ self.assertEqual(state(up=True).word, "Linked")++ def test_a_link_still_looking_is_waiting_and_a_wake_is_named(self):+ self.assertEqual(state(kind="connected", status="Connecting").word, "Waiting")+ self.assertEqual(state().word, "Waiting")+ self.assertEqual(state(waking=True).detail, "Waking Studio Mac…")+ self.assertEqual(state(waking=True).word, "Waiting")++ def test_each_fault_kind_has_its_word_and_the_links_own_sentence(self):+ cases = {+ "unauthenticated": "Refused", "wrong_id": "Refused", "different": "Refused", "unreadable": "Refused",+ "older": "Version", "newer": "Version", "not_beamer": "Version",+ "unreachable": "Unreachable", "timeout": "Unreachable",+ "refused": "Not listening",+ "stopped": "Dropped", "closed": "Dropped", "failed": "Dropped",+ }+ for kind, word in cases.items():+ found = state(kind=kind, status=f"sentence for {kind}")+ self.assertEqual(found.word, word, kind)+ self.assertEqual(found.tone, "fault", kind)+ self.assertIn(f"sentence for {kind}", found.detail)++ def test_a_peer_that_closed_before_it_ever_linked_is_a_version_problem(self):+ found = state(entry(linked=False), kind="closed",+ status="Update Beamer on Studio Mac to 1.5.0; if it is up to date, pair the two again")+ self.assertEqual(found.word, "Version")++ def test_a_typed_token_is_asked_to_pair_again(self):+ found = state(entry(token="typed by hand"))+ self.assertEqual((found.word, found.tone), ("Pair again", "amber"))+ self.assertIn("pair", found.detail)++ def test_sending_off_with_no_link_waits_for_the_other_end(self):+ found = state(entry(send=False))+ self.assertEqual(found.word, "Waiting")+ self.assertIn("connect", found.detail)++ def test_a_removed_or_stopped_link_is_not_a_fault(self):+ self.assertEqual(state(kind="removed").word, "Waiting")+ self.assertEqual(state(kind="off").word, "Waiting")++ def test_a_fault_with_no_sentence_still_says_something(self):+ self.assertTrue(state(kind="refused").detail)+++class FactsTest(unittest.TestCase):+ def test_platform_names(self):+ for platform, name in (("macos", "Mac"), ("windows", "Windows"), ("linux", "Linux"), ("ios", "iPhone"),+ ("android", "Android"), ("", "Other"), ("beos", "Other")):+ self.assertEqual(peers_view.platform_name({"platform": platform}), name)++ def test_the_address_line_is_the_address_and_port_and_hides_on_request(self):+ self.assertEqual(peers_view.address_line(entry(), False), "192.168.77.5 · port 24820")+ self.assertNotIn("192.168.77.5", peers_view.address_line(entry(), True))+ self.assertEqual(peers_view.address_line(entry(host="", port=0), False), "No address")+ self.assertEqual(peers_view.address_line(entry(host=""), False), "No address")+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_qr_code.py b/win_app/tests/test_qr_code.pynew file mode 100644index 0000000..2d9381f--- /dev/null+++ b/win_app/tests/test_qr_code.py@@ -0,0 +1,32 @@+import os+import sys+import unittest++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import qr_code+from core import pairing++[email protected](qr_code.segno is None, "needs segno")+class QrCodeTest(unittest.TestCase):+ TEXT = pairing.qr_text("192.168.77.5", 24821, "123456", bytes(range(16)))++ def test_the_grid_is_square_with_a_quiet_zone_and_the_three_finder_corners(self):+ rows = qr_code.modules(self.TEXT)+ size = len(rows)+ self.assertTrue(all(len(row) == size for row in rows))+ self.assertFalse(any(any(row) for row in rows[: qr_code.QUIET]))+ self.assertFalse(any(any(row[: qr_code.QUIET]) for row in rows))+ top, left, right = qr_code.QUIET, qr_code.QUIET, size - qr_code.QUIET - 7+ for row_at, column_at in ((top, left), (top, right), (size - qr_code.QUIET - 7, left)):+ self.assertTrue(all(rows[row_at][column_at + step] for step in range(7)))+ self.assertTrue(all(rows[row_at + 6][column_at + step] for step in range(7)))++ def test_the_text_of_a_real_code_fits_a_small_symbol(self):+ self.assertLessEqual(len(qr_code.modules(self.TEXT)), 37 + 2 * qr_code.QUIET + 8)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_receiver.py b/win_app/tests/test_receiver.pydeleted file mode 100644index 955d5e5..0000000--- a/win_app/tests/test_receiver.py+++ /dev/null@@ -1,1246 +0,0 @@-import socket-import threading-import time-import unittest-from unittest import mock-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--import input_injector-from core import protocol-from core import receiver-from app_config import Config-from core.receiver import ReceiverServer, ServerState, handle_message--from core.return_edge import Rect-from fakes import FakeClipboard, FakeDesktop, FakeInjector, connected_socket_pair, wait_for_calls, wait_for_status---FAKE_PNG = protocol.PNG_SIGNATURE + b"\x00" * 64---def make_config(port=0, token="shared-token"):- return Config(host="127.0.0.1", port=port, auth_token=token)---class ReceiverHandshakeTests(unittest.TestCase):- def _serve(self, client_token="shared-token"):- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))- client, connection, address = connected_socket_pair(token=client_token)- stop_event = threading.Event()- # _session_thread, not _handle_client: it closes the socket when the- # handler returns, which is what a rejected client actually sees.- thread = threading.Thread(- target=server._session_thread,- args=(connection, address, make_config(), stop_event),- )- thread.start()- self.addCleanup(connection.close)- self.addCleanup(thread.join, 1)- self.addCleanup(stop_event.set)- self.addCleanup(client.close)- return statuses, client, thread-- def test_hello_receives_welcome_and_reports_connected(self):- statuses, client, thread = self._serve()- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- # The welcome is sent before the status callback fires on the- # session thread, so poll rather than assert immediately.- _, detail = wait_for_status(statuses, ServerState.CONNECTED)- self.assertEqual(detail, "Connected to 127.0.0.1")-- def test_wrong_token_is_closed_without_a_reply(self):- statuses, client, thread = self._serve(client_token="not-the-token")- client.send(protocol.hello_msg())- client.settimeout(2.0)- with self.assertRaises(protocol.ConnectionClosed):- client.recv()- thread.join(timeout=1)- self.assertFalse(thread.is_alive())- self.assertNotIn(ServerState.CONNECTED, [state for state, _ in statuses])-- def test_replayed_frame_drops_the_connection(self):- statuses, client, thread = self._serve()- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- frame = client.session.seal(protocol.ping_msg())- client.sock.sendall(frame)- client.sock.sendall(frame)- client.settimeout(2.0)- with self.assertRaises(protocol.ConnectionClosed):- while True:- client.recv()- thread.join(timeout=1)- self.assertFalse(thread.is_alive())-- def test_hello_without_version_is_rejected_with_welcome_error(self):- statuses, client, thread = self._serve()- client.send({"type": protocol.MSG_HELLO, "data": {}})- reply = client.recv()- self.assertEqual(reply["type"], protocol.MSG_WELCOME)- self.assertEqual(reply["data"].get("error"), "version_mismatch")- thread.join(timeout=1)- self.assertFalse(thread.is_alive())- self.assertNotIn(ServerState.CONNECTED, [state for state, _ in statuses])- self.assertIn(- (ServerState.ERROR, "Mac app is an older Beamer version — update both apps"),- statuses,- )-- def test_unsupported_version_is_rejected_with_welcome_error(self):- statuses, client, thread = self._serve()- client.send({"type": protocol.MSG_HELLO, "data": {"version": 1}})- self.assertEqual(client.recv(), protocol.welcome_msg(error="version_mismatch"))- self.assertNotIn(ServerState.CONNECTED, [state for state, _ in statuses])-- def test_pre_v4_client_gets_a_cleartext_version_mismatch(self):- # A v3 Mac opens with a length-prefixed cleartext hello, no preamble.- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))- listener = socket.socket()- listener.bind(("127.0.0.1", 0))- listener.listen(1)- raw = socket.create_connection(listener.getsockname())- connection, address = listener.accept()- listener.close()- stop_event = threading.Event()- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- raw.sendall(protocol.legacy_frame({"type": protocol.MSG_HELLO, "data": {"token": "shared-token", "version": 3}}))- raw.settimeout(2.0)- expected = protocol.legacy_frame(protocol.welcome_msg(error="version_mismatch"))- got = b""- while len(got) < len(expected):- chunk = raw.recv(4096)- if not chunk:- break- got += chunk- self.assertEqual(got, expected)- thread.join(timeout=1)- self.assertFalse(thread.is_alive())- self.assertIn(- (ServerState.ERROR, "Mac app is an older Beamer version — update both apps"),- statuses,- )- finally:- raw.close()- stop_event.set()- thread.join(timeout=1)- connection.close()-- def test_other_wire_version_is_answered_with_our_preamble_and_closed(self):- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))- listener = socket.socket()- listener.bind(("127.0.0.1", 0))- listener.listen(1)- raw = socket.create_connection(listener.getsockname())- connection, address = listener.accept()- listener.close()- stop_event = threading.Event()- thread = threading.Thread(- target=server._session_thread,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- raw.sendall(protocol.WIRE_MAGIC + bytes([protocol.PROTOCOL_VERSION + 1]) + b"\x01" * protocol.NONCE_PREFIX_SIZE)- raw.settimeout(2.0)- got = raw.recv(protocol.PREAMBLE_SIZE)- self.assertEqual(got[: len(protocol.WIRE_MAGIC) + 1], protocol.WIRE_MAGIC + bytes([protocol.PROTOCOL_VERSION]))- self.assertEqual(raw.recv(4096), b"")- thread.join(timeout=1)- self.assertFalse(thread.is_alive())- self.assertIn(- (ServerState.ERROR, f"Mac app is Beamer protocol v{protocol.PROTOCOL_VERSION + 1}, this PC is v{protocol.PROTOCOL_VERSION} — update both apps"),- statuses,- )- finally:- raw.close()- stop_event.set()- thread.join(timeout=1)- connection.close()---class ReceiverPreemptionTests(unittest.TestCase):- # This test used to shorten SESSION_READ_TIMEOUT_SECONDS to 0.3s for the- # whole test, on the theory that a short read timeout is the- # deterministic backstop bounding how long a preempted session can take- # to notice it was superseded. Two separate timing problems made that- # ~1-in-8 flaky, both now fixed below:- #- # 1. That backstop starts counting down from the moment A authenticates,- # independent of anything B does. On a slow/loaded run, A's *own*- # silence could trip the shortened timeout before B ever finished- # connecting, making the server legitimately (but spuriously, for this- # test's purposes) report WAITING before the handover even started.- # Fixed by resetting A's idle clock at a point the test controls,- # immediately before connecting B: a `ping` is a real message, so- # receiving it makes thread_a's blocked recv() return and loop back- # into a fresh recv() call with a fresh timeout window, decoupling the- # deadline from whatever setup work (A's own authentication,- # wait_for_status, ...) came before it.- #- # 2. Closing a socket from a different thread than the one blocked in- # recv() on it doesn't reliably interrupt that recv() on macOS --- # confirmed empirically (a throwaway probe: ~20-40% of trials left the- # blocked thread stuck until its full configured read timeout- # elapsed, unmoved by another thread's shutdown()+close() of the same- # fd). So thread_a's own recv() may not notice the server's- # preemption-driven close of connection_a promptly, and nothing the- # test can do from the client side afterwards wakes a recv() already- # blocked on an fd the server has *already fully closed* -- there is- # no live socket left to deliver anything to. thread_a's own- # (shortened) read timeout is the only way it reliably exits in that- # unlucky case, which means the test's own wait for thread_a to join- # can itself take up to that same short timeout. B's *own* idle- # detection must not have a chance to fire for real during that wait- # -- it would legitimately (B really has gone quiet) but spuriously- # (for this test) report WAITING too. Fixed by giving B, once- # connected, a read timeout far larger than anything this test could- # take: B's own liveness detection isn't what's under test here, only- # that its status doesn't flap while A is being torn down.- _READ_TIMEOUT_SECONDS = 0.4- _B_READ_TIMEOUT_SECONDS = 30.0-- def test_new_authenticated_client_preempts_the_previous_one_without_flapping_status(self):- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))- config = make_config()- stop_event = threading.Event()-- with mock.patch.object(receiver, "SESSION_READ_TIMEOUT_SECONDS", self._READ_TIMEOUT_SECONDS):- client_a, connection_a, address_a = connected_socket_pair()- thread_a = threading.Thread(- target=server._handle_client,- args=(connection_a, address_a, config, stop_event),- )- thread_a.start()- client_a.send(protocol.hello_msg())- self.assertEqual(client_a.recv(), protocol.welcome_msg())- wait_for_status(statuses, ServerState.CONNECTED)-- client_b = connection_b = thread_b = None- try:- # Reset A's idle clock right here, at a moment the test controls,- # so its (still short, unpatched-again-below) read timeout races- # only the setup immediately following (fast, local, and- # bounded) rather than everything before it.- with mock.patch.object(receiver, "SESSION_READ_TIMEOUT_SECONDS", self._READ_TIMEOUT_SECONDS):- client_a.send(protocol.ping_msg())-- # B gets a generously long read timeout (see the class docstring)- # so its own idle detection can't fire for real while the test- # waits out thread_a's worst case below. Kept in effect for the- # rest of the test, since thread_b reads this constant once, the- # first time it calls connection.settimeout(...).- with mock.patch.object(receiver, "SESSION_READ_TIMEOUT_SECONDS", self._B_READ_TIMEOUT_SECONDS):- client_b, connection_b, address_b = connected_socket_pair()- thread_b = threading.Thread(- target=server._handle_client,- args=(connection_b, address_b, config, stop_event),- )- thread_b.start()- client_b.send(protocol.hello_msg())- self.assertEqual(client_b.recv(), protocol.welcome_msg())-- # A must be severed once B takes over. This is a real,- # server-initiated shutdown()+close() of connection_a, which- # reliably delivers a FIN to client_a's end of an actual TCP- # connection -- unlike interrupting thread_a's own blocked- # recv() from another thread (see the class docstring above),- # a peer-visible EOF over an actual socket is a genuine- # incoming network event, not a same-process fd-close- # notification, so it isn't subject to that race.- client_a.settimeout(2.0)- self.assertEqual(client_a.sock.recv(4096), b"")-- # thread_a must actually exit. Sized with headroom over the- # patched read timeout: the common case is a prompt close,- # but the worst case is thread_a's own recv() falling back to- # the (freshly-reset, still short) timeout above.- thread_a.join(timeout=self._READ_TIMEOUT_SECONDS + 2.0)- self.assertFalse(thread_a.is_alive())-- # ...and B must be reported CONNECTED without status ever- # having dropped to WAITING in between (a stale session must- # not be able to flap the UI while a reconnect takes over).- wait_for_status(statuses, ServerState.CONNECTED)- self.assertNotIn(ServerState.WAITING, [state for state, _ in statuses])- finally:- # Close the test's own client sockets first: that's a real- # network-level close, so the peer's blocked recv() unblocks- # promptly. Only close the server-side sockets afterwards,- # once their handler threads have already joined -- closing- # them earlier would race the same thread that's blocked in- # recv() on them.- client_a.close()- if client_b is not None:- client_b.close()- stop_event.set()- thread_a.join(timeout=1.0)- if thread_b is not None:- thread_b.join(timeout=1.0)- connection_a.close()- if connection_b is not None:- connection_b.close()---class ReceiverReadTimeoutTests(unittest.TestCase):- def test_silent_authenticated_client_is_declared_dead_after_the_read_timeout(self):- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- with mock.patch.object(receiver, "SESSION_READ_TIMEOUT_SECONDS", 0.2):- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- wait_for_status(statuses, ServerState.CONNECTED)- # Say nothing further. A dead/half-open peer must be detected- # from the (now short) read timeout alone -- no TCP-level- # close required.- wait_for_status(statuses, ServerState.WAITING, timeout=2.0)- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()- self.assertFalse(thread.is_alive())---class ReceiverPingTests(unittest.TestCase):- def test_ping_is_never_recorded_or_specially_acked(self):- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- client.send(protocol.ping_msg())- client.send(protocol.ping_msg())- # A ping never bumps the processed sequence, so every ack the- # client observes afterwards -- whether the periodic heartbeat or- # one for a genuine event -- must still read seq 0.- client.settimeout(1.0)- self.assertEqual(client.recv(), protocol.ack_msg(0))- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()---class HandleMessageInjectorTests(unittest.TestCase):- def test_keydown_is_routed_to_the_injector(self):- injector = FakeInjector()- processed = handle_message(- {"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}}, injector=injector- )- self.assertTrue(processed)- self.assertEqual(injector.calls, [("key", ("a", True))])-- def test_gesture_is_routed_to_the_injector_by_name(self):- injector = FakeInjector()- processed = handle_message(protocol.gesture_msg("swipe_up"), injector=injector)- self.assertTrue(processed)- self.assertEqual(injector.calls, [("gesture", ("swipe_up",))])-- def test_unknown_type_is_ignored(self):- injector = FakeInjector()- processed = handle_message({"type": "bogus", "data": {}}, injector=injector)- self.assertFalse(processed)- self.assertEqual(injector.calls, [])-- def test_scroll_passes_dx_and_mode_through_to_the_injector(self):- injector = FakeInjector()- processed = handle_message(- {"type": protocol.MSG_SCROLL, "data": {"dy": 12.5, "dx": -3.25, "mode": "pixel"}},- injector=injector,- )- self.assertTrue(processed)- self.assertEqual(injector.calls, [("scroll", (12.5, -3.25, "pixel"))])-- def test_scroll_defaults_dx_and_mode_when_omitted(self):- # Backward tolerance: an older sender (or a plain line-mode wheel- # click) may omit dx/mode entirely.- injector = FakeInjector()- processed = handle_message(- {"type": protocol.MSG_SCROLL, "data": {"dy": 1}}, injector=injector- )- self.assertTrue(processed)- self.assertEqual(injector.calls, [("scroll", (1, 0, "line"))])---class ReceiverAckTests(unittest.TestCase):- def test_a_burst_of_events_is_acked_once_promptly(self):- # Input is acked as soon as it lands, batched by ACK_COALESCE_SECONDS:- # a per-event ACK would roughly double packet count at ~100Hz mouse- # rates, but the old fixed 400ms timer put up to 400ms of pure waiting- # into the round trip the Mac measures and reports.- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(- receiver, "ACK_COALESCE_SECONDS", 0.2- ), mock.patch.object(input_injector, "inject_mouse_move"):- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- for _ in range(3):- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 1, "dy": 1}}- )- # Well inside the parked idle heartbeat, so an ACK arriving at- # all proves the burst itself woke the thread.- client.settimeout(1.0)- ack = client.recv()- self.assertEqual(ack["type"], protocol.MSG_ACK)- # seq 3 in the FIRST ACK is the coalescing: all three events- # were covered by one reply rather than one ACK each. Asserting- # on a second ACK not arriving would be a test of thread- # scheduling, so it is deliberately not asserted here.- self.assertEqual(ack["data"]["seq"], 3)- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()-- def test_an_idle_link_still_gets_a_heartbeat_ack(self):- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 0.05):- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- client.settimeout(1.0)- ack = client.recv()- self.assertEqual(ack["type"], protocol.MSG_ACK)- self.assertEqual(ack["data"]["seq"], 0)- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()---class ReceiverClipboardTests(unittest.TestCase):- def test_focus_mac_replies_with_the_local_clipboard_text(self):- statuses = []- clipboard = FakeClipboard(text="hello from windows")- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- client.send(protocol.focus_msg("mac"))- client.settimeout(1.0)- self.assertEqual(client.recv(), protocol.clipboard_msg("hello from windows"))- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()-- def test_focus_windows_is_a_reserved_noop(self):- statuses = []- clipboard = FakeClipboard(text="must not be sent")- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0):- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- client.send(protocol.focus_msg("windows"))- client.settimeout(0.3)- with self.assertRaises((socket.timeout, TimeoutError)):- client.recv()- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()-- def test_focus_mac_with_empty_clipboard_sends_no_reply(self):- statuses = []- clipboard = FakeClipboard(text="")- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0):- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- client.send(protocol.focus_msg("mac"))- client.settimeout(0.3)- with self.assertRaises((socket.timeout, TimeoutError)):- client.recv()- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()-- def test_focus_mac_with_oversized_clipboard_sends_no_reply(self):- statuses = []- clipboard = FakeClipboard(text="z" * (protocol.CLIPBOARD_MAX_BYTES + 1))- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0):- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- client.send(protocol.focus_msg("mac"))- client.settimeout(0.3)- with self.assertRaises((socket.timeout, TimeoutError)):- client.recv()- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()-- def test_inbound_clipboard_sets_the_windows_clipboard(self):- statuses = []- clipboard = FakeClipboard()- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- client.send(protocol.clipboard_msg("copied on the Mac"))- wait_for_calls(clipboard.set_calls, minimum=1)- self.assertEqual(clipboard.set_calls, [("copied on the Mac", None)])- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()-- def test_inbound_clipboard_ignores_oversized_payload(self):- statuses = []- clipboard = FakeClipboard()- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- oversized = "y" * (protocol.CLIPBOARD_MAX_BYTES + 1)- client.send(protocol.clipboard_msg(oversized))- # Follow up with a normal clipboard message and wait for that one- # instead of sleeping blind: if the oversized one had been- # applied, set_calls would already be non-empty by this point.- client.send(protocol.clipboard_msg("ok"))- wait_for_calls(clipboard.set_calls, minimum=1)- self.assertEqual(clipboard.set_calls, [("ok", None)])- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()-- def test_focus_mac_replies_with_text_and_image(self):- statuses = []- clipboard = FakeClipboard(text="shot.png", image=FAKE_PNG)- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- client.send(protocol.focus_msg("mac"))- client.settimeout(1.0)- self.assertEqual(client.recv(), protocol.clipboard_msg("shot.png", FAKE_PNG))- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()-- def test_focus_mac_drops_an_oversized_image_but_sends_the_text(self):- statuses = []- big = protocol.PNG_SIGNATURE + b"\x00" * protocol.CLIPBOARD_IMAGE_MAX_BYTES- clipboard = FakeClipboard(text="shot.png", image=big)- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- client.send(protocol.focus_msg("mac"))- client.settimeout(1.0)- self.assertEqual(client.recv(), protocol.clipboard_msg("shot.png"))- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()-- def test_inbound_clipboard_sets_text_and_image_and_ignores_a_malformed_image(self):- statuses = []- clipboard = FakeClipboard()- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- client.send({"type": protocol.MSG_CLIPBOARD, "data": {"text": "bad", "image": "not base64!", "image_format": "png"}})- client.send(protocol.clipboard_msg("shot.png", FAKE_PNG))- wait_for_calls(clipboard.set_calls, minimum=2)- self.assertEqual(clipboard.set_calls, [("bad", None), ("shot.png", FAKE_PNG)])- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()-- def test_focus_and_clipboard_do_not_bump_the_processed_sequence(self):- # Mirrors ReceiverPingTests.test_ping_is_never_recorded_or_specially_acked:- # control messages must not be recorded, and must not trigger their- # own immediate ack -- only the periodic ack timer's seq 0 shows up.- statuses = []- clipboard = FakeClipboard(text="")- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- try:- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- client.send(protocol.focus_msg("windows"))- client.send(protocol.clipboard_msg("from the mac"))- client.settimeout(1.0)- self.assertEqual(client.recv(), protocol.ack_msg(0))- finally:- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()---class ReceiverCrossingTests(unittest.TestCase):- """The way home, end to end on the wire: a focus that names the return- edge arms it and places the pointer; pushing through it sends switch."""-- MONITORS = [Rect(0, 0, 2560, 1440), Rect(-1920, 200, 1920, 1080)]-- def _session(self, desktop, pressures=None, arrivals=None):- statuses = []- server = ReceiverServer(- lambda state, detail: statuses.append((state, detail)),- clipboard=FakeClipboard(text=""),- desktop=desktop,- pressure_callback=None if pressures is None else (lambda *args: pressures.append(args)),- arrival_callback=None if arrivals is None else (lambda *args: arrivals.append(args)),- )- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- return server, client, connection, stop_event, thread-- @staticmethod- def _teardown(client, connection, stop_event, thread):- client.close()- stop_event.set()- thread.join(timeout=1.0)- connection.close()-- @staticmethod- def _focus_windows(**extra):- return {"type": protocol.MSG_FOCUS, "data": {"target": "windows", **extra}}-- def test_arrival_places_the_pointer_and_arms_the_return_edge(self):- desktop = FakeDesktop(self.MONITORS, cursor=(500, 500))- server, client, connection, stop_event, thread = self._session(desktop)- try:- client.send(self._focus_windows(edge="left", offset=0.5, return_edge="left", resistance_px=100))- wait_for_calls(desktop.set_calls, minimum=1)- self.assertEqual(desktop.set_calls, [(-1920, 720)])- self.assertEqual(server.return_edge, "left")- finally:- self._teardown(client, connection, stop_event, thread)-- def test_arrival_callback_gets_the_edge_and_where_the_pointer_landed(self):- desktop = FakeDesktop(self.MONITORS, cursor=(500, 500))- arrivals = []- server, client, connection, stop_event, thread = self._session(desktop, arrivals=arrivals)- try:- client.send(self._focus_windows(edge="left", offset=0.5, return_edge="left", resistance_px=100))- wait_for_calls(arrivals, minimum=1)- self.assertEqual(arrivals, [("left", -1920, 720)])- finally:- self._teardown(client, connection, stop_event, thread)-- def test_shortcut_switch_arms_without_moving_the_pointer(self):- desktop = FakeDesktop(self.MONITORS, cursor=(500, 500))- arrivals = []- server, client, connection, stop_event, thread = self._session(desktop, arrivals=arrivals)- try:- client.send(self._focus_windows(return_edge="top", resistance_px=120))- client.send(protocol.ping_msg())- client.settimeout(1.0)- self.assertEqual(client.recv(), protocol.ack_msg(0))- self.assertEqual(desktop.set_calls, [])- # A switch, reported with no edge and wherever the pointer was left, to show where it is.- self.assertEqual(arrivals, [(None, 500, 500)])- self.assertEqual(server.return_edge, "top")- finally:- self._teardown(client, connection, stop_event, thread)-- def test_pushing_through_the_return_edge_sends_switch_to_the_mac(self):- desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 720))- pressures = []- with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(- input_injector, "inject_mouse_move"- ) as inject:- server, client, connection, stop_event, thread = self._session(desktop, pressures)- try:- client.send(self._focus_windows(return_edge="left", resistance_px=100))- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 3}})- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})- client.settimeout(1.0)- self.assertEqual(client.recv(), protocol.switch_msg("mac", "right", 723 / 1440))- # Held at the edge first (clamped, lateral movement kept), then- # crossed; neither move reached SendInput.- self.assertEqual(desktop.set_calls, [(-1920, 723)])- inject.assert_not_called()- # The receiver sends the switch before it reports the breakthrough pressure, so- # the second entry can land after recv() returns: this was flaky without the wait.- wait_for_calls(pressures, minimum=2)- self.assertEqual([entry[0] for entry in pressures], ["left", "left"])- self.assertAlmostEqual(pressures[0][1], 0.6)- self.assertEqual(pressures[1][1:], (1.0, True, None))- # Disarmed after the crossing: the next move injects normally.- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})- wait_for_calls(inject.call_args_list, minimum=1)- inject.assert_called_once_with(-60, 0)- finally:- self._teardown(client, connection, stop_event, thread)-- def test_pause_on_this_machine_holds_the_way_home_too(self):- desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 720))- with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(- input_injector, "inject_mouse_move"- ) as inject:- server, client, connection, stop_event, thread = self._session(desktop)- server.edges_held = lambda: True- try:- client.send(self._focus_windows(return_edge="left", resistance_px=100))- for _ in range(4):- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})- wait_for_calls(inject.call_args_list, minimum=4)- # Every push went through as an ordinary move; nothing was held or sent home.- self.assertEqual(desktop.set_calls, [])- self.assertTrue(server._return_edge.armed)- finally:- self._teardown(client, connection, stop_event, thread)-- def test_the_way_home_follows_this_machines_own_thirds(self):- # This PC has Part of the edge with only the top third: a push lower down is a wall.- desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 1100))- pressures = []- with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(- input_injector, "inject_mouse_move"- ) as inject:- server, client, connection, stop_event, thread = self._session(desktop, pressures)- server.return_model = lambda edge, resistance: receiver.crossing.PartEdge(edge, ("start",), resistance)- try:- client.send(self._focus_windows(return_edge="left", resistance_px=100))- for _ in range(3):- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})- wait_for_calls(inject.call_args_list, minimum=3)- self.assertEqual(pressures, [])- desktop.cursor = (-1920, 300)- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})- client.settimeout(1.0)- self.assertEqual(client.recv()["type"], protocol.MSG_SWITCH)- wait_for_calls(pressures, minimum=1)- self.assertEqual(pressures[0][3], "start")- finally:- self._teardown(client, connection, stop_event, thread)-- def test_a_crossing_setting_changed_mid_visit_applies_at_once(self):- # Toby, 28-09-2026: a change to Part of the edge applied only after crossing out and back.- desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 1100))- settings = {"parts": ("start",)}- with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(- input_injector, "inject_mouse_move"- ) as inject:- server, client, connection, stop_event, thread = self._session(desktop, [])- server.return_model = lambda edge, resistance: receiver.crossing.PartEdge(edge, settings["parts"], resistance)- # Both apps pass one; it is what records that the peer is driving.- server._focus_callback = lambda target: None- try:- client.send(self._focus_windows(return_edge="left", resistance_px=100))- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})- wait_for_calls(inject.call_args_list, minimum=1)- self.assertEqual(server._return_edge.parts, frozenset({"start"}))- settings["parts"] = ("end",)- server.rearm_return()- self.assertEqual(server._return_edge.parts, frozenset({"end"}))- self.assertEqual((server.return_edge, server.return_resistance), ("left", 100))- finally:- self._teardown(client, connection, stop_event, thread)-- def test_rearming_does_nothing_once_input_has_gone_home(self):- server = receiver.ReceiverServer(lambda *args: None)- server.return_model = lambda edge, resistance: receiver.crossing.ReturnEdge(edge, resistance)- server.rearm_return()- self.assertIsNone(server._return_edge)-- def test_rearming_never_revives_a_way_home_that_was_handed_back(self):- # Codex on 74e8e96: send_home drops the way home while the peer still counts as driving,- # until its focus arrives; a settings save in between must not arm it again.- server = receiver.ReceiverServer(lambda *args: None, focus_callback=lambda target: None)- server.return_model = lambda edge, resistance: receiver.crossing.ReturnEdge(edge, resistance)- server._notify_focus(server._self_target)- server._arm_return({"return_edge": "left", "resistance_px": 100})- server._drop_return()- server.rearm_return()- self.assertIsNone(server._return_edge)-- def test_rearming_never_revives_a_way_home_already_pushed_through(self):- desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 300))- with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(input_injector, "inject_mouse_move"):- server, client, connection, stop_event, thread = self._session(desktop, [])- server.return_model = lambda edge, resistance: receiver.crossing.ReturnEdge(edge, resistance)- server._focus_callback = lambda target: None- try:- client.send(self._focus_windows(return_edge="left", resistance_px=100))- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})- client.settimeout(1.0)- self.assertEqual(client.recv()["type"], protocol.MSG_SWITCH)- server.rearm_return()- self.assertFalse(server._return_edge is not None and server._return_edge.armed)- finally:- self._teardown(client, connection, stop_event, thread)-- def test_no_way_home_by_the_pointer_when_this_machine_has_none(self):- desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 720))- with mock.patch.object(input_injector, "inject_mouse_move") as inject:- server, client, connection, stop_event, thread = self._session(desktop)- server.return_model = lambda edge, resistance: None- try:- client.send(self._focus_windows(return_edge="left", resistance_px=100))- for _ in range(4):- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})- wait_for_calls(inject.call_args_list, minimum=4)- self.assertIsNone(server.return_edge)- self.assertEqual(desktop.set_calls, [])- finally:- self._teardown(client, connection, stop_event, thread)-- def test_moves_inject_normally_when_no_return_edge_is_armed(self):- desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 720))- with mock.patch.object(input_injector, "inject_mouse_move") as inject:- server, client, connection, stop_event, thread = self._session(desktop)- try:- client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})- wait_for_calls(inject.call_args_list, minimum=1)- self.assertEqual(desktop.set_calls, [])- finally:- self._teardown(client, connection, stop_event, thread)---class ReceiverHandBackTests(unittest.TestCase):- """The peer's input is here and the link that brought it ends. The peer- fails open on its own side, but the focus saying so dies with the socket,- so the receiver raises it: otherwise this machine keeps treating the peer- as driving and its own edge and shortcut stay dead."""-- def _session(self, focuses, unlock=None):- server = ReceiverServer(- lambda state, detail: None,- clipboard=FakeClipboard(text=""),- desktop=FakeDesktop([Rect(0, 0, 1920, 1080)], cursor=(500, 500)),- focus_callback=focuses.append,- unlock=unlock,- )- client, connection, address = connected_socket_pair()- stop_event = threading.Event()- thread = threading.Thread(- target=server._handle_client,- args=(connection, address, make_config(), stop_event),- )- thread.start()- client.send(protocol.hello_msg())- self.assertEqual(client.recv(), protocol.welcome_msg())- return server, client, connection, thread-- @staticmethod- def _focus(target, **extra):- return {"type": protocol.MSG_FOCUS, "data": {"target": target, **extra}}-- def test_a_peer_that_drops_while_driving_hands_input_back(self):- focuses = []- server, client, connection, thread = self._session(focuses)- try:- client.send(self._focus("windows", return_edge="left", resistance_px=100))- wait_for_calls(focuses, minimum=1)- self.assertEqual(server.return_edge, "left")- client.close()- thread.join(timeout=2.0)- self.assertEqual(focuses, ["windows", "mac"])- self.assertIsNone(server.return_edge)- finally:- connection.close()-- def test_send_home_while_driving_sends_the_peer_its_input(self):- # The escape that does not depend on the return edge: without it, the- # PC's mouse stayed on the Mac after a push through the edge never fired.- focuses = []- server, client, connection, thread = self._session(focuses)- try:- client.send(self._focus("windows", return_edge="left", resistance_px=100))- wait_for_calls(focuses, minimum=1)- self.assertTrue(server.send_home())- client.settimeout(1.0)- self.assertEqual(client.recv(), protocol.switch_msg("mac"))- self.assertIsNone(server.return_edge)- finally:- client.close()- thread.join(timeout=2.0)- connection.close()-- def _next_switch(self, client, seconds):- # Pings keep the session inside its read timeout, as the Mac's would.- client.settimeout(0.2)- deadline = time.monotonic() + seconds- while time.monotonic() < deadline:- client.send(protocol.ping_msg())- try:- message = client.recv()- except socket.timeout:- continue- except OSError:- return None- if message.get("type") == protocol.MSG_SWITCH:- return message- return None-- def test_a_pc_that_locks_while_the_peer_drives_sends_its_input_home(self):- # Issue #5, 30-09-2026: Windows locked while the Mac drove it, and the Mac's pointer was- # stuck on the lock screen, where Beamer cannot inject or watch the return edge, until- # the PC was unlocked by hand.- class Lock:- locked = False-- def is_locked(self):- return self.locked-- def ensure_unlocked(self):- return False-- lock = Lock()- focuses = []- server, client, connection, thread = self._session(focuses, unlock=lock)- try:- client.send(self._focus("windows", return_edge="left", resistance_px=100))- wait_for_calls(focuses, minimum=1)- self.assertIsNone(self._next_switch(client, 0.8))- lock.locked = True- self.assertEqual(self._next_switch(client, 3.0), protocol.switch_msg("mac"))- finally:- client.close()- thread.join(timeout=2.0)- connection.close()-- def test_switching_to_a_locked_pc_that_cannot_unlock_sends_the_input_straight_back(self):- # The same trap from the other side: with no unlock provider, a switch to a PC already on- # its lock screen pointed the Mac's input at nothing.- class Locked:- def is_locked(self):- return True-- def ensure_unlocked(self):- return False-- focuses = []- server, client, connection, thread = self._session(focuses, unlock=Locked())- try:- client.send(self._focus("windows", return_edge="left", resistance_px=100))- wait_for_calls(focuses, minimum=1)- self.assertEqual(self._next_switch(client, 3.0), protocol.switch_msg("mac"))- finally:- client.close()- thread.join(timeout=2.0)- connection.close()-- def test_a_slow_arrival_on_a_locked_pc_still_gets_its_unlock(self):- # The lock check runs on the ACK thread. When the arrival itself took a second, it saw a- # locked PC with the peer driving and sent the input home before the unlock was asked for.- class Unlockable:- locked = True- asked = 0-- def is_locked(self):- return self.locked-- def ensure_unlocked(self):- self.asked += 1- self.locked = False- return True-- class SlowOwner(list):- def append(self, target):- if target == "windows":- time.sleep(1.4)- super().append(target)-- lock = Unlockable()- focuses = SlowOwner()- server, client, connection, thread = self._session(focuses, unlock=lock)- try:- client.send(self._focus("windows", return_edge="left", resistance_px=100))- self.assertIsNone(self._next_switch(client, 3.0))- self.assertEqual(lock.asked, 1)- self.assertEqual(focuses, ["windows"])- finally:- client.close()- thread.join(timeout=2.0)- connection.close()-- def test_send_home_with_input_already_home_does_nothing(self):- focuses = []- server, client, connection, thread = self._session(focuses)- try:- self.assertFalse(server.send_home())- finally:- client.close()- thread.join(timeout=2.0)- connection.close()-- def test_a_peer_that_drops_with_input_at_home_says_nothing_more(self):- focuses = []- server, client, connection, thread = self._session(focuses)- try:- client.send(self._focus("windows"))- client.send(self._focus("mac"))- wait_for_calls(focuses, minimum=2)- client.close()- thread.join(timeout=2.0)- self.assertEqual(focuses, ["windows", "mac"])- finally:- connection.close()-- def test_stopping_the_listener_while_driving_hands_input_back(self):- focuses = []- server, client, connection, thread = self._session(focuses)- try:- client.send(self._focus("windows", return_edge="left", resistance_px=100))- wait_for_calls(focuses, minimum=1)- server.stop()- self.assertEqual(focuses, ["windows", "mac"])- self.assertIsNone(server.return_edge)- client.close()- thread.join(timeout=2.0)- # The session's own end finds nothing left to hand back.- self.assertEqual(focuses, ["windows", "mac"])- finally:- connection.close()-- def test_a_peer_that_reconnects_while_driving_starts_with_input_at_home(self):- focuses = []- server, client, connection, thread = self._session(focuses)- try:- client.send(self._focus("windows"))- wait_for_calls(focuses, minimum=1)- # A second session authenticates before the first has noticed- # anything: the preempt closes the first, and either way the- # peer's input is at home the moment it is back.- second_client, second_connection, second_address = connected_socket_pair()- second_thread = threading.Thread(- target=server._handle_client,- args=(second_connection, second_address, make_config(), threading.Event()),- )- second_thread.start()- second_client.send(protocol.hello_msg())- self.assertEqual(second_client.recv(), protocol.welcome_msg())- wait_for_calls(focuses, minimum=2)- self.assertEqual(focuses, ["windows", "mac"])- second_client.close()- second_thread.join(timeout=2.0)- self.assertEqual(focuses, ["windows", "mac"])- second_connection.close()- client.close()- thread.join(timeout=2.0)- finally:- connection.close()---class ReceiverBindTests(unittest.TestCase):- def test_a_held_port_is_waited_out_rather_than_ending_the_listener(self):- # WinNAT's dynamic reservations move on every reboot and have landed on- # Beamer's port, which used to kill the server thread for the whole run.- holder = socket.socket()- # The receiver listens on 0.0.0.0, and SO_REUSEADDR only collides with- # a holder on the same address, so 127.0.0.1 here would bind happily.- holder.bind(("0.0.0.0", 0))- holder.listen(1)- port = holder.getsockname()[1]- self.addCleanup(holder.close)-- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))- self.addCleanup(server.stop)- with mock.patch.object(receiver, "BIND_RETRY_SECONDS", 0.05):- server.start(make_config(port=port))- _, detail = wait_for_status(statuses, ServerState.ERROR, timeout=2.0)- self.assertIn(f"port {port}", detail)- self.assertIn("Connection page", detail)- holder.close()- deadline = time.monotonic() + 3.0- waiting = (ServerState.WAITING, f"Waiting on port {port}")- while waiting not in statuses and time.monotonic() < deadline:- time.sleep(0.01)- self.assertIn(waiting, statuses)-- def test_a_reuseaddr_zombie_still_blocks_the_new_bind(self):- # A held port is normally a third-party program (the test above) or a- # WinNAT reservation, but it can also be a zombie copy of Beamer- # itself, whose listener was opened by this same _bind() and so also- # carries SO_REUSEADDR. If Windows' SO_REUSEADDR let a second- # SO_REUSEADDR socket steal a listening one, this is the scenario- # where it would happen — the "held port" detection would never fire- # and the two zombies would silently split inbound connections.- holder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- holder.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)- holder.bind(("0.0.0.0", 0))- holder.listen(1)- port = holder.getsockname()[1]- self.addCleanup(holder.close)-- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))- self.addCleanup(server.stop)- with mock.patch.object(receiver, "BIND_RETRY_SECONDS", 0.05):- server.start(make_config(port=port))- _, detail = wait_for_status(statuses, ServerState.ERROR, timeout=2.0)- self.assertIn(f"port {port}", detail)----class InputScaleTests(unittest.TestCase):- def test_a_slower_pointer_carries_its_fractions(self):- scale = receiver.InputScale(pointer=0.5)- moves = [scale.move(1, 1) for _ in range(4)]- self.assertEqual(moves, [(0, 0), (1, 1), (0, 0), (1, 1)])-- def test_a_faster_pointer_multiplies(self):- self.assertEqual(receiver.InputScale(pointer=2.0).move(3, -4), (6, -8))-- def test_speeds_are_held_to_their_range(self):- scale = receiver.InputScale(pointer=99, scroll=0)- self.assertEqual((scale.pointer, scale.scroll), (4.0, 0.25))-- def test_scroll_speed_and_reverse(self):- self.assertEqual(receiver.InputScale(scroll=2.0).wheel(3, 1), (6.0, 2.0))- self.assertEqual(receiver.InputScale(reverse=True).wheel(3, -1), (-3.0, 1.0))- self.assertEqual(receiver.InputScale().wheel(3, 1), (3, 1))-- def test_handle_message_applies_the_scale_and_drops_a_move_that_rounds_to_nothing(self):- injector = FakeInjector()- scale = receiver.InputScale(pointer=0.5)- handle_message({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 1, "dy": 0}}, injector, scale)- handle_message({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 1, "dy": 0}}, injector, scale)- handle_message({"type": protocol.MSG_SCROLL, "data": {"dy": 2, "dx": 0}}, injector, receiver.InputScale(reverse=True))- self.assertEqual(injector.calls, [("mouse_move", (1, 0)), ("scroll", (-2.0, -0.0, "line"))])---if __name__ == "__main__":- unittest.main()diff --git a/win_app/tests/test_replay.py b/win_app/tests/test_replay.pyindex ebc2dd4..a3b832e 100644--- a/win_app/tests/test_replay.py+++ b/win_app/tests/test_replay.py@@ -6,23 +6,23 @@ initiator bytes in order: the preamble, the hello and every input frame after itreplay inside a connection was always refused; this is the whole stream again, into a freshresponder, and it must fail the tag rather than type what was recorded."""+import functoolsimport socketimport timeimport unittest-import os-import sys-sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+from links_rig import make_config+import senderfrom core import protocolfrom core import receiver-import sender-from app_config import Config-from fakes import FakeClipboard, FakeDesktop, FakeInjector, wait_for_calls+from core.link import OutboundLinkfrom core.return_edge import Rect-from test_sender import NoUnlock, free_port, make_config, wait_for+from core.tests import responder_harness as harness+from core.tests.responder_harness import B, HERE, TOKENS, Machine, entry, wait_forMONITORS = [Rect(0, 0, 1920, 1080)]+PREAMBLE = protocol.LINK_PREAMBLE_SIZEclass Recording:@@ -60,14 +60,14 @@ def replay(port, data):# The responder's preamble is read before the frames go: on Windows a socket closed with# bytes still unread resets the connection, and the reset throws away whatever this end# had not read yet, so sending everything at once lost the preamble about a run in five.- attacker.sendall(data[:protocol.PREAMBLE_SIZE])- while len(reply) < protocol.PREAMBLE_SIZE:- chunk = attacker.recv(protocol.PREAMBLE_SIZE - len(reply))+ attacker.sendall(data[:PREAMBLE])+ while len(reply) < PREAMBLE:+ chunk = attacker.recv(PREAMBLE - len(reply))if not chunk:return bytes(reply)reply += chunktry:- attacker.sendall(data[protocol.PREAMBLE_SIZE:])+ attacker.sendall(data[PREAMBLE:])attacker.shutdown(socket.SHUT_WR)except (ConnectionResetError, ConnectionAbortedError):return bytes(reply)@@ -83,50 +83,46 @@ def replay(port, data):class WholeConnectionReplayTests(unittest.TestCase):- def test_the_pcs_recorded_keystrokes_replayed_into_the_mac_are_refused(self):- injector = FakeInjector()- server = receiver.ReceiverServer(- status_callback=lambda state, detail: None,- clipboard=FakeClipboard(),- unlock=NoUnlock(),- desktop=FakeDesktop(MONITORS, cursor=(900, 500)),- injector=injector,- self_name="Mac",- peer_name="PC",- self_target="mac",- peer_target="windows",- )- port = free_port()- server.start(Config(host="127.0.0.1", port=port, auth_token="shared-token"))- self.addCleanup(server.stop)+ def test_the_pcs_recorded_keystrokes_replayed_into_the_peer_are_refused(self):+ far = Machine([entry(B, "Near", platform="windows")]).start()+ self.addCleanup(far.stop)recordings = []- def connect(address, timeout):+ def connect(address, timeout=None):recordings.append(Recording(socket.create_connection(address, timeout)))return recordings[-1]- link = sender.MacSender(- desktop=FakeDesktop(MONITORS, cursor=(0, 500)),- clipboard=FakeClipboard(),+ peer = entry(HERE, "Far", token=TOKENS[B], host="127.0.0.1", port=far.port, side="left")+ settings = harness.Settings([peer], [{"peer": protocol.id_text(HERE), "kind": "edge"}])+ link = sender.LinkSender(+ receiver.PeerBook(settings.load, settings.save),+ lambda: {"id": B, "name": "Near", "platform": "windows", "app": "1.5.0", "caps": list(harness.CAPS), "port": 24820},+ zones=lambda: settings.data["zones"],+ desktop=harness.FakeDesktop(MONITORS, (0, 500)),+ clipboard=harness.FakeClipboard(),is_local=lambda host: False,- socket_factory=connect,+ links=lambda owner: sender.LinkSet(+ owner, lambda host: False, functools.partial(OutboundLink, socket_factory=connect)+ ),)- link.start(make_config(port=port))- self.assertTrue(wait_for(lambda: link.connected), f"never connected: {link.status}")- link.set_redirecting(True, arrival_edge="right", offset=0.5)- link.on_key("a", True)- link.on_key("a", False)- wait_for_calls(injector.calls, 2)+ link.start(make_config(machine_id=protocol.id_text(B)))+ self.addCleanup(link.stop)+ self.assertTrue(wait_for(lambda: link.connected, 5), f"never connected: {link.status}")+ link.set_redirecting(True)+ self.assertTrue(wait_for(lambda: far.owners and far.owners[-1] == B))+ link.on_key("a", True, 0x41, "a")+ link.on_key("a", False, 0x41, "a")+ self.assertTrue(wait_for(lambda: len([call for call in far.injected() if call[0] == "key"]) == 2))+ typed = [call for call in far.injected() if call[0] == "key"]link.stop()- typed = [call for call in injector.calls if call[0] == "key"]- self.assertEqual(typed, [("key", ("a", True)), ("key", ("a", False))])+ self.assertEqual(typed, [("key", "a", True), ("key", "a", False)])self.assertEqual(len(recordings), 1)- reply = replay(port, recordings[0].sent)+ reply = replay(far.port, recordings[0].sent)time.sleep(0.2)- self.assertEqual([call for call in injector.calls if call[0] == "key"], typed, "replayed keys reached the Mac")- self.assertEqual(len(reply), protocol.PREAMBLE_SIZE, "the Mac answered past its preamble")+ self.assertEqual([call for call in far.injected() if call[0] == "key"], typed, "replayed keys reached the peer")+ self.assertEqual(len(reply), PREAMBLE, "the peer answered past its preamble")if __name__ == "__main__":diff --git a/win_app/tests/test_same_on_both.py b/win_app/tests/test_same_on_both.pyindex a34ac1d..2b16a51 100644--- a/win_app/tests/test_same_on_both.py+++ b/win_app/tests/test_same_on_both.py@@ -15,18 +15,21 @@ try:import pages_winfrom core import settings_syncimport theme+ import app_configfrom app_config import load_config+ from core import protocol+ from core.tests import responder_harness as harnessexcept ImportError: # PySide6 is only in the Windows venvkvm_bridge_win = None-def mac_message(on, set_at, **values):- base = dict(methods=["corner"], edge_parts=["start"], corner="top_right", resistance_px=60,+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)+ return settings_sync.message_data(on, set_at, base, by=by or protocol.id_text(harness.B))@unittest.skipIf(kvm_bridge_win is None, "needs PySide6")@@ -35,15 +38,17 @@ class SameOnBothTest(unittest.TestCase):os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")self.app = QApplication.instance() or QApplication([])theme.init_fonts()- self.path = Path(tempfile.mkdtemp()) / "config.json"- self.path.write_text(json.dumps({+ folder = Path(tempfile.mkdtemp())+ self.path = folder / "settings.json"+ (folder / "config.json").write_text(json.dumps({"host": "192.168.1.20", "port": 24820, "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.window.sender.send_settings = lambda data: self.sent.append(("pc-to-mac", data)) or True- self.window.server.send_settings = lambda data: self.sent.append(("mac-to-pc", data)) or True+ 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 Trueself.window._refresh_window()def tearDown(self):@@ -54,12 +59,10 @@ class SameOnBothTest(unittest.TestCase):self.assertEqual(self.window.scope_labels["design"].text(), pages_win.SCOPE["design"])def test_the_macs_settings_arrive_on_this_pcs_fields_and_controls(self):- self.window._on_settings(mac_message(True, 100))+ self.window._on_settings(protocol.id_text(harness.B), mac_message(True, 100))config = self.window._configself.assertTrue(config.same_on_both)- self.assertEqual((config.crossing_methods, config.crossing_edge_parts), (["corner"], ["start"]))- # The Mac is on this PC's left, so its top right is this PC's top left.- self.assertEqual(config.crossing_corner, "top_left")+ 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)@@ -69,21 +72,32 @@ class SameOnBothTest(unittest.TestCase):self.window._refresh_window()self.assertTrue(self.window.same_switch.isChecked())self.assertEqual(self.window.scope_labels["crossing"].text(),- "Kept the same as your Mac. Change it on either machine.")- # Applying what arrived is not a change made here, so nothing is sent back.- self.assertEqual(self.sent, [])+ "Kept the same as MacBook Pro. Change it on any 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(mac_message(True, 100))- self.window._on_settings(mac_message(True, 90, glow_style="glow"))+ 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_turning_it_on_here_sends_this_pcs_values_on_both_links(self):+ 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([link for link, _data in self.sent], ["pc-to-mac", "mac-to-pc"])+ 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.assertEqual(data["crossing"]["corner"], "top_right")+ 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)@@ -97,18 +111,44 @@ class SameOnBothTest(unittest.TestCase):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_sent_as_it_arrived(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(self.sent, [(harness.C, message)])+def test_a_change_here_while_off_goes_nowhere(self):self.window._config.effect_length = "short"self.window._persist()self.assertEqual(self.sent, [])- def test_announcing_carries_a_chosen_arrangement_but_not_a_learned_one(self):- self.assertEqual([m["type"] for m in self.window._announce()], ["settings"])- self.window._config.arrangement_set_at = 500- messages = self.window._announce()- self.assertEqual(messages[0], {"type": "arrangement", "data": {"mac_edge": "right", "set_at": 500}})+ 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)+ app_config.write_settings(self.path, settings)+ self.peers = {harness.B: {"settings"}}+ self.assertEqual([m["type"] for m in self.window._announce(harness.B)], ["paired", "settings"])+ 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__":diff --git a/win_app/tests/test_sender.py b/win_app/tests/test_sender.pydeleted file mode 100644index 7f417ef..0000000--- a/win_app/tests/test_sender.py+++ /dev/null@@ -1,464 +0,0 @@-"""The Windows-to-Mac direction, driven over a real loopback socket against-the same receiver.py the Mac runs, so the two halves are proved against each-other rather than against a mock of each other."""--import socket-import threading-import time-import unittest-import os-import sys--sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))--import capture_win-from core import protocol-from core import receiver-import sender-from app_config import Config-from fakes import FakeClipboard, FakeDesktop, FakeInjector, wait_for_calls-from core.return_edge import Rect--MONITORS = [Rect(0, 0, 1920, 1080)]---def make_config(**overrides):- values = dict(- host="127.0.0.1",- port=0,- auth_token="shared-token",- mac_host="127.0.0.1",- mac_return_edge="left",- mac_resistance_px=40,- crossing_resistance_px=40,- )- values.update(overrides)- return Config(**values)---class EdgeTests(unittest.TestCase):- """The outward crossing, with no link in the way: the model, the gate and- the pin, which is everything the hook thread does per mouse move."""-- def setUp(self):- self.desktop = FakeDesktop(MONITORS, cursor=(0, 500))- self.link = MacSenderWithLink(desktop=self.desktop)-- def tearDown(self):- self.link.close()-- def push(self, times, dx=-20):- """The hand still moving left with the cursor already stopped at the- left edge: the position never changes, which is exactly why the- movement has to come from raw input rather than from the hook."""- for _ in range(times):- self.link.sender.on_motion(dx, 0)-- def test_a_push_against_the_edge_crosses(self):- self.push(4)- self.assertTrue(self.link.sender.redirecting, "a sustained push against the left edge never crossed")-- def test_the_push_lights_the_edge_it_is_pressing(self):- # The app once built its sender with no pressure callback, so the PC's own push out to- # the Mac crossed in the dark while the same edge lit for the Mac's push home.- seen = []- self.link.sender._pressure_callback = lambda edge, pressure, crossed, part: seen.append((edge, crossed))- self.push(4)- self.assertTrue(seen, "a push against the edge reported no pressure")- self.assertTrue(all(edge == "left" for edge, _ in seen))- self.assertEqual(seen[-1][1], True)-- def test_part_of_the_edge_lights_only_the_third_it_is_pushing(self):- seen = []- self.link.sender.update_config(make_config(crossing_methods=["part"], crossing_edge_parts=["middle", "end"]))- self.link.sender._pressure_callback = lambda edge, pressure, crossed, part: seen.append((edge, part))- self.desktop.cursor = (0, 900)- self.push(4)- self.assertTrue(seen, "a push along a chosen third reported no pressure")- self.assertEqual(set(seen), {("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.- desktop = FakeDesktop([Rect(0, 200, 1920, 1080), Rect(1920, 0, 2560, 1440)], cursor=(0, 1000))- link = MacSenderWithLink(desktop=desktop)- self.addCleanup(link.close)- seen = []- link.sender.update_config(make_config(crossing_methods=["part"], crossing_edge_parts=["end"]))- link.sender._pressure_callback = lambda edge, pressure, crossed, part: seen.append(part)- for _ in range(4):- link.sender.on_motion(-20, 0)- self.assertEqual(set(seen), {"end"})-- def test_the_whole_edge_names_no_third(self):- seen = []- self.link.sender._pressure_callback = lambda edge, pressure, crossed, part: seen.append(part)- self.push(4)- self.assertEqual(set(seen), {None})-- def test_coming_home_reports_where_the_pointer_landed(self):- # The crossing effects play their arrival where the pointer is placed.- arrivals = []- self.link.sender._arrival_callback = lambda edge, x, y: arrivals.append((edge, x, y))- self.link.sender._handle_switch({"target": "windows", "edge": "left", "offset": 0.5})- self.assertEqual(arrivals, [("left",) + self.desktop.set_calls[-1]])-- def test_a_raising_arrival_callback_only_logs(self):- def boom(edge, x, y):- raise RuntimeError("effect fell over")-- self.link.sender._arrival_callback = boom- with self.assertLogs(sender.LOGGER, "ERROR"):- self.link.sender._handle_switch({"target": "windows", "edge": "left", "offset": 0.5})- self.assertTrue(self.desktop.set_calls)-- def test_a_switch_without_an_edge_while_already_home_reports_no_arrival(self):- arrivals = []- self.link.sender._arrival_callback = lambda edge, x, y: arrivals.append(edge)- self.link.sender._handle_switch({"target": "windows"})- self.assertEqual(arrivals, [])-- def _home_by(self, action):- """Input on the Mac, then brought home by `action`; what the arrival callback heard."""- arrivals = []- self.link.sender._arrival_callback = lambda edge, x, y: arrivals.append((edge, x, y))- self.link.sender.redirecting = True- action()- self.assertFalse(self.link.sender.redirecting)- return arrivals-- def test_the_shortcut_home_reports_where_the_pointer_is(self):- self.assertEqual(self._home_by(self.link.sender.toggle), [(None, 0, 500)])-- def test_the_mac_sending_input_home_by_its_switch_reports_it(self):- arrivals = self._home_by(lambda: self.link.sender._handle_switch({"target": "windows"}))- self.assertEqual(arrivals, [(None, 0, 500)])-- def test_a_crossing_home_reports_only_its_own_arrival(self):- arrivals = self._home_by(- lambda: self.link.sender._handle_switch({"target": "windows", "edge": "left", "offset": 0.5}))- self.assertEqual([edge for edge, _x, _y in arrivals], ["left"])-- def test_the_mac_taking_this_pc_over_is_not_a_switch_home(self):- self.assertEqual(self._home_by(lambda: self.link.sender.set_receiving(True)), [])-- def test_a_dropped_link_shows_nothing(self):- self.assertEqual(self._home_by(lambda: self.link.sender._force_local("The Mac stopped responding")), [])-- def test_this_pcs_own_mouse_pushing_out_while_the_mac_drives_takes_the_pointer_across(self):- # Before this, the Mac's trackpad could cross to the PC but the PC's own mouse could not- # push back out. The Mac's injected moves carry INJECTED_MARK and never reach on_motion,- # so a push here is the hand's: the Mac gets its input back and this mouse follows it across.- sent_home = []- self.link.sender.send_peer_home = lambda: sent_home.append(True) or True- self.link.sender.set_receiving(True)- self.push(4)- self.assertEqual(sent_home, [True])- self.assertTrue(self.link.sender.redirecting)-- def test_a_push_while_the_mac_drives_and_cannot_be_sent_home_stays_here(self):- self.link.sender.send_peer_home = lambda: False- self.link.sender.set_receiving(True)- self.push(10)- self.assertFalse(self.link.sender.redirecting)-- def test_the_shortcut_while_the_mac_is_driving_sends_its_input_home(self):- sent_home = []- self.link.sender.send_peer_home = lambda: sent_home.append(True) or True- self.link.sender.set_receiving(True)- self.assertTrue(self.link.sender.set_redirecting(True))- self.assertEqual(sent_home, [True])- self.assertFalse(self.link.sender.redirecting)-- def test_a_push_away_from_the_edge_never_crosses(self):- self.push(10, dx=20)- self.assertFalse(self.link.sender.redirecting)-- def test_a_pointer_off_the_edge_never_crosses(self):- self.desktop.cursor = (900, 500)- self.push(10)- self.assertFalse(self.link.sender.redirecting)-- def test_the_edge_can_be_turned_off(self):- self.link.sender.update_config(make_config(crossing_methods=["shortcut"]))- self.push(10)- self.assertFalse(self.link.sender.redirecting)- self.assertTrue(self.link.sender.shortcut_armed)-- def test_the_shortcut_can_be_turned_off_on_its_own(self):- self.link.sender.update_config(make_config(crossing_methods=["edge"]))- self.assertFalse(self.link.sender.shortcut_armed)- self.push(4)- self.assertTrue(self.link.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):- self.desktop = FakeDesktop(MONITORS, cursor=(0, 0))- self.link = MacSenderWithLink(desktop=self.desktop)- self.link.sender.update_config(- make_config(crossing_methods=["corner"], crossing_corner="top_left")- )-- def tearDown(self):- self.link.close()-- def test_a_diagonal_push_in_the_corner_crosses(self):- for _ in range(4):- self.link.sender.on_motion(-20, -20)- self.assertTrue(self.link.sender.redirecting)-- def test_the_push_names_its_corner_for_the_effects(self):- seen = []- self.link.sender._pressure_callback = lambda edge, pressure, crossed, part: seen.append((edge, part))- for _ in range(4):- self.link.sender.on_motion(-20, -20)- self.assertTrue(seen)- self.assertEqual(set(part for _edge, part in seen), {"top_left"})-- def test_a_straight_push_along_the_edge_does_not(self):- for _ in range(10):- self.link.sender.on_motion(-20, 0)- self.assertFalse(self.link.sender.redirecting)-- def test_the_same_diagonal_away_from_the_corner_does_not(self):- self.desktop.cursor = (900, 500)- for _ in range(10):- self.link.sender.on_motion(-20, -20)- self.assertFalse(self.link.sender.redirecting)---class SelfConnectionTests(unittest.TestCase):- """The one way this PC could take its own daily link down: learning its- own address as the Mac's, connecting to its own receiver with the shared- token, and having the preempt rule close the real Mac's session."""-- def test_loopback_and_this_pcs_own_addresses_are_refused(self):- self.assertTrue(sender.is_this_machine("127.0.0.1"))- self.assertTrue(sender.is_this_machine("0.0.0.0"))- self.assertTrue(sender.is_this_machine(""))- self.assertTrue(sender.is_this_machine("192.168.1.3", ["192.168.1.3"]))-- def test_the_macs_address_is_not(self):- self.assertFalse(sender.is_this_machine("192.168.1.5", ["192.168.1.3"], address_towards=lambda host: "192.168.1.3"))-- def test_this_pcs_own_real_address_is_not_missed_when_enumeration_fails(self):- # local_addresses=[] is what pairing._local_ipv4_addresses() returns- # when the hostname does not resolve; the route probe then answers,- # and for this PC's own address it answers with that address.- self.assertTrue(sender.is_this_machine("192.168.1.3", [], address_towards=lambda host: host))- self.assertFalse(sender.is_this_machine("192.168.1.5", [], address_towards=lambda host: "192.168.1.3"))-- def test_a_route_probe_that_fails_does_not_stop_the_link(self):- def refuse(host):- raise OSError("network is unreachable")-- self.assertFalse(sender.is_this_machine("192.168.1.5", [], address_towards=refuse))-- def test_a_sender_pointed_at_this_pc_never_opens_a_link(self):- attempts = []-- def refuse(address, timeout):- attempts.append(address)- raise AssertionError("the sender tried to connect to this PC")-- link = sender.MacSender(socket_factory=refuse, desktop=FakeDesktop(MONITORS))- link.update_config(make_config(mac_host="127.0.0.1", port=51820))- self.assertIsNone(link._ready_config())- self.assertEqual(attempts, [])---class LinkTests(unittest.TestCase):- def setUp(self):- self.injector = FakeInjector()- self.clipboard = FakeClipboard()- self.mac_desktop = FakeDesktop(MONITORS, cursor=(900, 500))- self.statuses = []- self.arrangements = []- self.server = receiver.ReceiverServer(- status_callback=lambda state, detail: self.statuses.append((state, detail)),- arrangement_callback=lambda edge, set_at: self.arrangements.append((edge, set_at)),- clipboard=self.clipboard,- unlock=NoUnlock(),- desktop=self.mac_desktop,- injector=self.injector,- self_name="Mac",- peer_name="PC",- self_target="mac",- peer_target="windows",- )- self.port = free_port()- self.server.start(Config(host="127.0.0.1", port=self.port, auth_token="shared-token"))- self.desktop = FakeDesktop(MONITORS, cursor=(0, 500))- # The loopback address is this PC's own, which the real guard refuses- # to connect to; here it is the Mac at the other end of the test.- self.sender = sender.MacSender(- desktop=self.desktop, clipboard=FakeClipboard("copied"), is_local=lambda host: False- )- self.sender.start(make_config(port=self.port))- self.assertTrue(wait_for(lambda: self.sender.connected), f"never connected: {self.sender.status}")-- def tearDown(self):- self.sender.stop()- self.server.stop()-- def test_keys_reach_the_mac_injector(self):- self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)- self.sender.on_key("cmd", True)- self.sender.on_key("c", True)- self.sender.on_key("c", False)- self.sender.on_key("cmd", False)- wait_for_calls(self.injector.calls, 4)- self.assertEqual(- self.injector.calls,- [- ("key", ("cmd", True)),- ("key", ("c", True)),- ("key", ("c", False)),- ("key", ("cmd", False)),- ],- )-- def test_the_switch_places_the_mac_pointer_and_arms_its_way_home(self):- self.sender.set_redirecting(True, arrival_edge="right", offset=0.25)- self.assertTrue(wait_for(lambda: self.server.return_edge == "right"))- self.assertEqual(self.mac_desktop.cursor[0], MONITORS[0].right)-- def test_nothing_is_sent_while_input_is_this_pcs(self):- self.sender.on_key("a", True)- time.sleep(0.2)- self.assertEqual(self.injector.calls, [])-- def test_the_mac_pushing_home_takes_input_back(self):- self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)- self.assertTrue(wait_for(lambda: self.server.return_edge == "right"))- # The Mac's own pointer, pushed off its right edge: the receiver- # answers with a switch, which must stop this PC sending.- self.mac_desktop.cursor = (MONITORS[0].right, 500)- for _ in range(20):- self.sender.on_motion(40, 0)- self.mac_desktop.cursor = (MONITORS[0].right, 500)- if not self.sender.redirecting:- break- self.assertTrue(wait_for(lambda: not self.sender.redirecting), "the Mac's push home was ignored")-- def test_the_arrangement_travels_to_the_mac(self):- self.sender.send_arrangement("right", 1758100000)- wait_for_calls(self.arrangements, 1)- self.assertEqual(self.arrangements[0], ("right", 1758100000))-- def test_the_arrangement_travels_back_from_the_mac(self):- heard = []- self.sender._arrangement_callback = lambda edge, set_at: heard.append((edge, set_at))- self.assertTrue(self.server.send_arrangement("top", 1758100001))- wait_for_calls(heard, 1)- self.assertEqual(heard[0], ("top", 1758100001))-- def test_a_malformed_arrangement_does_not_take_the_link_down(self):- self.sender._send_raw({"type": protocol.MSG_ARRANGEMENT, "data": {"mac_edge": "sideways"}})- time.sleep(0.2)- self.assertEqual(self.arrangements, [])- self.assertTrue(self.sender.connected)-- def test_the_clipboard_travels_with_the_switch(self):- self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)- wait_for_calls(self.clipboard.set_calls, 1)- self.assertEqual(self.clipboard.set_calls[0][0], "copied")---class ConnectionFailedTests(unittest.TestCase):- """A deliberate stop drops the socket before the reader thread's blocked- recv() notices, so the OSError it then raises names a socket nobody owns- any more -- Windows' WinError 10038 on the off switch, reproduced here- without a real stop()."""-- def setUp(self):- self.statuses = []- self.redirected = []- self.sender = sender.MacSender(- status_callback=lambda connected, detail: self.statuses.append(detail),- redirect_callback=self.redirected.append,- )-- def test_an_error_on_an_already_dropped_socket_is_not_a_failure(self):- old_sock, peer = socket.socketpair()- self.addCleanup(old_sock.close)- self.addCleanup(peer.close)- self.sender._sock = old_sock- self.sender.redirecting = True- self.sender._sock = None # what stop()/_drop_connection() does first- self.sender._connection_failed("Receiving from the Mac failed: boom", expected_socket=old_sock)- self.assertEqual(self.statuses, [])- self.assertEqual(self.redirected, [])- self.assertTrue(self.sender.redirecting, "a stale error forced input back to this PC")-- def test_an_error_on_the_live_socket_is_still_reported(self):- sock, peer = socket.socketpair()- self.addCleanup(sock.close)- self.addCleanup(peer.close)- self.sender._sock = sock- self.sender.redirecting = True- self.sender._connection_failed("Receiving from the Mac failed: boom", expected_socket=sock)- self.assertEqual(self.statuses, ["Receiving from the Mac failed: boom"])- self.assertFalse(self.sender.redirecting)---class NoUnlock:- def is_locked(self):- return None---class MacSenderWithLink:- """A sender with no socket at all, for the edge tests: `connected` is- forced true so the gate opens, and nothing is ever sent."""-- def __init__(self, desktop):- self.sender = sender.MacSender(desktop=desktop, clipboard=FakeClipboard(), is_local=lambda host: False)- self.sender.update_config(make_config())- self.sender._sock = object()- self.sender._connected_at = time.monotonic()- self.sender._last_ack_at = time.monotonic()-- def close(self):- self.sender._sock = None---def free_port():- with socket.socket() as probe:- probe.bind(("127.0.0.1", 0))- return probe.getsockname()[1]---def wait_for(predicate, timeout=5.0):- deadline = time.monotonic() + timeout- while time.monotonic() < deadline:- if predicate():- return True- time.sleep(0.02)- return False----class LinkDropTests(unittest.TestCase):- def test_the_edge_crosses_again_after_the_link_dropped_while_redirecting(self):- desktop = FakeDesktop(MONITORS, cursor=(0, 500))- link = MacSenderWithLink(desktop=desktop)- self.addCleanup(link.close)- sender = link.sender- for _ in range(4):- sender.on_motion(-20, 0)- self.assertTrue(sender.redirecting)- sender._force_local("the link to the Mac went quiet")- sender._sock = object()- sender._connected_at = sender._last_ack_at = time.monotonic()- desktop.cursor = (0, 500)- for _ in range(6):- sender.on_motion(-20, 0)- self.assertTrue(sender.redirecting)---if __name__ == "__main__":- unittest.main()diff --git a/win_app/tests/test_settings_migration.py b/win_app/tests/test_settings_migration.pynew file mode 100644index 0000000..2116769--- /dev/null+++ b/win_app/tests/test_settings_migration.py@@ -0,0 +1,675 @@+"""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, "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_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_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)+ skipped = {"host", "mac_resistance_px"}+ 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})++ def test_a_save_writes_the_peer_and_the_zones_not_the_old_names(self):+ 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([(zone["kind"], zone.get("off", False)) for zone in settings["zones"]],+ [("edge", False), ("part", True), ("corner", True)])+ self.assertEqual(settings["zones"][2]["corner"], "bottom_left")+ self.assertEqual(settings["zones"][2]["edge"], "left")++ def test_turning_a_way_off_keeps_its_zone_and_its_setting(self):+ app_config.save_config(self.path, replace(self.config, crossing_methods=["edge"]))+ app_config.save_config(self.path, replace(self.config, crossing_methods=["part"]))+ again = app_config.load_config(self.path)+ self.assertEqual((again.crossing_methods, again.crossing_edge_parts), (["part"], ["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_changed_side_is_stamped_by_this_machine_and_an_unchanged_one_is_not(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))+ self.assertEqual(self.settings()["peers"][0]["side_by"], OTHER_ID)+ app_config.save_config(self.path, replace(self.config, mac_return_edge="top", arrangement_set_at=1790000005))+ self.assertEqual(self.settings()["peers"][0]["side_by"], 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 --git a/win_app/tests/test_stuck_modifier_on_drop.py b/win_app/tests/test_stuck_modifier_on_drop.pyindex c4e53d8..f9cc675 100644--- a/win_app/tests/test_stuck_modifier_on_drop.py+++ b/win_app/tests/test_stuck_modifier_on_drop.py@@ -5,46 +5,12 @@ import ossys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))import input_injector-from core import receiver-class FakeInjector:- def __init__(self):- self.calls = []-- def inject_key(self, name, down, us=None):- self.calls.append((name, down))-- def release_all(self):- self.calls.append(("release_all",))---class PeerKeysReleasedTests(unittest.TestCase):- """Invariant 3: anything injected for the peer is released when input- comes home or the link dies, on this PC exactly as on the Mac."""-- def _server(self, injector):- server = receiver.ReceiverServer(- status_callback=lambda *a: None,- injector=injector,- focus_callback=lambda target: None,- )- server._peer_driving = True- return server-- def test_hand_back_releases_what_the_peer_held(self):- injector = FakeInjector()- server = self._server(injector)- receiver.handle_message({"type": "keydown", "data": {"key": "ctrl"}}, injector=injector)- server._hand_back("peer went away")- self.assertIn(("release_all",), injector.calls)-- def test_input_going_home_releases_what_the_peer_held(self):- injector = FakeInjector()- server = self._server(injector)- server._clipboard = type("C", (), {"changed_contents": staticmethod(lambda: (None, None))})- server._handle_focus({"type": "focus", "data": {"target": "mac"}}, None, None, "peer", "192.168.1.5")- self.assertIn(("release_all",), injector.calls)+class WindowsInjectorReleaseTests(unittest.TestCase):+ """Anything injected for the peer is released when input comes home or the link dies; that the+ responder calls release_all then is held by core/tests (LinkResponder). This is the Windows+ injector doing it."""@unittest.skipUnless(sys.platform == "win32", "the scan-code lookup needs user32")def test_the_windows_injector_releases_keys_and_buttons(self):diff --git a/win_app/tests/test_style_for.py b/win_app/tests/test_style_for.pyindex b881757..1114e73 100644--- a/win_app/tests/test_style_for.py+++ b/win_app/tests/test_style_for.py@@ -1,5 +1,5 @@"""The Design page's Style for switch shows the tiles it names, in the real window: built offscreen-from a synthetic config as tools/readme_shots_win.py builds it, which starts no receiver, hooks or+from a synthetic config as the README's screenshots build it, which starts no receiver, hooks orannouncer."""import json@@ -23,12 +23,12 @@ class StyleForTest(unittest.TestCase):os.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({+ folder = Path(tempfile.mkdtemp())+ (folder / "config.json").write_text(json.dumps({"host": "192.168.1.20", "port": 24820, "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._select_page("design")self.window._refresh_window()diff --git a/win_app/tests/test_two_scripts.py b/win_app/tests/test_two_scripts.pyindex ea9ebe4..32ab421 100644--- a/win_app/tests/test_two_scripts.py+++ b/win_app/tests/test_two_scripts.py@@ -5,7 +5,6 @@ their place on a US keyboard (`us`), from the scan code here and the key code oncharacter the receiving layout cannot type lands on that place when a shortcut needs it or itsletter is from another script than the one typed there."""-import timeimport unittestimport osimport sys@@ -14,11 +13,8 @@ sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(import capture_winfrom core import protocol-from core import receiver-import sender-from fakes import FakeClipboard, FakeDesktopfrom input_injector import KEYEVENTF_KEYUP, KEYEVENTF_UNICODE, plan_key_inputs-from test_key_up_after_switch_back import MONITORS, make_config+from links_rig import B, RigVK_C, VK_2 = 0x43, 0x32SCANS = {VK_C: 0x2E, VK_2: 0x03}@@ -77,19 +73,6 @@ class PlaceTests(unittest.TestCase):# A phone's keyboard, or a Mac on an older Beamer, sends no place.self.assertEqual(plan("с", ENGLISH, ENGLISH_PLACES, {"cmd"}), [(0, ord("с"), KEYEVENTF_UNICODE)])- def test_the_receiver_hands_the_place_on(self):- class Injector:- def __init__(self):- self.calls = []-- def inject_key(self, name, down, us=None):- self.calls.append((name, down, us))-- injector = Injector()- receiver.handle_message({"type": protocol.MSG_KEYDOWN, "data": {"key": "с", "us": "c"}}, injector=injector)- receiver.handle_message({"type": protocol.MSG_KEYUP, "data": {"key": "с"}}, injector=injector)- self.assertEqual(injector.calls, [("с", True, "c"), ("с", False, None)])-class CaptureTests(unittest.TestCase):def test_scan_codes_name_the_us_place(self):@@ -104,23 +87,13 @@ class CaptureTests(unittest.TestCase):class SenderTests(unittest.TestCase):def setUp(self):- self.sender = sender.MacSender(desktop=FakeDesktop(MONITORS, cursor=(0, 500)), clipboard=FakeClipboard(), is_local=lambda host: False)- self.sender.update_config(make_config())- self.sender._sock = object()- self.sender._connected_at = time.monotonic()- self.sender._last_ack_at = time.monotonic()- self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)-- def tearDown(self):- self.sender._sock = None+ self.rig = Rig(cursor=(0, 500))+ self.sender = self.rig.sender+ self.sender.set_redirecting(True)+ self.rig.accept_take()def keys(self):- sent = []- while not self.sender._outbound.empty():- message = self.sender._outbound.get_nowait()- if message.get("type") in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP):- sent.append((message["type"], message["data"]))- return sent+ return [(m["type"], m["data"]) for m in self.rig.sent(B) if m["type"] in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP)]def test_a_key_carries_its_place_both_ways(self):self.sender.on_key("с", True, VK_C, "c")diff --git a/win_app/tests/test_unlock_win.py b/win_app/tests/test_unlock_win.pyindex 2580934..4d3cd23 100644--- a/win_app/tests/test_unlock_win.py+++ b/win_app/tests/test_unlock_win.py@@ -1,8 +1,9 @@"""Unlock orchestration, exercised on any platform.unlock_win talks to kernel32, so every test here passes a fake `mem32` in its-place -- the same dependency-injection trick clipboard_win.py and-handle_message use, so this suite runs on the Mac.+place -- the same dependency-injection trick clipboard_win.py uses, so this suite+runs on the Mac. What the responder does about a locked PC is held by+core/tests (LinkResponder)."""import unittest@@ -11,10 +12,7 @@ import syssys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))-from core import protocol-from core import receiverimport unlock_win-from core.receiver import ReceiverServer, ServerStateclass FakeKernel32:@@ -127,77 +125,5 @@ class EnsureUnlockedTests(unittest.TestCase):self.assertFalse(unlock_win.ensure_unlocked(fake, sleep=lambda _: None))-class FakeUnlockModule:- def __init__(self, locked, unlocks=True):- self.locked = locked- self.unlocks = unlocks- self.ensure_calls = 0-- def is_locked(self):- return self.locked-- def ensure_unlocked(self):- self.ensure_calls += 1- return self.unlocks---class ReceiverUnlockTests(unittest.TestCase):- """focus{target:"windows"} is the moment input starts arriving here, so it- is where the lock screen has to be cleared out of its way."""-- def _server(self, unlock):- statuses = []- server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), unlock=unlock)- return server, statuses-- def test_unlocked_pc_does_no_work_on_focus(self):- unlock = FakeUnlockModule(locked=False)- server, _ = self._server(unlock)- server._begin_unlock("192.168.1.5:1", "192.168.1.5")- self.assertEqual(unlock.ensure_calls, 0)- self.assertFalse(server._unlocking.is_set())-- def test_locked_pc_unlocks_and_restores_the_connected_status(self):- unlock = FakeUnlockModule(locked=True)- server, statuses = self._server(unlock)- server._begin_unlock("192.168.1.5:1", "192.168.1.5")- for _ in range(200):- if not server._unlocking.is_set():- break- import time- time.sleep(0.01)- self.assertEqual(unlock.ensure_calls, 1)- self.assertIn((ServerState.CONNECTED, "Unlocking Windows…"), statuses)- self.assertEqual(statuses[-1], (ServerState.CONNECTED, "Connected to 192.168.1.5"))-- def test_failed_unlock_says_so_rather_than_claiming_a_connection(self):- unlock = FakeUnlockModule(locked=True, unlocks=False)- server, statuses = self._server(unlock)- server._begin_unlock("192.168.1.5:1", "192.168.1.5")- for _ in range(200):- if not server._unlocking.is_set():- break- import time- time.sleep(0.01)- self.assertEqual(- statuses[-1],- (ServerState.CONNECTED, "Windows is locked — unlock it at the PC"),- )-- def test_a_session_that_ended_mid_unlock_does_not_report_a_connection(self):- """An unlock outlives a Mac that disconnects during it; the session's- own exit has already set WAITING and must not be overwritten."""- unlock = FakeUnlockModule(locked=True)- server, statuses = self._server(unlock)- server._unlock_worker(unlock, "192.168.1.5:1", "192.168.1.5", generation=-1)- self.assertEqual(statuses, [])-- def test_ack_advertises_the_unlock_only_while_it_is_running(self):- """The Mac reads this to explain the pause; it must not linger, or the- Mac shows 'Unlocking Windows…' forever."""- self.assertNotIn("locked", protocol.ack_msg(7)["data"])- self.assertIs(protocol.ack_msg(7, locked=True)["data"]["locked"], True)--if __name__ == "__main__":unittest.main()diff --git a/win_app/tests/test_way_home.py b/win_app/tests/test_way_home.pyindex 6256749..8faebcb 100644--- a/win_app/tests/test_way_home.py+++ b/win_app/tests/test_way_home.py@@ -1,33 +1,35 @@-import sysimport unittest-from types import SimpleNamespace+from core import receiver, return_edge+from core.protocol import id_text+from core.tests.responder_harness import B++PEER = id_text(B)[email protected](sys.platform == "win32", "the app module needs Windows")-class WayHomeFollowsThisPcTests(unittest.TestCase):- """The Mac's pointer comes home through this PC's edge as this PC's own settings say."""- def model(self, methods, parts=("middle",), corner="bottom_left", edge="bottom"):- import kvm_bridge_win+class WayHomeFollowsThisPcTests(unittest.TestCase):+ """A peer's pointer goes on from this PC through the zones this PC's own settings hold, the ones+ its own pointer crosses by."""- config = SimpleNamespace(crossing_methods=list(methods), crossing_edge_parts=list(parts), crossing_corner=corner)- return kvm_bridge_win.WindowsApplication._return_model(SimpleNamespace(_config=config), edge, 120)+ def arm(self, zones, side="bottom"):+ peers = [{"id": PEER, "side": side}]+ return [model for _peer, model in receiver.zone_models(zones, peers, {B}, 120)]def test_part_of_the_edge_arms_only_its_thirds(self):- from core import return_edge-- armed = self.model(["part", "shortcut"], parts=("start", "end"))- self.assertIsInstance(armed, return_edge.PartEdge)- self.assertEqual(armed.parts, frozenset({"start", "end"}))+ armed = self.arm([{"peer": PEER, "kind": "part", "parts": ["start", "end"]}])+ self.assertIsInstance(armed[0], return_edge.PartEdge)+ self.assertEqual(armed[0].parts, frozenset({"start", "end"}))- def test_a_corner_on_that_edge_and_none_elsewhere(self):- from core import return_edge+ def test_a_corner_zone_arms_the_edge_it_names(self):+ armed = self.arm([{"peer": PEER, "kind": "corner", "corner": "bottom_left", "edge": "bottom"}])+ self.assertIsInstance(armed[0], return_edge.CornerPush)+ self.assertEqual(armed[0].edge, "bottom")- self.assertIsInstance(self.model(["corner"], corner="bottom_left"), return_edge.CornerPush)- self.assertIsNone(self.model(["corner"], corner="top_left"))+ def test_the_shortcut_alone_leaves_no_way_on_by_the_pointer(self):+ self.assertEqual(self.arm([]), [])- def test_the_shortcut_alone_leaves_no_way_home_by_the_pointer(self):- self.assertIsNone(self.model(["shortcut"]))+ def test_a_zone_that_is_off_is_not_armed(self):+ self.assertEqual(self.arm([{"peer": PEER, "kind": "edge", "off": True}]), [])if __name__ == "__main__":diff --git a/win_app/theme.py b/win_app/theme.pyindex 49915e6..2c161e2 100644--- a/win_app/theme.py+++ b/win_app/theme.py@@ -110,12 +110,13 @@ def system_dark() -> bool:"""The system's own light/dark choice. AppsUseLightTheme, not the taskbar'sSystemUsesLightTheme, which Windows lets disagree with it -- this window is an app."""try:- import winreg+ if sys.platform == "win32":+ import winreg- with winreg.OpenKey(- winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"- ) as key:- return winreg.QueryValueEx(key, "AppsUseLightTheme")[0] == 0+ with winreg.OpenKey(+ winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"+ ) as key:+ return winreg.QueryValueEx(key, "AppsUseLightTheme")[0] == 0except (ImportError, OSError):passfrom PySide6.QtGui import QGuiApplication