One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.5.0-beta.4
Toby Kalkmand5376673d459
diff --git a/PAIRING.md b/PAIRING.mdindex 5cffd02..dca2004 100644--- a/PAIRING.md+++ b/PAIRING.md@@ -127,11 +127,21 @@ keeps every one.1. **A host answers one `pair_start` per code.** The first one binds the code. The samedatagram again gets the same answer (UDP retransmits). A different one gets `refused`, andthe exchange under way is left alone. Every answer would be another guess for its sender.-2. **A requester judges one `pair_answer` per share.** It takes the first `pair_answer` from- the host's address that carries its `pair` and decides on it. It never waits for a better+2. **A requester judges one `pair_answer` per share.** It takes the first `pair_answer` that+ carries its `pair` from the address it asked and decides on it. It never waits for a betterone: each answer it judged would be a guess for whoever is answering. A new attempt means a- new nonce and a new scalar. The source address only sorts the replies; it proves nothing,- and nothing may rest on it.+ new nonce and a new scalar. The source address proves nothing, but it sorts the replies: a+ host whose routing table sends the requester's network through a VPN answers from the VPN's+ address, and a stranger who read the `pair` from a beacon can send from any address. So an+ answer from elsewhere is held (the first `ok:true` one and the first refusal, no more), and+ is the one judged only when a resend's 1.5 seconds pass with nothing from the address asked,+ counting what has already arrived, an `ok:true` one before a refusal; an answer from the+ address asked beats a stranger's from anywhere else. Each side sends from its own address on+ the other's network where it has one and the routing table would pick another, so this+ fallback is for hosts older than 1.5.0-beta.4. A `pair_done` from the address asked decides+ as before. One from elsewhere decides at once if its tag checks out; an `ok:true` one whose+ tag fails is ignored, since checking it tests no guess, and a refusal is held like an+ answer.3. **A requester does not send a code again once an `ok:true` answer to it has failed.** Whoeversent that answer has had a guess at the code. The real host has by then bound the code tothat attempt or dropped it, so sending it again cannot pair; it would only buy a second@@ -170,8 +180,8 @@ keeps every one.- The requester's list of hosts holds 64. When it is full, the one heard from longest ago makesway for a new one, except a host the user asked for by address, which always stays.- The requester sends each datagram up to three times, 1.5 seconds apart, until the reply- comes. It keeps only replies from the host's address that carry its pairing id, at most 64- of them, and only while an attempt is under way.+ comes. It keeps only replies that carry its pairing id, from any address and sorted as rule 2+ says, at most 64 of them, and only while an attempt is under way.- A datagram that does not parse, a nest of brackets included, is dropped, and nothing onedatagram does ends the loop that read it.diff --git a/VERSION b/VERSIONindex 9a97bef..6dea063 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.5.0-beta.3+1.5.0-beta.4diff --git a/WIRE.md b/WIRE.mdindex c8e7ee3..b66d72f 100644--- a/WIRE.md+++ b/WIRE.md@@ -38,21 +38,30 @@ first design, what has been decided, and the questions still open.clear on a link: the preamble carries the pair's key id instead (section 2). Pairing sendsboth 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).+ encode again to themselves. That spelling proves nothing about where a token came from: 43 `A`s+ spell 32 zero bytes, and a user could have typed them. So what links is an entry made by+ pairing on 1.5.0 or later (`from_1_4` false) whose token has that spelling. A token migrated+ from 1.4.x never links, whatever its spelling, and neither does one of any other shape, a+ **typed token** (sections 1 and 2).- **Messages** are UTF-8 JSON objects of the shape `{"type": <string>, "data": <object>}`, withno 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+- **Not a message.** A frame's plaintext that is not UTF-8, not JSON, or JSON whose top level is+ not an object (`[]`, `"x"`, `1`) is not a message at all. It ends the link once the handshake+ is done (section 2, frames); as the first frame it is answered `invalid_hello` (section 2,+ step 7). Nothing below applies to it.+- **Malformed messages.** A message is malformed when it has no string `type` or no object+ `data`, holds `NaN` or an infinity, or has a known field whose value is outside what this+ document allows; section 10's shared values are the one exception, each left out on its own.+ A field that does not belong to a message, or to that kind of the message, is ignored like an+ unknown one. A sender never repeats a key; a receiver may refuse a message that does, or keep+ the last value (Swift's decoders keep the last, Android's `org.json` refuses), and neither may+ matter to what a correct sender sends. A malformed message is ignored as a whole, with threeexceptions: 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.+ 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 mustcheck the text, not the value: Swift's `JSONSerialization` gives `true` and `1.0` as numbers@@ -94,7 +103,7 @@ 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 |+| `id` | `b64` or `""` | the peer's machine id; `""` only for the entry migrated from 1.4.x || `name` | string | the peer's name, from pairing, then from every `hello` or `welcome` || `platform` | string | the peer's platform, from pairing, then from every `hello` or `welcome` || `token` | string | the shared token from pairing, never reused for another peer |@@ -109,7 +118,8 @@ A peer entry:| `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 |+| `from_1_4` | boolean | this entry was migrated from a 1.4.x pairing, and never links |+| `way_back` | boolean, optional | what the peer last said in `arrangement`'s `way_back` (section 8): whether one of its zones leads here; absent until it says |Rules:@@ -118,11 +128,12 @@ Rules:- **Two entries never share a key id** (section 2: 16 bytes computed from the token, neverstored). Pairing refuses a token whose key id is already an entry's (section 6), and there-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.+- **At most one entry has `id: ""`**, and it is the one with `from_1_4: true`. Zones for it+ name it by `""`.+- **An entry migrated from 1.4.x, or with a typed token,** is kept and shown, but never linked:+ it is not dialled, the responder never computes or matches its key id, and Overview asks the+ user to pair that machine again: "*name* was paired on Beamer 1.4. Pair the two again to link+ them on 1.5.0." A new pairing with that machine replaces it (section 6).- **Removing a peer** deletes its entry, token included, closes its links at once, and ends itsownership if it holds it (section 4). The peer is told nothing; its next link's key id isunknown here, so it is closed with nothing sent, and the peer says this machine closed the@@ -208,12 +219,16 @@ migration made them, and is not added at all when the list already holds 32), withat named the replaced entry name `""`; and `migrated_token_sha256` is updated. A token thathas not changed is never migrated twice, so a peer the user removed stays removed. A token whosekey 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.+A typed token is never refused by that check. Either way the migrated entry 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).+**Why a migrated pairing never links.** 1.4.x kept one `auth_token` and nothing about where it+came from: pairing wrote it, and so did the token field on the Mac's Connection page and the+PC's settings, and the name pairing saved beside it stayed when a user typed a new token. A+typed token can be weak, and its key id (section 2), seen on any link, lets someone test guesses+against it offline. The spelling cannot tell the two apart, so the migration keeps the entry to+show the user which machine it was, and the user pairs the two again. The entry keeps `id: ""`,+since 1.4.x never had ids. 1.5.0's first two betas let a migrated token of pairing's spelling+link and learn its peer's id; such an entry keeps that id and does not link either.## 2. The link@@ -253,9 +268,10 @@ key_id = HKDF-SHA-256(ikm = the token as saved, as text, salt = b"beamer-link-v6```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).+when it is needed and never stored. A key id is an offline test of its token, harmless for 256+random bits and fatal for a typed word, and a token's spelling cannot tell the two apart, so a+key id is only ever sent or matched for an entry this machine made by pairing on 1.5.0 or later+(section 1). Every other entry is never used for a link at all.The ephemeral share is `X25519(secret, 9)` (RFC 7748's base point), from 32 bytes of freshrandomness the side draws for this link alone and forgets once the link's keys are made.@@ -268,7 +284,11 @@ The responder:(the source IPv4 address, whatever the port). A new connection from an address that alreadyhas 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.+ and the whole handshake within **5 seconds** of the connection being accepted. Beside the+ four slots, at most **32** connections are being dealt with before they authenticate,+ counting those in a slot, those being answered and drained (step 2) and those whose slot+ was taken by a newer one but are not yet closed; a connection past the 32 is closed at+ once, with nothing read or sent.2. Reads 6 bytes.- Not `BEAMY`: a Beamer from before version 4, which opened with a cleartext frame. Itanswers with the version 5 legacy frame, a 4-byte big-endian length then the JSON@@ -281,8 +301,10 @@ The responder:Wherever it answers and closes, it frees the connection's handshake slot, shuts its sendingside, 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+ not lost to a reset. At most **8** connections drain at once; past that one is closed as+ soon as its answer is sent, without draining. A draining connection still counts against+ the 32 of step 1.+3. Reads the other 56 bytes, and looks up the entry made by pairing (section 1) whose token hasthis key id. None: it closes, sending nothing. There is never a second try with anothertoken, and no entry is looked up by anything else.4. Draws its own ephemeral secret and share, and computes the shared secret from the@@ -298,27 +320,10 @@ The responder: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 isnot 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."+8. Checks the `id` in `hello`. When it is this machine's own, or is not the entry's, it answers+ `welcome` carrying only `version` 6 and `error: "wrong_id"`, and closes. Only a holder of the+ token can read that answer, so it tells nobody else anything. Otherwise it sets `linked`, and+ saves what changed.9. Sends `welcome`, then its announcements (section 3).10. Closes any earlier link it accepted from the same peer id; a link this machine opened to thatpeer is a separate link and stays. If the closed link's peer was the owner, the ownership@@ -327,7 +332,7 @@ The responder: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.+ handshake must finish within **5 seconds**. It dials only an entry made by pairing (section 1).2. Draws its ephemeral secret and share and sends its preamble, with the entry's key id.3. Reads 6 bytes.- Not `BEAMY`: says the peer did not answer as a Beamer, and closes.@@ -356,13 +361,9 @@ The initiator:its settings change or the app starts again, and says "*name* has this pairing under anothermachine: remove it on both and pair again." Any other `error` is a `welcome` that is notvalid.-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`.+7. Checks the `id` in `welcome`: not this machine's own, and the entry's. On a failure it+ closes, sending nothing more, and says a different Beamer answered at that address. Otherwise+ it sets `linked`.8. Sends its announcements.The initiator sends `hello`, and its own id in it, before it has seen the responder's id. Both@@ -416,13 +417,16 @@ AEAD = ChaCha20-Poly1305 (RFC 8439), no associated datathan the last it accepted. The last frame a side may send carries 2^32 - 1; a sender that needsanother closes the link and reconnects.- The plaintext is one message. A frame may claim at most 16 MiB, except the first each way.+- **A frame begins** when its first length byte arrives, by a monotonic clock, and must arrive+ whole within **30 seconds** of that byte, whatever its size; one still arriving after that+ ends the link. Between its bytes the link's liveness still holds (section 3).- Only a `clipboard` is ever larger than 64 KiB of plaintext, and a receiver parses such a frameonly 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.+ it let go of no more than 10 seconds before the frame began (section 5, the clipboard). Any+ other plaintext over 64 KiB is authenticated, so its counter is spent, and dropped unparsed;+ the link stays up.+- Anything that fails (the tag, the counter, a length out of range, a frame past its 30 seconds,+ a plaintext that is not a message: Encodings) ends the link.### `hello` and `welcome`@@ -486,15 +490,6 @@ anyway drops it, and still acknowledges it when it carries a `seq`.- **The address is not authenticated.** A peer's `host` comes from pairing, a beacon, a QR, orthe source of an authenticated link. Something on the path can point a machine at the wrongaddress; 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@@ -549,8 +544,24 @@ Either way:on hardware. Any other sender, a phone included, sends what a Mac would for the samemovement. A sender always sends all three; a receiver takes amissing `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.+- **Clipboard limits**: text at most 256 KiB as UTF-8. An image at most 8 MiB before base64,+ and a PNG a receiver can decode without the file deciding how much memory that takes, checked+ from its bytes before anything decodes it:+ - the PNG signature, then an `IHDR` chunk of 13 bytes, whose width and height are each 1 to+ 16384 and whose product is at most 2^25 (33,554,432 pixels: an 8K screen is 33,177,600);+ - every chunk (4-byte big-endian length, type, data, CRC) inside the file, up to `IEND`; bytes+ after `IEND` are ignored, and CRCs are not checked;+ - a still with one header: no second `IHDR`, and none of APNG's `acTL`, `fcTL` or `fdAT`;+ - what a decoder inflates besides the pixels, the zlib streams of `iCCP`, `zTXt` and an `iTXt`+ whose compression flag is 1, at most 4 MiB inflated in all. Each stream must be one whole+ zlib stream ending where its chunk ends: one that is not zlib, is cut short or has bytes after+ its end counts as over, and so does an `iTXt` whose compression flag is neither 0 nor 1, or+ any of the three without the null bytes that end its keyword (and, in `iTXt`, its language+ and translated keyword, when it is compressed).++ A few megabytes of PNG can otherwise claim gigabytes once decoded. A sender never sends an+ image outside these limits, and a receiver drops one, without decoding it. Over any limit,+ that part is dropped and the rest of the message stands.- **Liveness.** An initiator sends `ping` when it has sent nothing for a second; a responder's`ack` heartbeat does the same the other way (section 9). A side that receives no byte at all for2.5 seconds (a responder) or 2 seconds (an initiator) ends the link. Any byte counts, so a large@@ -651,7 +662,7 @@ and both stay at home, and the next try works.|---|---|| `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 |+| `edge`, `offset` | where to land the pointer: `left`, `right`, `top` or `bottom`, and how far along that edge of the responder, any number, which the receiver clamps to 0.0 to 1.0 (never malformed for its range) || `resistance_px` | integer 0 to 1000: how far the owner's hand must push through a zone on the responder || `reach` | list of `b64`, at most 32, no repeats: the peers the owner can send input to now, less the owner and the responder || `stay` | `true`: re-arm in place; land nothing, play nothing |@@ -673,8 +684,9 @@ anything but `true`, is malformed; on a re-arm `edge` and `offset` do not belong`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.+one of `"owned"`, `"not_allowed"`, `"busy"`, `"sent_home"` and `"malformed"`. A valid `route` is+all a `refuse` needs: one whose `why` is missing, not a string, or another string is not+malformed, and the initiator acts on it at once as a refusal it cannot name.`switch`, responder to its owner only:@@ -682,7 +694,7 @@ any other `why` as a refusal it cannot name.|---|---|| `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 |+| `edge`, `offset` | where to arrive on `next`, both or neither, as in `focus` (`offset` clamped, never malformed for its range) |### The route@@ -723,11 +735,13 @@ 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.+**From the owner's own screen, from home, or by its own shortcut or menu.** A desktop's pointer+pushes through one of its zones (section 8) to peer P, or the shortcut or a menu picks P, whether+the input is at home or on another machine B. The owner raises the route. When the input is on+B, it first lets go of B: B's releases, then `focus {route, target: P}` to B. Then it sends P the+taking `focus`, then its clipboard, then input, without waiting: a refusal sends the input home,+not back to B, and whatever reached P in the meantime was dropped there. No answer within 1+second also sends it home. A phone picking a machine does the same.**Onward from the machine being driven.** While owned, a responder watches its own pointer, asversion 5's return edge did. It arms each of its own zones whose peer is the owner or is in the@@ -748,11 +762,21 @@ machine's own mouse, so a local push through a zone sends the owner onward too,- 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 leavesN 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.+ - Anything else that moves the input while it waits (a send-home from B, a lost link to B, the+ owner's own shortcut or menu) ends the wait and cancels its timer.+ - **A take given up closes N's link.** When the wait ends with no answer from N, by its 1+ second or by anything above, the owner closes the link it opened to N before it sends+ anything else, then goes on as that event says. N may have accepted already with its+ `accept` held up on the path; the close ends that ownership (section 4), so N is never left+ owned by an owner that drives elsewhere. N is out of `reach` until its link is up again, and+ the owner acts on nothing more that arrives on the closed link, an `accept` it had already+ read included. The one exception is the owner's own shortcut or menu picking N itself: that+ take follows the first on the same link, and its answer is the one awaited.+ - It ignores an `accept` whose route is not that of a take it sent. An `accept` for a take+ from home or by the shortcut that comes after its wait ended is answered with a let-go+ `focus` carrying the owner's current route and naming wherever its input is now (its own id+ when home); that take's own let-go has gone on the same link already, so this one changes+ nothing.- `next` is anything else (outside that `reach`, or a link that has dropped since): the same as arefusal from N, without asking N.@@ -786,9 +810,18 @@ which is what lets a phone drive a chain.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, andevery 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.+a zone only when every one of them is. That is open question 3, built as its recommendation in+1.5.0: `reach` already stops a zone firing for an owner that could not follow it, so the zone is+offered, and the page names each machine that may drive M, has linked, and is not paired with P.+A zone never leads to a phone.++### Which machine the shortcut picks++The shortcut, a Send button and a menu's own item with no machine named send input to the machine+it was last on, while that one can take it (its link is up and it accepts input); else to the+first in the list of peers that can; else to the first this machine sends to at all, so the+refusal or the wake names it. Never to a phone, or to an entry with no id yet. A menu item that+names a machine sends input there, from home or straight from the machine it is on.### The clipboard follows the input@@ -802,7 +835,8 @@ that are missing. A zone never leads to a phone.is never echoed back. It never sends one otherwise, so a paired device cannotcollect 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+ frame begins (its first length byte arrives, section 2) within 10 seconds of that let-go; any+ other is dropped. Like any frame it then has 30 seconds to arrive whole. A later move (a refusalfrom the next machine, say) does not cost the machine let go its one clipboard. It sets it onitself (a desktop) or keeps it (a phone), and sends it on to the machine its input is on now, ifany. That is how something copied on B reaches C in a chain, through A, and it leaves it on A's@@ -857,14 +891,18 @@ The exchange is PAIRING.md's, CPace with the code as the password, with these chbefore, and has the same name and platform as the new pairing proves, is replaced by itrather 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.+ - The entry migrated from 1.4.x (`from_1_4` true), which never links (section 1), is replaced+ by a pairing that proves its id, when an earlier beta linked it and so learnt one; and, when+ it has `id: ""`, by a pairing that completes with the machine at its saved `host` (the+ address `pair_start` came from, for the host; the address it reached, for the requester),+ or that proves its `name` and `platform`. It is replaced, never counted, under the rule in+ item 5. A pairing with the machine at its saved `host` that proves the entry's `platform`+ takes over its `side`, `side_set_at`, `side_by` and zones: every 1.4.x upgrader pairs again,+ since no 1.4.x token migrates, and is at the screen pairing that machine on purpose, so the+ arrangement should not have to be set twice. A match by name alone takes nothing, and the+ entry's zones go with it: pairing proves the code, not which machine that entry was, and+ anyone who saw the code can claim a name, which is safe only because the entry never links+ and nothing of it carries over.- To pair two linked machines afresh, the user removes each from the other's list first.Re-pairing never replaces a linked peer's token.- An id proves only that it arrived unaltered, not that the machine sending it owns it.@@ -934,7 +972,9 @@ it hears. Any desktop can show a code (and be the host) or enter one (and be the**Finding a peer whose address changed.** When the link to a peer with `send` true has been downfor 10 seconds, a desktop tries a link at the source address of a beacon carrying that peer'sexact 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,+It never tries a beacon with another name, nor one whose `id` is not the peer's; one at another+paired machine's saved address it tries after the rest, since two machines may have swapped+addresses. With several such beacons it tries them in turn. It tries at most one address per peer every 30 seconds,and shows nothing when a try fails. A forged beacon can therefore cost one failed connection attempt every 30 seconds, nevera saved address and never a message that prompts the user to pair again.@@ -1080,7 +1120,7 @@ A zone is part of this machine's screen that leads to one peer:```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.+only for the entry migrated from 1.4.x, which never links. A zone never names a phone.- **Which edge a zone crosses.** An `edge` zone is the whole of its peer's `side`, and a `part`zone is some of its thirds (`start`, `middle` and `end`, top to bottom or left to right), so@@ -1104,10 +1144,17 @@ only for the entry migrated from 1.4.x until its id is learnt. A zone never namecover the same stretch: the settings refuse a list where they would, and an `arrangement` thatwould make two overlap is applied and turns the clashing zones for the sender `off`, with anotice 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+ chosen thirds of it for a `part` zone, and the corner for a `corner` zone; the `notch` is a+ stretch of its own, which only another `notch` zone covers: it fires on a dwell and 1.4.x let+ it stand beside the edge, but a Mac has one notch, so it leads to one machine. 1.4.x let theedge 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`.+ save of those methods write the thirds `off`. Two machines may share one side by thirds.+- **Every machine starts with its whole edge.** Pairing gives the new machine an `edge` zone,+ and so does an `arrangement` for a machine that has no zone yet, and so does reading a+ settings file in which a paired desktop has none (pairing made no zones before 1.5.0-beta.5).+ An `edge` zone whose side another zone in use already covers is written `off`, so the file+ stays one the settings accept. A machine with a side and no way in, because another machine+ holds that side, is named on the Crossing page with the machine that holds it.- **A peer with no zones** can still be reached by the shortcut and the menus.- **The same list, both ways.** A machine's zones are where its own pointer crosses when its ownhardware drives, and where a driven pointer is sent onward or home (section 5).@@ -1124,6 +1171,17 @@ bytes. It ignores one whose `set_at` is more than a day ahead of its own clock,held plus one. A side is never cleared by message. A machine with three peers keeps three sides,each settled with that one peer.+`arrangement` may also carry **`way_back`**, a boolean: whether the sender has a zone in use, and+able to fire (an `edge` or `part` zone of a side that is set, a `corner` or a `notch`), that leads+to the receiver. The sender includes it every time it sends an `arrangement`: when the link comes+up, when it changes that machine's side or zones, and, once it has applied an `arrangement` from+that machine, in answer, so the machine that set the side learns at once that it was taken but+leads nowhere. The receiver keeps the last one it was told as `way_back` on the sender's entry,+whether or not the side in the same message was newer, and its Crossing page names the sender as+having no way back while it is `false`. An answer is sent only after an `arrangement` that changed+something here, so two machines never answer each other in turn. A version 6 machine from before+1.5.0-beta.5 ignores it, as it ignores any unknown key (Encodings).+**From 1.4.x's settings.** The migration turns the one pair's ways across into zones for its onepeer, 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@@ -1184,9 +1242,18 @@ every peer."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:+- `on` is a boolean, `set_at` an integer of unix seconds, `by` the `b64` id of the machine that+ made the change, or `""`. A sender always sends all three. A receiver reads a missing `by` as+ `""`, and also reads a `by` spelt in standard base64 with padding, as the desktops do; a+ message missing `on` or `set_at`, or with any of the three of the wrong type or not an id, is+ malformed and ignored whole. `crossing` and `design` are objects, present only when `on` is+ true; one that is absent or is not an object brings no values, and the message stands.+- **Each value stands alone.** Unlike every other message, a value in `crossing` or `design`+ outside the table below, or one this receiver cannot hold (an effect it does not have), is+ left out and the rest still applied, and the message is not malformed for it; an unknown key+ is ignored. Whether a message is newer, and whether it is sent on, is decided by `set_at` and+ `by` alone: one with values left out still wins, takes its stamp, and is sent on as it came.+- The values:| Key | Allowed ||---|---|@@ -1233,7 +1300,7 @@ one against the code and against the primitives written out by hand.take the X25519 result beside the token and bind the key id, both shares and a direction bytein 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.+ is answered `wrong_id`; a typed token, and any token migrated from 1.4.x, no longer links.- The handshake is bounded as a whole (5 seconds, the preamble in 1) on both sides, where version5'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@@ -1274,17 +1341,19 @@ one against the code and against the primitives written out by hand.## Decided-Decided on 30-09-2026. The text above already follows these.+Decided on 30-09-2026, and 6 amended on 01-10-2026. The text above already follows these.1. **A per-pair key id in the preamble, not the machine id.** The first 16 bytes of`HKDF-SHA-256(token, salt "beamer-link-v6", info "beamer-key-id")`; the machine ids travel in- `hello` and `welcome` and are checked there; 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).+ `hello` and `welcome` and are checked there; there is no empty-id lookup; key ids are unique+ across entries (section 2).2. **Forward secrecy in version 6.** An ephemeral X25519 share in each preamble, the result in`ikm` and both shares in `info`; a zero result ends the handshake (section 2).-6. **No typed tokens.** 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).+6. **No typed tokens, and no migrated ones.** Follows from 1: 1.5.0 has no token field, and a+ key id is an offline test of its token. The first decision let a migrated token of pairing's+ spelling link; since a typed token can have that spelling and 1.4.x kept no record of which+ it was, no migrated token links, and Overview asks the user to pair that machine again+ (sections 1 and 2).7. **The QR's extra secret.** 16 random bytes per code in the QR as `k`; `qr: 1` in`pair_start` makes the password the code followed by those bytes (section 6).diff --git a/core/keytable.py b/core/keytable.pyindex 4de3b0c..732408e 100644--- a/core/keytable.py+++ b/core/keytable.py@@ -66,6 +66,14 @@ 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)})+# What each key types on a US keyboard, by evdev code, which names the key's place rather than its+# label: `us` in a key message. Codes 1 to 88 are the PC's set-1 scan codes, so Windows reads this+# table by scan code.+EVDEV_US = dict(zip(range(0x02, 0x0E), "1234567890-="))+EVDEV_US.update(zip(range(0x10, 0x1C), "qwertyuiop[]"))+EVDEV_US.update(zip(range(0x1E, 0x2A), "asdfghjkl;'`"))+EVDEV_US.update(zip(range(0x2B, 0x36), "\\zxcvbnm,./"))+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",diff --git a/core/link.py b/core/link.pyindex c36b0e2..2784095 100644--- a/core/link.py+++ b/core/link.py@@ -11,8 +11,7 @@ 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 toshow; `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."""+being the `welcome` as protocol.read_welcome gives it (`id` as 16 bytes); `message(link, message)`."""import collectionsimport errno@@ -81,7 +80,6 @@ class OutboundLink:state=None,up=None,message=None,- notice=None,socket_factory=socket.create_connection,tunnel=None,clock=time.monotonic,@@ -100,7 +98,7 @@ class OutboundLink:# 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._callbacks = (state, up, message)self._muted = Falseself._factory = socket_factoryself._tunnel = tunnel@@ -142,6 +140,7 @@ class OutboundLink:self._blocked_for = Noneself._try_host = Noneself._followed_at = None+ self._followed_to = Noneself._answered = Falseself._checked_at = 0.0self.status = ""@@ -223,8 +222,10 @@ class OutboundLink:@staticmethoddef _target(entry):+ """Where to dial the entry, or None when it is not dialled: send off, no address, or not+ made by pairing (a typed token, or any token migrated from 1.4.x)."""host, port = entry.get("host"), entry.get("port")- if entry.get("send") is not True or not host or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:+ if not protocol.linkable(entry) or entry.get("send") is not True or not host or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:return Nonereturn host, port@@ -254,7 +255,7 @@ class OutboundLink: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+ target = self._target(entry)shape = (entry.get("host"), entry.get("port"), entry.get("id"))if self._blocked_for is not None and self._blocked_for != shape:self._blocked_for = None@@ -302,15 +303,6 @@ class OutboundLink: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:@@ -435,7 +427,7 @@ class OutboundLink:if direct and host != entry.get("host"):changes["host"] = hosttry:- outcome, saved = self._book.admit(self.key_id, own_id, welcome["id"], changes)+ outcome, _ = self._book.admit(self.key_id, own_id, welcome["id"], changes)except Exception:LOGGER.exception("Could not save what the link to %s taught", name)raise LinkEnded(f"Could not save what {name} told this machine", "failed") from None@@ -443,13 +435,6 @@ class OutboundLink: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"] = sessionreturn welcome@@ -545,6 +530,8 @@ class OutboundLink:raise protocol.ProtocolError(f"invalid message length: {length}")if len(buffer) < protocol.HEADER_SIZE + length:break+ if now - began > protocol.FRAME_COMPLETE_SECONDS:+ raise LinkEnded(f"{name} took too long to send one message", "stopped")body = bytes(buffer[protocol.HEADER_SIZE:protocol.HEADER_SIZE + length])del buffer[:protocol.HEADER_SIZE + length]plain = session.open_raw(body)@@ -553,6 +540,8 @@ class OutboundLink:else:self._deal(protocol.parse_message(plain), began or now)began = now if buffer else None+ if buffer and now - began > protocol.FRAME_COMPLETE_SECONDS:+ raise LinkEnded(f"{name} took too long to send one message", "stopped")self._tick(now)def _large_due(self, began):@@ -741,9 +730,13 @@ class OutboundLink:# 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."""+ """`machines`: what discovery hears, dicts with `name`, `address` and, while that machine shows+ a code, `id`. A link down for ten seconds is tried once at the address of a beacon with this+ entry's exact name, at its saved port, at most every thirty seconds. The address is saved only+ once the link authenticates. Two machines may share a name, so a beacon whose `id` is another+ machine's is passed over, one at another paired machine's saved address is tried after the+ rest (the two may have swapped addresses), and several are tried in turn rather than the+ first for ever."""if self._live or self.key_id is None:returnnow = self._clock()@@ -752,12 +745,19 @@ class OutboundLink:if self._followed_at is not None and now - self._followed_at < FOLLOW_EVERY_SECONDS:returnentry = self.entry()- if entry is None or entry.get("send") is not True or not entry.get("name"):+ if entry is None or self._target(entry) is None 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:+ others = {peer.get("host") for peer in self._book.peers() if peer.get("token") != self.token}+ own_id = entry.get("id")+ found = [m["address"] for m in machines+ if m.get("name") == entry["name"] and m.get("address") and m["address"] != entry.get("host")+ and not (own_id and m.get("id") and m["id"] != own_id)]+ found = [address for address in found if address not in others] + [address for address in found if address in others]+ if not found:return+ address = found[(found.index(self._followed_to) + 1) % len(found)] if self._followed_to in found else found[0]self._followed_at = now+ self._followed_to = addresswith self._lock:self._try_host = addressself._wake.set()diff --git a/core/owner.py b/core/owner.pyindex 65c888d..522fee0 100644--- a/core/owner.py+++ b/core/owner.py@@ -21,7 +21,9 @@ order:The actions: `Send` a message on the link this machine opened to a peer; `SendClipboard` (thismachine's clipboard, to that peer); `SetClipboard` (here); `Moved` (the input is now on a peer, orhome, 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).+that did not happen, to say so); `Drop` (close the link this machine opened to a peer and let it+reconnect: a hand-over to it was given up before it answered, and its `accept` may still be on the+way); 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@@ -73,6 +75,15 @@ class Unreachable:why: str # a refusal's `why`, "refused", "no_answer", "link_lost", "unreachable"+@dataclass(frozen=True)+class Drop:+ peer: str+++# What the dropped link says of itself until it reconnects.+DROPPED = "A hand-over to this machine was called off before it answered"++@dataclass(frozen=True)class Local:pass@@ -184,17 +195,18 @@ class Owner: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 self._abandon() + self._stay() + self._replay_held()return []if peer not in self._links & self._accepting:return [Unreachable(peer, "unreachable")]if self.held_back(peer):return []left = self.on- self._wait = None+ # A hand-over waiting on `peer` itself is not given up: this take follows it on that link.+ actions = self._abandon(unless=peer)self.route += 1- actions = self._let_go_of(left, peer) if left is not None else []+ if left is not None:+ actions += self._let_go_of(left, peer)actions += self._take(peer, edge, offset, chain=False)self._arrive(peer, self._wait.reach)actions += self._clipboard_to(peer)@@ -220,7 +232,8 @@ class Owner:def accept(self, peer, data):route = data.get("route")took = self._takes.get(route)- if took is None or took[0] != peer:+ # Not from a link this machine dropped: closing it already ended what this accept began.+ if took is None or took[0] != peer or peer not in self._links:return []wait = self._waitif wait is not None and wait.peer == peer and wait.route == route:@@ -258,7 +271,7 @@ class Owner:wait = self._waitif wait is not None and now >= wait.due:if wait.chain:- actions += self._not_taken(wait.peer, "no_answer")+ actions += self._abandon() + 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]@@ -378,18 +391,30 @@ class Owner: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+ actions = self._abandon()self.route += 1if left in self._links:- actions = self._let_go_of(left, self.own_id)+ actions += self._let_go_of(left, self.own_id)else:self._forget_pressed(left)- actions = []self.on = Noneself.reach_sent = []actions.append(Moved(None, left, why, edge, offset))return actions + self._replay_held()+ def _abandon(self, unless=None):+ """Ends the wait. A hand-over given up before its answer closes the next machine's link,+ first, so a late `accept` cannot leave that machine owned while nobody drives it: the+ responder ends an ownership when its link ends (section 5). That machine is out of `reach`+ until its link is up again."""+ wait, self._wait = self._wait, None+ if wait is None or not wait.chain or wait.peer == unless:+ return []+ self._links.discard(wait.peer)+ self._accepting.discard(wait.peer)+ self._clipboard_at.discard(wait.peer)+ return [Drop(wait.peer)]+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 = Nonediff --git a/core/pairing.py b/core/pairing.pyindex 05709f9..c392a0c 100644--- a/core/pairing.py+++ b/core/pairing.py@@ -55,6 +55,8 @@ from __future__ import annotationsimport base64import contextlib+import ctypes+import ctypes.utilimport hashlibimport hmacimport ipaddress@@ -65,6 +67,7 @@ import queueimport secretsimport socketimport struct+import sysimport threadingimport time@@ -98,6 +101,8 @@ CODE_DIGITS = 6MAX_DATAGRAM_BYTES = 1024PAIR_REPLY_TIMEOUT_SECONDS = 1.5PAIR_ATTEMPTS = 3+# How many replies already waiting are read for one from the address asked before a held one decides.+MAX_HELD_SWEEP = 64NONCE_BYTES = 16SHARE_BYTES = 32TAG_BYTES = 64@@ -333,14 +338,17 @@ def peer_entry(identity: bytes, name: str, platform: str, port: int, token: str,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` isTrue 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."""+ there is none; `replaced` is the entry this pairing replaces: the one left by a lost pair_done,+ or one migrated from 1.4.x that an earlier beta linked and so knows the id of. A migrated entry+ never links, so replacing it takes nothing that works."""if theirs == own:return True, Nonewanted = _b64(theirs)for known in peers:if known.get("id") != wanted:continue+ if known.get("from_1_4") is True:+ return None, knownpaired_at = known.get("paired_at")lost_done = (known.get("linked") is False@@ -351,15 +359,17 @@ def _find_known(peers: list, own: bytes, theirs: bytes, name: str, platform: strreturn 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+def _migrated_for(peers: list, address: str, name: str, platform: str):+ """The entry migrated from 1.4.x (`id: ""`) that a fresh pairing with the machine at `address`,+ proving `name` and `platform`, replaces, or None: its saved host is `address`, or (its address+ having changed) its name and platform are the ones proved. A name is anyone's to claim, which+ is safe only because a migrated entry never links and a match by name carries nothing over+ (peerlist.add_peer gives its side and zones only to the machine at its host on its platform):+ taking it loses nothing that works, and left, it would ask to be paired again beside this pairing."""for known in peers:- if known.get("id") == "" and known.get("from_1_4") is True and known.get("host") == address:+ if known.get("id") == "" and known.get("from_1_4") is True and (+ (address and known.get("host") == address)+ or (known.get("name") == name and known.get("platform") == platform)):return knownreturn None@@ -710,7 +720,7 @@ class PairingHost:reply = self._end(MSG_PAIR_DONE, sent, pair_id, ERROR_KNOWN, "known")self.known = None if known is True else knownreturn reply- replaced = replaced or _migrated_for(peers, bound["address"])+ replaced = replaced or _migrated_for(peers, bound["address"], bound["name"], bound["platform"])if _clashes(peers, bound["token"], replaced):return self._end(MSG_PAIR_DONE, sent, pair_id, ERROR_REFUSED, "refused")if replaced is None and len(peers) >= MAX_PEERS:@@ -889,6 +899,14 @@ class PairingClient:raise PairingError(ERROR_REFUSED)return self._token+ def proves(self, done: dict) -> bool:+ """Whether an ok pair_done carries the tag only the host holding this attempt's token could+ make. Checking it tests no guess at the code."""+ try:+ return self._done_tag is not None and hmac.compare_digest(_unb64(done.get("tag")), self._done_tag)+ except PairingError:+ return False+def entry(self, address: str) -> dict:"""Version 3: the peer entry for the host, reached at `address`, once finish() hasreturned the token."""@@ -916,9 +934,9 @@ def local_address_towards(host: str) -> str:probe.close()-def broadcast_targets(port: int) -> list:- """Every address worth sending a beacon to, one per local IPv4 interface plus the limited- broadcast as a backstop.+def broadcast_targets(port: int, interfaces=None) -> list:+ """Every address worth sending a beacon to, one per local IPv4 network plus the limited+ broadcast as a backstop. `interfaces` is _interfaces()'s list, read afresh when None.⚠ 255.255.255.255 alone is not enough and this is not theoretical: it leaves by the defaultroute only, so a PC with a second interface — a Hyper-V vEthernet switch is the common case —@@ -927,24 +945,29 @@ def broadcast_targets(port: int) -> list:then paired against a stale id from an older beacon that had got through, which is whatproduced `not_pairing`.- The per-interface directed broadcast assumes a /24, because the stdlib exposes no netmask.- A wrong guess costs one datagram that goes nowhere; the limited broadcast is still sent, so- this can only add delivery, never remove it."""+ Each network's directed broadcast follows its own netmask: a /24 guess sent a 169.254/16+ link-local interface to an address no host holds. Only where the platform will not list its+ interfaces is a /24 still assumed. The limited broadcast is always sent, so a wrong guess can+ only add delivery, never remove it."""+ if interfaces is None:+ interfaces = _interfaces()+ if interfaces:+ directed = [str(ipaddress.IPv4Network(f"{address}/{netmask}", strict=False).broadcast_address)+ for address, netmask in interfaces]+ else:+ directed = [".".join(address.split(".")[:3] + ["255"]) for address in _local_ipv4_addresses()+ if len(address.split(".")) == 4]targets = [("255.255.255.255", port)]seen = {"255.255.255.255"}- for address in _local_ipv4_addresses():- parts = address.split(".")- if len(parts) != 4:- continue- directed = ".".join(parts[:3] + ["255"])- if directed not in seen:- seen.add(directed)- targets.append((directed, port))+ for address in directed:+ if address not in seen:+ seen.add(address)+ targets.append((address, port))return targetsdef _local_ipv4_addresses() -> list:- found = []+ found = [address for address, _netmask in _interfaces()]try:for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):address = info[4][0]@@ -955,6 +978,163 @@ def _local_ipv4_addresses() -> list:return found+def _interfaces() -> list:+ """(address, netmask) as dotted quads for each IPv4 interface that is up and has a network to+ broadcast on: loopback, point-to-point tunnels (a VPN's) and a /31 or /32 are left out. [] when+ the platform will not say, and the callers then do as they did before they could ask."""+ try:+ listed = _windows_interfaces() if sys.platform == "win32" else _posix_interfaces()+ except Exception:+ # ctypes over the C library: whatever goes wrong there costs this list and nothing else.+ return []+ found = []+ for address, netmask in listed:+ try:+ network = ipaddress.IPv4Network(f"{address}/{netmask}", strict=False)+ except ValueError:+ continue+ if ipaddress.IPv4Address(address).is_loopback or address == "0.0.0.0" or not 0 < network.prefixlen < 31:+ continue+ if (address, netmask) not in found:+ found.append((address, netmask))+ return found+++class _Ifaddrs(ctypes.Structure):+ pass+++# The same layout on macOS and Linux; the sockaddrs it points at are not (BSD's start with a length).+_Ifaddrs._fields_ = [+ ("ifa_next", ctypes.POINTER(_Ifaddrs)),+ ("ifa_name", ctypes.c_char_p),+ ("ifa_flags", ctypes.c_uint),+ ("ifa_addr", ctypes.c_void_p),+ ("ifa_netmask", ctypes.c_void_p),+ ("ifa_dstaddr", ctypes.c_void_p),+ ("ifa_data", ctypes.c_void_p),+]+_IFF_UP, _IFF_BROADCAST, _IFF_LOOPBACK, _IFF_POINTOPOINT = 0x1, 0x2, 0x8, 0x10+++def _sockaddr_ipv4(pointer):+ """(family, the four address bytes) of a sockaddr from getifaddrs. A BSD netmask may be cut+ short by its length byte, and may say no family: the bytes it leaves out are zeros."""+ if sys.platform == "darwin":+ length = ctypes.string_at(pointer, 1)[0]+ raw = ctypes.string_at(pointer, min(max(length, 2), 8))+ family = raw[1]+ else:+ raw = ctypes.string_at(pointer, 8)+ family = int.from_bytes(raw[:2], sys.byteorder)+ return family, raw[4:8].ljust(4, b"\0")+++def _posix_interfaces() -> list:+ libc = ctypes.CDLL(ctypes.util.find_library("c"), use_errno=True)+ libc.getifaddrs.argtypes = [ctypes.POINTER(ctypes.POINTER(_Ifaddrs))]+ libc.freeifaddrs.argtypes = [ctypes.POINTER(_Ifaddrs)]+ head = ctypes.POINTER(_Ifaddrs)()+ if libc.getifaddrs(ctypes.byref(head)) != 0:+ raise OSError(ctypes.get_errno(), "getifaddrs failed")+ found = []+ try:+ node = head+ while node:+ item = node.contents+ node = item.ifa_next+ wanted = _IFF_UP | _IFF_BROADCAST+ if item.ifa_flags & (wanted | _IFF_LOOPBACK | _IFF_POINTOPOINT) != wanted or not item.ifa_addr or not item.ifa_netmask:+ continue+ family, address = _sockaddr_ipv4(item.ifa_addr)+ if family != socket.AF_INET:+ continue+ found.append((socket.inet_ntoa(address), socket.inet_ntoa(_sockaddr_ipv4(item.ifa_netmask)[1])))+ finally:+ libc.freeifaddrs(head)+ return found+++class _IpAddrRow(ctypes.Structure):+ _fields_ = [+ ("dwAddr", ctypes.c_uint32),+ ("dwIndex", ctypes.c_uint32),+ ("dwMask", ctypes.c_uint32),+ ("dwBCastAddr", ctypes.c_uint32),+ ("dwReasmSize", ctypes.c_uint32),+ ("unused1", ctypes.c_ushort),+ ("wType", ctypes.c_ushort),+ ]+++def _windows_interfaces() -> list:+ """GetIpAddrTable: every IPv4 address with its mask, each stored in network order. Windows+ gives no point-to-point flag here; a VPN adapter's /32 is what leaves it out."""+ iphlpapi = ctypes.WinDLL("iphlpapi")+ iphlpapi.GetIpAddrTable.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong), ctypes.c_int]+ size = ctypes.c_ulong(0)+ iphlpapi.GetIpAddrTable(None, ctypes.byref(size), 0)+ for _attempt in range(3):+ table = ctypes.create_string_buffer(size.value)+ result = iphlpapi.GetIpAddrTable(table, ctypes.byref(size), 0)+ if result != 122: # ERROR_INSUFFICIENT_BUFFER: an address came up in between+ break+ if result != 0:+ raise OSError(result, "GetIpAddrTable failed")+ count = ctypes.c_uint32.from_buffer(table).value+ rows = (_IpAddrRow * count).from_buffer(table, ctypes.sizeof(ctypes.c_uint32))+ gone = 0x0008 | 0x0040 # MIB_IPADDR_DISCONNECTED, MIB_IPADDR_DELETED+ return [(socket.inet_ntoa(struct.pack("=I", row.dwAddr)), socket.inet_ntoa(struct.pack("=I", row.dwMask)))+ for row in rows if not row.wType & gone]+++def _answer_source(host: str, interfaces=None, towards=None):+ """The address to answer `host` from when the routing table would pick a different one: this+ machine's address on the network `host` is on. None when `host` is on none of them, or the+ routing table agrees. Seen on 01-10-2026: a VPN's route for the home network sent the laptop's+ answer out from the VPN's address, and the requester never knew it for an answer."""+ try:+ requester = ipaddress.IPv4Address(host)+ except ValueError:+ return None+ ours = [address for address, netmask in (_interfaces() if interfaces is None else interfaces)+ if requester in ipaddress.IPv4Network(f"{address}/{netmask}", strict=False)]+ if not ours:+ return None+ try:+ routed = (towards or local_address_towards)(host)+ except OSError:+ routed = None+ # Two addresses on one network: whichever the routing table picks is already right.+ return None if routed in ours else ours[0]+++def _oversized(exc: OSError) -> bool:+ """Windows' WSAEMSGSIZE: a datagram larger than the buffer, which Windows reports as an error+ where other platforms cut it short. Anyone can send one, so it must cost only itself; it once+ stopped a PC's pairing loop for good."""+ return getattr(exc, "winerror", None) == 10040+++def _receive_on(sock, timeout: float):+ """The next datagram on `sock` as (message, address), {} for one that is not a message, or None+ once `timeout` passes."""+ sock.settimeout(max(timeout, 0.001))+ try:+ data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)+ except socket.timeout:+ return None+ except ConnectionResetError:+ # Windows: the port-unreachable of an earlier datagram.+ return {}, ("", 0)+ except OSError as exc:+ if _oversized(exc):+ return {}, ("", 0)+ raise PairingError("no_answer") from exc+ message = decode(data)+ return (message if isinstance(message, dict) else {}), address++def machine_name() -> str:return socket.gethostname().split(".", 1)[0] or "This machine"@@ -1083,6 +1263,8 @@ class Announcer:# fine; the peer that was not listening is the Mac's problem.continueexcept OSError as exc:+ if _oversized(exc):+ continueif self._stop.is_set():breakself.error = str(exc)@@ -1269,18 +1451,65 @@ class Discovery: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."""+ self._awaiting = client.pair_id+ source = _answer_source(target[0])+ if source is not None:+ # The routing table would send to `target` from another of this machine's addresses (a+ # VPN's route for the home network, the laptop on 01-10), which the host may have no+ # way back to. The attempt goes from the address on the target's network instead, on+ # a socket of its own that hears the replies itself.+ own = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ own.bind((source, 0))+ except OSError as exc:+ own.close()+ self.logger.warning("pairing not sent from %s, sent as routed: %s", source, exc)+ else:+ with own:+ return self._exchange_on(own, lambda timeout: _receive_on(own, timeout), target, client, code)+ return self._exchange_on(sock, self._take_reply, target, client, code)++ def _exchange_on(self, sock, receive, target, client, code: str) -> str:+ send = lambda datagram: sock.sendto(datagram, target)+ answer = self._ask(send, receive, target, client.pair_id, client.start(), MSG_PAIR_ANSWER)+ confirm = self._judge(client, answer, code, lambda abort: send(encode(abort)))+ return client.finish(self._ask(send, receive, target, client.pair_id, confirm, MSG_PAIR_DONE, client.proves))++ def _take_reply(self, timeout: float):+ try:+ return self._replies.get(timeout=timeout)+ except queue.Empty:+ return None++ def _ask(self, send, receive, target, pair_id: str, message: dict, reply_type: str, proves=None) -> dict:+ """Sends `message` to `target` until the reply of `reply_type` for `pair_id` comes back;+ `receive(timeout)` gives the next (reply, address), or None once `timeout` passes.++ A reply from `target` decides at once: the caller judges it and never waits for a better+ one. A reply from any other address is held (the first ok one and the first refusal), and+ decides only if a window ends with nothing from `target`, even among replies already+ waiting, an ok one before a refusal: a host whose answer a VPN's route sent out from its+ own address (01-10) is still heard, while a stranger who read the pairing id from a beacon+ loses to a host's answer from the address asked. `proves`, for a receipt, says whether an+ ok one carries the host's proof: from another address one that does decides at once and+ one that does not is ignored, since checking it tests no guess."""datagram = encode(message)+ # The first ok reply and the first refusal from elsewhere, and nothing more.+ held = {}++ def consider(reply, address):+ if reply.get("pair") != pair_id or reply.get("type") != reply_type:+ return None+ if address[0] == target[0]:+ return reply+ if proves is not None and reply.get("ok") is True:+ return reply if proves(reply) else None+ held.setdefault(reply.get("ok") is True, reply)+ return None+for _attempt in range(PAIR_ATTEMPTS):try:- sock.sendto(datagram, target)+ send(datagram)except OSError as exc:raise PairingError("no_answer") from excdeadline = self.clock() + PAIR_REPLY_TIMEOUT_SECONDS@@ -1288,13 +1517,22 @@ class Discovery:remaining = deadline - self.clock()if remaining <= 0:break- try:- reply, address = self._replies.get(timeout=remaining)- except queue.Empty:+ received = receive(remaining)+ if received is None:break- if address[0] != target[0] or reply.get("pair") != pair_id or reply.get("type") != reply_type:- continue- return reply+ decided = consider(*received)+ if decided is not None:+ return decided+ if held:+ # What has already come from the address asked still beats what was held.+ for _waiting in range(MAX_HELD_SWEEP):+ received = receive(0)+ if received is None:+ break+ decided = consider(*received)+ if decided is not None:+ return decided+ return held.get(True) or held[False]raise PairingError("no_answer")def _run(self) -> None:@@ -1316,6 +1554,8 @@ class Discovery:except ConnectionResetError:continueexcept OSError as exc:+ if _oversized(exc):+ continueif self._stop.is_set():breakself.error = str(exc)@@ -1330,7 +1570,7 @@ class Discovery:self._note_beacon(message, address)except Exception:self.logger.exception("beacon dropped")- elif kind in (MSG_PAIR_ANSWER, MSG_PAIR_DONE) and self._awaiting == (address[0], message.get("pair")):+ elif kind in (MSG_PAIR_ANSWER, MSG_PAIR_DONE) and self._awaits(message):# Only what the attempt under way is waiting for is kept, and only so much# of it, so nothing a stranger sends piles up in memory.try:@@ -1344,6 +1584,10 @@ class Discovery:self._sock = Nonesock.close()+ def _awaits(self, message: dict) -> bool:+ awaiting = self._awaiting+ return awaiting is not None and message.get("pair") == awaiting+def _send_find(self, sock) -> None:with self._lock:target = self._finding@@ -1790,6 +2034,8 @@ class PairingService(Discovery):except ConnectionResetError:continueexcept OSError as exc:+ if _oversized(exc):+ continueif self._stop.is_set():breakself.error = str(exc)@@ -1821,7 +2067,7 @@ class PairingService(Discovery):# 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)+ self._answer(sock, self._beacon(), address)elif kind in (MSG_PAIR_START, MSG_PAIR_CONFIRM, MSG_PAIR_REQUEST):reply, paired, fresh = self._host_handle(message, address[0], "udp")# A refusal is larger than the smallest datagram that draws one, so it is rationed.@@ -1829,16 +2075,40 @@ class PairingService(Discovery):if fresh:self._stop.wait(max(0.0, arrived + PAIR_ANSWER_SECONDS - time.monotonic()))try:- sock.sendto(encode(reply), address)+ self._answer(sock, encode(reply), address)except OSError as exc:self.logger.warning("pairing reply not sent: %s", exc)self._paired(paired, address[0])- elif kind in (MSG_PAIR_ANSWER, MSG_PAIR_DONE) and self._awaiting == (address[0], message.get("pair")):+ elif kind in (MSG_PAIR_ANSWER, MSG_PAIR_DONE) and self._awaits(message):try:self._replies.put_nowait((message, address))except queue.Full:pass+ def _answer(self, sock, data: bytes, address) -> None:+ """Sends a reply to a pairing request or a `find` from this machine's address on the+ requester's own network, where the routing table would pick another (_answer_source): a+ requester sorts answers by the address it asked, though never by port.++ ⚠ The socket that does it takes a port of its own. Bound to the pairing port beside the+ main socket, it would take any datagram for that address arriving while it lived (a+ pair_confirm, another machine's request), and Windows does not say which of two such+ sockets gets one. A requester takes beacons from strangers on its pairing port, so an+ answer from another port reaches it as well."""+ source = _answer_source(address[0])+ if source is not None:+ try:+ out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ out.bind((source, 0))+ out.sendto(data, address)+ return+ finally:+ out.close()+ except OSError as exc:+ self.logger.warning("pairing reply not sent from %s, sent as routed: %s", source, exc)+ sock.sendto(data, address)+def _beacon_entry(self, message: dict, address):entry = super()._beacon_entry(message, address)if entry is not None:@@ -1943,7 +2213,7 @@ class PairingService(Discovery):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)+ replaced = replaced or _migrated_for(peers, address, client.host_name, client.host_platform)if _clashes(peers, entry["token"], replaced):raise PairingError(ERROR_REFUSED)if replaced is None and len(peers) >= MAX_PEERS:diff --git a/core/peerlist.py b/core/peerlist.pyindex fb7bb9c..8fb9e19 100644--- a/core/peerlist.py+++ b/core/peerlist.py@@ -36,6 +36,16 @@ def labels(peers: list) -> dict:return result+def sharing_a_name(machines: list) -> list:+ """For each machine heard, in order, whether another in the list has its name (as `labels()`+ compares them): one machine heard on two interfaces is two rows, told apart by address."""+ counts = {}+ for machine in machines:+ key = _name(machine).casefold()+ counts[key] = counts.get(key, 0) + 1+ return [counts[_name(machine).casefold()] > 1 for machine in machines]++def label_for(peers: list, *, token: Optional[str] = None, peer_id: Optional[str] = None, host: Optional[str] = None) -> str:"""`labels()` for one machine, found by its token, its id (`b64`) or its address, in that order ofpreference; "" when none matches. What a status or a notice calls a machine, so two of one name@@ -53,15 +63,28 @@ def add_peer(settings: dict, entry: dict, replaced: Optional[dict] = None) -> No"""Puts a newly paired `entry` in `settings` (WIRE.md section 6, item 5). `replaced`, an entryas `peers()` gave it, is dropped by its token and the new one takes its place: the first entryis 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."""+ an id no entry has any more go with it; a machine paired again under its own id keeps its zones.+ The entry migrated from 1.4.x (`id` empty) gives its side and zones to a pairing with the machine+ at its saved host on its platform (section 6, item 4): that is the machine the user meant to pair+ again, and a match by name alone takes nothing, a name being anyone's to claim."""peers = settings["peers"]at = next((index for index, held in enumerate(peers) if replaced is not None and held.get("token") == replaced.get("token")), None)if at is None:peers.append(entry)else:peers[at] = entry+ if (replaced is not None and replaced.get("from_1_4") is True and replaced.get("id") == "" and entry.get("id")+ and replaced.get("host") and replaced.get("host") == entry.get("host")+ and replaced.get("platform") == entry.get("platform")):+ entry.update({field: replaced.get(field, default) for field, default in+ (("side", ""), ("side_set_at", 0), ("side_by", ""))})+ for zone in settings["zones"]:+ if zone.get("peer") == "":+ zone["peer"] = entry["id"]_drop_orphan_zones(settings)+ # Imported here: ways names machines by this module's labels.+ from core import ways+ ways.ensure_zones(settings)def remove_peer(settings: dict, token: str) -> Optional[dict]:diff --git a/core/protocol.py b/core/protocol.pyindex 47f62fc..a924b1e 100644--- a/core/protocol.py+++ b/core/protocol.py@@ -27,6 +27,7 @@ import socketimport structimport threadingimport time+import zlibfrom nacl.bindings import (crypto_aead_chacha20poly1305_ietf_ABYTES,@@ -67,11 +68,21 @@ CLIPBOARD_MAX_BYTES = 256 * 1024# 0.1s on wired gigabit and half a second on decent Wi-Fi. Beyond it the text still goes.CLIPBOARD_IMAGE_MAX_BYTES = 8 * 1024 * 1024CLIPBOARD_IMAGE_PNG = "png"+# What a PNG may decode to, checked from its bytes first (png_fits): 2^25 pixels holds an 8K screen+# (7680x4320 is 33,177,600) and is 128 MiB as 8-bit RGBA, 256 MiB at 16 bits a channel, where a+# few compressed megabytes could otherwise claim gigabytes. Metadata a decoder inflates (colour profiles, compressed text) is held+# to 4 MiB in all; a real colour profile is a few kilobytes.+PNG_MAX_SIDE = 16384+PNG_MAX_PIXELS = 2**25+PNG_METADATA_MAX_BYTES = 4 * 1024 * 1024# The largest sealed frame either end accepts. It must hold the biggest clipboard message -- an# 8MB image is ~10.7MB as base64, beside up to 256KB of text -- because the clipboard also travels# 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 frame arrives whole within this of its first length byte, or the link ends (WIRE.md section 2,+# frames): liveness alone lets a peer that sends a byte a second hold a 16 MiB read open for days.+FRAME_COMPLETE_SECONDS = 30.0# 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@@ -163,11 +174,12 @@ def legacy_frame(msg: dict) -> bytes:return struct.pack(">I", len(body)) + body-def _recv_exact(sock: socket.socket, n: int, deadline: float = None) -> bytes:+def _recv_exact(sock: socket.socket, n: int, deadline: float = None, idle: float = None) -> bytes:"""`deadline` is a time.monotonic() moment the whole read must finish by.A socket timeout alone bounds each recv, not the read: a peer sending onebyte every few seconds would hold a handshake open for as long as it- liked. Past the deadline this raises socket.timeout like a quiet peer."""+ liked. Past the deadline this raises socket.timeout like a quiet peer.+ `idle`, when given, still bounds each recv."""chunks = []remaining = nwhile remaining > 0:@@ -175,7 +187,7 @@ def _recv_exact(sock: socket.socket, n: int, deadline: float = None) -> bytes:left = deadline - time.monotonic()if left <= 0:raise socket.timeout("deadline passed while reading")- sock.settimeout(left)+ sock.settimeout(left if idle is None else min(left, idle))chunk = sock.recv(remaining)if not chunk:raise ConnectionClosed("socket closed while reading")@@ -194,12 +206,30 @@ def recv_msg(sock: socket.socket, session, limit: int = MAX_FRAME_BYTES, deadlindef 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 _recv_exact(sock, length, deadline)+ """One frame as it came, after its length (held to `limit`) and before it is opened. Without a+ `deadline` the wait for the frame's first byte is the socket's own timeout (the link's+ liveness), and the frame then has FRAME_COMPLETE_SECONDS from that byte to arrive whole+ (WIRE.md section 2, frames), each read still bounded by that timeout."""+ if deadline is not None:+ 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 _recv_exact(sock, length, deadline)+ idle = sock.gettimeout()+ first = _recv_exact(sock, 1)+ deadline = time.monotonic() + FRAME_COMPLETE_SECONDS+ try:+ header = first + _recv_exact(sock, HEADER_SIZE - 1, deadline, idle)+ (length,) = struct.unpack(">I", header)+ if length < 1 or length > limit:+ raise ProtocolError(f"invalid message length: {length}")+ return _recv_exact(sock, length, deadline, idle)+ finally:+ try:+ sock.settimeout(idle)+ except OSError:+ pass # closed meanwhile by another thread: what the read raised is the newsdef ping_msg() -> dict:@@ -244,13 +274,80 @@ def clipboard_image(data) -> bytes:image = base64.b64decode(encoded, validate=True)except (binascii.Error, ValueError):return None- if len(image) > CLIPBOARD_IMAGE_MAX_BYTES or not image.startswith(PNG_SIGNATURE):+ return image if png_fits(image) else None+++def png_fits(image) -> bool:+ """Whether a clipboard image may be sent, or set where something will decode it (WIRE.md+ section 3), judged from its bytes alone: at most CLIPBOARD_IMAGE_MAX_BYTES; the PNG signature,+ then IHDR, whole, with each side 1 to PNG_MAX_SIDE pixels and PNG_MAX_PIXELS in all; every+ chunk inside the file, up to IEND; and the metadata a decoder inflates (iCCP, zTXt, a+ compressed iTXt) at most PNG_METADATA_MAX_BYTES in all. Nothing here touches the pixels: a PNG of a few+ megabytes can decode to gigabytes, and these bounds are what keeps that from happening."""+ if not isinstance(image, (bytes, bytearray)) or len(image) > CLIPBOARD_IMAGE_MAX_BYTES or not image.startswith(PNG_SIGNATURE):+ return False+ at, budget = len(PNG_SIGNATURE), PNG_METADATA_MAX_BYTES+ while at + 12 <= len(image):+ length, kind = struct.unpack_from(">I4s", image, at)+ data_at = at + 8+ if data_at + length + 4 > len(image):+ return False+ data = bytes(image[data_at:data_at + length])+ if at == len(PNG_SIGNATURE):+ if kind != b"IHDR" or length != 13:+ return False+ width, height = struct.unpack_from(">II", data)+ if not (1 <= width <= PNG_MAX_SIDE and 1 <= height <= PNG_MAX_SIDE) or width * height > PNG_MAX_PIXELS:+ return False+ elif kind in (b"IHDR", b"acTL", b"fcTL", b"fdAT"):+ # A clipboard image is a still with one header: these would claim sizes unchecked.+ return False+ elif kind in (b"iCCP", b"zTXt", b"iTXt"):+ budget = _inflated_within(_png_compressed(kind, data), budget)+ if budget is None:+ return False+ elif kind == b"IEND":+ return True+ at = data_at + length + 4+ return False+++def _png_compressed(kind: bytes, data: bytes):+ """The zlib stream inside an iCCP, zTXt or compressed iTXt, False for an uncompressed iTXt,+ or None when the chunk is not shaped as the PNG specification says."""+ name_end = data.find(b"\x00")+ if name_end < 0:return None- return image+ if kind != b"iTXt":+ return data[name_end + 2:]+ flag = data[name_end + 1:name_end + 2]+ if flag == b"\x00":+ return False+ language_end = data.find(b"\x00", name_end + 3)+ translated_end = data.find(b"\x00", language_end + 1) if language_end >= 0 else -1+ return data[translated_end + 1:] if flag == b"\x01" and translated_end >= 0 else None+++def _inflated_within(stream, budget):+ """What is left of `budget` once `stream` is inflated, or None when it would pass the budget+ or is not one whole zlib stream ending where the chunk does (not zlib, cut short, or with+ bytes after its end). Inflates at most one byte past the budget."""+ if stream is None:+ return None+ if stream is False:+ return budget+ inflater = zlib.decompressobj()+ try:+ inflated = inflater.decompress(stream, budget + 1)+ except zlib.error:+ return None+ if len(inflated) > budget or not inflater.eof or inflater.unused_data:+ return None+ return budget - len(inflated)def settings_msg(data: dict) -> dict:- """Same on both machines: whether it is on, its stamp and, while on, the shared values, as+ """Same on all machines: whether it is on, its stamp and, while on, the shared values, assettings_sync.message_data builds them. Sent on every change while on and announced on everynew connection; an older Beamer ignores the type."""return {"type": MSG_SETTINGS, "data": dict(data)}@@ -370,11 +467,20 @@ def read_id(text):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)."""+ """Whether `token` has the shape pairing gives: the `b64` of 32 bytes, in its one spelling.+ Anything else is a typed token. The shape proves nothing about where a token came from (a+ user could type 43 "A"s); `linkable` is what decides whether an entry links."""return _from_b64(token, TOKEN_SIZE) is not None+def linkable(entry) -> bool:+ """Whether a peer entry may link, and so have a key id: its token was made by 1.5.0's pairing.+ An entry migrated from 1.4.x never links, whatever its token looks like, because 1.4.x kept+ no record of whether its token was paired or typed, and a key id is an offline test of its+ token (WIRE.md sections 1 and 2)."""+ return isinstance(entry, dict) and entry.get("from_1_4") is not True and is_paired_token(entry.get("token"))++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 typedtoken, because a key id is an offline test of its token."""@@ -1040,13 +1146,18 @@ def read_clipboard(message):return {"text": text, "image": clipboard_image(data)}-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 arrangement_v6(edge: str, set_at: int, by: bytes, way_back=None) -> dict:+ """`way_back`, when a boolean, says whether one of the sender's zones leads to the receiver (WIRE.md section 8)."""+ data = {"edge": edge, "set_at": int(set_at), "by": id_text(by)}+ if isinstance(way_back, bool):+ data["way_back"] = way_back+ return {"type": MSG_ARRANGEMENT, "data": 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."""+ """{edge, set_at, by} from an `arrangement`, with `way_back` when it carried a boolean one, or+ None: malformed, or stamped more than a day ahead of `now` or above 2^53 - 2, which the+ receiver ignores. A `way_back` that is not a boolean is left out, and the side still stands."""parsed = read_message(message)if parsed is None or parsed[0] != MSG_ARRANGEMENT:return None@@ -1055,7 +1166,10 @@ def read_arrangement_v6(message, now: float):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}+ read = {"edge": data["edge"], "set_at": set_at, "by": by}+ if isinstance(data.get("way_back"), bool):+ read["way_back"] = data["way_back"]+ return readdef paired_msg(ids) -> dict:diff --git a/core/receiver.py b/core/receiver.pyindex cc8234f..a31f0ff 100644--- a/core/receiver.py+++ b/core/receiver.py@@ -117,8 +117,6 @@ SENT_HOME_SECONDS = 5.0OUTBOX_LIMIT = 512ADMITTED = "admitted"-FIRST_LINK = "first_link"-FOLDED = "folded"WRONG_ID = "wrong_id"GONE = "gone"@@ -224,14 +222,13 @@ def zone_stretch(zone: dict, sides: dict) -> set:@functools.lru_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 _key_id_of(token) -> bytes:+ return protocol.key_id(token)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+ # Only for an entry made by pairing: a key id is an offline test of its token (section 2).+ return _key_id_of(entry["token"]) if protocol.linkable(entry) else Noneclass HandshakeSlots:@@ -303,83 +300,22 @@ class PeerBook:"""Section 2's id checks for a link under `key_id` whose first frame named `peer_id`, and onsuccess 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."""+ the key id any longer; ADMITTED otherwise. `changes` and `linked` are applied and saved when+ they change anything."""with self.lock:settings = copy.deepcopy(self._load() or {})peers = settings.get("peers") or []entry = next((p for p in peers if _entry_key_id(p) is not None and hmac.compare_digest(_entry_key_id(p), key_id)), None)if entry is None:return GONE, None- text = protocol.id_text(peer_id)- first = not entry.get("id")- if peer_id == own_id:+ if peer_id == own_id or entry.get("id") != protocol.id_text(peer_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"] = textif 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+ return ADMITTED, copy.deepcopy(entry)class _Link:@@ -474,8 +410,7 @@ class LinkResponder:`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+ peer whose `caps` list `settings`; `paired_callback(peer, ids)`; `link_callback(peer, up)`; and`announce(peer)`, the messages to send once a link is up (section 3, announcements).`status_callback(state, detail)` takes ServerState.@@ -503,7 +438,6 @@ class LinkResponder:arrangement_callback=None,settings_callback=None,paired_callback=None,- notice_callback=None,link_callback=None,announce=None,) -> None:@@ -521,7 +455,7 @@ class LinkResponder: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,+ "link": link_callback,}self._announce = announce or (lambda peer: [])# This machine's speed for a peer's pointer and scroll, and whether@@ -756,25 +690,10 @@ class LinkResponder: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 Noneif 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 Truewelcome = protocol.welcome_v6(own_id, identity["name"], identity["platform"], identity["app"], identity["caps"], allow_drive, self._hardware_towards(host, identity)@@ -879,7 +798,7 @@ class LinkResponder:continuemessage = protocol.parse_message(plain)except socket.timeout:- LOGGER.warning("%s went quiet; its link is over", link.name)+ LOGGER.warning("%s went quiet, or took too long over one message; its link is over", link.name)breakexcept (protocol.ConnectionClosed, protocol.ProtocolError, OSError) as exc:if not link.closed.is_set():@@ -1378,7 +1297,7 @@ class LinkResponder:returnif "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:+ if "clipboard_image" not in link.caps or image is None or not protocol.png_fits(image):image = Noneif text is None and image is None:returndiff --git a/core/settings_sync.py b/core/settings_sync.pyindex 70f69f3..9fbe175 100644--- a/core/settings_sync.py+++ b/core/settings_sync.py@@ -240,7 +240,7 @@ def scope(page, who, on, own):def switch_note(who, on, peer_too_old):- """The note under Overview's Same on both machines switch."""+ """The note under Overview's Same on all machines switch; `who` names the machines it keeps in step with."""if peer_too_old:return f"{who}'s Beamer is too old to keep settings in step. Update it to turn this on."if on:diff --git a/core/tests/pngs.py b/core/tests/pngs.pynew file mode 100644index 0000000..53cddb6--- /dev/null+++ b/core/tests/pngs.py@@ -0,0 +1,82 @@+"""PNG files built byte by byte for the clipboard tests: the shape WIRE.md section 3 checks before+anything decodes an image. Only a 1 by 1 image carries pixels a decoder could draw.++The zlib streams are written here rather than by zlib.compress, whose output differs between zlib+builds (the Mac's and Windows' Pythons disagree), so the vectors made from these are the same+bytes on every machine."""++import struct+import zlib++from core import protocol+++def stored(data: bytes) -> bytes:+ """A zlib stream holding `data` in stored blocks: no compression, the same bytes everywhere."""+ blocks = [data[at:at + 65535] for at in range(0, len(data), 65535)] or [b""]+ body = b"".join(+ bytes([index == len(blocks) - 1]) + struct.pack("<HH", len(block), len(block) ^ 0xFFFF) + block+ for index, block in enumerate(blocks)+ )+ return b"\x78\x01" + body + struct.pack(">I", zlib.adler32(data))+++def run(byte: bytes, count: int) -> bytes:+ """A zlib stream inflating to `byte` repeated `count` times, about count / 258 bytes long: one+ fixed-Huffman block of the literal, then copies of 258 at distance 1, then literals."""+ bits, used, out = 0, 0, bytearray()++ def put(value, width):+ nonlocal bits, used+ bits |= value << used+ used += width+ while used >= 8:+ out.append(bits & 0xFF)+ bits >>= 8+ used -= 8++ def code(value, width):+ put(int(format(value, f"0{width}b")[::-1], 2), width)++ literal = byte[0]+ put(1, 1) # the last block+ put(1, 2) # fixed Huffman codes+ copies, rest = divmod(count - 1, 258)+ for _ in range(1 + rest if count else 0):+ code(0x30 + literal, 8) if literal < 144 else code(0x190 + literal - 144, 9)+ for _ in range(copies):+ code(0xC5, 8) # length 258 (code 285)+ code(0, 5) # distance 1+ code(0, 7) # end of block+ if used:+ out.append(bits & 0xFF)+ return b"\x78\x01" + bytes(out) + struct.pack(">I", zlib.adler32(byte * count))+++def chunk(kind: bytes, data: bytes) -> bytes:+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))+++def ihdr(width: int, height: int) -> bytes:+ return chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0))+++def png(width: int = 1, height: int = 1, *extra: bytes, header: bytes = None) -> bytes:+ """A PNG of `width` by `height` (8-bit RGBA), with the chunks in `extra` after its header."""+ pixels = stored(b"\x00" + b"\x00\x00\x00\x00") if (width, height) == (1, 1) else stored(b"")+ return (protocol.PNG_SIGNATURE + (ihdr(width, height) if header is None else header) + b"".join(extra)+ + chunk(b"IDAT", pixels) + chunk(b"IEND", b""))+++def ztxt(size: int, keyword: bytes = b"Comment") -> bytes:+ """A zTXt chunk whose text inflates to `size` bytes."""+ return chunk(b"zTXt", keyword + b"\x00\x00" + run(b"a", size))+++def iccp(size: int) -> bytes:+ return chunk(b"iCCP", b"Display P3\x00\x00" + run(b"p", size))+++def itxt(size: int, compressed: bool) -> bytes:+ text = run(b"x", size) if compressed else b"x" * size+ return chunk(b"iTXt", b"XML:com.adobe.xmp\x00" + bytes([int(compressed), 0]) + b"en\x00\x00" + text)diff --git a/core/tests/responder_harness.py b/core/tests/responder_harness.pyindex 156978e..2da3e5a 100644--- a/core/tests/responder_harness.py+++ b/core/tests/responder_harness.py@@ -166,6 +166,15 @@ class FakeClipboard:CAPS = ["clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings"]+def free_port():+ """A port nothing listens on now. A test's own settings use it, never Beamer's 24820, which the+ installed app on the same machine holds whenever it runs: a suite run while it was closed+ once took that port from it (01-10-2026)."""+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ return probe.getsockname()[1]++def wait_for(predicate, timeout=3.0):deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:@@ -188,7 +197,6 @@ class Machine:self.clipboard = FakeClipboard(events=self.events)self.away = awayself.statuses = []- self.notices = []self.owners = []self.arrivals = []self.pressures = []@@ -215,7 +223,6 @@ class Machine: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, [])),)diff --git a/core/tests/test_link.py b/core/tests/test_link.pyindex b07748c..6a30342 100644--- a/core/tests/test_link.py+++ b/core/tests/test_link.py@@ -3,6 +3,7 @@ LinkResponder on loopback (responder_harness.Machine) and a scripted responder wa peer that misbehaves."""import socket+import structimport threadingimport timeimport unittest@@ -26,7 +27,7 @@ class Side:self.settings.data["machine_id"] = protocol.id_text(own)self.own = ownself.book = receiver.PeerBook(self.settings.load, self.settings.save)- self.states, self.ups, self.messages, self.notices = [], [], [], []+ self.states, self.ups, self.messages = [], [], []def identity(self, **fields):data = {"id": self.own, "name": "Near", "platform": "macos", "app": "1.5.0", "caps": list(CAPS), "port": 24820}@@ -40,7 +41,6 @@ class Side: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@@ -131,15 +131,6 @@ class LinkHandshakeTests(unittest.TestCase):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"] = Falseside = Side(self.machine)@@ -161,6 +152,21 @@ class LinkHandshakeTests(unittest.TestCase):self.assertEqual(self.machine.links, [])self.assertFalse(link.live())+ def test_a_migrated_entry_is_never_dialled_whatever_its_token(self):+ for fields in ({"linked": False, "id": ""}, {"linked": True}):+ with self.subTest(fields=fields):+ side = Side(self.machine, from_1_4=True)+ side.peer().update(fields)+ now = [1000.0]+ link = self.start(side, clock=lambda: now[0])+ time.sleep(0.4)+ self.assertEqual(self.machine.links, [])+ self.assertFalse(link.live())+ now[0] += 60+ link.follow([{"name": "Far", "address": "127.0.0.2"}])+ self.assertIsNone(link._try_host)+ link.stop()+def test_send_off_is_not_dialled(self):side = Side(self.machine)side.peer()["send"] = False@@ -573,6 +579,38 @@ class LinkFollowTests(unittest.TestCase):link.follow(beacon)self.assertTrue(wait_for(lambda: ("192.168.77.9", 24820) in tried), tried)+ def test_a_beacon_that_names_another_machine_is_never_tried_and_one_at_its_address_is_tried_last(self):+ clock, tried = FakeClock(), []+ side, link = self.link(clock, tried)+ side.settings.data["peers"].append(entry(C, "Far", token=TOKENS[C], host="192.168.77.20", port=24820, send=True))+ link.start()+ self.assertTrue(wait_for(lambda: tried))+ beacons = [{"name": "Far", "address": "192.168.77.20"},+ {"name": "Far", "address": "192.168.77.21", "id": protocol.id_text(C)},+ {"name": "Far", "address": "192.168.77.22", "id": protocol.id_text(HERE)}]+ tried.clear()+ clock.now += 11+ link.follow(beacons)+ self.assertTrue(wait_for(lambda: ("192.168.77.22", 24820) in tried), tried)+ self.assertNotIn(("192.168.77.20", 24820), tried)+ # Two machines may have swapped addresses, so the other machine's saved one is still tried, last.+ clock.now += 31+ link.follow(beacons)+ self.assertTrue(wait_for(lambda: ("192.168.77.20", 24820) in tried), tried)+ self.assertNotIn(("192.168.77.21", 24820), tried)++ def test_several_beacons_with_the_name_are_tried_in_turn(self):+ clock, tried = FakeClock(), []+ side, link = self.link(clock, tried)+ link.start()+ self.assertTrue(wait_for(lambda: tried))+ beacons = [{"name": "Far", "address": "192.168.77.9"}, {"name": "Far", "address": "192.168.77.10"}]+ for address in ("192.168.77.9", "192.168.77.10", "192.168.77.9"):+ tried.clear()+ clock.now += 31+ link.follow(beacons)+ self.assertTrue(wait_for(lambda: (address, 24820) in tried), (address, tried))+def test_a_failed_try_shows_nothing_and_saves_nothing(self):clock, tried = FakeClock(), []side, link = self.link(clock, tried)@@ -624,23 +662,7 @@ class LinkTunnelTests(unittest.TestCase):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, [])-+class LinkHeldTests(unittest.TestCase):def test_held_us_is_taken_off_the_sample_and_never_goes_below_zero(self):def script(connection):session, hello = scripted_session(connection, TOKENS[B])@@ -740,7 +762,7 @@ class LinkReviewFindingsTests(unittest.TestCase):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.assertEqual((side.states, side.ups), (states, ups))self.assertFalse(link.running)before = server.connectionslink.start()@@ -912,6 +934,43 @@ class LinkFramingTests(unittest.TestCase):self.assertTrue(wait_for(lambda: side.messages), side.states)self.assertEqual(side.messages[0]["data"]["route"], 3)+ def test_a_frame_that_takes_longer_than_its_deadline_from_its_first_byte_ends_the_link(self):+ # A byte every tenth of a second keeps the link alive, so only the frame's own deadline,+ # counted from its first length byte, can end it.+ def after(connection, session):+ connection.sendall(struct.pack(">I", 1000))+ for _ in range(40):+ connection.sendall(b"\x00")+ time.sleep(0.1)++ with mock.patch.object(protocol, "FRAME_COMPLETE_SECONDS", 0.8):+ side, link = self.serve(after)+ self.assertTrue(wait_for(lambda: side.states and not side.states[-1][0], 3.0), side.states)+ self.assertIn("too long", side.last_text())+ self.assertEqual(side.messages, [])++ def test_a_frame_completed_after_its_deadline_is_not_dispatched(self):+ class Socket:+ def __init__(self, chunks):+ self.chunks = iter(chunks)++ def recv(self, size):+ return next(self.chunks)++ frame = struct.pack(">I", protocol.MIN_FRAME_BYTES) + bytes(protocol.MIN_FRAME_BYTES)+ sock = Socket((frame[:1], frame[1:], b""))+ times = iter((-1.0, 0.0, 0.25))+ link = OutboundLink("", None, lambda: {}, clock=lambda: next(times, 0.3))+ link._sock = sock+ session = mock.Mock()+ session.open_raw.return_value = b"{}"+ with mock.patch.object(protocol, "FRAME_COMPLETE_SECONDS", 0.2):+ with mock.patch.object(protocol, "parse_message", return_value={"type": "accept", "data": {}}):+ with mock.patch.object(link, "_deal") as deal:+ with self.assertRaisesRegex(link_module.LinkEnded, "took too long to send one message"):+ link._read(sock, session, "peer")+ deal.assert_not_called()+def test_two_frames_in_one_segment_are_two_messages(self):def after(connection, session):connection.sendall(session.seal(protocol.accept_msg(3)) + session.seal(protocol.accept_msg(4)))diff --git a/core/tests/test_owner.py b/core/tests/test_owner.pyindex 6b33952..9099c38 100644--- a/core/tests/test_owner.py+++ b/core/tests/test_owner.py@@ -5,7 +5,7 @@ the timers."""import unittestfrom core import owner-from core.owner import LOCAL, Moved, Send, SendClipboard, SetClipboard, Unreachable+from core.owner import LOCAL, Drop, Moved, Send, SendClipboard, SetClipboard, Unreachableclass Clock:@@ -344,12 +344,22 @@ class SwitchTests(OwnerCase):self.assertEqual(focuses(actions, "C"), [])def test_a_late_accept_is_let_go_naming_where_the_input_is_now(self):+ # A hand-over given up closes its link, so what is still let go late is a take from home+ # or from the owner's own shortcut, on a link that stayed up.+ self.take("B")+ self.o.go("C") # route 2, eager: B let go, C taken+ self.o.go("D") # route 3, before C answered: C let go, D taken+ self.assertEqual(sent(self.o.accept("C", {"route": 2})),+ [("C", {"type": "focus", "data": {"route": 3, "target": "D"}})])+ self.assertEqual(self.o.on, "D")++ def test_a_late_accept_on_a_link_closed_for_it_is_ignored(self):+ # Read before the link closed, and acted on after: the close already ended that ownership.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.assertIn(Drop("C"), self.o.tick())+ self.assertEqual(self.o.accept("C", {"route": 2}), [])self.assertEqual(self.o.on, "B")def test_a_late_accept_after_coming_home_names_the_owner(self):@@ -359,6 +369,48 @@ class SwitchTests(OwnerCase):self.assertEqual(sent(self.o.accept("C", {"route": 1})),[("C", {"type": "focus", "data": {"route": 2, "target": "A"}})])+ def test_an_abandoned_hand_over_closes_the_next_machines_link_before_the_input_goes_anywhere(self):+ # Its `accept` may still be on the way: closing the link is what ends an ownership nobody+ # will use, however late that accept is or however long the owner remembers the take.+ abandon = {+ "no answer": lambda: (setattr(self.clock, "now", 1001.0), self.o.tick())[1],+ "the shortcut home": lambda: self.o.go(None),+ "the shortcut to the machine it is on": lambda: self.o.go("B"),+ "the shortcut to a third machine": lambda: self.o.go("D"),+ "a send-home from the machine left": lambda: self.switch("B", "A", route=1),+ "the link to the machine left lost": lambda: self.o.link_down("B"),+ }+ for how, event in abandon.items():+ with self.subTest(how=how):+ self.setUp()+ self.take("B")+ self.switch("B", "C")+ actions = event()+ self.assertEqual([a for a in actions if isinstance(a, Drop)], [Drop("C")])+ self.assertIsInstance(actions[0], Drop)+ self.assertNotIn("C", self.o.reach_for(self.o.on))++ def test_a_hand_over_answered_or_already_gone_closes_nothing(self):+ answered = {+ "refused": lambda: self.o.refuse("C", {"route": 2, "why": "owned"}),+ "accepted": lambda: self.o.accept("C", {"route": 2}),+ "its link lost": lambda: self.o.link_down("C"),+ "taken again from here, on the same link": lambda: self.o.go("C"),+ }+ for how, event in answered.items():+ with self.subTest(how=how):+ self.setUp()+ self.take("B")+ self.switch("B", "C")+ self.assertEqual([a for a in event() if isinstance(a, Drop)], [])++ def test_a_take_from_home_with_no_answer_is_let_go_on_its_own_link_and_closes_nothing(self):+ self.o.go("C")+ self.clock.now = 1001.0+ actions = self.o.tick()+ self.assertEqual([a for a in actions if isinstance(a, Drop)], [])+ self.assertEqual(focuses(actions, "C"), [{"route": 2, "target": "A"}])+def test_an_accept_for_a_route_never_taken_there_is_ignored(self):self.take("B")self.switch("B", "C")@@ -388,7 +440,7 @@ class SwitchTests(OwnerCase):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"]}])+ {"route": 3, "target": "D", "resistance_px": 120, "reach": ["B"]}])self.assertEqual(sent(actions)[0][0], "B")self.o.accept("D", {"route": 3})self.clock.now = 1001.0@@ -402,7 +454,7 @@ class SwitchTests(OwnerCase):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"]}}),+ "reach": ["D"]}}),("B", MOVE),])self.clock.now = 1001.0diff --git a/core/tests/test_pairing_paths.py b/core/tests/test_pairing_paths.pynew file mode 100644index 0000000..bd880d6--- /dev/null+++ b/core/tests/test_pairing_paths.py@@ -0,0 +1,326 @@+"""Pairing over a machine with more than one way to the other (beta.4).++On 01-10-2026 the spare laptop took a VPN's subnet route for its own home network, so its UDP answer+left from the VPN's address rather than the Wi-Fi address the request had come in on, and the+requester, which took an answer only from the address it asked, ignored it: both directions said+"did not answer". Now the host answers from the address on the requester's own network where it has+one, and the requester takes an answer by its pairing id and its crypto, from any address.++The beacons' directed broadcasts used to assume a /24; they now follow each interface's netmask.+"""++import ipaddress+import socket+import threading+import unittest+from unittest import mock++from core import pairing+from core.pairing import PairingError++from .test_pairing_service import MAC_ID, PC_ID, Machine, free_port, wait_until+++def _can_bind(address):+ probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ probe.bind((address, 0))+ return True+ except OSError:+ return False+ finally:+ probe.close()+++class BroadcastTargetTests(unittest.TestCase):+ def test_each_interface_is_sent_the_broadcast_of_its_own_netmask(self):+ interfaces = [("192.168.1.20", "255.255.255.0"), ("169.254.3.7", "255.255.0.0"),+ ("10.1.2.5", "255.255.255.252"), ("172.20.9.9", "255.240.0.0")]+ self.assertEqual(pairing.broadcast_targets(47000, interfaces), [+ ("255.255.255.255", 47000), ("192.168.1.255", 47000), ("169.254.255.255", 47000),+ ("10.1.2.7", 47000), ("172.31.255.255", 47000),+ ])++ def test_two_addresses_on_one_network_send_it_one_broadcast(self):+ interfaces = [("192.168.1.20", "255.255.255.0"), ("192.168.1.21", "255.255.255.0")]+ self.assertEqual(pairing.broadcast_targets(1, interfaces), [("255.255.255.255", 1), ("192.168.1.255", 1)])++ def test_with_no_interfaces_known_it_falls_back_to_a_24(self):+ with mock.patch.object(pairing, "_local_ipv4_addresses", return_value=["10.9.8.7"]):+ self.assertEqual(pairing.broadcast_targets(1, []), [("255.255.255.255", 1), ("10.9.8.255", 1)])+++class InterfaceTests(unittest.TestCase):+ def test_this_machine_s_interfaces_are_read_with_real_netmasks(self):+ found = pairing._interfaces()+ if not found:+ self.skipTest("no IPv4 network here")+ for address, netmask in found:+ network = ipaddress.IPv4Network(f"{address}/{netmask}", strict=False)+ self.assertFalse(ipaddress.IPv4Address(address).is_loopback, address)+ self.assertLess(network.prefixlen, 31, (address, netmask))+ # Checked against the routing table, which knows nothing of how the list was read.+ routed = pairing.pairing_address()+ if routed is not None:+ self.assertIn(routed, [address for address, _netmask in found])++ def test_a_platform_that_will_not_say_gives_none(self):+ failing = mock.patch.object(pairing, "_posix_interfaces" if pairing.sys.platform != "win32" else "_windows_interfaces",+ side_effect=OSError("no"))+ with failing:+ self.assertEqual(pairing._interfaces(), [])+++class AnswerSourceTests(unittest.TestCase):+ INTERFACES = [("192.168.50.22", "255.255.255.0"), ("192.168.56.1", "255.255.255.0")]++ def test_a_requester_on_one_of_this_machine_s_networks_is_answered_from_that_network(self):+ source = pairing._answer_source("192.168.50.5", self.INTERFACES, towards=lambda host: "100.64.0.7")+ self.assertEqual(source, "192.168.50.22")++ def test_where_the_routing_table_agrees_nothing_changes(self):+ self.assertIsNone(pairing._answer_source("192.168.50.5", self.INTERFACES, towards=lambda host: "192.168.50.22"))++ def test_two_addresses_on_the_requester_s_network_leave_the_routing_table_s_choice_alone(self):+ interfaces = [("192.168.50.10", "255.255.255.0"), ("192.168.50.20", "255.255.255.0")]+ self.assertIsNone(pairing._answer_source("192.168.50.5", interfaces, towards=lambda host: "192.168.50.20"))+ self.assertEqual(pairing._answer_source("192.168.50.5", interfaces, towards=lambda host: "100.64.0.7"), "192.168.50.10")++ def test_a_requester_on_no_network_of_this_machine_s_is_routed_as_ever(self):+ self.assertIsNone(pairing._answer_source("203.0.113.9", self.INTERFACES, towards=lambda host: "100.64.0.7"))+ self.assertIsNone(pairing._answer_source("not an address", self.INTERFACES, towards=lambda host: "x"))+++class RequesterTakesAnAnswerFromAnyAddressTests(unittest.TestCase):+ def setUp(self):+ mac_udp, pc_udp = free_port(socket.SOCK_DGRAM), free_port(socket.SOCK_DGRAM)+ self.mac = Machine(self, "Loop Mac", MAC_ID, "macos", peer_udp=pc_udp, udp_port=mac_udp)+ self.pc = Machine(self, "Loop PC", PC_ID, "windows", peer_udp=mac_udp, udp_port=pc_udp)++ def _answer_from(self, address):+ """The PC's answers leave from `address`, as a VPN's route sent the laptop's."""+ out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ out.bind((address, 0))+ self.addCleanup(out.close)+ sent = []++ def answer(sock, data, to):+ sent.append(to)+ out.sendto(data, to)++ self.pc.service._answer = answer+ return sent++ def _pair(self):+ code = self.pc.service.begin_pairing()+ self.assertTrue(wait_until(lambda: any(m["pair_id"] for m in self.mac.service.machines())))+ seen = [m for m in self.mac.service.machines() if m["pair_id"]][0]+ return seen, code++ def test_an_answer_from_another_address_still_pairs(self):+ # macOS's loopback holds 127.0.0.1 alone; a LAN address reaches it as well.+ stand_in = "127.0.0.2" if _can_bind("127.0.0.2") else pairing.pairing_address()+ if stand_in is None:+ self.skipTest("no second address to answer from")+ sent = self._answer_from(stand_in)+ seen, code = self._pair()+ saved = self.mac.service.pair(seen, code)+ self.assertTrue(sent, "the PC answered through the stand-in")+ self.assertEqual(saved["host"], "127.0.0.1", "the entry keeps the address the beacon came from")+ self.assertTrue(wait_until(lambda: self.pc.paired))+ self.assertEqual(self.pc.paired[0]["token"], saved["token"])++ def test_an_answer_for_another_pairing_id_is_not_taken(self):+ service = self.mac.service+ service._awaiting = "ours"+ for message in ({"type": "pair_answer", "pair": "theirs"}, {"type": "pair_answer"}):+ service._dispatch(None, message, ("192.0.2.9", 1), 0.0, {}, {})+ self.assertTrue(service._replies.empty())+ service._dispatch(None, {"type": "pair_answer", "pair": "ours"}, ("192.0.2.9", 1), 0.0, {}, {})+ self.assertEqual(service._replies.get_nowait()[1], ("192.0.2.9", 1))++ def test_nothing_is_taken_while_no_attempt_is_under_way(self):+ service = self.mac.service+ service._dispatch(None, {"type": "pair_answer"}, ("192.0.2.9", 1), 0.0, {}, {})+ service._dispatch(None, {"type": "pair_answer", "pair": None}, ("192.0.2.9", 1), 0.0, {}, {})+ self.assertTrue(service._replies.empty())++ def _forge(self, forged):+ """Each reply in `forged`, by type, reaches the requester from a stranger's address just+ before the host's own."""+ service = self.mac.service+ real_ask = service._ask++ def ask(send, receive, target, pair_id, message, reply_type, proves=None):+ for reply in forged.get(reply_type, ()):+ service._replies.put((dict(reply, pair=pair_id), ("192.0.2.9", 4)))+ return real_ask(send, receive, target, pair_id, message, reply_type, proves)++ service._ask = ask++ def test_forged_answers_from_another_address_lose_to_the_host_s_own(self):+ seen, code = self._pair()+ good = {"type": "pair_answer", "ok": True, "share": pairing._b64(bytes(32)), "tag": pairing._b64(bytes(32)),+ "id": pairing._b64(PC_ID), "name": "Loop PC", "platform": "windows", "port": 24820}+ self._forge({"pair_answer": [good, {"type": "pair_answer", "ok": False, "error": "refused"}]})+ saved = self.mac.service.pair(seen, code)+ self.assertNotIn(code, self.mac.service._failed, "no forgery was judged")+ self.assertTrue(wait_until(lambda: self.pc.paired))+ self.assertEqual(self.pc.paired[0]["token"], saved["token"])++ def test_a_forged_receipt_from_any_address_leaves_no_half_pairing(self):+ seen, code = self._pair()+ self._forge({"pair_done": [{"type": "pair_done", "ok": True, "tag": pairing._b64(bytes(32))},+ {"type": "pair_done", "ok": True, "tag": "not base64!"}]})+ saved = self.mac.service.pair(seen, code)+ self.assertEqual(len(self.mac.book.entries), 1)+ self.assertTrue(wait_until(lambda: self.pc.paired))+ self.assertEqual(self.pc.paired[0]["token"], saved["token"])++ def test_with_nothing_from_the_host_a_refusal_from_elsewhere_still_ends_the_attempt(self):+ service = self.mac.service+ service.clock = iter(range(0, 10**6, 1)).__next__+ replies = iter([({"type": "pair_answer", "pair": "p", "ok": False, "error": "busy"}, ("192.0.2.9", 4)), None])+ reply = service._ask(lambda data: None, lambda timeout: next(replies, None), ("127.0.0.1", 1), "p",+ {"type": "pair_start"}, "pair_answer")+ self.assertEqual(reply["error"], "busy")+++class AskTests(unittest.TestCase):+ """_ask on its own, with replies handed in as they would arrive."""++ TARGET = ("192.168.50.3", 47000)+ ELSEWHERE = ("192.0.2.9", 4)++ def ask(self, arrivals, reply_type="pair_answer", proves=None, windows=None):+ """`arrivals`: per window, the (reply, address) pairs that come in it; the window then ends."""+ service = pairing.Discovery(logger=None)+ now = [0.0]+ service.clock = lambda: now[0]+ windows = [list(window) for window in arrivals]+ queued = []++ def send(data):+ if windows:+ queued.extend(windows.pop(0))++ def receive(timeout):+ if queued:+ return queued.pop(0)+ now[0] += timeout+ return None++ return service._ask(send, receive, self.TARGET, "p", {"type": "pair_start"}, reply_type, proves)++ def reply(self, ok=True, **fields):+ return dict({"type": "pair_answer", "pair": "p", "ok": ok}, **fields)++ def test_the_asked_address_wins_even_when_its_reply_is_queued_behind_the_window_s_end(self):+ service = pairing.Discovery(logger=None)+ now = [0.0]+ service.clock = lambda: now[0]+ queued = [(self.reply(name="forged"), self.ELSEWHERE), (self.reply(name="real"), self.TARGET)]++ def receive(timeout):+ # The forgery is read just as the window closes; the real answer is already waiting.+ now[0] += pairing.PAIR_REPLY_TIMEOUT_SECONDS+ return queued.pop(0) if queued else None++ reply = service._ask(lambda data: None, receive, self.TARGET, "p", {"type": "pair_start"}, "pair_answer")+ self.assertEqual(reply["name"], "real")++ def test_with_nothing_from_the_asked_address_an_ok_reply_from_elsewhere_beats_a_refusal(self):+ reply = self.ask([[(self.reply(ok=False, error="busy"), self.ELSEWHERE), (self.reply(name="ok"), self.ELSEWHERE)]])+ self.assertEqual(reply["name"], "ok")++ def test_only_the_first_of_each_kind_from_elsewhere_is_kept(self):+ flood = [(self.reply(name=str(n)), self.ELSEWHERE) for n in range(500)]+ reply = self.ask([flood])+ self.assertEqual(reply["name"], "0")++ def test_a_bad_receipt_from_elsewhere_is_ignored_and_one_from_the_asked_address_decides(self):+ done = lambda ok=True, tag="bad": {"type": "pair_done", "pair": "p", "ok": ok, "tag": tag}+ proves = lambda reply: reply["tag"] == "good"+ reply = self.ask([[(done(), self.ELSEWHERE), (done(tag="good"), self.ELSEWHERE)]], "pair_done", proves)+ self.assertEqual(reply["tag"], "good")+ reply = self.ask([[(done(), self.TARGET), (done(tag="good"), self.ELSEWHERE)]], "pair_done", proves)+ self.assertEqual(reply["tag"], "bad", "the asked address decides, and finish() refuses it")+ with self.assertRaises(PairingError):+ self.ask([[(done(), self.ELSEWHERE)], [], []], "pair_done", proves)+++class ReceiveTests(unittest.TestCase):+ class Socket:+ def __init__(self, error):+ self.error = error++ def settimeout(self, timeout):+ pass++ def recvfrom(self, size):+ raise self.error++ def test_an_oversized_datagram_on_windows_is_passed_over(self):+ error = OSError(10040, "message too long")+ error.winerror = 10040+ self.assertEqual(pairing._receive_on(self.Socket(error), 1.0), ({}, ("", 0)))++ def test_any_other_failure_ends_the_attempt_as_no_answer(self):+ with self.assertRaises(PairingError) as caught:+ pairing._receive_on(self.Socket(OSError(9, "bad file descriptor")), 1.0)+ self.assertEqual(str(caught.exception), "no_answer")+++class OversizedDatagramTests(unittest.TestCase):+ def test_a_datagram_too_large_for_the_buffer_does_not_stop_the_service(self):+ mac_udp, pc_udp = free_port(socket.SOCK_DGRAM), free_port(socket.SOCK_DGRAM)+ mac = Machine(self, "Loop Mac", MAC_ID, "macos", peer_udp=pc_udp, udp_port=mac_udp)+ Machine(self, "Loop PC", PC_ID, "windows", peer_udp=mac_udp, udp_port=pc_udp)+ self.assertTrue(wait_until(lambda: mac.service.machines()))+ stranger = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ self.addCleanup(stranger.close)+ for _ in range(3):+ stranger.sendto(b"x" * 4000, ("127.0.0.1", mac_udp))+ mac.service._seen.clear()+ self.assertTrue(wait_until(lambda: mac.service.machines()), "the PC's beacons are still heard")+ self.assertIsNone(mac.service.error)+++class HostAnswersFromTheRequesterSNetworkTests(unittest.TestCase):+ def test_both_ends_send_from_the_address_on_the_other_s_network(self):+ mac_udp, pc_udp = free_port(socket.SOCK_DGRAM), free_port(socket.SOCK_DGRAM)+ mac = Machine(self, "Loop Mac", MAC_ID, "macos", peer_udp=pc_udp, udp_port=mac_udp)+ pc = Machine(self, "Loop PC", PC_ID, "windows", peer_udp=mac_udp, udp_port=pc_udp)+ sent = {}+ real_sendto = socket.socket.sendto++ def sendto(sock, data, address):+ result = real_sendto(sock, data, address)+ kind = (pairing.decode(data) or {}).get("type")+ if kind in ("pair_start", "pair_confirm", "pair_answer", "pair_done"):+ sent.setdefault(kind, []).append((sock.getsockname(), address))+ return result++ code = pc.service.begin_pairing()+ self.assertTrue(wait_until(lambda: any(m["pair_id"] for m in mac.service.machines())))+ seen = [m for m in mac.service.machines() if m["pair_id"]][0]+ # Each machine's routing table would send to 127.0.0.1 from elsewhere; its loopback holds it.+ with mock.patch.object(pairing, "_interfaces", return_value=[("127.0.0.1", "255.0.0.0")]), \+ mock.patch.object(pairing, "local_address_towards", return_value="192.0.2.1"), \+ mock.patch.object(socket.socket, "sendto", sendto):+ saved = mac.service.pair(seen, code)+ (start_from, start_to), = sent["pair_start"][:1]+ self.assertEqual(start_to, ("127.0.0.1", pc_udp))+ self.assertEqual(start_from[0], "127.0.0.1")+ self.assertNotEqual(start_from[1], mac_udp, "the request went on a socket of its own")+ self.assertEqual({source for source, _to in sent["pair_confirm"]}, {start_from})+ for kind in ("pair_answer", "pair_done"):+ for (address, port), to in sent[kind]:+ self.assertEqual((address, to), ("127.0.0.1", start_from), kind)+ self.assertNotEqual(port, pc_udp, "never bound beside the main socket, whose datagrams it could take")+ self.assertTrue(wait_until(lambda: pc.paired))+ self.assertEqual(pc.paired[0]["token"], saved["token"])+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_pairing_service.py b/core/tests/test_pairing_service.pyindex 6fa0bd3..6ff5f8d 100644--- a/core/tests/test_pairing_service.py+++ b/core/tests/test_pairing_service.py@@ -199,8 +199,15 @@ class BeaconTests(unittest.TestCase):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)+ while True:+ try:+ old.recvfrom(2048)+ except socket.timeout:+ break+ except ConnectionResetError:+ # Windows: the port-unreachable of a beacon sent before the service had bound.+ continue+ self.fail("the older machine was sent something")class TcpTests(unittest.TestCase):diff --git a/core/tests/test_pairing_v3.py b/core/tests/test_pairing_v3.pyindex 6fffb43..a6d96b1 100644--- a/core/tests/test_pairing_v3.py+++ b/core/tests/test_pairing_v3.py@@ -434,14 +434,29 @@ class MigratedEntryTests(unittest.TestCase):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")]))+ def test_a_machine_elsewhere_replaces_it_only_by_the_name_and_platform_it_proves(self):+ # The machine's address changed since 1.4.x. A migrated entry never links, so taking it by a+ # name anyone could claim costs nothing that works; left, it would ask to be paired again+ # beside the pairing just made.+ for name, platform, replaced in (("Requester Mac", "macos", True), ("Other Mac", "macos", False),+ ("Requester Mac", "windows", False)):+ with self.subTest(name=name, platform=platform):+ old = dict(migrated(host="192.168.77.99", name=name), platform=platform)+ rig = Rig(host_book=Book([old]))+ rig.begin()+ rig.exchange(address="192.168.77.5")+ ids = sorted(e["id"] for e in rig.host_book.entries)+ self.assertEqual(ids, [b64(REQUESTER_ID)] if replaced else ["", b64(REQUESTER_ID)])++ def test_one_an_earlier_beta_linked_is_replaced_by_its_own_id_wherever_it_now_is(self):+ # Betas 1 and 2 let a migrated token link and learn its peer's id. It never links now, so+ # pairing that machine again replaces it rather than refusing it as known.+ linked = dict(migrated(host="192.168.77.99"), id=b64(REQUESTER_ID), linked=True)+ rig = Rig(host_book=Book([linked]))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])+ self.assertEqual([(e["id"], e["from_1_4"]) for e in rig.host_book.entries], [(b64(REQUESTER_ID), False)])+ self.assertEqual(rig.host_book.stored[-1][1]["from_1_4"], True)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")])diff --git a/core/tests/test_peerlist.py b/core/tests/test_peerlist.pyindex af5931a..c4332e3 100644--- a/core/tests/test_peerlist.py+++ b/core/tests/test_peerlist.py@@ -59,10 +59,44 @@ class AddPeerTests(unittest.TestCase):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"}])+ def test_a_machine_paired_crosses_by_its_whole_edge_until_its_ways_are_chosen(self):+ # Pairing made no zones before beta.5, so a second machine's side, once set, led nowhere+ # (the rig and the laptop, 01-10-2026).+ held = settings(peer(A, side="left"), zones=[{"peer": A, "kind": "edge"}])+ peerlist.add_peer(held, peer(B, token="second"))+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])++ def test_the_replaced_entrys_zones_go_with_it_when_it_was_matched_by_name_alone(self):+ held = settings(peer("", token="legacy", host="10.1.1.9", from_1_4=True), zones=[{"peer": "", "kind": "edge"}])peerlist.add_peer(held, peer(A), replaced=copy.deepcopy(held["peers"][0]))- self.assertEqual(held["zones"], [])+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"}])++ def test_the_machine_at_the_1_4_entrys_host_takes_over_its_side_and_zones(self):+ # Every 1.4.x upgrader pairs again (no token migrates), and the user is at the screen+ # pairing that machine on purpose: its arrangement is not theirs to set a second time.+ old = peer("", token="legacy", from_1_4=True, linked=False, side="left", side_set_at=1_790_000_000,+ side_by=C, paired_at=0)+ held = settings(old, zones=[{"peer": "", "kind": "edge"}, {"peer": "", "kind": "corner", "corner": "top_left",+ "edge": "left", "off": True}])+ peerlist.add_peer(held, peer(A, token="fresh"), replaced=copy.deepcopy(old))+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"},+ {"peer": A, "kind": "corner", "corner": "top_left", "edge": "left", "off": True}])+ entry = held["peers"][0]+ self.assertEqual((entry["side"], entry["side_set_at"], entry["side_by"]), ("left", 1_790_000_000, C))+ self.assertEqual(entry["token"], "fresh")++ def test_a_machine_at_that_host_of_another_platform_takes_nothing(self):+ old = peer("", token="legacy", platform="macos", from_1_4=True, side="left")+ held = settings(old, zones=[{"peer": "", "kind": "edge"}])+ peerlist.add_peer(held, peer(A, token="fresh"), replaced=copy.deepcopy(old))+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"}])+ self.assertEqual(held["peers"][0]["side"], "")++ def test_an_entry_that_is_not_the_1_4_one_gives_nothing_by_host(self):+ old = peer(B, token="legacy", linked=False, side="left")+ held = settings(old, zones=[{"peer": B, "kind": "edge"}])+ peerlist.add_peer(held, peer(A, token="fresh"), replaced=copy.deepcopy(old))+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"}])def test_zones_of_a_machine_paired_again_under_its_own_id_stay(self):held = settings(peer(A, linked=False), zones=[{"peer": A, "kind": "edge"}])@@ -73,7 +107,7 @@ class AddPeerTests(unittest.TestCase):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"}])+ self.assertEqual(held["zones"], [{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])def test_an_entry_replaced_by_token_is_found_though_the_caller_holds_a_copy(self):held = settings(peer(A, token="one"))@@ -170,5 +204,15 @@ class LabelForTests(unittest.TestCase):self.assertEqual(peerlist.label_for([], peer_id="nope"), "")+class SharingANameTests(unittest.TestCase):+ def test_names_are_compared_as_labels_compares_them(self):+ machines = [{"name": " Studio "}, {"name": "studio"}, {"name": "Other"}]+ self.assertEqual(peerlist.sharing_a_name(machines), [True, True, False])++ def test_a_lone_machine_shares_with_nobody(self):+ self.assertEqual(peerlist.sharing_a_name([{"name": "Studio"}]), [False])+ self.assertEqual(peerlist.sharing_a_name([]), [])++if __name__ == "__main__":unittest.main()diff --git a/core/tests/test_protocol_v6.py b/core/tests/test_protocol_v6.pyindex 00d68e8..3291191 100644--- a/core/tests/test_protocol_v6.py+++ b/core/tests/test_protocol_v6.py@@ -16,10 +16,12 @@ import structimport threadingimport timeimport unittest+import zlibfrom nacl.bindings import crypto_aead_chacha20poly1305_ietf_decryptfrom core import protocol+from core.tests import pngsTOKEN = base64.urlsafe_b64encode(bytes(range(32))).decode("ascii").rstrip("=")OTHER_TOKEN = base64.urlsafe_b64encode(bytes(range(1, 33))).decode("ascii").rstrip("=")@@ -118,6 +120,17 @@ class Tokens(unittest.TestCase):self.assertEqual(protocol.key_id(token), _key_id(token))self.assertNotEqual(protocol.key_id(TOKEN), protocol.key_id(OTHER_TOKEN))+ def test_only_an_entry_made_by_pairing_links(self):+ # 43 "A"s spell 32 zero bytes in the one spelling: the encoding proves nothing about where a+ # token came from, and 1.4.x kept no record of whether its token was paired or typed.+ zeros = "A" * 43+ self.assertTrue(protocol.is_paired_token(zeros))+ self.assertTrue(protocol.linkable({"token": TOKEN, "from_1_4": False}))+ for entry in ({"token": zeros, "from_1_4": True}, {"token": TOKEN, "from_1_4": True}, {"token": "hunter2", "from_1_4": False},+ {"from_1_4": False}, None):+ with self.subTest(entry=entry):+ self.assertFalse(protocol.linkable(entry))+def test_a_typed_token_has_no_key_id_and_no_session(self):with self.assertRaises(ValueError):protocol.key_id("hunter2")@@ -693,9 +706,80 @@ class Input(unittest.TestCase):self.assertEqual(protocol.read_input({"type": "text", "data": {"text": "é" * 2048, "seq": 9}})["text"], "é" * 2048)+class ClipboardImages(unittest.TestCase):+ """An image's size in pixels and its inflated metadata are bounded from its bytes before anything+ decodes it (WIRE.md section 3): a PNG of a few megabytes can otherwise decode to gigabytes."""++ def test_screens_up_to_8k_fit(self):+ for width, height in ((1, 1), (6016, 3384), (7680, 4320), (16384, 2048), (2048, 16384)):+ with self.subTest(size=(width, height)):+ self.assertTrue(protocol.png_fits(pngs.png(width, height)))++ def test_a_side_over_16384_or_more_than_2_to_the_25_pixels_does_not(self):+ for width, height in ((16385, 1), (1, 16385), (0, 1), (1, 0), (6000, 6000), (16384, 16384), (2**31 - 1, 1)):+ with self.subTest(size=(width, height)):+ self.assertFalse(protocol.png_fits(pngs.png(width, height)))++ def test_the_header_must_come_first_and_be_whole(self):+ self.assertFalse(protocol.png_fits(protocol.PNG_SIGNATURE + pngs.chunk(b"tEXt", b"a\x00b") + pngs.ihdr(1, 1)))+ self.assertFalse(protocol.png_fits(pngs.png(header=pngs.chunk(b"IHDR", bytes(12)))))+ self.assertFalse(protocol.png_fits(protocol.PNG_SIGNATURE))+ self.assertFalse(protocol.png_fits(protocol.PNG_SIGNATURE + b"\x00" * 64))+ self.assertFalse(protocol.png_fits(b"GIF89a" + pngs.png()[8:]))++ def test_a_chunk_that_runs_past_the_end_does_not(self):+ whole = pngs.png()+ self.assertFalse(protocol.png_fits(whole[:-5]))+ self.assertFalse(protocol.png_fits(whole[:33] + struct.pack(">I", 10**6) + whole[37:]))++ def test_metadata_inflates_to_at_most_4_mib_in_all(self):+ limit = protocol.PNG_METADATA_MAX_BYTES+ self.assertEqual(limit, 4 * 1024 * 1024)+ self.assertTrue(protocol.png_fits(pngs.png(64, 64, pngs.iccp(600_000), pngs.ztxt(limit - 600_000))))+ for extra in ((pngs.ztxt(limit + 1),), (pngs.iccp(limit + 1),), (pngs.itxt(limit + 1, compressed=True),),+ (pngs.iccp(limit // 2), pngs.ztxt(limit // 2), pngs.ztxt(1))):+ with self.subTest(chunks=[c[4:8] for c in extra]):+ self.assertFalse(protocol.png_fits(pngs.png(64, 64, *extra)))+ # Uncompressed text is bounded by the file itself.+ self.assertTrue(protocol.png_fits(pngs.png(64, 64, pngs.itxt(limit + 1, compressed=False))))++ def test_metadata_that_does_not_inflate_does_not_fit(self):+ stream = zlib.compress(b"a" * 1000)+ for data in (b"not zlib at all", stream[:-6], stream + b"junk"):+ with self.subTest(data=data[:8]):+ self.assertFalse(protocol.png_fits(pngs.png(8, 8, pngs.chunk(b"zTXt", b"Comment\x00\x00" + data))))+ self.assertFalse(protocol.png_fits(pngs.png(8, 8, pngs.chunk(b"iTXt", b"Key\x00\x02\x00en\x00\x00text"))))++ def test_compressed_text_needs_a_whole_zlib_stream_even_when_empty(self):+ for chunk in (+ pngs.chunk(b"zTXt", b"Comment\x00\x00"),+ pngs.chunk(b"iTXt", b"Key\x00\x01\x00en\x00\x00"),+ pngs.chunk(b"zTXt", b"Comment\x00\x00" + pngs.run(b"a", 1)[:-1]),+ ):+ with self.subTest(kind=chunk[4:8], data_length=len(chunk) - 12):+ self.assertFalse(protocol.png_fits(pngs.png(8, 8, chunk)))+ self.assertTrue(protocol.png_fits(pngs.png(8, 8, pngs.chunk(b"iTXt", b"Key\x00\x00\x00en\x00\x00"))))++ def test_a_clipboard_image_is_a_still_with_one_header(self):+ # A second IHDR or an animation's frames would claim sizes the first header never checked.+ for extra in (pngs.ihdr(100000, 100000), pngs.chunk(b"acTL", bytes(8)),+ pngs.chunk(b"fcTL", struct.pack(">IIIII", 0, 60000, 60000, 0, 0) + bytes(6)),+ pngs.chunk(b"fdAT", bytes(8))):+ with self.subTest(chunk=extra[4:8]):+ self.assertFalse(protocol.png_fits(pngs.png(8, 8, extra)))++ def test_bytes_after_iend_are_ignored(self):+ self.assertTrue(protocol.png_fits(pngs.png() + b"trailing"))++ def test_only_the_image_part_of_a_clipboard_is_dropped(self):+ for image in (pngs.png(16385, 1), pngs.png(8, 8, pngs.ztxt(5 * 1024 * 1024))):+ with self.subTest(size=len(image)):+ self.assertEqual(protocol.read_clipboard(protocol.clipboard_msg(text="hi", image=image)), {"text": "hi", "image": None})++class Others(unittest.TestCase):def test_clipboard(self):- png = protocol.PNG_SIGNATURE + b"x"+ png = pngs.png()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)}})@@ -719,6 +803,21 @@ class Others(unittest.TestCase):self.assertIsNotNone(protocol.read_arrangement_v6({"type": "arrangement", "data": {"edge": "top", "set_at": now + 86400, "by": protocol.id_text(ID_A)}}, now))+ def test_arrangement_way_back(self):+ now = 1_790_000_000+ for way_back in (True, False):+ message = protocol.arrangement_v6("left", now, ID_A, way_back=way_back)+ self.assertIs(message["data"]["way_back"], way_back)+ self.assertEqual(protocol.read_arrangement_v6(message, now),+ {"edge": "left", "set_at": now, "by": ID_A, "way_back": way_back})+ self.assertNotIn("way_back", protocol.arrangement_v6("left", now, ID_A)["data"])+ # Anything but a boolean is left out, and the side it came with still stands.+ for odd in (1, "false", None, [True]):+ data = {"edge": "left", "set_at": now, "by": protocol.id_text(ID_A), "way_back": odd}+ with self.subTest(way_back=odd):+ self.assertEqual(protocol.read_arrangement_v6({"type": "arrangement", "data": data}, now),+ {"edge": "left", "set_at": now, "by": ID_A})+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([])), [])diff --git a/core/tests/test_responder_handshake.py b/core/tests/test_responder_handshake.pyindex 4930647..d313a57 100644--- a/core/tests/test_responder_handshake.py+++ b/core/tests/test_responder_handshake.py@@ -8,7 +8,6 @@ import osimport selectimport socketimport struct-import threadingimport timeimport unittestfrom unittest import mock@@ -16,7 +15,7 @@ from unittest import mockfrom core import protocol, receiverfrom core.tests import v5_linkfrom core.tests.responder_harness import (- B, C, D, HERE, TOKENS, Initiator, Machine, entry, ident, silent_close, token, wait_for,+ B, C, D, HERE, TOKENS, Initiator, Machine, entry, silent_close, token, wait_for,)@@ -163,155 +162,17 @@ class TheMigratedEntry(Case):def migrated(self):return self.machine.settings.peer(token(50))- def test_its_first_link_learns_the_id_and_rewrites_its_zones(self):+ def test_its_token_is_never_matched_however_it_is_spelled(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.assertTrue(silent_close(link.sock))self.assertEqual(self.migrated()["id"], "")+ self.assertFalse(self.migrated()["linked"])- 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)+ def test_nor_once_an_earlier_beta_linked_it(self):+ # Betas 1 and 2 let a migrated token link and learn its peer's id.+ self.migrated().update(id=protocol.id_text(B), linked=True)+ link = self.initiator(peer=B, key=token(50))+ self.assertTrue(silent_close(link.sock))class TheIdsInHello(Case):diff --git a/core/tests/test_responder_input.py b/core/tests/test_responder_input.pyindex 2a2b47c..7ac0d0a 100644--- a/core/tests/test_responder_input.py+++ b/core/tests/test_responder_input.py@@ -8,6 +8,7 @@ import unittestfrom unittest import mockfrom core import protocol, receiver+from core.tests import pngsfrom core.tests.responder_harness import B, C, TOKENS, Initiator, Machine, entry, wait_for@@ -132,7 +133,7 @@ class WithoutCapabilities(Case):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))+ link.send(protocol.clipboard_msg("words", pngs.png()))self.assertTrue(wait_for(lambda: self.machine.clipboard.set_calls == [("words", None)]))diff --git a/core/tests/test_responder_ported.py b/core/tests/test_responder_ported.pyindex f5b0b99..42e1f79 100644--- a/core/tests/test_responder_ported.py+++ b/core/tests/test_responder_ported.py@@ -12,14 +12,25 @@ import unittestfrom unittest import mockfrom core import protocol, receiver+from core.tests import pngsfrom core.receiver import ServerStatefrom core.tests.responder_harness import (B, C, HERE, TOKENS, Initiator, Machine, entry, ident, silent_close, wait_for,)-from core.tests.test_responder_handshake import SlotPerConnectionACCEPT, ACK, SWITCH, CLIPBOARD = protocol.MSG_ACCEPT, protocol.MSG_ACK, protocol.MSG_SWITCH, protocol.MSG_CLIPBOARD-PNG = protocol.PNG_SIGNATURE + b"\x00" * 64+PNG = pngs.png()+++class SlotPerConnection(receiver.HandshakeSlots):+ """Slots keyed by connection, for tests that need several handshakes at once from loopback's+ one address."""++ def take(self, host, connection):+ return super().take((host, id(connection)), connection)++ def free(self, host, connection):+ super().free((host, id(connection)), connection)class Case(unittest.TestCase):@@ -205,6 +216,11 @@ class TheClipboardOnLettingGo(Case):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_an_image_too_large_to_decode_is_dropped_and_the_text_kept(self):+ link = self.link()+ self.visit(link, "shot.png", pngs.png(16384, 16384))+ 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))diff --git a/core/tests/test_responder_races.py b/core/tests/test_responder_races.pyindex 8a0125c..f4d0e4f 100644--- a/core/tests/test_responder_races.py+++ b/core/tests/test_responder_races.py@@ -3,13 +3,15 @@ Opus as an attacker, and Gemini 3.1 Pro on the handshake), written before its fiimport osimport socket+import structimport threadingimport timeimport unittestfrom unittest import mockfrom core import protocol, receiver-from core.tests.responder_harness import B, C, TOKENS, Initiator, Machine, entry, token, wait_for+from core.tests import pngs+from core.tests.responder_harness import B, C, TOKENS, Initiator, Machine, entry, wait_forACCEPT, REFUSE = protocol.MSG_ACCEPT, protocol.MSG_REFUSE@@ -64,26 +66,6 @@ class TheClipboardAndTheOwnerCallbacks(Case):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):@@ -95,7 +77,7 @@ class ALargeFrameToASlowReader(Case):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.image = pngs.png(64, 64, pngs.chunk(b"tEXt", b"noise\x00" + os.urandom(3_000_000)))self.machine.clipboard.stamp += 1b.send(protocol.focus_v6(2, B))received, started = 0, time.monotonic()@@ -114,6 +96,27 @@ class ALargeFrameToASlowReader(Case):self.assertIn(B, self.machine.responder.links())+class AFrameThatNeverFinishes(Case):+ def test_a_frame_still_arriving_past_its_deadline_from_its_first_byte_ends_the_link(self):+ # A byte every tenth of a second keeps the link alive, so only the frame's own deadline,+ # counted from its first length byte, can end it.+ with mock.patch.object(protocol, "FRAME_COMPLETE_SECONDS", 0.8):+ b = Initiator(self.machine, B)+ self.addCleanup(b.close)+ b.handshake()+ self.assertTrue(wait_for(lambda: B in self.machine.responder.links()))+ started = time.monotonic()+ b.sock.sendall(struct.pack(">I", 1000))+ while B in self.machine.responder.links() and time.monotonic() - started < 3:+ try:+ b.sock.sendall(b"\x00")+ except OSError:+ break+ time.sleep(0.1)+ self.assertNotIn(B, self.machine.responder.links())+ self.assertLess(time.monotonic() - started, 2.0)++def receiver_id(machine):return machine.responder._identity()["id"]diff --git a/core/tests/test_settings_sync.py b/core/tests/test_settings_sync.pyindex a5d1658..d55eba7 100644--- a/core/tests/test_settings_sync.py+++ b/core/tests/test_settings_sync.py@@ -1,4 +1,4 @@-"""Same on both machines, without AppKit or Qt: the message, the merge and the window's words."""+"""Same on all machines, without AppKit or Qt: the message, the merge and the window's words."""import base64import unittestdiff --git a/core/tests/test_three_desks.py b/core/tests/test_three_desks.pynew file mode 100644index 0000000..57d794c--- /dev/null+++ b/core/tests/test_three_desks.py@@ -0,0 +1,310 @@+"""Three desktops over real sockets on loopback, each its own owner and its own responder, paired as a+full mesh (WIRE.md sections 4, 5 and 8): in a row and in an L, every border crossed both ways with+the keyboard on each machine in turn, a chain out and back, and a machine dropping in the middle of+one. A machine's own pointer crosses by core/receiver.zone_models, the models the PC's sender uses;+a driven pointer crosses by the responder's zones and a `switch`, all core/owner.py's decisions."""++import time+import unittest++from core import owner as owner_module+from core import protocol+from core import receiver+from core import return_edge+from core import ways+from core.tests.responder_harness import Machine, entry, ident, wait_for+from core.tests.test_three_machines import NAMES, ScriptedOwner, key, moves, text++A, B, C = ident(190), ident(220), ident(250)+POINT = {"left": (0, 540), "right": (1919, 540), "top": (960, 0), "bottom": (960, 1079)}+PUSH = {"left": (-200, 0), "right": (200, 0), "top": (0, -200), "bottom": (0, 200)}+++class Desk:+ """One desktop: `machine` is its responder (what drives it from elsewhere lands there, and its+ screen), `owner` its own keyboard and mouse, linked to the other two."""++ def __init__(self, test, own, sides, zones):+ self.own = own+ self.machine = Machine(+ [entry(peer, NAMES[peer], token=key(own, peer), side=side) for peer, side in sides.items()],+ [{"peer": text(peer), **zone} for peer, zone in zones], own=own, name=NAMES[own],+ away=lambda: self.owner is not None and self.owner.owner.away,+ ).start()+ test.addCleanup(self.machine.stop)+ self.owner = None++ def connect(self, test, others):+ self.owner = ScriptedOwner(test, self.own, [desk.machine for desk in others])+++class Desks(unittest.TestCase):+ """Subclasses set `LAYOUT`: for each machine its peers' sides and its zones."""++ LAYOUT = {}++ def setUp(self):+ self.desks = {own: Desk(self, own, sides, zones) for own, (sides, zones) in self.LAYOUT.items()}+ for own, desk in self.desks.items():+ desk.connect(self, [other for ident_, other in self.desks.items() if ident_ != own])++ def at(self, holder):+ """The machine whose screen `holder`'s pointer is on."""+ on = self.desks[holder].owner.on+ return holder if on is None else next(own for own in self.desks if text(own) == on)++ def push(self, holder, side):+ """`holder`'s hand pushes its pointer through `side` of the screen it is on."""+ owner = self.desks[holder].owner+ here = self.at(holder)+ if here == holder:+ desk = self.desks[holder]+ entries = desk.machine.settings.data["peers"]+ allowed = {protocol.read_id(item["id"]) for item in entries}+ models = receiver.zone_models(desk.machine.settings.data["zones"], entries, allowed, 120)+ desk.machine.desktop.cursor = POINT[side]+ for _ in range(5):+ for peer, model in models:+ outcome = model.feed(desk.machine.desktop.monitors(), POINT[side], *PUSH[side])+ if outcome.action == return_edge.CROSS:+ owner.carry_out(owner.owner.go(text(peer), outcome.edge, outcome.offset))+ return+ return+ self.desks[here].machine.desktop.cursor = POINT[side]+ owner.move(*PUSH[side])++ def assert_on(self, holder, machine):+ """`holder`'s input is on `machine` (home when it is `holder`), and only there."""+ owner = self.desks[holder].owner+ want = None if machine == holder else text(machine)+ self.assertTrue(owner.until(lambda: owner.on == want), (NAMES[holder], owner.on, NAMES[machine]))+ for own, desk in self.desks.items():+ expected = holder if own == machine and machine != holder else None+ self.assertTrue(wait_for(lambda: desk.machine.responder.owner == expected),+ (NAMES[own], desk.machine.responder.owner, expected))++ def walk(self, holder, steps):+ """Each step: push through a side of the screen the pointer is on, and land on a machine."""+ for side, machine in steps:+ self.push(holder, side)+ self.assert_on(holder, machine)+ # The machine reached takes this holder's input and nobody else's.+ if machine != holder:+ target = self.desks[machine].machine+ before = len(moves(target))+ target.desktop.cursor = (960, 540)+ self.desks[holder].owner.move(3, 4)+ self.assertTrue(self.desks[holder].owner.until(lambda: len(moves(target)) == before + 1))+++ROW = {+ A: ({B: "right", C: ""}, [(B, {"kind": "edge"})]),+ B: ({A: "left", C: "right"}, [(A, {"kind": "edge"}), (C, {"kind": "edge"})]),+ C: ({B: "left", A: ""}, [(B, {"kind": "edge"})]),+}+++class ARow(Desks):+ """Ay | Bee | Sea."""++ LAYOUT = ROW++ def test_with_the_keyboard_on_ay_every_border_both_ways_out_and_back(self):+ self.walk(A, [("right", B), ("right", C), ("left", B), ("left", A)])++ def test_with_the_keyboard_on_bee_both_neighbours_and_home_from_each(self):+ self.walk(B, [("left", A), ("right", B), ("right", C), ("left", B)])++ def test_with_the_keyboard_on_sea_the_chain_the_other_way(self):+ self.walk(C, [("left", B), ("left", A), ("right", B), ("right", C)])++ def test_the_far_end_of_the_chain_comes_home_through_the_machine_between(self):+ self.walk(A, [("right", B), ("right", C), ("left", B), ("left", A), ("right", B)])+ hand = self.desks[A].owner+ takes = [peer for peer, data in hand.sent if data["target"] == peer]+ self.assertEqual([NAMES[next(own for own in self.desks if text(own) == peer)] for peer in takes],+ ["Bee", "Sea", "Bee", "Bee"])++ def test_an_edge_with_no_zone_leads_nowhere(self):+ self.push(A, "left")+ self.assertFalse(self.desks[A].owner.until(lambda: self.desks[A].owner.on is not None, timeout=0.3))+ self.walk(A, [("right", B), ("right", C)])+ self.push(A, "right")+ time.sleep(0.2)+ self.assertEqual(self.desks[A].owner.on, text(C))++ def test_two_keyboards_never_share_a_machine(self):+ self.walk(A, [("right", B)])+ hand = self.desks[C].owner+ hand.go(self.desks[B].machine)+ self.assertTrue(hand.until(lambda: hand.moved and hand.moved[-1].why == "owned"))+ self.assertIsNone(hand.on)+ self.assertEqual(self.desks[B].machine.responder.owner, A)+++class ARowLosingAMachine(Desks):+ LAYOUT = ROW++ def drop(self, gone):+ """`gone` stops, and every other machine's link to it ends, as its watchdog would end it."""+ self.desks[gone].machine.stop()+ for own, desk in self.desks.items():+ if own != gone:+ desk.owner.carry_out(desk.owner.owner.link_down(text(gone)))++ def test_the_far_end_dropping_brings_the_input_home_and_leaves_no_machine_owned(self):+ self.walk(A, [("right", B), ("right", C)])+ self.drop(C)+ hand = self.desks[A].owner+ self.assertTrue(hand.until(lambda: hand.on is None))+ self.assertTrue(wait_for(lambda: self.desks[B].machine.responder.owner is None))+ self.walk(A, [("right", B)])++ def test_the_next_machine_dropping_mid_chain_keeps_the_input_where_it_is_and_out_of_its_reach(self):+ self.walk(A, [("right", B)])+ hand = self.desks[A].owner+ stays = len([data for peer, data in hand.sent if data.get("stay")])+ self.drop(C)+ # The owner re-arms Bee at once with a reach that leaves Sea out, so Bee's zone to Sea is+ # dead and a push through it is not even asked about.+ self.assertTrue(hand.until(lambda: len([data for peer, data in hand.sent if data.get("stay")]) > stays))+ self.assertNotIn(text(C), [data for peer, data in hand.sent if data.get("stay")][-1]["reach"])+ takes = len([peer for peer, data in hand.sent if data["target"] == peer])+ self.push(A, "right")+ time.sleep(0.3)+ hand.pump()+ self.assertEqual(hand.on, text(B))+ self.assertEqual(len([peer for peer, data in hand.sent if data["target"] == peer]), takes)+ self.walk(A, [("left", A)])++ def test_the_machine_between_dropping_takes_the_far_one_out_of_the_way_home_but_not_out_of_reach(self):+ self.walk(A, [("right", B), ("right", C)])+ self.drop(B)+ hand = self.desks[A].owner+ # Still on Sea: its link to Ay is its own, so losing Bee costs only the way back through Bee.+ time.sleep(0.2)+ hand.pump()+ self.assertEqual(hand.on, text(C))+ self.push(A, "left")+ time.sleep(0.3)+ hand.pump()+ self.assertEqual(hand.on, text(C))+ hand.go(None)+ self.assertIsNone(hand.on)+ self.assertTrue(wait_for(lambda: self.desks[C].machine.responder.owner is None))+++class AMachinePairedLate(Desks):+ """The rig of 01-10-2026: Bee paired first with its edge, Sea paired second with no zone at all.+ Sea's side arrives over its link, as `arrangement` brings it, and has to give Ay a way to it."""++ LAYOUT = {+ A: ({B: "left", C: ""}, [(B, {"kind": "edge"})]),+ B: ({A: "right", C: ""}, [(A, {"kind": "edge"})]),+ C: ({A: "left", B: ""}, [(A, {"kind": "edge"})]),+ }++ def arrives(self, here, sender, edge, set_at, by=None, way_back=None):+ """`sender`'s arrangement over its own link to `here`, applied as both apps apply it."""+ link = self.desks[sender].owner.links[text(here)]+ machine = self.desks[here].machine+ seen = len(machine.arrangements)+ link.send(protocol.arrangement_v6(edge, set_at, by or sender, way_back=way_back))+ self.assertTrue(wait_for(lambda: len(machine.arrangements) > seen))+ peer, read = machine.arrangements[seen]+ return ways.arrangement(machine.settings.data, text(peer), read["edge"], read["set_at"],+ text(read["by"]), "this PC", read.get("way_back"))++ def answers(self, here, to):+ """`here`'s own arrangement for `to`, as both apps send it after one that changed something."""+ settings = self.desks[here].machine.settings.data+ held = next(item for item in settings["peers"] if item["id"] == text(to))+ by = protocol.read_id(held["side_by"])+ return self.arrives(to, here, held["side"], held["side_set_at"], by, ways.has_way(settings, text(to)))++ def test_a_side_arriving_for_a_machine_with_no_zone_gives_it_its_edge_and_it_can_be_crossed_to(self):+ self.assertEqual(self.arrives(A, C, "left", 1_790_000_100), (True, []))+ self.walk(A, [("right", C), ("left", A), ("left", B), ("right", A)])++ def test_a_side_arriving_onto_another_machines_edge_is_refused_out_loud_and_the_thirds_share_it(self):+ changed, notices = self.arrives(A, C, "right", 1_790_000_100)+ self.assertTrue(changed)+ # The harness's handshakes name every machine "Peer", so the sentences are held by their shape.+ self.assertEqual(len(notices), 1)+ self.assertIn("now lead from the same part of this PC's screen", notices[0])+ self.assertTrue(notices[0].endswith("edge is off."))+ settings = self.desks[A].machine.settings.data+ self.assertIn("has no way in", ways.blocked_sentence(settings, text(C), "this PC"))+ self.assertFalse(ways.has_way(settings, text(C)))+ # Ay answers, and Sea learns at once that its side was taken but leads nowhere.+ on_sea = self.desks[C].machine.settings.data+ self.assertEqual(self.answers(A, C), (True, []))+ self.assertIn("has no way back", ways.no_way_back_sentence(on_sea, text(A)))+ self.assertEqual(self.answers(A, C), (False, []))+ # What the Crossing page then offers: each its own thirds of the left edge.+ ways.edit(settings, text(B), side="left", methods=["part"], parts=["start"], corner="top_left",+ kinds=("edge", "part", "corner"), corner_edge=lambda corner, side: side, now=time.time())+ ways.edit(settings, text(C), side="left", methods=["part"], parts=["end"], corner="top_left",+ kinds=("edge", "part", "corner"), corner_edge=lambda corner, side: side, now=time.time())+ self.assertIsNone(ways.clash(settings, "this PC"))+ self.assertTrue(ways.has_way(settings, text(C)))+ self.assertEqual(self.answers(A, C), (True, []))+ self.assertEqual(ways.no_way_back_sentence(on_sea, text(A)), "")+ POINT["left"] = (0, 100)+ self.addCleanup(POINT.__setitem__, "left", (0, 540))+ self.walk(A, [("left", B)])+ self.desks[A].owner.go(None)+ POINT["left"] = (0, 1000)+ self.walk(A, [("left", C)])+++L_SHAPE = {+ A: ({B: "right", C: "top"}, [(B, {"kind": "edge"}), (C, {"kind": "edge"})]),+ B: ({A: "left", C: ""}, [(A, {"kind": "edge"})]),+ C: ({A: "bottom", B: ""}, [(A, {"kind": "edge"})]),+}+++class AnL(Desks):+ """Sea above Ay, Bee to Ay's right: Ay has peers on two edges."""++ LAYOUT = L_SHAPE++ def test_from_the_corner_machine_out_to_each_and_back(self):+ self.walk(A, [("right", B), ("left", A), ("top", C), ("bottom", A)])++ def test_from_one_arm_to_the_other_through_the_corner_machine(self):+ self.walk(B, [("left", A), ("top", C), ("bottom", A), ("right", B)])+ self.walk(C, [("bottom", A), ("right", B), ("left", A), ("top", C)])++ def test_the_arms_have_no_border_of_their_own(self):+ self.walk(B, [("left", A), ("top", C)])+ for side in ("left", "right", "top"):+ self.push(B, side)+ time.sleep(0.2)+ self.desks[B].owner.pump()+ self.assertEqual(self.desks[B].owner.on, text(C))+++class SharedEdge(Desks):+ """Bee on the top third of Ay's right edge and Sea on the bottom third: two machines on one side."""++ LAYOUT = {+ A: ({B: "right", C: "right"}, [(B, {"kind": "part", "parts": ["start"]}), (C, {"kind": "part", "parts": ["end"]})]),+ B: ({A: "left", C: ""}, [(A, {"kind": "edge"})]),+ C: ({A: "left", B: ""}, [(A, {"kind": "edge"})]),+ }++ def test_each_third_leads_to_its_own_machine(self):+ POINT["right"] = (1919, 100)+ self.addCleanup(POINT.__setitem__, "right", (1919, 540))+ self.walk(A, [("right", B), ("left", A)])+ POINT["right"] = (1919, 1000)+ self.walk(A, [("right", C), ("left", A)])+ POINT["right"] = (1919, 540)+ self.push(A, "right")+ self.assertFalse(self.desks[A].owner.until(lambda: self.desks[A].owner.on is not None, timeout=0.3))+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/test_three_machines.py b/core/tests/test_three_machines.pyindex d02bea4..57d96e1 100644--- a/core/tests/test_three_machines.py+++ b/core/tests/test_three_machines.py@@ -39,6 +39,7 @@ class ScriptedOwner:self.links = {}self.sent = []self.moved = []+ self.dropped = []self.clipboard = "owner's"self.clipboards = []for machine in machines:@@ -65,6 +66,9 @@ class ScriptedOwner:self.clipboards.append(self.clipboard)elif isinstance(action, owner_module.Moved):self.moved.append(action)+ elif isinstance(action, owner_module.Drop):+ self.links[action.peer].close()+ self.dropped.append(action.peer)def pump(self):for peer, link in self.links.items():@@ -230,6 +234,27 @@ class WhereTheRoutesMustAgree(Chain):self.o.move(5, 0)self.assertTrue(self.o.until(lambda: len(moves(self.a)) == before + 1))+ def test_a_hand_over_given_up_before_its_accept_arrives_closes_that_link_and_its_ownership(self):+ # B takes the input, but its `accept` is held up on the way (here: never read) until the+ # owner's second has passed. Without closing B's link, B would stay owned by an owner that+ # drives A, refusing everyone else for as long as the link lives.+ self.push_right(self.a)+ switch = self.o.links[text(A)].expect(protocol.MSG_SWITCH)+ self.o.carry_out(self.o.owner.switch(text(A), switch))+ self.assertTrue(wait_for(lambda: self.b.responder.owner == O))+ time.sleep(owner_module.TAKE_WAIT + 0.05)+ self.o.carry_out(self.o.owner.tick())+ self.assertEqual(self.o.dropped, [text(B)])+ self.assertTrue(wait_for(lambda: self.b.responder.owner is None))+ self.assertEqual(self.o.on, 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.assertTrue(wait_for(lambda: self.a.responder.owner == O))+ 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))diff --git a/core/tests/test_v6_vectors.py b/core/tests/test_v6_vectors.pyindex b1d4f53..8dc072c 100644--- a/core/tests/test_v6_vectors.py+++ b/core/tests/test_v6_vectors.py@@ -730,6 +730,18 @@ class PairingV3TcpTests(unittest.TestCase):self.assertIn("id", tcp["frames"][0]["message"])+class ClipboardImageVectors(unittest.TestCase):+ def test_every_case_fits_or_not_as_committed_and_drops_only_the_image(self):+ cases = V6["clipboard_images"]["cases"]+ self.assertEqual({case["fits"] for case in cases}, {True, False})+ for case in cases:+ with self.subTest(case=case["comment"]):+ image = unhex(case["png_hex"])+ self.assertIs(protocol.png_fits(image), case["fits"])+ read = protocol.read_clipboard(protocol.clipboard_msg("words", image))+ self.assertEqual(read, {"text": "words", "image": image if case["fits"] else None})++@unittest.skipUnless(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 = {diff --git a/core/tests/test_ways.py b/core/tests/test_ways.pynew file mode 100644index 0000000..9bd9531--- /dev/null+++ b/core/tests/test_ways.py@@ -0,0 +1,367 @@+"""core/ways.py: a machine's zones read and written one peer at a time, the side settled with each+peer, the machine the shortcut picks, and the pairings a zone needs (WIRE.md sections 5 and 8)."""++import unittest++from core import protocol, ways++HERE = protocol.id_text(bytes(range(1, 17)))+A = protocol.id_text(bytes(range(20, 36)))+B = protocol.id_text(bytes(range(40, 56)))+C = protocol.id_text(bytes(range(60, 76)))+PHONE = protocol.id_text(bytes(range(80, 96)))+++def peer(ident, name, **fields):+ data = {"id": ident, "name": name, "platform": "windows", "host": "10.9.9.9", "port": 24820, "hw": "",+ "send": True, "allow_drive": True, "side": "", "side_set_at": 0, "side_by": "", "paired_with": [],+ "paired_at": 1, "linked": True, "from_1_4": False, "token": "k" + ident}+ data.update(fields)+ return data+++def settings(*peers, zones=()):+ return {"machine_id": HERE, "shortcut": True, "peers": list(peers), "zones": list(zones)}+++def mac_corner_edge(corner, side):+ return corner.split("_")[1]+++def pc_corner_edge(corner, side):+ return side if side in ways.EDGES else corner.split("_")[1]+++MAC = ("edge", "part", "corner", "notch")+PC = ("edge", "part", "corner")+++class ReadingOnePeer(unittest.TestCase):+ def test_a_peer_with_no_zones_reads_as_nothing_in_use_and_the_defaults(self):+ found = ways.ways(settings(peer(A, "Ay", side="left")), A)+ self.assertEqual(found, {"side": "left", "methods": [], "parts": ["middle"], "corner": "top_left"})++ def test_only_that_peers_zones_in_use_count(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee", side="right"), zones=[+ {"peer": A, "kind": "edge"},+ {"peer": A, "kind": "corner", "corner": "bottom_left", "edge": "left", "off": True},+ {"peer": B, "kind": "part", "parts": ["start", "end"]},+ {"peer": B, "kind": "corner", "corner": "top_right", "edge": "right"},+ ])+ self.assertEqual(ways.ways(held, A), {"side": "left", "methods": ["edge"], "parts": ["middle"], "corner": "bottom_left"})+ self.assertEqual(ways.ways(held, B), {"side": "right", "methods": ["part", "corner"], "parts": ["start", "end"],+ "corner": "top_right"})++ def test_an_unknown_peer_reads_as_nothing(self):+ self.assertEqual(ways.ways(settings(), A)["methods"], [])+++class WritingOnePeer(unittest.TestCase):+ def test_one_zone_of_each_kind_is_written_for_that_peer_and_the_others_are_left_alone(self):+ other = {"peer": B, "kind": "edge"}+ held = settings(peer(A, "Ay"), peer(B, "Bee", side="right"), zones=[other])+ changed = ways.edit(held, A, side="left", methods=["corner"], parts=["start"], corner="top_left",+ kinds=MAC, corner_edge=mac_corner_edge, now=1000)+ self.assertTrue(changed)+ mine = [zone for zone in held["zones"] if zone["peer"] == A]+ self.assertEqual(sorted(zone["kind"] for zone in mine), sorted(MAC))+ self.assertEqual({zone["kind"] for zone in mine if not zone.get("off")}, {"corner"})+ self.assertEqual(next(zone for zone in mine if zone["kind"] == "corner")["edge"], "left")+ self.assertIn(other, held["zones"])+ self.assertEqual(held["peers"][1]["side"], "right")++ def test_a_new_side_is_stamped_by_this_machine_and_never_below_the_last_stamp(self):+ held = settings(peer(A, "Ay", side="right", side_set_at=5000, side_by=A))+ self.assertTrue(ways.edit(held, A, side="top", methods=["edge"], parts=["middle"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=100))+ entry = held["peers"][0]+ self.assertEqual((entry["side"], entry["side_set_at"], entry["side_by"]), ("top", 5001, HERE))++ def test_an_unchanged_side_keeps_its_stamp_and_says_so(self):+ held = settings(peer(A, "Ay", side="right", side_set_at=5000, side_by=A))+ self.assertFalse(ways.edit(held, A, side="right", methods=["part"], parts=["end"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=9000))+ self.assertEqual((held["peers"][0]["side_set_at"], held["peers"][0]["side_by"]), (5000, A))++ def test_the_pc_corner_crosses_the_side(self):+ held = settings(peer(A, "Ay"))+ ways.edit(held, A, side="top", methods=["corner"], parts=["middle"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=1)+ corner = next(zone for zone in held["zones"] if zone["kind"] == "corner")+ self.assertEqual(corner["edge"], "top")++ def test_edge_and_its_thirds_both_on_write_the_thirds_off(self):+ held = settings(peer(A, "Ay"))+ ways.edit(held, A, side="left", methods=["edge", "part"], parts=["start"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=1)+ self.assertEqual(ways.ways(held, A)["methods"], ["edge"])++ def test_an_unknown_peer_raises(self):+ with self.assertRaises(KeyError):+ ways.edit(settings(), A, side="left", methods=[], parts=["middle"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=1)++ def test_a_zone_the_user_kept_keeps_its_other_fields(self):+ held = settings(peer(A, "Ay", side="left"), zones=[{"peer": A, "kind": "edge", "off": True, "later": 1}])+ ways.edit(held, A, side="left", methods=["edge"], parts=["middle"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=1)+ self.assertEqual([zone for zone in held["zones"] if zone["kind"] == "edge"], [{"peer": A, "kind": "edge", "later": 1}])+++class Clashes(unittest.TestCase):+ def test_two_machines_on_one_whole_edge_clash_and_the_sentence_names_both(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="right"),+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])+ self.assertEqual(ways.clash(held, "this Mac"),+ "Ay and Bee would both lead from the right edge of this Mac. Move one of them to another "+ "side, or give each its own thirds of the edge.")++ def test_two_machines_on_different_thirds_of_one_edge_do_not_clash(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="right"), zones=[+ {"peer": A, "kind": "part", "parts": ["start"]}, {"peer": B, "kind": "part", "parts": ["middle", "end"]}])+ self.assertIsNone(ways.clash(held, "this PC"))++ def test_a_corner_inside_another_machines_edge_does_not_clash(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="top"), zones=[+ {"peer": A, "kind": "edge"}, {"peer": B, "kind": "corner", "corner": "top_right", "edge": "top"}])+ self.assertIsNone(ways.clash(held, "this PC"))++ def test_one_corner_for_two_machines_clashes(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="top"), zones=[+ {"peer": A, "kind": "corner", "corner": "top_right", "edge": "right"},+ {"peer": B, "kind": "corner", "corner": "top_right", "edge": "top"}])+ self.assertEqual(ways.clash(held, "this PC"),+ "Ay and Bee would both lead from the top right corner of this PC. Choose another corner "+ "for one of them.")++ def test_one_notch_for_two_machines_clashes(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="top"), zones=[+ {"peer": A, "kind": "notch"}, {"peer": B, "kind": "notch"}])+ self.assertEqual(ways.clash(held, "this Mac"),+ "Ay and Bee would both lead from the notch of this Mac. Turn the notch off for one of them.")++ def test_two_of_one_machines_own_zones_over_one_stretch_clash(self):+ held = settings(peer(A, "Ay", side="right"), zones=[+ {"peer": A, "kind": "edge"}, {"peer": A, "kind": "part", "parts": ["middle"]}])+ self.assertEqual(ways.clash(held, "this Mac"), "Two of the ways to Ay cover the right edge of this Mac. Keep one of them.")++ def test_zones_that_are_off_never_clash(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="right"),+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True}])+ self.assertIsNone(ways.clash(held, "this PC"))+++class EveryMachineHasAWayIn(unittest.TestCase):+ """A machine paired, or one whose side arrives, crosses by its whole edge unless that edge is+ another machine's already (the rig's beta.3 file of 01-10: the laptop's side set, no zone)."""++ def test_a_machine_with_no_zone_gets_its_whole_edge(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee", side="right"), zones=[{"peer": A, "kind": "edge"}])+ self.assertTrue(ways.ensure_zones(held))+ self.assertIn({"peer": B, "kind": "edge"}, held["zones"])+ self.assertFalse(ways.ensure_zones(held))++ def test_one_whose_side_is_another_machines_edge_gets_it_off_so_the_settings_stay_readable(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee", side="left"), zones=[{"peer": A, "kind": "edge"}])+ ways.ensure_zones(held)+ self.assertIn({"peer": B, "kind": "edge", "off": True}, held["zones"])+ self.assertIsNone(ways.clash(held, "this PC"))++ def test_a_machine_with_its_zones_all_off_keeps_them_as_they_are(self):+ held = settings(peer(A, "Ay", side="left"), zones=[{"peer": A, "kind": "edge", "off": True}])+ self.assertFalse(ways.ensure_zones(held))++ def test_a_phone_and_an_entry_with_no_id_get_none(self):+ held = settings(peer(PHONE, "Phone", port=0, host="", send=False), peer("", "Old", from_1_4=True))+ self.assertFalse(ways.ensure_zones(held))+ self.assertEqual(held["zones"], [])++ def test_an_arrangement_for_a_machine_with_no_zone_gives_it_its_edge(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee"), zones=[{"peer": A, "kind": "edge"}])+ self.assertEqual(ways.arrangement(held, B, "left", 20, B, "this PC"), (True, []))+ self.assertIn({"peer": B, "kind": "edge"}, held["zones"])++ def test_an_arrangement_onto_another_machines_edge_gives_it_the_edge_off_and_says_so(self):+ held = settings(peer(A, "MacBook Pro", side="left"), peer(B, "Laptop"), zones=[{"peer": A, "kind": "edge"}])+ changed, notices = ways.arrangement(held, B, "right", 20, B, "this PC")+ self.assertTrue(changed)+ self.assertEqual(notices, ["MacBook Pro and Laptop now lead from the same part of this PC's screen, so "+ "Laptop's edge is off."])+ self.assertIn({"peer": B, "kind": "edge", "off": True}, held["zones"])+++class Blocked(unittest.TestCase):+ def test_a_machine_whose_side_is_taken_and_has_no_way_in_is_told_which_machine_has_it(self):+ held = settings(peer(A, "MacBook Pro", side="left"), peer(B, "Laptop", side="left"),+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True}])+ self.assertEqual(ways.blocked_sentence(held, B, "this PC"),+ "Laptop has no way in: MacBook Pro already leads from the left edge of this PC. "+ "Give each its own thirds of that edge under Part of the edge, or move one to another side.")+ self.assertEqual(ways.blocked_sentence(held, A, "this PC"), "")++ def test_thirds_left_free_by_another_machine_are_no_block(self):+ held = settings(peer(A, "MacBook Pro", side="left"), peer(B, "Laptop", side="left"), zones=[+ {"peer": A, "kind": "part", "parts": ["start"]}, {"peer": B, "kind": "part", "parts": ["end"]}])+ self.assertEqual(ways.blocked_sentence(held, B, "this PC"), "")++ def test_a_machine_with_a_corner_in_use_is_not_blocked(self):+ held = settings(peer(A, "MacBook Pro", side="left"), peer(B, "Laptop", side="left"), zones=[+ {"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True},+ {"peer": B, "kind": "corner", "corner": "top_left", "edge": "left"}])+ self.assertEqual(ways.blocked_sentence(held, B, "this PC"), "")++ def test_a_machine_with_no_side_is_not_blocked(self):+ held = settings(peer(A, "MacBook Pro", side="left"), peer(B, "Laptop"), zones=[{"peer": A, "kind": "edge"}])+ self.assertEqual(ways.blocked_sentence(held, B, "this PC"), "")+++class WayBack(unittest.TestCase):+ """What a machine tells another with its `arrangement`: whether it has a zone in use leading there."""++ def test_a_zone_in_use_with_a_side_or_a_corner_is_a_way(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee"), peer(C, "Sea", side="top"), zones=[+ {"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"},+ {"peer": C, "kind": "edge", "off": True}, {"peer": C, "kind": "corner", "corner": "top_left", "edge": "top"}])+ self.assertEqual([ways.has_way(held, ident) for ident in (A, B, C)], [True, False, True])++ def test_an_arrangement_keeps_what_the_sender_said_whether_or_not_its_side_is_newer(self):+ held = settings(peer(A, "Ay", side="left", side_set_at=50, side_by=A))+ self.assertEqual(ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False), (True, []))+ self.assertIs(held["peers"][0]["way_back"], False)+ self.assertEqual(ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False), (False, []))+ self.assertEqual(ways.arrangement(held, A, "right", 50, A, "this PC"), (False, []))+ self.assertIs(held["peers"][0]["way_back"], False)+ self.assertEqual(ways.arrangement(held, A, "right", 50, A, "this PC", way_back=True), (True, []))+ self.assertIs(held["peers"][0]["way_back"], True)++ def test_the_sentence_names_the_machine_with_no_way_back(self):+ held = settings(peer(A, "Desk-PC", way_back=False), peer(B, "Bee", way_back=True), peer(C, "Sea"))+ self.assertEqual(ways.no_way_back_sentence(held, A),+ "Desk-PC has no way back to this machine: none of its edges leads here. Its own "+ "Crossing page says why.")+ self.assertEqual(ways.no_way_back_sentence(held, B), "")+ self.assertEqual(ways.no_way_back_sentence(held, C), "")+++class Arrangement(unittest.TestCase):+ def test_a_newer_arrangement_sets_the_opposite_side_for_that_peer_only(self):+ held = settings(peer(A, "Ay", side="left", side_set_at=10, side_by=HERE), peer(B, "Bee", side="right"))+ changed, notices = ways.arrangement(held, A, "left", 20, A, "this PC")+ self.assertTrue(changed)+ self.assertEqual(notices, [])+ self.assertEqual((held["peers"][0]["side"], held["peers"][0]["side_set_at"], held["peers"][0]["side_by"]),+ ("right", 20, A))+ self.assertEqual(held["peers"][1]["side"], "right")++ def test_an_older_one_or_a_tie_lost_on_the_id_changes_nothing(self):+ held = settings(peer(A, "Ay", side="left", side_set_at=10, side_by=C))+ self.assertEqual(ways.arrangement(held, A, "left", 9, A, "this PC"), (False, []))+ self.assertEqual(ways.arrangement(held, A, "left", 10, A, "this PC"), (False, []))+ self.assertEqual(held["peers"][0]["side"], "left")++ def test_a_tie_won_on_the_id_applies(self):+ held = settings(peer(A, "Ay", side="left", side_set_at=10, side_by=A))+ self.assertEqual(ways.arrangement(held, A, "left", 10, C, "this PC"), (True, []))++ def test_a_side_that_now_overlaps_turns_the_senders_zones_off_and_names_both(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee", side="right"),+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])+ changed, notices = ways.arrangement(held, A, "left", 20, A, "this Mac")+ self.assertTrue(changed)+ self.assertEqual(notices, ["Bee and Ay now lead from the same part of this Mac's screen, so Ay's edge is off."])+ self.assertTrue(next(zone for zone in held["zones"] if zone["peer"] == A)["off"])+ self.assertNotIn("off", next(zone for zone in held["zones"] if zone["peer"] == B))++ def test_an_unknown_peer_bad_edge_or_bad_by_changes_nothing(self):+ held = settings(peer(A, "Ay", side="left"))+ self.assertEqual(ways.arrangement(held, B, "left", 20, B, "this PC"), (False, []))+ self.assertEqual(ways.arrangement(held, A, "middle", 20, A, "this PC"), (False, []))+ self.assertEqual(ways.arrangement(held, A, "left", 20, "nope", "this PC"), (False, []))+++class TheShortcutsMachine(unittest.TestCase):+ def test_the_machine_input_was_last_on_while_it_can_take_input(self):+ peers = [peer(A, "Ay"), peer(B, "Bee")]+ self.assertEqual(ways.shortcut_peer(peers, B, lambda ident: True), B)++ def test_else_the_first_that_can_take_input(self):+ peers = [peer(A, "Ay"), peer(B, "Bee"), peer(C, "Sea")]+ self.assertEqual(ways.shortcut_peer(peers, A, lambda ident: ident == C), C)+ self.assertEqual(ways.shortcut_peer(peers, None, lambda ident: ident != A), B)++ def test_else_the_first_this_machine_sends_to_so_the_refusal_or_the_wake_names_it(self):+ peers = [peer(A, "Ay", send=False), peer(B, "Bee"), peer(C, "Sea")]+ self.assertEqual(ways.shortcut_peer(peers, None, lambda ident: False), B)++ def test_a_machine_this_one_does_not_send_to_is_never_picked(self):+ peers = [peer(A, "Ay", send=False)]+ self.assertIsNone(ways.shortcut_peer(peers, A, lambda ident: True))++ def test_a_phone_or_an_entry_without_an_id_is_never_picked(self):+ peers = [peer(PHONE, "Phone", port=0, host="", send=False), peer("", "Old", from_1_4=True)]+ self.assertIsNone(ways.shortcut_peer(peers, None, lambda ident: True))++ def test_nothing_paired_picks_nothing(self):+ self.assertIsNone(ways.shortcut_peer([], None, lambda ident: True))+++class MissingPairings(unittest.TestCase):+ def test_a_machine_that_may_drive_this_one_and_is_not_paired_with_the_zones_peer_is_named(self):+ held = settings(peer(A, "Ay", paired_with=[B]), peer(B, "Bee", paired_with=[A]), peer(C, "Sea", paired_with=[A]))+ self.assertEqual([entry["id"] for entry in ways.missing_pairings(held, B)], [C])+ self.assertEqual([entry["id"] for entry in ways.missing_pairings(held, A)], [])++ def test_a_machine_not_allowed_to_drive_this_one_needs_no_pairing(self):+ held = settings(peer(A, "Ay"), peer(B, "Bee", allow_drive=False))+ self.assertEqual(ways.missing_pairings(held, A), [])++ def test_a_machine_that_has_never_linked_is_not_judged(self):+ held = settings(peer(A, "Ay"), peer(B, "Bee", linked=False))+ self.assertEqual(ways.missing_pairings(held, A), [])++ def test_a_phone_that_may_drive_this_one_counts(self):+ held = settings(peer(A, "Ay"), peer(PHONE, "Phone", port=0, host="", send=False))+ self.assertEqual([entry["id"] for entry in ways.missing_pairings(held, A)], [PHONE])++ def test_the_sentence_names_each_machine_and_the_one_it_needs(self):+ held = settings(peer(A, "Ay"), peer(B, "Bee", paired_with=[]))+ self.assertEqual(ways.missing_sentence(held, A, "this Mac"),+ "While Bee drives this Mac, this way to Ay does nothing: Bee is not paired with Ay. "+ "Pair them to use it from there too.")+ held["peers"].append(peer(C, "Sea"))+ self.assertEqual(ways.missing_sentence(held, A, "this Mac"),+ "While Bee or Sea drives this Mac, this way to Ay does nothing: neither is paired "+ "with Ay. Pair them to use it from there too.")+ self.assertEqual(ways.missing_sentence(settings(peer(A, "Ay")), A, "this Mac"), "")++++class TheShownDefault(unittest.TestCase):+ """The Mac's page shows Right for its one machine before a side is set, and a save writes it."""++ def test_a_side_written_as_the_pages_default_is_unstamped_so_the_peers_own_wins(self):+ held = settings(peer(A, "Ay"), zones=[{"peer": A, "kind": "edge"}])+ self.assertTrue(ways.edit(held, A, side="right", methods=["edge"], parts=["middle"], corner="top_left",+ kinds=MAC, corner_edge=mac_corner_edge, now=1_900_000_000, default=True))+ entry = held["peers"][0]+ self.assertEqual((entry["side"], entry["side_set_at"], entry["side_by"]), ("right", 0, ""))+ self.assertEqual(ways.arrangement(held, A, "bottom", 1_899_999_000, A, "this Mac"), (True, []))+ self.assertEqual(held["peers"][0]["side"], "top")++ def test_a_default_never_moves_a_side_already_set(self):+ held = settings(peer(A, "Ay", side="left", side_set_at=5, side_by=A), zones=[{"peer": A, "kind": "edge"}])+ self.assertFalse(ways.edit(held, A, side="right", methods=["edge"], parts=["middle"], corner="top_left",+ kinds=MAC, corner_edge=mac_corner_edge, now=1_900_000_000, default=True))+ self.assertEqual(held["peers"][0]["side"], "left")+++class TheCornerFollowsAnArrivingSide(unittest.TestCase):+ def test_a_corner_that_crosses_the_side_is_rewritten_for_the_side_that_arrives(self):+ held = settings(peer(A, "Ay", side="top", side_set_at=5, side_by=A),+ zones=[{"peer": A, "kind": "corner", "corner": "top_right", "edge": "top"}])+ self.assertEqual(ways.arrangement(held, A, "left", 10, A, "this PC", corner_edge=pc_corner_edge), (True, []))+ self.assertEqual((held["peers"][0]["side"], held["zones"][0]["edge"]), ("right", "right"))+++if __name__ == "__main__":+ unittest.main()diff --git a/core/tests/v6_vectors.json b/core/tests/v6_vectors.jsonindex 3680df8..67a50a2 100644--- a/core/tests/v6_vectors.json+++ b/core/tests/v6_vectors.json@@ -1609,6 +1609,81 @@}}]+ },+ "clipboard_images": {+ "$comment": "Clipboard images judged from their bytes before anything decodes them (WIRE.md section 3). `fits` false drops the image part of a clipboard message and keeps its text. Pixel data is not real past 1 by 1: nothing here decodes it.",+ "cases": [+ {+ "comment": "a 1 by 1 image",+ "png_hex": "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c48900000010494441547801010500faff000000000000050001647895380000000049454e44ae426082",+ "fits": true+ },+ {+ "comment": "an 8K screen's header, 7680 by 4320",+ "png_hex": "89504e470d0a1a0a0000000d4948445200001e00000010e00806000000b69114930000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",+ "fits": true+ },+ {+ "comment": "16384 by 2048, exactly 2^25 pixels",+ "png_hex": "89504e470d0a1a0a0000000d4948445200004000000008000806000000de2c2b9a0000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",+ "fits": true+ },+ {+ "comment": "bytes after IEND are ignored",+ "png_hex": "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c48900000010494441547801010500faff000000000000050001647895380000000049454e44ae426082747261696c696e67",+ "fits": true+ },+ {+ "comment": "zTXt inflating to exactly 4 MiB",+ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b000068417a545874436f6d6d656e74000078014b4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c1c05a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1280000e9966bd03978c9330000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",+ "fits": true+ },+ {+ "comment": "a side of 16385",+ "png_hex": "89504e470d0a1a0a0000000d4948445200004001000000010806000000c95ddd660000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",+ "fits": false+ },+ {+ "comment": "6000 by 6000, past 2^25 pixels",+ "png_hex": "89504e470d0a1a0a0000000d4948445200001770000017700806000000e35487430000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",+ "fits": false+ },+ {+ "comment": "IHDR not the first chunk",+ "png_hex": "89504e470d0a1a0a0000000374455874610062dc49a23b0000000d49484452000000010000000108060000001f15c48900000010494441547801010500faff000000000000050001647895380000000049454e44ae426082",+ "fits": false+ },+ {+ "comment": "no IEND",+ "png_hex": "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c48900000010494441547801010500faff00000000000005000164789538",+ "fits": false+ },+ {+ "comment": "a second IHDR",+ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b0000000d49484452000186a0000186a00806000000a8520bc80000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",+ "fits": false+ },+ {+ "comment": "an APNG acTL",+ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b000000086163544c0000000000000000894dc0100000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",+ "fits": false+ },+ {+ "comment": "zTXt inflating to 4 MiB and one byte",+ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b000068427a545874436f6d6d656e74000078014b4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c1c05a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c1281805a360148c8251300a46c128000055d66c31d393054f0000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",+ "fits": false+ },+ {+ "comment": "zTXt whose zlib stream is cut short",+ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b000000f27a545874436f6d6d656e74000078014b4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c1c05a36014e766143a0000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",+ "fits": false+ },+ {+ "comment": "iTXt with a compression flag of 2",+ "png_hex": "89504e470d0a1a0a0000000d4948445200000008000000080806000000c40fbe8b0000000e695458744b6579000200656e0000746578748fa003e70000000b494441547801010000ffff0000000189d6ae5f0000000049454e44ae426082",+ "fits": false+ }+ ]}},"pairing_v3": {diff --git a/core/ways.py b/core/ways.pynew file mode 100644index 0000000..5fbfec4--- /dev/null+++ b/core/ways.py@@ -0,0 +1,328 @@+"""A machine's zones, one peer at a time (WIRE.md sections 5 and 8), shared by both desktops.++What the Crossing page reads and writes for the machine it has chosen, the side settled with each+peer by `arrangement`, the sentence for two zones over one stretch, which machine the shortcut and+the Send button pick, and which machines that may drive this one cannot follow a zone. Pure: each+app calls these on its settings under its own lock and writes the file itself.+"""++import base64+import binascii+from typing import Callable, Optional++from core import peerlist+from core import return_edge+from core.settings_sync import next_stamp++EDGES = return_edge.EDGES+CORNERS = return_edge.CORNERS+PARTS = return_edge.PARTS+DEFAULT_PARTS = ["middle"]+DEFAULT_CORNER = "top_left"+# How a notice names each kind of zone.+KIND_WORDS = {"edge": "edge", "part": "part of the edge", "corner": "corner", "notch": "notch"}+++def _entry(settings: dict, peer: str) -> Optional[dict]:+ return next((entry for entry in settings["peers"] if entry.get("id") == peer), None)+++def _mine(settings: dict, peer: str) -> dict:+ found = {}+ for zone in settings["zones"]:+ if zone.get("peer") == peer:+ found.setdefault(zone.get("kind"), zone)+ return found+++def ways(settings: dict, peer: str) -> dict:+ """The ways across to one peer as the Crossing page shows them: its `side`, the kinds of zone in+ use in section 8's order of kinds, the thirds and the corner its zones hold (the defaults where+ it has none)."""+ entry = _entry(settings, peer) or {}+ mine = _mine(settings, peer)+ parts = mine.get("part", {}).get("parts")+ corner = mine.get("corner", {}).get("corner")+ return {+ "side": entry.get("side") if entry.get("side") in EDGES else "",+ "methods": [kind for kind in KIND_WORDS if kind in mine and mine[kind].get("off") is not True],+ "parts": [part for part in PARTS if part in parts] if isinstance(parts, list) and parts else list(DEFAULT_PARTS),+ "corner": corner if corner in CORNERS else DEFAULT_CORNER,+ }+++def edit(settings: dict, peer: str, *, side: str, methods, parts, corner: str, kinds,+ corner_edge: Callable[[str, str], str], now: float, default: bool = False) -> bool:+ """Writes one peer's ways: its `side`, and one zone of each of `kinds` (the kinds this app+ offers), in use when named in `methods` and `off` otherwise. The whole edge covers its thirds,+ so with both chosen the thirds are written `off` (section 8). `corner_edge(corner, side)` is+ the edge this app's corner crosses. A changed side is stamped by this machine, never below the+ stamp held plus one. `default` says `side` is only what the page shows for a machine not placed+ yet, which nobody chose: it is written only while no side is held, unstamped and with no author,+ so a side either machine does choose wins over it. Returns whether the side changed, which the+ caller sends as `arrangement`. KeyError when no entry has `peer`."""+ entry = _entry(settings, peer)+ if entry is None:+ raise KeyError(peer)+ side = side if side in EDGES else ""+ if default and entry.get("side") in EDGES:+ side = entry["side"]+ moved = bool(side) and side != entry.get("side")+ if moved and default:+ entry.update(side=side, side_set_at=0, side_by="")+ elif moved:+ entry.update(side=side, side_set_at=next_stamp(entry.get("side_set_at"), now), side_by=settings["machine_id"])+ methods = set(methods)+ if "edge" in methods:+ methods.discard("part")+ parts = [part for part in PARTS if part in parts] or list(DEFAULT_PARTS)+ corner = corner if corner in CORNERS else DEFAULT_CORNER+ fields = {"edge": {}, "part": {"parts": parts}, "corner": {"corner": corner, "edge": corner_edge(corner, side)},+ "notch": {}}+ mine = _mine(settings, peer)+ for kind in kinds:+ zone = mine.get(kind)+ if zone is None:+ zone = {"peer": peer, "kind": kind}+ settings["zones"].append(zone)+ zone.update(fields[kind])+ if kind in methods:+ zone.pop("off", None)+ else:+ zone["off"] = True+ return moved+++def _stretch(zone: dict, sides: dict) -> set:+ """What a zone in use covers, for the rule that two never share one (section 8); the notch is+ one stretch of its own, as a Mac has one notch."""+ if zone.get("kind") == "notch":+ return {("notch",)}+ side = sides.get(zone.get("peer"), "")+ kind = zone.get("kind")+ if kind == "corner" and zone.get("corner") in CORNERS:+ return {("corner", zone["corner"])}+ if kind == "edge" and side in EDGES:+ return {(side, part) for part in PARTS}+ if kind == "part" and side in EDGES and isinstance(zone.get("parts"), list):+ return {(side, part) for part in zone["parts"] if part in PARTS}+ return set()+++def _clashing(settings: dict):+ """The first two zones in use that cover one stretch, and that stretch; None when none do."""+ sides = {entry.get("id"): entry.get("side", "") for entry in settings["peers"]}+ seen = {}+ for zone in settings["zones"]:+ if zone.get("off") is True:+ continue+ for stretch in sorted(_stretch(zone, sides)):+ if stretch in seen:+ return seen[stretch], zone, stretch+ seen[stretch] = zone+ return None+++def clash(settings: dict, here: str) -> Optional[str]:+ """The sentence for two zones in use over one stretch of this machine's screen, naming the+ machines they lead to, or None when there is no such pair. `here` is "this Mac" or "this PC"."""+ found = _clashing(settings)+ if found is None:+ return None+ first, second, stretch = found+ peers = settings["peers"]+ one = peerlist.label_for(peers, peer_id=first.get("peer")) or peerlist.UNNAMED+ other = peerlist.label_for(peers, peer_id=second.get("peer")) or peerlist.UNNAMED+ where = {"notch": "the notch", "corner": f"the {stretch[-1].replace('_', ' ')} corner"}.get(+ stretch[0], f"the {stretch[0]} edge")+ if first.get("peer") == second.get("peer"):+ return f"Two of the ways to {one} cover {where} of {here}. Keep one of them."+ fix = {"notch": "Turn the notch off for one of them.", "corner": "Choose another corner for one of them."}.get(+ stretch[0], "Move one of them to another side, or give each its own thirds of the edge.")+ return f"{one} and {other} would both lead from {where} of {here}. {fix}"+++def _id_bytes(text) -> Optional[bytes]:+ if not isinstance(text, str) or not text:+ return None+ try:+ data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))+ except (binascii.Error, ValueError):+ return None+ return data if len(data) == 16 and base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") == text else None+++def arrangement(settings: dict, peer: str, edge: str, set_at: int, by: str, here: str, way_back=None,+ corner_edge: Optional[Callable[[str, str], str]] = None):+ """A peer's `arrangement` (section 8): `edge` is the peer's edge that faces this machine, so this+ machine's side for it is the opposite. Taken when newer than the side held: a higher stamp, or the+ same stamp and the larger `by` as bytes. A machine with no zone yet gets its whole edge for that+ side, and a side that would put two zones in use over one stretch is applied and turns this peer's+ clashing zones off. `way_back`, when the message carried it, is kept on the entry whether or not+ the side was newer. `corner_edge(corner, side)`, the app's own, rewrites the edge its corner zones+ for the peer cross, as `edit` does, since a PC's corner crosses the side. Returns (changed,+ notices), a sentence for each zone turned off; `here` is "this Mac" or "this PC"."""+ entry = _entry(settings, peer)+ by_bytes = _id_bytes(by)+ if entry is None or edge not in EDGES or by_bytes is None:+ return False, []+ told = isinstance(way_back, bool) and entry.get("way_back") is not way_back+ if told:+ entry["way_back"] = way_back+ held = (int(entry.get("side_set_at") or 0), _id_bytes(entry.get("side_by")) or b"")+ if (int(set_at), by_bytes) <= held:+ return told, []+ entry.update(side=return_edge.OPPOSITE[edge], side_set_at=int(set_at), side_by=by)+ if corner_edge is not None:+ for zone in settings["zones"]:+ if zone.get("peer") == peer and zone.get("kind") == "corner" and zone.get("corner") in CORNERS:+ zone["edge"] = corner_edge(zone["corner"], entry["side"])+ if peer not in {zone.get("peer") for zone in settings["zones"]}:+ settings["zones"].append({"peer": peer, "kind": "edge"})+ return True, _turn_off_clashes(settings, entry, here)+++def _zoned(entry: dict) -> bool:+ """A machine that crosses by zones: a desktop with an id, never a phone."""+ return bool(entry.get("id")) and entry.get("port") != 0+++def ensure_zones(settings: dict) -> bool:+ """Gives every machine with no zone at all its whole edge, `off` when its side is another machine's+ already, so the settings stay readable (section 8, overlap). Pairing never made zones before+ 1.5.0-beta.5, so a machine paired since 1.4.x has none until this runs. True when it added any."""+ sides = {entry.get("id"): entry.get("side", "") for entry in settings["peers"]}+ covered = set()+ for zone in settings["zones"]:+ if zone.get("off") is not True:+ covered |= _stretch(zone, sides)+ zoned = {zone.get("peer") for zone in settings["zones"]}+ added = False+ for entry in settings["peers"]:+ if not _zoned(entry) or entry["id"] in zoned:+ continue+ zone = {"peer": entry["id"], "kind": "edge"}+ stretch = _stretch(zone, sides)+ if stretch & covered:+ zone["off"] = True+ else:+ covered |= stretch+ settings["zones"].append(zone)+ added = True+ return added+++def has_way(settings: dict, peer: str) -> bool:+ """Whether a zone in use leads to `peer` and can fire: a corner or the notch, or an edge or thirds+ of a side that is set. What `arrangement`'s `way_back` says to that machine."""+ sides = {entry.get("id"): entry.get("side", "") for entry in settings["peers"]}+ return any(zone.get("peer") == peer and zone.get("off") is not True and _stretch(zone, sides)+ for zone in settings["zones"])+++def blocked_sentence(settings: dict, peer: str, here: str) -> str:+ """The Crossing page's sentence for a machine whose side another machine's edge already holds and+ that has no way in of its own; "" otherwise."""+ entry = _entry(settings, peer) or {}+ side = entry.get("side")+ if side not in EDGES or has_way(settings, peer):+ return ""+ sides = {item.get("id"): item.get("side", "") for item in settings["peers"]}+ holder = next((zone.get("peer") for zone in settings["zones"]+ if zone.get("peer") != peer and zone.get("off") is not True and zone.get("kind") in ("edge", "part")+ and _stretch(zone, sides) & {(side, part) for part in PARTS}), None)+ if holder is None:+ return ""+ peers = settings["peers"]+ name = peerlist.label_for(peers, peer_id=peer) or peerlist.UNNAMED+ other = peerlist.label_for(peers, peer_id=holder) or peerlist.UNNAMED+ return (f"{name} has no way in: {other} already leads from the {side} edge of {here}. Give each its own "+ "thirds of that edge under Part of the edge, or move one to another side.")+++def no_way_back_sentence(settings: dict, peer: str) -> str:+ """The Crossing page's sentence for a machine that said, in its `arrangement`, that none of its+ zones leads to this one; "" otherwise."""+ entry = _entry(settings, peer) or {}+ if entry.get("way_back") is not False:+ return ""+ name = peerlist.label_for(settings["peers"], peer_id=peer) or peerlist.UNNAMED+ return f"{name} has no way back to this machine: none of its edges leads here. Its own Crossing page says why."+++def settle(settings: dict, peer: str, here: str) -> list:+ """After a machine's side moved here: its zones that now clash with another machine's are turned+ off, as when the side arrives from that machine, and a sentence for each is returned."""+ entry = _entry(settings, peer)+ return _turn_off_clashes(settings, entry, here) if entry is not None else []+++def _turn_off_clashes(settings: dict, entry: dict, here: str) -> list:+ sides = {item.get("id"): item.get("side", "") for item in settings["peers"]}+ peers = settings["peers"]+ covered = {}+ mine = []+ for zone in settings["zones"]:+ if zone.get("off") is True:+ continue+ if zone.get("peer") == entry.get("id"):+ mine.append(zone)+ continue+ for stretch in _stretch(zone, sides):+ covered.setdefault(stretch, zone.get("peer"))+ notices = []+ name = peerlist.label_for(peers, peer_id=entry.get("id")) or peerlist.UNNAMED+ for zone in mine:+ stretch = _stretch(zone, sides)+ other = next((covered[item] for item in sorted(stretch) if item in covered), None)+ if other is None:+ for item in stretch:+ covered.setdefault(item, entry.get("id"))+ continue+ zone["off"] = True+ other_name = peerlist.label_for(peers, peer_id=other) or peerlist.UNNAMED+ notices.append(f"{other_name} and {name} now lead from the same part of {here}'s screen, so {name}'s "+ f"{KIND_WORDS.get(zone.get('kind'), 'zone')} is off.")+ return notices+++def _sendable(entry: dict) -> bool:+ return bool(entry.get("id")) and entry.get("send") is True and entry.get("port") != 0+++def shortcut_peer(peers: list, last: Optional[str], ready: Callable[[str], bool]) -> Optional[str]:+ """The machine the shortcut, the Send button and the tray send this machine's input to: the one+ it was last on while that one can take it, else the first in the list that can, else the first+ this machine sends to at all, so the refusal or the wake names it. Never a machine this one does+ not send to, a phone, or an entry with no id yet. `ready(id)` says whether one can take input now."""+ candidates = [entry["id"] for entry in peers if _sendable(entry)]+ if last in candidates and ready(last):+ return last+ return next((ident for ident in candidates if ready(ident)), candidates[0] if candidates else None)+++def missing_pairings(settings: dict, peer: str) -> list:+ """The machines that may drive this one and that a zone to `peer` cannot take onward, because+ they are not paired with `peer` (section 5, "What the Crossing page may offer"). A machine is+ judged only once it has linked, since its `paired` list arrives on a link."""+ return [entry for entry in settings["peers"]+ if entry.get("id") != peer and entry.get("allow_drive") is True and entry.get("linked") is True+ and peer not in (entry.get("paired_with") or [])]+++def missing_sentence(settings: dict, peer: str, here: str) -> str:+ """The Crossing page's sentence for `missing_pairings`, "" when there are none."""+ missing = missing_pairings(settings, peer)+ if not missing:+ return ""+ peers = settings["peers"]+ names = [peerlist.label_for(peers, peer_id=entry.get("id")) or peerlist.UNNAMED for entry in missing]+ target = peerlist.label_for(peers, peer_id=peer) or peerlist.UNNAMED+ drivers = names[0] if len(names) == 1 else ", ".join(names[:-1]) + " or " + names[-1]+ if len(names) == 1:+ why = f"{names[0]} is not paired with {target}"+ elif len(names) == 2:+ why = f"neither is paired with {target}"+ else:+ why = f"none of them is paired with {target}"+ return f"While {drivers} drives {here}, this way to {target} does nothing: {why}. Pair them to use it from there too."diff --git a/mac_app/bridge.py b/mac_app/bridge.pyindex 9ea7971..59c2625 100644--- a/mac_app/bridge.py+++ b/mac_app/bridge.py@@ -29,6 +29,7 @@ from core import owner as owner_modulefrom core import peerlistfrom core import protocolfrom core import receiver+from core import waysfrom pointer_hide import PointerHiderfrom key_codes import (KEY_NAME_TO_CODE,@@ -627,7 +628,85 @@ class KVMController:self._home_notify = Trueself._home_presses = set()self._letting_go = False+ # The machine this Mac's input was last on, which the shortcut goes back to.+ self._last_peer = Noneself._sync_links()+ self.crossing = self._crossing_engine()++ # The machines, and which one a shortcut or a status means++ def _crossing_engine(self):+ """This Mac's zones for every machine it sends to (WIRE.md section 8). A controller made from a+ Config alone has the flat crossing settings for its one machine instead."""+ if self._memory is not None:+ if not self.cfg.send_to_windows:+ return crossing.CrossingEngine(resistance_px=self.cfg.crossing["resistance_px"],+ block_while_dragging=self.cfg.crossing["block_while_dragging"], ways=[])+ return crossing.CrossingEngine.from_config(self.cfg.crossing)+ peers = [entry for entry in self.book.peers() if entry.get("send") is True]+ return crossing.CrossingEngine.from_zones(self.cfg.crossing, self.book.zones(), peers)++ def zones_changed(self):+ """A machine's side or zones changed in the settings: the engine is built again from them."""+ self.crossing = self._crossing_engine()++ def _ready(self, peer):+ """Whether `peer` can take this Mac's input now: its link is up and it accepts input."""+ link = self._peers_up.get(peer) if peer else None+ return link is not None and link.live() and self._accepts.get(peer, False)++ def _crossing_ready(self, peer):+ """Whether a zone to `peer` has a wall now: its link is up, this Mac sends to it, and it is not+ held back after a refusal, as Windows' zones are, since a push that cannot take it must not pin+ the pointer and glow as if it would. One that does not accept input keeps its wall, so the push+ says why it cannot cross. The one machine of a Config-built controller is its primary link's."""+ if peer is None:+ link = self._primary_link+ peer = link.peer_id if link is not None else None+ link = self._peers_up.get(peer) if peer else None+ if link is None or not link.live() or not self._may_send(peer):+ return False+ with self._owner_lock:+ return not self.owner.held_back(peer)++ def _may_send(self, peer):+ """Whether this Mac's direction switch for `peer` is on, as the settings have it this moment:+ its link goes only at the next sync."""+ if self._memory is not None:+ return bool(self.cfg.send_to_windows)+ return any(entry.get("id") == peer and entry.get("send") is True for entry in self.book.peers())++ def _zone_peer(self, step):+ """The machine a push through a zone goes to; a Config-built controller's one machine has no id in its zones."""+ if step.peer is not None:+ return step.peer+ link = self._primary_link+ return link.peer_id if link is not None else None++ def _shortcut_peer(self):+ """The machine the shortcut, the Send button and the menu's own item send input to (core/ways.py)."""+ if self._memory is not None:+ link = self._primary_link+ return link.peer_id if link is not None and link.peer_id else None+ return ways.shortcut_peer(self.book.peers(), self._last_peer, self._ready)++ def _link_of(self, peer):+ """The link to `peer`, up or not; None when this Mac has none to it."""+ link = self._peers_up.get(peer) if peer else None+ if link is not None:+ return link+ for candidate in list(self.links.values()):+ if candidate.peer_id == peer or (candidate.entry() or {}).get("id") == peer:+ return candidate+ return None++ def _in_question(self):+ """The machine the window's status speaks of: where input is, else where the shortcut would send it."""+ return self.owner.on or self._shortcut_peer()++ def _status_link(self):+ link = self._link_of(self._in_question())+ return link if link is not None else self._primary_link# The machine, as its links say it@@ -648,9 +727,15 @@ class KVMController:@propertydef 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)+ """The machine the window's status speaks of (where input is, else where the shortcut would+ send it), as the window shows it: its name, with the end of its id where two share one; the+ first machine when neither is known, None when nothing is paired."""+ peer = self._in_question()+ if peer:+ label = self._label(lambda entry: entry.get("id") == peer)+ if label:+ return label+ return self._label(lambda entry: entry.get("token") == self._primary_token)@propertydef on_label(self):@@ -671,9 +756,11 @@ class KVMController:@propertydef connection_status(self):- link = self._primary_link+ link = self._status_link()if link is not None and link.peer_locked:return f"Unlocking {self.peer_label or 'the other machine'}…"+ if link is not None and link is not self._primary_link and link.status:+ return link.statusreturn self._connection_status@connection_status.setter@@ -682,27 +769,28 @@ class KVMController:@propertydef status_kind(self):- """What the primary link last did, as core.link.OutboundLink.kind says it."""- link = self._primary_link+ """What the link to the machine in question last did, as core.link.OutboundLink.kind says it."""+ link = self._status_link()return link.kind if link is not None else "none"@propertydef via_tunnel(self):- link = self._primary_link+ link = self._status_link()return bool(link is not None and link.via_tunnel and link.live())@propertydef windows_locked(self):- link = self._primary_link+ link = self._status_link()return bool(link is not None and link.peer_locked)@propertydef 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():+ """Whether every machine with a link up keeps Same on all machines, None while no link is up:+ one that does not is left out of it, and the window says so."""+ live = [link for link in list(self._peers_up.values()) if link.live()]+ if not live:return None- return "settings" in link.caps+ return all("settings" in link.caps for link in live)@propertydef full_screen_app(self):@@ -718,7 +806,7 @@ class KVMController:@propertydef connected(self):- link = self._primary_link+ link = self._status_link()return link is not None and link.live()@property@@ -732,10 +820,8 @@ class KVMController:few seconds. The upper median of the last few trips, so an even count rounds towards theslower one. The responder holds each `ack` for however long it waited to batch it and saysso (`held_us`), which the link has already taken off."""- if not self.redirecting or not self.connected:- return None- link = self._peers_up.get(self.owner.on) or self._primary_link- if link is None:+ link = self._peers_up.get(self.owner.on) if self.redirecting else None+ if link is None or not link.live():return Nonetrips = sorted(link.round_trips(ROUND_TRIP_MAX_AGE_SECONDS)[-ROUND_TRIP_SAMPLES:])if not trips:@@ -828,10 +914,10 @@ class KVMController:self.translator.printable_down.clear()self.translator.reset_mouse_accumulators()self.ignore_gate.configure(cfg.ignored_inputs)- self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)- self._crossing_failed = Falseif self._memory is not None:self._memory.follow(cfg)+ self.crossing = self._crossing_engine()+ self._crossing_failed = Falseself._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.@@ -848,25 +934,23 @@ class KVMController:touching the link: the trigger, key map, crossing and how it looks and feels. The settingswindow calls this as each control changes; update_config is for a new address or token,which has to reconnect."""- was = self.cfg.crossing.get("edge") if self.cfg is not None else Nonewith self._cfg_lock:self.cfg = cfg- edge = cfg.crossing.get("edge")- if edge != was and edge in crossing.EDGES:- # The arrangement is one value both machines hold. Changing it- # here is a change for 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))+ # No machine's side goes from here: the flat settings only mirror the first machine's, and a+ # new first machine's would be the default. Sides go from the window, one machine at a time+ # (`send_arrangement`), and with every link that comes up.self.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]self.ignore_gate.configure(cfg.ignored_inputs)- self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)- self._crossing_failed = Falseif self._memory is not None:self._memory.follow(cfg)+ self.crossing = self._crossing_engine()+ self._crossing_failed = False- def set_redirecting(self, value, edge=None, offset=None, came_home=True):+ def set_redirecting(self, value, edge=None, offset=None, came_home=True, peer=None):"""`edge` and `offset` are the edge of the other machine and fraction along it acrossing arrives at; absent for the shortcut, when it leaves its pointer where it is.+ `peer` is the machine to send input to: a zone's, or one a menu names; without it, the+ machine the shortcut picks (core/ways.py).Input coming home this way is a switch, the shortcut or the menu, and says so throughon_crossing as "home" with where the pointer is, for the arrival that shows it.@@ -875,10 +959,13 @@ class KVMController:value = bool(value)if not value:self._go_generation += 1- if value == self.redirecting:+ onward = value and self.redirecting and peer is not None and peer != self.owner.on+ if value == self.redirecting and not onward:return Falseif value:- return self._redirect(edge, offset)+ # A menu naming another machine while input is away moves it straight there (WIRE.md+ # section 5, "Moving input"): the owner lets go of the one it leaves in the same route.+ return self._redirect(edge, offset, peer)self._return_local()self.logger.info("input returned to this Mac")if came_home:@@ -887,29 +974,39 @@ 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}")+ def _cannot_reach(self, peer):+ """Why a switch to `peer` cannot start, in the words its link last used."""+ link = self._link_of(peer)+ if link is None or link is self._primary_link:+ status = self.connection_status+ else:+ status = link.status or "Waiting to connect"+ name = self._name_of(peer) if peer else None+ return status if not name or name in status else f"{name}: {status}"++ def _redirect(self, edge, offset, peer=None):+ peer = peer or self._shortcut_peer()+ link = self._peers_up.get(peer) if peer else None+ if link is None or not link.live():+ self.logger.warning("cannot redirect: %s is not connected", self._name_of(peer) if peer else "the other machine")+ self._alert("Beamer", f"Cannot switch — {self._cannot_reach(peer)}")return Falseif 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_homeif send_home is not None and send_home():- self._go_after_let_go(edge, offset)+ self._go_after_let_go(edge, offset, peer=peer)return Trueself.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")+ if not self._may_send(peer):+ self.logger.info("cannot redirect: sending this Mac's input to %s is switched off", self._name_of(peer))return Falseself.redirect_started_at = self.clock()self._note_clipboard()- peer = link.peer_idself._step(lambda owner: owner.go(peer, edge, offset))- if not self.redirecting:+ if not self.redirecting or self.owner.on != peer:return Falseresponder = self.responderif responder is not None and responder.driven:@@ -920,7 +1017,7 @@ class KVMController:return Falsereturn True- def _go_after_let_go(self, edge, offset, step=None):+ def _go_after_let_go(self, edge, offset, step=None, peer=None):if self._letting_go:returnself._letting_go = True@@ -936,7 +1033,7 @@ class KVMController: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:+ if self.set_redirecting(True, edge, offset, peer=peer) and step is not None:self._notify_crossing("cross", step)finally:self._letting_go = False@@ -1328,19 +1425,12 @@ class KVMController:self._crossing_failed = Falseif not self.crossing.armed:return event- if self.crossing_paused or self.full_screen_app is not None or not self.cfg.send_to_windows:+ if self.crossing_paused or self.full_screen_app is not None:return eventif event_type not in self.translator.movement_event_types:self.crossing.reset()return event- if not self.connected:- return event- peer = self._primary_link.peer_id- with self._owner_lock:- # Held back after a refusal, as Windows' zones are: a push that cannot take it must not- # pin the pointer and glow as if it would.- held_back = bool(peer) and self.owner.held_back(peer)- if held_back:+ if not any(self._crossing_ready(peer) for peer in self.crossing.peers):self.crossing.reset()return eventtry:@@ -1361,6 +1451,7 @@ class KVMController:# Each display's own edges count where nothing lies beyond them, and Part of the# edge measures its thirds along the pointer's display.displays=self._current_displays(),+ ready=self._crossing_ready,)except Exception:self._crossing_failed = True@@ -1377,9 +1468,9 @@ class KVMController:if send_home is None or not send_home():self.logger.warning("cannot cross: another machine is driving this Mac and cannot be reached")return event- self._go_after_let_go(step.edge, step.offset, step)+ self._go_after_let_go(step.edge, step.offset, step, peer=self._zone_peer(step))return event- if self.set_redirecting(True, edge=step.edge, offset=step.offset):+ if self.set_redirecting(True, edge=step.edge, offset=step.offset, peer=self._zone_peer(step)):self._notify_crossing("cross", step)return Nonereturn event@@ -1618,7 +1709,7 @@ class KVMController: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,+ state=self._link_state, up=self._link_up, message=self._link_message,socket_factory=self.socket_factory,tunnel=self._connect_via_ssh_fallback if token == first else None,clock=self.clock, reconnect_seconds=self.cfg.reconnect_interval_s, **hardware,@@ -1639,6 +1730,7 @@ class KVMController:"""The peers changed under the links (a pairing made or removed): bring the links in step,and tell every peer we can send to who else this machine has (`paired`)."""self._sync_links()+ self.zones_changed()for link in list(self.links.values()):link.refresh()if link.live():@@ -1688,10 +1780,6 @@ class KVMController:"Open /Applications/Beamer Tunnel.command",) from exc- 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"@@ -1726,10 +1814,16 @@ class KVMController:self._step(lambda owner: owner.link_down(peer))returnself.logger.info("connected to %s", fields["name"])+ # The handshake may have just given a migrated machine its id, and its zones with it.+ self.zones_changed()self._announce_to(link, fields)+ self._peer_up(link, fields)if link.token == self._primary_token:self._primary_up(link, fields)+ def _peer_up(self, link, fields):+ """Any machine's link is up: a hook for WakingController, which learns its hardware address."""+def _primary_up(self, link, fields):"""The primary peer's link is up: its saved address is the one now in use. A hook forWakingController, which learns the hardware address."""@@ -1753,7 +1847,8 @@ class KVMController: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))+ link.post(protocol.arrangement_v6(entry["side"], entry.get("side_set_at", 0), by,+ way_back=self.way_back(link.peer_id)))if "settings" in link.caps:try:announcements = list(self.announce())@@ -1832,25 +1927,30 @@ class KVMController: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."""+ """A machine changed which edge of its screen faces this one. Handed to the app, which owns+ the settings file, as (that machine's id, its edge, the stamp, who made it); nothing is+ applied here."""read = protocol.read_arrangement_v6(message, time.time())- if read is None or self.on_arrangement is None:- 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")+ if read is None or self.on_arrangement is None or not peer: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+ self.on_arrangement(peer, read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back"))++ def way_back(self, peer):+ """Whether one of this Mac's zones in use leads to `peer` and can fire: what every `arrangement`+ to it says as `way_back` (WIRE.md section 8)."""+ with self.book.lock:+ return ways.has_way({"peers": self.book.peers(), "zones": self.book.zones()}, peer)++ def send_arrangement(self, peer, mac_edge, set_at, by=None):+ """Tell `peer` which edge of this Mac faces it, stamped `set_at` by `by` (a b64 id, this Mac when+ None), with whether a way leads there, over this Mac's own link to it. Sent straight out: it is+ not input, and it goes whether or not input is redirected. False when that link is not up; the+ app then tries the link the peer opened."""+ link = self._peers_up.get(peer) if peer else Noneif link is None or not link.live():return False- return link.post(protocol.arrangement_v6(mac_edge, int(set_at), bytes(self.identity()["id"])))+ author = protocol.read_id(by) or bytes(self.identity()["id"])+ return link.post(protocol.arrangement_v6(mac_edge, int(set_at), author, way_back=self.way_back(peer)))def send_settings(self, data, source=None):"""Tell every peer that keeps Same on all machines this Mac's state, but `source` (the peer@@ -1879,11 +1979,13 @@ class KVMController:"""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)):+ if not isinstance(action, (owner_module.Send, owner_module.SendClipboard, owner_module.SetClipboard, owner_module.Drop)):effects.append(action)continuetry:- if isinstance(action, (owner_module.Send, owner_module.SendClipboard)):+ if isinstance(action, owner_module.Drop):+ self._drop(action.peer)+ elif isinstance(action, (owner_module.Send, owner_module.SendClipboard)):self._deliver(action)else:self._on_pasteboard(lambda message=action.message: self._set_clipboard(message))@@ -1973,6 +2075,14 @@ class KVMController:except Exception:self.logger.exception("a message held behind the clipboard could not be sent")+ def _drop(self, peer):+ """A hand-over given up before its answer: that machine's link is closed, which ends any+ ownership a late accept began there, and it reconnects (WIRE.md section 5)."""+ self._forget_held(peer)+ link = self._peers_up.get(peer)+ if link is not None:+ link.drop(owner_module.DROPPED)+def _forget_held(self, peer):"""`peer`'s link is lost: what waited for its clipboard is for a link that is gone."""with self._clip_lock:@@ -2024,6 +2134,7 @@ class KVMController:self.cursor_pin_point = self._capture_cursor_pin_point()self._set_cursor_follows_mouse(False)self.pointer.hide()+ self._last_peer = moved.toself.logger.info("redirecting input to %s", self._name_of(moved.to))returnself._local_cleanup()@@ -2084,7 +2195,7 @@ class KVMController:def _send_clipboard(self, peer, waiting):"""Read this Mac's clipboard and send it as a clipboard message. Text over CLIPBOARD_MAX_BYTES- and an image over CLIPBOARD_IMAGE_MAX_BYTES are each dropped on their own, so an oversized+ and an image protocol.png_fits refuses are each dropped on their own, so an oversizedscreenshot still lets its text through; with nothing left nothing is sent. Nothing is senteither when `waiting` was dropped with its link while the pasteboard was read."""if self._peers_up.get(peer) is None:@@ -2099,12 +2210,8 @@ class KVMController: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- if image is not None and len(image) > protocol.CLIPBOARD_IMAGE_MAX_BYTES:- self.logger.warning(- "local clipboard image is %d bytes, over the %d cap; skipping the image",- len(image),- protocol.CLIPBOARD_IMAGE_MAX_BYTES,- )+ if image is not None and not protocol.png_fits(image):+ self.logger.warning("local clipboard image (%d bytes) is past what a clipboard may carry; skipping the image", len(image))image = Noneif not text and image is None:self.logger.debug("local clipboard is empty; not sending it")diff --git a/mac_app/config.py b/mac_app/config.pyindex f6502ba..f8744fc 100644--- a/mac_app/config.py+++ b/mac_app/config.py@@ -77,7 +77,7 @@ class Config:check_updates: bool = True# Every address the window shows is hidden; see pages.redact.hide_addresses: bool = False- # Same on both machines: the Crossing and Design pages kept in step with the PC's, and the unix+ # Same on all machines: the Crossing and Design pages kept in step with the PC's, and the unix# seconds of the last change to that or to a shared value; see settings_sync.same_on_both: bool = Falsesame_set_at: int = 0diff --git a/mac_app/crossing.py b/mac_app/crossing.pyindex fbdf3f5..9f8f3ae 100644--- a/mac_app/crossing.py+++ b/mac_app/crossing.py@@ -80,10 +80,10 @@ def tick_fires(steps, pressure):@dataclassclass Step:"""What the bridge does with one movement event. `hold` means swallow it and warp the- pointer back to `pin`; `crossed` means hand input to Windows, arriving at `edge` (a Windows- edge) at `offset` along it. `mac_edge` and `region` describe the strip being pushed, for- the glow, and `via` names the method that owns that strip, so the notch can get its own- feedback; `pressure` is the fraction of the way to breakthrough."""+ pointer back to `pin`; `crossed` means hand input to `peer`, the machine the zone leads to,+ arriving at `edge` (that machine's edge) at `offset` along it. `mac_edge` and `region` describe+ the strip being pushed, for the glow, and `via` names the method that owns that strip, so the+ notch can get its own feedback; `pressure` is the fraction of the way to breakthrough."""pressure: float = 0.0hold: bool = False@@ -95,6 +95,19 @@ class Step:mac_edge: str = Noneregion: tuple = Nonevia: str = None+ peer: str = None+++@dataclass(frozen=True)+class Ways:+ """One machine's zones on this Mac (WIRE.md section 8): the kinds in use, the side it is on, the+ thirds of that side and the corner. `peer` is its id, None for an engine built the 1.4.x way."""++ peer: str+ methods: frozenset+ edge: str+ parts: frozenset+ corner: strclass CrossingEngine:@@ -106,11 +119,11 @@ class CrossingEngine:resistance_px=120,block_while_dragging=True,parts=("middle",),+ ways=None,):- self.methods = frozenset(methods)- self.edge = edge- self.parts = frozenset(parts)- self.corner = corner+ if ways is None:+ ways = [Ways(None, frozenset(methods), edge, frozenset(parts), corner)]+ self.ways = list(ways)self.resistance_px = float(resistance_px)self.block_while_dragging = block_while_draggingself.reset()@@ -126,9 +139,61 @@ class CrossingEngine:parts=crossing.get("edge_parts", ("middle",)),)+ @classmethod+ def from_zones(cls, crossing, zones, peers):+ """An engine for every zone in use that leads to one of `peers` (settings entries, each with+ its `id` and `side`): the machines this Mac can send to now. A machine with no side keeps its+ corner and the notch, which do not need one."""+ sides = {entry.get("id"): entry.get("side") for entry in peers if entry.get("id")}+ found = {}+ for zone in zones:+ peer = zone.get("peer")+ if zone.get("off") is True or peer not in sides:+ continue+ held = found.setdefault(peer, {"methods": set(), "parts": ("middle",), "corner": "top_right"})+ kind = zone.get("kind")+ if kind in ("edge", "part") and sides[peer] not in EDGES:+ continue+ if kind == "part":+ held["parts"] = tuple(part for part in zone.get("parts") or () if part in return_edge.PARTS)+ elif kind == "corner":+ if zone.get("corner") not in CORNERS:+ continue+ held["corner"] = zone["corner"]+ elif kind not in ("edge", "notch"):+ continue+ held["methods"].add(kind)+ ways = [Ways(peer, frozenset(held["methods"]), sides[peer] if sides[peer] in EDGES else "right",+ frozenset(held["parts"]), held["corner"])+ for peer, held in found.items() if held["methods"]]+ return cls(resistance_px=crossing["resistance_px"], block_while_dragging=crossing["block_while_dragging"],+ ways=ways)+@propertydef armed(self):- return bool(self.methods & {"edge", "part", "corner", "notch"})+ return any(way.methods & {"edge", "part", "corner", "notch"} for way in self.ways)++ @property+ def peers(self):+ """The machines this engine's zones lead to."""+ return {way.peer for way in self.ways if way.methods}++ # The one machine's settings, for an engine built the 1.4.x way.+ @property+ def methods(self):+ return self.ways[0].methods if self.ways else frozenset()++ @property+ def edge(self):+ return self.ways[0].edge if self.ways else "right"++ @property+ def parts(self):+ return self.ways[0].parts if self.ways else frozenset()++ @property+ def corner(self):+ return self.ways[0].corner if self.ways else "top_right"def reset(self):self.touching = False@@ -137,6 +202,7 @@ class CrossingEngine:self.mac_edge = Noneself.region = Noneself._quarter_reached = 0+ self._peer = Noneself._last_at = Noneself._last_x = Noneself._last_y = None@@ -149,9 +215,10 @@ class CrossingEngine:remaining = self.pressure - self._decay(now - self._last_at)return max(0.0, min(1.0, remaining / self.resistance_px))- def feed(self, x, y, dx, dy, bounds, now, notch_range=None, dragging=False, displays=None):+ def feed(self, x, y, dx, dy, bounds, now, notch_range=None, dragging=False, displays=None, ready=None):"""`displays` is each display's (left, top, right, bottom), which Part of the edge measures- its thirds along; without them it measures along `bounds`."""+ its thirds along; without them it measures along `bounds`. `ready(peer)` says whether a+ machine can take input now: one that cannot has no wall."""if self._last_at is not None:self.pressure = max(0.0, self.pressure - self._decay(now - self._last_at))self._last_at = now@@ -161,20 +228,26 @@ class CrossingEngine:self.touching = Falsereturn self._release()- target = self._target(x, y, bounds, notch_range, displays)+ target = self._target(x, y, bounds, notch_range, displays, ready=ready)# Whether the pointer is at an armed region at all, whatever the pressure: a slow push# drains to nothing between events and releases, but is still against the edge.self.touching = target is not Noneif target is None:return self._release()- mac_edge, region, diagonal, via = target+ mac_edge, region, diagonal, via, peer = targetoutward, inward = self._push(mac_edge, diagonal, x, y, dx, dy, previous_x, previous_y, self._push_box)if via == "corner" and outward <= 0.0:# A straight push in the corner's box is still a push on the edge it sits on, as on the PC.- edge_target = self._target(x, y, bounds, notch_range, displays, corner=False)+ edge_target = self._target(x, y, bounds, notch_range, displays, corner=False, ready=ready)if edge_target is not None:- mac_edge, region, diagonal, via = edge_target+ mac_edge, region, diagonal, via, peer = edge_targetoutward, inward = self._push(mac_edge, diagonal, x, y, dx, dy, previous_x, previous_y, self._push_box)+ if self._peer is not None and peer != self._peer:+ # Pressure built against one machine's zone is not a push on another's beside it.+ self.pressure = 0.0+ self.pin = None+ self._quarter_reached = 0+ self._peer = peerbefore = self.pressureself.pressure = max(0.0, self.pressure + outward - inward)if self.pressure <= 0.0:@@ -194,6 +267,7 @@ class CrossingEngine:mac_edge=mac_edge,region=region,via=via,+ peer=peer,)self.reset()return step@@ -211,6 +285,7 @@ class CrossingEngine:mac_edge=mac_edge,region=region,via=via,+ peer=peer,)@staticmethod@@ -243,6 +318,7 @@ class CrossingEngine:self.mac_edge = Noneself.region = Noneself._quarter_reached = 0+ self._peer = Nonereturn Step()def _fraction(self, pressure):@@ -255,9 +331,12 @@ class CrossingEngine:return 0return min(3, int(4 * pressure / self.resistance_px))- def _target(self, x, y, bounds, notch_range, displays=None, corner=True):- """Which armed region the pointer is touching, as (mac_edge, region, diagonal, method). The- corner wins over the edge it sits on, since its box is inside that edge's strip."""+ def _target(self, x, y, bounds, notch_range, displays=None, corner=True, ready=None):+ """Which armed region the pointer is touching, as (mac_edge, region, diagonal, method, peer).+ Every machine's corners are checked first, then edges, then thirds, then the notch (WIRE.md+ section 8): a corner wins over the edge it sits on, since its box is inside that edge's strip.+ `ready(peer)`, when given, leaves out the zones of machines that cannot take input now."""+ ways = [way for way in self.ways if ready is None or ready(way.peer)]left, top, right, bottom = boundsx_max, y_max = right - 1, bottom - 1at = {@@ -267,36 +346,43 @@ class CrossingEngine:"bottom": y >= y_max - EDGE_TOLERANCE,}own = next((d for d in displays or () if d[0] <= x < d[2] and d[1] <= y < d[3]), None)- edge_box = bounds- if own is not None and not at[self.edge] and self._exposed(self.edge, x, y, own, displays):- # The edge of a display that stops short of the desktop's, with nothing beyond it: a- # wall all the same, as on the PC. Against the whole desktop it could never be reached.- at[self.edge] = True- edge_box = own+ edge_box = {}+ for edge in {way.edge for way in ways if way.methods & {"edge", "part"}}:+ edge_box[edge] = bounds+ if own is not None and not at[edge] and self._exposed(edge, x, y, own, displays):+ # The edge of a display that stops short of the desktop's, with nothing beyond it: a+ # wall all the same, as on the PC. Against the whole desktop it could never be reached.+ at[edge] = True+ edge_box[edge] = own# What the push is measured against: the display's own edge when that is the wall.self._push_box = bounds- if corner and "corner" in self.methods:- vertical, horizontal = self.corner.split("_")+ for way in ways if corner else ():+ if "corner" not in way.methods:+ continue+ vertical, horizontal = way.corner.split("_")near_x = x <= left + CORNER_PX if horizontal == "left" else x >= x_max - CORNER_PXnear_y = y <= top + CORNER_PX if vertical == "top" else y >= y_max - CORNER_PXif near_x and near_y and (at[horizontal] or at[vertical]):box_x = left if horizontal == "left" else x_max - CORNER_PX + 1box_y = top if vertical == "top" else y_max - CORNER_PX + 1- return horizontal, (box_x, box_y, CORNER_PX, CORNER_PX), vertical, "corner"- if "edge" in self.methods and at[self.edge]:- self._push_box = edge_box- return self.edge, self._strip(self.edge, edge_box), None, "edge"- if "part" in self.methods and at[self.edge]:- # The thirds are the pointer's own display's, as the PC measures them: along the whole- # desktop, a short display beside a tall one could hold none of the middle third.- part = return_edge.part_of(self._offset(self.edge, (x, y), own or bounds))- if part in self.parts:- self._push_box = edge_box- return self.edge, self._part_strip(self.edge, own or bounds, part), None, "edge"- if "notch" in self.methods and notch_range is not None and at["top"]:- notch_left, notch_right = notch_range- if notch_left <= x <= notch_right:- return "top", (notch_left, top, notch_right - notch_left, 1), None, "notch"+ return horizontal, (box_x, box_y, CORNER_PX, CORNER_PX), vertical, "corner", way.peer+ for way in ways:+ if "edge" in way.methods and at[way.edge]:+ self._push_box = edge_box[way.edge]+ return way.edge, self._strip(way.edge, edge_box[way.edge]), None, "edge", way.peer+ for way in ways:+ if "part" in way.methods and at[way.edge]:+ # The thirds are the pointer's own display's, as the PC measures them: along the whole+ # desktop, a short display beside a tall one could hold none of the middle third.+ part = return_edge.part_of(self._offset(way.edge, (x, y), own or bounds))+ if part in way.parts:+ self._push_box = edge_box[way.edge]+ return way.edge, self._part_strip(way.edge, own or bounds, part), None, "edge", way.peer+ for way in ways:+ if "notch" in way.methods and notch_range is not None and at["top"]:+ notch_left, notch_right = notch_range+ if notch_left <= x <= notch_right:+ return "top", (notch_left, top, notch_right - notch_left, 1), None, "notch", way.peerreturn None@staticmethoddiff --git a/mac_app/diagram.py b/mac_app/diagram.pyindex e28d02f..9a8812f 100644--- a/mac_app/diagram.py+++ b/mac_app/diagram.py@@ -53,9 +53,18 @@ def _collapsed(frame, side):class ArrangementDiagram(AppKit.NSView):- """This Mac's screen with the other machine's beside it on the chosen side, lit where a way in crosses."""+ """This Mac's screen in the middle, each placed machine's beside the side it is on, and this+ Mac lit where a way in crosses: the chosen machine's ways in the signal colour, the others'+ quieter, so the picture says which edge leads where."""- HEIGHT = 186.0+ # The screens take the space above the legend row (the key cap and the machines not placed),+ # which they would otherwise run into once neighbours push this Mac off the middle.+ HEIGHT = 210.0+ LEGEND = 36.0+ # A mark's colour by its tone in pages.diagram_marks. A third the chosen machine does not use+ # stays as a dim track while Part of the edge is on, so the gaps read as walls, not as nothing.+ # signal_dim all but vanishes on the dark ground, so the others' marks are signal held back.+ TONES = {"chosen": "signal", "other": ("signal", 0.45), "track": "edge"}def isFlipped(self):return True@@ -69,14 +78,9 @@ class ArrangementDiagram(AppKit.NSView):theme.tint(root, background="ground", border="rule")root.setBorderWidth_(1)root.setCornerRadius_(3)- self.other = _box("panel", "rule", 4)self.this = _box("well", "edge", 4)self.this_label = _text_layer(theme.TYPE["small"], "ink_2")- self.other_label = _text_layer(theme.TYPE["small"], "ink_3")self.notch = _box("ground", None, 2)- self.side = _box("signal", None, 1.5)- self.thirds = {part: _box("signal", None, 1.5) for part in ("start", "middle", "end")}- self.corner = _box("signal", None, 2)self.key = _box("well", "edge", theme.RADIUS["keycap"])# The shortcut as a key cap in the corner, and how it is pressed beside it: a legend, not a# sentence, since the note above the drawing already says it in words.@@ -84,9 +88,13 @@ class ArrangementDiagram(AppKit.NSView):self.key_label.setFont_(theme.font(theme.TYPE["small"], 600))self.key.addSublayer_(self.key_label)self.key_how = _text_layer(theme.TYPE["small"], "ink_3", Quartz.kCAAlignmentLeft)- for layer in (self.other, self.this, self.this_label, self.other_label, self.notch, self.side,- *self.thirds.values(), self.corner, self.key, self.key_how):+ self.not_placed = _text_layer(theme.TYPE["small"], "ink_3", Quartz.kCAAlignmentRight)+ for layer in (self.this, self.this_label, self.notch, self.key, self.key_how, self.not_placed):root.addSublayer_(layer)+ # Made as machines and their marks first appear, by the machine's key, and dropped with it.+ self.screens = {}+ self.marks = {}+ self.machines = []self.state = Noneself.lit = {}self.setAccessibilityElement_(True)@@ -99,68 +107,123 @@ class ArrangementDiagram(AppKit.NSView):self._draw(False)@objc.python_method- def show(self, side, methods, parts, corner, key_text, other_name, has_notch, description, key_how=""):- """Draws the arrangement for these settings, moving from the last one when on screen.- `key_text` is the shortcut's key as its cap reads, `key_how` how it is pressed."""- state = (side, frozenset(methods), frozenset(parts), corner, key_text, other_name, has_notch, key_how)+ def show(self, machines, key_text, has_notch, description, key_how="", shortcut=False):+ """Draws these machines, moving from the last drawing when on screen. Each machine is a dict+ with `key`, `label`, `side` ("" when not placed), its ways (`methods`, `parts`, `corner`) and+ whether it is `chosen`. `key_text` is the shortcut's key as its cap reads, `key_how` how it+ is pressed, `shortcut` whether it is on."""+ state = (tuple((m["key"], m["label"], m["side"], tuple(m["methods"]), tuple(m["parts"]), m["corner"], m["chosen"])+ for m in machines), key_text, has_notch, key_how, shortcut)if state == self.state:returnfirst = self.state is Noneself.state = state+ self.machines = [dict(machine) for machine in machines]self.setAccessibilityLabel_(description)self._draw(not first and motion.live(self))+ @objc.python_method+ def _screen(self, key):+ if key not in self.screens:+ screen = _box("panel", "rule", 4)+ label = _text_layer(theme.TYPE["small"], "ink_3")+ # Under this Mac's marks, which may sit at its edge beside a screen.+ for layer in (screen, label):+ self.layer().insertSublayer_below_(layer, self.this)+ self.screens[key] = (screen, label)+ return self.screens[key]++ @objc.python_method+ def _mark_layer(self, key):+ if key not in self.marks:+ layer = _box("signal", None, 2 if key[1] == "corner" else 1.5)+ self.layer().insertSublayer_above_(layer, self.notch)+ self.marks[key] = layer+ return self.marks[key]+@objc.python_methoddef _draw(self, animate):- side, methods, parts, corner, key_text, other_name, has_notch, key_how = self.state+ _machines, key_text, has_notch, key_how, shortcut = self.state+ machines = self.machinesbounds = self.bounds().sizeif bounds.width <= 0:return- this, other = pages.arrangement(bounds.width, bounds.height, side)+ this, frames = pages.diagram_layout(bounds.width, bounds.height - self.LEGEND, [pages.placement(m) for m in machines])+ # With one machine nothing is chosen between, and it looks as the one-machine drawing did.+ several = len(machines) > 1motion.transaction(animate)self.this.setFrame_(_rect(this))- self.other.setFrame_(_rect(other))self.this_label.setString_("This Mac")- self.other_label.setString_(other_name)line = theme.TYPE["small"] + 4- for layer, (x, y, w, h) in ((self.this_label, this), (self.other_label, other)):- layer.setFrame_(((x + 6, y + (h - line) / 2 + (4 if layer is self.this_label and has_notch else 0)), (w - 12, line)))+ x, y, w, h = this+ self.this_label.setFrame_(((x + 6, y + (h - line) / 2 + (4 if has_notch else 0)), (w - 12, line)))+ keys = {machine["key"] for machine in machines}+ for key in [key for key in self.screens if key not in keys]:+ for layer in self.screens.pop(key):+ layer.removeFromSuperlayer()+ for machine, frame in zip(machines, frames):+ screen, label = self._screen(machine["key"])+ strong = several and machine["chosen"]+ screen.setHidden_(frame is None)+ label.setHidden_(frame is None)+ if frame is None:+ continue+ theme.tint(screen, border="ink_3" if strong else "rule")+ theme.tint(label, foreground="ink" if strong else "ink_3")+ label.setFont_(theme.font(theme.TYPE["small"], 600 if strong else 500))+ screen.setFrame_(_rect(frame))+ label.setString_(machine["label"])+ fx, fy, fw, fh = frame+ label.setFrame_(((fx + 4, fy + (fh - line) / 2), (fw - 8, line)))+ marks, notch = pages.diagram_marks(this, machines)+ for key in [key for key in self.marks if key not in marks]:+ self.marks.pop(key).removeFromSuperlayer()+ self.lit.pop(key, None)+ sides = {machine["key"]: machine["side"] for machine in machines}+ for key, (frame, tone) in marks.items():+ layer = self._mark_layer(key)+ if tone is not None:+ theme.tint(layer, background=self.TONES[tone])+ # The chosen machine's ways on top where two machines' marks meet.+ layer.setZPosition_(1.0 if tone in ("chosen", "track") else 0.0)+ self._mark(key, layer, frame, tone, sides[key[0]] if key[1] != "corner" else None, animate)self.notch.setFrame_(_rect(pages.notch_mark(this)))self.notch.setHidden_(not has_notch)- lit_notch = has_notch and "notch" in methods+ lit_notch = has_notch and notch is not Noneself.notch.setBorderWidth_(1.5 if lit_notch else 0)- theme.tint(self.notch, border="signal", background=("signal", 0.25) if lit_notch else "ground")- part = "part" in methods- self._mark("side", self.side, pages.side_mark(this, side), "edge" in methods, side, animate)- for name, frame in pages.third_marks(this, side).items():- layer = self.thirds[name]- chosen = part and name in parts- # Unchosen thirds stay as a dim track while Part of the edge is on, so the gaps read- # as walls rather than as nothing.- theme.tint(layer, background="signal" if chosen else "edge")- self._mark(name, layer, frame, part, side, animate, lit=chosen)- self._mark("corner", self.corner, pages.corner_mark(this, corner), "corner" in methods, None, animate)- shortcut = "shortcut" in methods and bool(key_text)+ theme.tint(self.notch, border=self.TONES[notch] if lit_notch else "signal",+ background=("signal", 0.25 if notch == "chosen" else 0.12) if lit_notch else "ground")+ shortcut = shortcut and bool(key_text)self.key_label.setString_(key_text)self.key_how.setString_(key_how)+ font = theme.font(theme.TYPE["small"], 500)width = min(bounds.width - 20, 24 + _text_width(key_text, theme.font(theme.TYPE["small"], 600)))top = bounds.height - 36self.key.setFrame_(((12, top), (width, 24)))self.key_label.setFrame_(((0, (24 - line) / 2), (width, line)))- self.key_how.setFrame_(((12 + width + 8, top + (24 - line) / 2), (max(0, bounds.width - width - 32), line)))+ how = _text_width(key_how, font) + 4+ self.key_how.setFrame_(((12 + width + 8, top + (24 - line) / 2), (how, line)))for layer in (self.key, self.key_how):layer.setOpacity_(1.0 if shortcut else 0.0)+ # The machines with no side, on the key cap's line, from wherever the legend ends.+ start = 12 + width + 8 + how + 16 if shortcut else 12+ self.not_placed.setString_(pages.not_placed(machines))+ self.not_placed.setFrame_(((start, top + (24 - line) / 2), (max(0, bounds.width - 12 - start), line)))Quartz.CATransaction.commit()@objc.python_method- def _mark(self, key, layer, frame, on, side, animate, lit=None):+ def _mark(self, key, layer, frame, tone, side, animate):"""Places a mark; switched on or newly lit while moving, it grows out from its middle as- it fades in."""+ it fades in. A mark with no frame (its machine has no side) is not drawn."""+ on = tone is not None and frame is not None# The side is part of the state: moved to another side, a mark grows in afresh there, which# reads far better than a strip stretching across the screen from one side to the other.- state = (on, on if lit is None else lit, self.state[0])+ state = (on, tone, side)was = self.lit.get(key)self.lit[key] = state+ if frame is None:+ layer.setOpacity_(0.0)+ returnif not (on and was != state and animate):layer.setFrame_(_rect(frame))layer.setOpacity_(1.0 if on else 0.0)diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.pyindex 5c103bb..c9869b5 100644--- a/mac_app/kvm_bridge_app.py+++ b/mac_app/kvm_bridge_app.py@@ -50,6 +50,7 @@ from core import protocolfrom core import pairingfrom core import peerlistfrom core import settings_sync+from core import ways as core_waysfrom settings_store import (SettingsError,SettingsStore,@@ -81,6 +82,8 @@ MENU_BAR_STATES = {"held": "Input held on this Mac; crossing is off","windows": "Input on another machine",}+# The menu's one Send input item, by the key rumps files it under, its first title.+TOGGLE_ITEM = "Send input"def menu_bar_glyph(state):@@ -960,6 +963,12 @@ class ControlWindow(AppKit.NSObject):self.haptics = Noneself.previews = Noneself._apply_serial = 0+ self._save_pending = False+ # The machine the Crossing page shows and writes the ways of: an id ("" is the entry+ # migrated from 1.4.x), None while nothing is paired.+ self.chosen_peer = None+ self._picker_choices = None+ self.machine_select = Noneself.page = Noneself.opened = Falseself.window = AppKit.NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(@@ -1033,7 +1042,7 @@ class ControlWindow(AppKit.NSObject):widgets.add(pane, self._commit())self.page_titles = []- # Same on both machines: each shared page's scope line, and the notes on this Mac's own rows.+ # Same on all machines: each shared page's scope line, and the notes on this Mac's own rows.self.scope_labels = {}self.own_notes = []self.page_paddings = []@@ -1156,7 +1165,7 @@ class ControlWindow(AppKit.NSObject):self.updates_switch.value = raw["check_updates"]self.modifier_select.value = raw["key_map"] if isinstance(raw["key_map"], str) else "custom"crossing_raw = raw["crossing"]- self.edge_select.value = crossing_raw["edge"]+ self._load_ways(crossing_raw)self.haptics_box.value = crossing_raw["haptics"]self.glow_box.value = crossing_raw["glow"]self.notch_style_select.value = crossing_raw["notch_style"]@@ -1167,18 +1176,15 @@ class ControlWindow(AppKit.NSObject):@objc.python_methoddef _load_shared(self, raw):- """The controls Same on both machines keeps in step, and nothing else: settings arriving- from the PC must not reset a half-typed address or the pairing card."""+ """The controls Same on all machines keeps in step, and nothing else: settings arriving+ from another machine must not reset a half-typed address, the pairing card, or the chosen+ machine's ways, which are never shared."""self.key_recorder.set_value(raw["trigger_key"])self.style_select.value = raw["trigger_style"]self.double_tap_ruler.value = raw["double_tap_ms"]self.double_tap_numeral.set(str(raw["double_tap_ms"]))crossing_raw = raw["crossing"]- for name, tile in self.method_boxes.items():- tile.value = name in crossing_raw["methods"]- for name, tile in self.part_boxes.items():- tile.value = name in crossing_raw["edge_parts"]- self.corner_select.value = crossing_raw["corner"]+ self.method_boxes["shortcut"].value = "shortcut" in crossing_raw["methods"]self.resistance_ruler.value = crossing_raw["resistance_px"]self.landing_box.value = crossing_raw["shortcut_arrival"]self.switch_style_select.value = crossing_raw["shortcut_arrival_style"]@@ -1281,7 +1287,7 @@ class ControlWindow(AppKit.NSObject):)after = (self.notch_after_select.value or 1200) / 1000self.notch_note.set(- f"Once the pointer is through to the other machine the notch keeps playing for {after:g} seconds, so the "+ f"Once the pointer is through to another machine the notch keeps playing for {after:g} seconds, so the ""animation finishes instead of cutting off.")self._run_previews()@@ -1289,23 +1295,30 @@ class ControlWindow(AppKit.NSObject):notch.set_detail(f"Top edge, {round(notch_range[1] - notch_range[0])} pt wide" if self.has_notch and notch_range else "This Mac has no notch")- self.method_boxes["shortcut"].set_detail(widgets.key_title(self.key_recorder.value))+ # Among the chosen machine's ways the shortcut is the one that is not that machine's: it is+ # this Mac's, and goes where input last went.+ several = len(self.settings_store.current()["peers"]) > 1+ self.method_boxes["shortcut"].set_detail(+ widgets.key_title(self.key_recorder.value) + (", to where input last went" if several else ""))self.ignored_recorder.set_trigger_code(KEY_NAME_TO_CODE.get(self.key_recorder.value))hold = self.style_select.value == "hold"motion.set_hidden(self.double_tap_head, hold)self.style_hint.set(- "Input is on the other machine for as long as the key is held."+ "Input is on another machine for as long as the key is held."if holdelse "Tap twice to switch; tap twice again to come back.")resistance = self.resistance_ruler.valueself.resistance_numeral.set(str(resistance))- self.push_strip.show(resistance / 500.0, link_state.peer_name(self.controller.cfg))+ self.push_strip.show(resistance / 500.0, self._chosen_label())+ side = self.edge_select.valueself.resistance_hint.set("Switches the moment the pointer touches the edge."if resistance == 0else "How far to push past the edge before it gives. It applies as you drag, and lights the "- f"{self.edge_select.value} edge of this screen so you can feel the size of it."+ f"{side} edge of this screen so you can feel the size of it."+ if side+ else "How far to push past the edge before it gives. It applies as you drag.")self.modifier_note.set({"semantic": "On a PC, Command arrives as Control, so Command-C copies there too, and Control arrives as the Windows key. "@@ -1314,21 +1327,124 @@ class ControlWindow(AppKit.NSObject):"Between two Macs every key arrives as itself.",}.get(self.modifier_select.value, "Custom: the key map in settings.json is kept as it is."))+ @objc.python_method+ def _load_ways(self, flat=None):+ """The chosen machine's ways into the page's controls, from the settings (core/ways.py);+ with nothing paired, from `flat`, the crossing settings as 1.4.x kept them. A chosen machine+ no longer paired gives way to the first."""+ settings = self.settings_store.current()+ peers = settings["peers"]+ if self.chosen_peer not in {entry["id"] for entry in peers}:+ self.chosen_peer = peers[0]["id"] if peers else None+ if self.chosen_peer is None:+ flat = flat or self.controller.cfg.crossing+ held = {"side": flat["edge"], "methods": flat["methods"], "parts": flat["edge_parts"], "corner": flat["corner"]}+ else:+ held = core_ways.ways(settings, self.chosen_peer)+ self.edge_select.value = pages.shown_side(held["side"], len(peers))+ for name in core_ways.KIND_WORDS:+ self.method_boxes[name].value = name in held["methods"]+ for name, tile in self.part_boxes.items():+ tile.value = name in held["parts"]+ self.corner_select.value = held["corner"]+ self._show_machines()++ @objc.python_method+ def _show_machines(self):+ """The machine picker, shown with more than one machine paired and built again when the+ machines or their names change, and the words on the page that name the chosen one."""+ settings = self.settings_store.current()+ peers = settings["peers"]+ if self.chosen_peer not in {entry["id"] for entry in peers} and (peers or self.chosen_peer is not None):+ self._load_ways()+ self._reflect()+ return+ labels = peerlist.labels(peers)+ choices = [(entry["id"], self._shown(labels[entry["token"]])) for entry in peers]+ several = len(choices) > 1+ if choices != self._picker_choices:+ self._picker_choices = choices+ for view in list(self.machine_row.arrangedSubviews()):+ self.machine_row.removeArrangedSubview_(view)+ view.removeFromSuperview()+ self.machine_select = None+ if several:+ self.machine_select = widgets.Segmented(choices, columns=min(len(choices), 4), on_change=self._machine_picked)+ widgets.add(self.machine_row, widgets.field_row("Machine", self.machine_select.view)[0])+ motion.set_hidden(self.machine_row, not several)+ if self.machine_select is not None and self.machine_select.value != self.chosen_peer:+ self.machine_select.value = self.chosen_peer+ label = self._chosen_label() if several else None+ caption = pages.where_caption(label)+ if self.edge_caption.text != caption:+ self.edge_caption.set(caption)+ self.edge_select.view.setAccessibilityLabel_(caption)+ self.edge_note.set(pages.notch_or_corner_note(label))+ chosen = self.chosen_peer+ for note, sentence in (+ (self.blocked_note, core_ways.blocked_sentence(settings, chosen, "this Mac") if chosen else ""),+ (self.missing_note, core_ways.missing_sentence(settings, chosen, "this Mac") if chosen else ""),+ (self.no_way_back_note, core_ways.no_way_back_sentence(settings, chosen) if chosen else "")):+ note.set(self._shown(sentence))+ motion.set_hidden(note.view, not sentence)++ @objc.python_method+ def _machine_picked(self, peer):+ # A change still waiting out the pause belongs to the machine being left.+ self._flush()+ self.chosen_peer = peer+ self._load_ways()+ self._reflect()++ @objc.python_method+ def _flush(self):+ """Writes a change still waiting out _changed's pause now, and the pause then writes nothing."""+ if self._save_pending:+ self._apply_serial += 1+ self._apply_settings()++ @objc.python_method+ def _chosen_label(self):+ """What the page calls the chosen machine; with nothing paired, what it always has."""+ peers = self.settings_store.current()["peers"]+ labels = peerlist.labels(peers)+ found = next((labels[entry["token"]] for entry in peers if entry["id"] == self.chosen_peer), None)+ return self._shown(found) if found else link_state.peer_name(self.controller.cfg)++ @objc.python_method+ def _diagram_machines(self, methods):+ """Every machine as the drawing shows it: the chosen one as the controls have it, which may+ be a moment ahead of the settings, the rest as saved."""+ settings = self.settings_store.current()+ peers = settings["peers"]+ live = {+ "side": self.edge_select.value or "",+ "methods": [name for name in methods if name != "shortcut"],+ "parts": [name for name, tile in self.part_boxes.items() if tile.value],+ "corner": self.corner_select.value or "top_right",+ }+ if not peers:+ return [{"key": "", "label": link_state.peer_name(self.controller.cfg), "chosen": True, **live}]+ labels = peerlist.labels(peers)+ machines = []+ for entry in peers:+ chosen = entry["id"] == self.chosen_peer+ held = live if chosen else core_ways.ways(settings, entry["id"])+ machines.append({"key": entry["id"], "label": self._shown(labels[entry["token"]]), "chosen": chosen,+ "side": held["side"], "methods": list(held["methods"]), "parts": list(held["parts"]),+ "corner": held["corner"]})+ return machines+@objc.python_methoddef _show_arrangement(self, methods):- cfg = self.controller.cfg- key = widgets.key_title(self.key_recorder.value)held = self.style_select.value == "hold"- side = self.edge_select.value or "right"- pc = link_state.peer_name(cfg)- where = {"left": "to the left of", "right": "to the right of", "top": "above", "bottom": "below"}[side]sentence = self._ways_in_sentence()self.ways_note.set(sentence + "." if sentence else "No way in is switched on. Choose one below.")+ machines = self._diagram_machines(methods)self.arrangement_diagram.show(- side, methods, [name for name, tile in self.part_boxes.items() if tile.value],- self.corner_select.value or "top_right", widgets.key_cap(self.key_recorder.value), pc,- self.has_notch, f"{pc} is {where} this Mac. {sentence + '.' if sentence else 'No way in is on.'}",- key_how="hold" if held else "double-tap",+ machines, widgets.key_cap(self.key_recorder.value), self.has_notch,+ pages.arrangement_description(machines, sentence), key_how="hold" if held else "double-tap",+ shortcut="shortcut" in methods,)@objc.python_method@@ -1337,12 +1453,15 @@ class ControlWindow(AppKit.NSObject):# follows a moment later, once the ruler stops moving.self.controller.crossing.resistance_px = float(value)self._changed()- if self.preview is not None and self.glow_box.value:+ # A machine not placed yet has no edge to light, and the glow turns itself off for the run+ # on one it cannot draw.+ if self.preview is not None and self.glow_box.value and self.edge_select.value:self.preview(self.edge_select.value, min(1.0, value / 500.0))@objc.python_methoddef _show_peer(self):- """The machine input is on, else the first one paired: its name and address."""+ """The machine the status speaks of (where input is, else where the shortcut would send it), else+ the first one paired: its name and address."""entry = self._focus_entry()if entry is None:self.peer.value.set("—")@@ -1363,8 +1482,8 @@ class ControlWindow(AppKit.NSObject):@objc.python_methoddef _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)+ wanted = self.controller._in_question()+ return next((peer for peer in peers if wanted is not None and peer.get("id") == wanted), peers[0] if peers else None)@objc.python_methoddef _machine_label(self):@@ -1394,14 +1513,14 @@ class ControlWindow(AppKit.NSObject):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."""+ address fields show the first machine. A change still waiting out the pause is written+ first: the page reloads from the settings below, which would otherwise drop it."""+ self._flush()try:cfg = self.settings_store.load()except SettingsError as exc:self.logger.warning("settings not read after the peers changed: %s", exc)return- # 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:@@ -1466,6 +1585,7 @@ class ControlWindow(AppKit.NSObject):applied once the control has been still for a moment, so a ruler being dragged writes onceat the end rather than on every step."""self._reflect()+ self._save_pending = Trueself._apply_serial += 1serial = self._apply_serialAppHelper.callLater(0.3, lambda: serial == self._apply_serial and self._apply_settings())@@ -1584,7 +1704,7 @@ class ControlWindow(AppKit.NSObject):def _same_module(self):module = widgets.Module(spacing=10)module.add(widgets.eyebrow("Settings"))- self.same_switch = widgets.Switch("Same on both machines", on_change=self._set_same)+ self.same_switch = widgets.Switch("Same on all machines", on_change=self._set_same)module.add(self.same_switch.view)self.same_note = widgets.note()module.add(self.same_note.view)@@ -1601,7 +1721,7 @@ class ControlWindow(AppKit.NSObject):@objc.python_methoddef _peer_too_old(self):"""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))]+ links = [(True, getattr(self.controller, "peer_settings", None))]if self.windows_input is not None:links.append((self.windows_input.state == ServerState.CONNECTED, self.windows_input.peer_settings))return any(up and known is False for up, known in links)@@ -1635,7 +1755,7 @@ class ControlWindow(AppKit.NSObject):try:cfg = self.settings_store.save(raw)except SettingsError as exc:- self.logger.warning("Same on both machines not saved: %s", exc)+ self.logger.warning("Same on all machines not saved: %s", exc)returnself.controller.apply_settings(cfg)self._send_same()@@ -1682,13 +1802,13 @@ class ControlWindow(AppKit.NSObject):try:cfg = self.settings_store.save(raw)except (SettingsError, TypeError, ValueError):- self.logger.exception("could not save the settings the PC sent")+ self.logger.exception("could not save the settings %s sent", peer)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")+ self.logger.info("settings from %s applied (same on all machines %s)", peer, "on" if on else "off")self._load_shared(config_to_raw(cfg))self.refresh()@@ -1849,13 +1969,13 @@ class ControlWindow(AppKit.NSObject):hand's movement, and this Mac's settings decide the rest."""module = widgets.Module()figure, self.pointer_numeral = self._numeral("%")- module.add(self._head("The other machine's pointer here", figure))+ module.add(self._head("Another machine's pointer here", figure))self.pointer_ruler = widgets.Ruler(25, 400, (25, 100, 200, 300, 400), step=5, minor=25, on_change=self._speed_moved,title="Pointer speed", arrow_step=25,)module.add(self.pointer_ruler.view)- module.add(widgets.note("Pointer speed for the other machine's mouse or trackpad while it drives this Mac.").view)+ module.add(widgets.note("Pointer speed for another machine's mouse or trackpad while it drives this Mac.").view)figure, self.scroll_numeral = self._numeral("%")module.add(self._head("Scrolling", figure))self.scroll_ruler = widgets.Ruler(@@ -1863,7 +1983,7 @@ class ControlWindow(AppKit.NSObject):title="Scroll speed", arrow_step=25,)module.add(self.scroll_ruler.view)- self.reverse_scroll_box = widgets.Switch("Reverse the other machine's scrolling", on_change=self._changed)+ self.reverse_scroll_box = widgets.Switch("Reverse other machines' scrolling", on_change=self._changed)module.add(self.reverse_scroll_box.view)return module@@ -1928,7 +2048,7 @@ class ControlWindow(AppKit.NSObject):module.add(self.hold_box.view)module.add(self._own_note())module.add(widgets.note(- "Off, your pointer can leave a full-screen game or video, and the other machine's pointer can come home "+ "Off, your pointer can leave a full-screen game or video, and another machine's pointer can go home ""through this Mac's edge. Useful if your keyboard has no key for the shortcut.").view)return module@@ -1953,6 +2073,12 @@ class ControlWindow(AppKit.NSObject):def _ways_module(self):module = widgets.Module()module.add(widgets.eyebrow("Ways in"))+ # With several machines paired, which one everything per machine below shows and writes.+ self.machine_row = widgets.stack(spacing=0)+ self.machine_row.setHidden_(True)+ module.add(self.machine_row)+ # The picker scopes everything under it, so it stands a step apart from what it scopes.+ module.body.setCustomSpacing_afterView_(18, self.machine_row)self.ways_note = widgets.note()module.add(self.ways_note.view)self.arrangement_diagram = diagram.ArrangementDiagram.alloc().init().setup()@@ -1972,13 +2098,13 @@ class ControlWindow(AppKit.NSObject):}module.add(widgets.grid([tile.view for tile in self.method_boxes.values()], 2))module.add(self._own_note(pages.OWN_NOTCH))- # The values are the side of this Mac the other machine is on, which is also the edge that crosses.+ # The values are the side of this Mac the chosen machine is on, which is also the edge that crosses.self.edge_select = widgets.Segmented([("left", "Left"), ("right", "Right"), ("top", "Above"), ("bottom", "Below")], on_change=self._changed)- self.edge_row = widgets.field_row("Where the other machine is", self.edge_select.view)[0]+ self.edge_row, self.edge_caption = widgets.field_row(pages.where_caption(None), self.edge_select.view)module.add(self.edge_row)- self.edge_note = widgets.note(pages.NOTCH_OR_CORNER_NOTE)+ self.edge_note = widgets.note(pages.notch_or_corner_note(None))self.edge_note.view.setHidden_(True)module.add(self.edge_note.view)self.part_boxes = {@@ -1999,6 +2125,15 @@ class ControlWindow(AppKit.NSObject):)self.corner_row = widgets.field_row("Corner", self.corner_select.view)[0]module.add(self.corner_row)+ # What stops a way working, under the ways it is about: a side another machine's edge holds,+ # a machine that may drive this Mac and is not paired with the chosen one, and the chosen one+ # saying none of its own ways leads back here.+ self.blocked_note = widgets.note(ink="amber")+ self.missing_note = widgets.note(ink="amber")+ self.no_way_back_note = widgets.note()+ for note in (self.blocked_note, self.missing_note, self.no_way_back_note):+ note.view.setHidden_(True)+ module.add(note.view)self.dragging_box = widgets.Switch("Don't cross while dragging", on_change=self._changed)module.add(self.dragging_box.view)return module@@ -2060,7 +2195,7 @@ class ControlWindow(AppKit.NSObject):self.ignored_entries = []self.ignored_list = widgets.stack(spacing=6)module.add(self.ignored_list)- self.ignored_empty = widgets.note("Nothing yet. Every key and button goes to the other machine while it has input.")+ self.ignored_empty = widgets.note("Nothing yet. Every key and button goes to the machine that has input.")module.add(self.ignored_empty.view)self.ignored_recorder = widgets.IgnoredRecorder(KEY_NAME_TO_CODE.get(self.key_recorder.value), on_recorded=self._add_ignored@@ -2129,7 +2264,7 @@ class ControlWindow(AppKit.NSObject):module.add(self.glow_box.view)module.add(self._own_note())module.add(widgets.note(- "Lights the edge, the corner or the notch as you push toward the other machine. Switched off, crossing "+ "Lights the edge, the corner or the notch as you push toward another machine. Switched off, crossing ""still works; you feel it rather than see it. Each machine sets how its own edge looks.").view)self.landing_box = widgets.Switch("Show where the pointer lands", on_change=self._changed)@@ -2432,7 +2567,10 @@ class ControlWindow(AppKit.NSObject):# sentence and the drawing's description would otherwise be one change behind.key = widgets.key_title(self.key_recorder.value)methods = {name for name, tile in self.method_boxes.items() if tile.value}- edge = self.edge_select.value or "right"+ edge = self.edge_select.value+ if not edge:+ # A machine not placed yet: its edge and thirds lead nowhere until a side is chosen.+ methods -= {"edge", "part"}parts = []if "shortcut" in methods:parts.append(f"{'Hold' if self.style_select.value == 'hold' else 'Double-tap'} {key}")@@ -2447,7 +2585,10 @@ class ControlWindow(AppKit.NSObject):ways.append("the notch")if ways:joined = ways[0] if len(ways) == 1 else ", ".join(ways[:-1]) + " or " + ways[-1]- parts.append(f"push through {joined}")+ # With several machines the pointer's ways lead to the chosen one; the shortcut goes+ # wherever input last was, so it is not said to.+ several = len(self.settings_store.current()["peers"]) > 1+ parts.append(f"push through {joined}" + (f" to reach {self._chosen_label()}" if several else ""))if not parts:return ""sentence = ", or ".join(parts)@@ -2532,7 +2673,9 @@ class ControlWindow(AppKit.NSObject):@objc.python_methoddef _apply_settings(self):- """Writes every setting outside the Connection page and applies it without dropping the link."""+ """Writes every setting outside the Connection page and applies it without dropping the link:+ this Mac's own through the flat settings, the chosen machine's ways through `set_ways`."""+ self._save_pending = Falseraw = config_to_raw(self.controller.cfg)try:raw["trigger_key"] = self.key_recorder.value@@ -2548,7 +2691,8 @@ class ControlWindow(AppKit.NSObject):raw["crossing"] = {"methods": [name for name, tile in self.method_boxes.items() if tile.value],"edge_parts": [name for name, tile in self.part_boxes.items() if tile.value] or ["middle"],- "edge": self.edge_select.value,+ # Read only while nothing is paired; a machine's side and zones go through set_ways.+ "edge": self.edge_select.value or self.controller.cfg.crossing["edge"],"corner": self.corner_select.value,"resistance_px": self.resistance_ruler.value,"haptics": self.haptics_box.value,@@ -2572,60 +2716,97 @@ class ControlWindow(AppKit.NSObject):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"] = 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")return- # apply_settings sends it over this Mac's own link; the PC's link is- # the other way it can be reached, and either may be the one that is- # up. Both are best-effort and say so by returning False.self.controller.apply_settings(cfg)if self.previews is not None:# The tiles' renderers read the colour from the applied settings, which land only now.self.previews.repaint()- if moved and self.windows_input is not None:- self.windows_input.send_arrangement(- cfg.crossing["edge"], cfg.crossing.get("arrangement_set_at", 0)- )if shared:self._send_same()- self._say("Saved. Changes apply as you make them.", "ink_2")-- @objc.python_method- def apply_arrangement(self, mac_edge, set_at, by=None):- """The peer changed which edge of this Mac leads to it. Applied here- rather than at either link, because this is the side that owns the- settings file. An arrangement 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 None- mine = self.controller.cfg.crossing.get("arrangement_set_at", 0)- 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)+ if self._write_ways():+ self._say("Saved. Changes apply as you make them.", "ink_2")++ @objc.python_method+ def _write_ways(self):+ """The chosen machine's side and zones from the page's controls (core/ways.py), the engine+ built again from them, and a side that moved, or a way there that opened or closed, sent to+ that machine (`_tell`). False, with the store's sentence said and the controls back at what is+ saved, when the store refuses them."""+ peer = self.chosen_peer+ current = self.settings_store.current()+ if peer not in {entry["id"] for entry in current["peers"]}:+ # None chosen, or one removed while its change waited: nothing of its to write.+ return True+ side = self.edge_select.value or ""+ had_way = core_ways.has_way(current, peer)+ # Right is shown for one machine not placed yet, and cannot be picked again while shown: written+ # unstamped, so it crosses here and a side either machine does choose wins over it.+ default = not core_ways.ways(current, peer)["side"] and side == pages.shown_side("", len(current["peers"]))+ try:+ moved = self.settings_store.set_ways(+ peer, side=side, default=default, corner=self.corner_select.value,+ methods=[name for name in core_ways.KIND_WORDS if self.method_boxes[name].value],+ parts=[name for name, tile in self.part_boxes.items() if tile.value] or ["middle"])+ cfg = self.settings_store.load()+ except SettingsError as exc:+ self._say(str(exc), "fault")+ self._load_ways()+ self._reflect()+ return False+ # Straight onto the controller rather than through apply_settings, which would send the+ # first machine's side a second time when that is the machine chosen.+ self.controller.cfg = cfg+ self.controller.zones_changed()+ if moved:+ # A side moved onto another machine's turns this machine's ways there off: show what was kept.+ self._load_ways()+ self._reflect()+ if moved or core_ways.has_way(self.settings_store.current(), peer) != had_way:+ self._tell(peer)+ return True++ @objc.python_method+ def _tell(self, peer):+ """This Mac's side for `peer` as held, with whether a way leads there (WIRE.md section 8), over+ this Mac's link to it, else the one it opened here. Nothing while no side is set."""+ entry = next((item for item in self.settings_store.current()["peers"] if item["id"] == peer), None)+ if entry is None or entry.get("side") not in crossing.EDGES:return- raw = config_to_raw(self.controller.cfg)- raw["crossing"] = {**raw["crossing"], "edge": mac_edge, "arrangement_set_at": int(set_at)}+ side, at, by = entry["side"], entry.get("side_set_at", 0), entry.get("side_by") or None+ if not self.controller.send_arrangement(peer, side, at, by) and self.windows_input is not None:+ self.windows_input.send_arrangement(peer, side, at, by)++ @objc.python_method+ def apply_arrangement(self, peer, edge, set_at, by, way_back=None):+ """A machine changed which of its edges faces this Mac (`edge` is its own). Applied here+ rather than at either link, because this is the side that owns the settings file; kept only+ when newer than the side held for that machine, a tie going to the larger `by` (WIRE.md+ section 8). A side that would put two machines' zones over one stretch turns that machine's+ clashing zones off, and says so. `way_back` is kept whatever the side; a message that changed+ anything here is answered with this Mac's own, so that machine learns at once whether a way+ leads back to it, and one that changed nothing is not, so two machines never answer in turn."""+ # A change still waiting out the pause is written first: the page reloads from the+ # settings below, which would otherwise drop it.+ self._flush()try:- cfg = self.settings_store.save(raw, side_by=by)+ changed, notices = self.settings_store.arrangement(peer, edge, set_at, by, way_back)+ cfg = self.settings_store.load() if changed else Noneexcept (SettingsError, TypeError, ValueError):- self.logger.exception("could not save the arrangement the PC sent")+ self.logger.exception("could not save the arrangement %s sent", peer)+ return+ if not changed:returnself.controller.cfg = cfg- self.controller.crossing = crossing.CrossingEngine.from_config(cfg.crossing)- self.logger.info("the PC moved the crossing to this Mac's %s edge", mac_edge)+ self.controller.zones_changed()+ for notice in notices:+ self.controller._alert("Beamer", notice)+ self.logger.info("%s's arrangement: this Mac's %s edge", peer, crossing.OPPOSITE[edge])+ self._load(config_to_raw(cfg))self.refresh()+ self._tell(peer)def quitApp_(self, _sender):self.quit_handler()@@ -2671,6 +2852,14 @@ class ControlWindow(AppKit.NSObject):self.controller.crossing_paused = not self.controller.crossing_pausedself.refresh()+ @objc.python_method+ def _persist_hardware(self, peer, mac):+ """A machine's hardware address, learnt from the ARP table when its link came up."""+ try:+ self.settings_store.set_hardware(peer, mac)+ except SettingsError as exc:+ self.logger.warning("hardware address not saved: %s", exc)+@objc.python_methoddef _persist_mac(self, _mac):"""The controller has already put the learned address on cfg; this writes it down."""@@ -2740,8 +2929,9 @@ class ControlWindow(AppKit.NSObject):ink="ink_2",)- sentence = self._ways_in_sentence()- self.ways_note.set(sentence + "." if sentence else "No way in is switched on. Choose one below.")+ # Names arrive with each link's hello, and the pairings a zone needs with its `paired`.+ self._show_machines()+ self._show_arrangement([name for name, tile in self.method_boxes.items() if tile.value])state = link_state.describe(controller)rows = self.panel.rows()self._place_machines(not rows)@@ -2768,7 +2958,10 @@ class ControlWindow(AppKit.NSObject):self.spark.setNeedsDisplay_(True)cfg = controller.cfgself._show_peer()- first = controller.peer_label+ # The first machine by name, which the Connection page edits; peer_label follows the+ # machine in question instead.+ peers = controller.book.peers()+ first = peerlist.labels(peers)[peers[0]["token"]] if peers else Noneself.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."))@@ -2806,7 +2999,7 @@ class ControlWindow(AppKit.NSObject):mac = cfg.mac_addressself.wake_state.set(self._shown(mac) if mac else "Not yet learned", ink="ink" if mac else "ink_3")self.wake_hint.set(- "Crossing to the other machine while it sleeps sends a wake-up packet and waits for it."+ self._shown(f"Crossing to {first or 'the other machine'} while it sleeps sends a wake-up packet and waits for it.")if macelse "Read from the network the first time this Mac connects; nothing to type.")@@ -2886,7 +3079,7 @@ class TrayApp(rumps.App):self.controller.on_user_alert = self.notify_userself.controller.on_crossing = self.crossing_feedbackself.controller.on_arrangement = self._arrangement- self.controller.on_mac_learned = lambda mac: AppHelper.callAfter(self.control_window._persist_mac, mac)+ self.controller.on_mac_learned = lambda peer, mac: AppHelper.callAfter(self.control_window._persist_hardware, peer, mac)# The other direction, listening from the moment Beamer opens: the PC# may want to send its own keyboard here before this Mac has ever# crossed the other way.@@ -2898,7 +3091,7 @@ class TrayApp(rumps.App):arrival_callback=self._driven_arrival,)self.control_window.windows_input = self.windows_input- # Same on both machines, over either link: applied on the main thread, and announced+ # Same on all machines, over either link: applied on the main thread, and announced# with the arrangement the moment either link comes up.controller.announce = self._announceself.windows_input.settings_callback = self._settings@@ -2926,7 +3119,9 @@ 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", callback=self.toggle_redirect)+ self.toggle_item = rumps.MenuItem(TOGGLE_ITEM, callback=self.toggle_redirect)+ # With several machines to send to, one item each after the one above, keyed by machine id.+ self._send_keys = []self.pause_item = rumps.MenuItem("Pause crossing", callback=self.toggle_pause)# One tick per direction, so either can be switched off while the other keeps working.self.send_item = rumps.MenuItem("This Mac drives other machines", callback=self.toggle_send_to_windows)@@ -2991,10 +3186,10 @@ class TrayApp(rumps.App):def _settings(self, data, peer=None):AppHelper.callAfter(self.control_window.apply_same, data, peer)- def _arrangement(self, mac_edge, set_at, by=None):- """An arrangement from the PC, over either link, applied on the main+ def _arrangement(self, peer, edge, set_at, by, way_back=None):+ """An arrangement from a machine, 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, by)+ AppHelper.callAfter(self.control_window.apply_arrangement, peer, edge, set_at, by, way_back)def show_on_startup(self, _timer):self.startup_timer.stop()@@ -3033,9 +3228,43 @@ class TrayApp(rumps.App):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._machine_items()self._direction_items()self.status_item.title = pages.redact(link_state.describe(controller).word, hide)+ def _machine_items(self):+ """With more than one machine to send to, Send input to each of them in place of the one+ item, and Bring input back on the one input is on; with one, the one item as it always was."""+ controller = self.controller+ wanted = pages.send_items(controller.book.peers(), controller.owner.on if controller.redirecting else None,+ controller.cfg.hide_addresses)+ keys = [ident for ident, _title in wanted]+ if keys != self._send_keys:+ for key in self._send_keys:+ del self.menu[key]+ anchor = TOGGLE_ITEM+ for ident in keys:+ # Created under its id, which is its key in the menu, then given its words.+ self.menu.insert_after(anchor, rumps.MenuItem(ident, callback=lambda _sender, ident=ident: self._send_to(ident)))+ anchor = ident+ self._send_keys = keys+ for ident, title in wanted:+ self.menu[ident].title = title+ self.toggle_item.hidden = bool(keys)++ def _send_to(self, peer):+ """One machine's item: input goes to it, straight from the machine it is on (WIRE.md section 5,+ "Moving input"), or home when it is already there."""+ controller = self.controller+ if not controller.input_ready:+ self.notify_user("Beamer", "Grant both Mac permissions first.")+ return+ if controller.redirecting and controller.owner.on == peer:+ controller.set_redirecting(False)+ else:+ controller.set_redirecting(True, peer=peer)+ self.refresh_status(None)+def _direction_items(self):"""The two direction ticks, named for the machine when there is one, for every machinewhen there are several; mixed when the machines differ."""diff --git a/mac_app/machines.py b/mac_app/machines.pyindex 3de9513..337acb5 100644--- a/mac_app/machines.py+++ b/mac_app/machines.py@@ -47,10 +47,10 @@ def row(entry: dict, label: str, live: bool, kind: str, status: str, here: bool,def _state(entry, label, live, kind, status, here, driving, inbound, has_link) -> LinkState:- if not protocol.is_paired_token(entry.get("token")):+ if not protocol.linkable(entry):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,+ f"{label} was paired on Beamer 1.4. Pair the two again to link them on 1.5.0.", AMBER,)if driving:return LinkState(diff --git a/mac_app/machines_panel.py b/mac_app/machines_panel.pyindex 039bd09..7a657ba 100644--- a/mac_app/machines_panel.py+++ b/mac_app/machines_panel.py@@ -507,8 +507,8 @@ class MachinesPanel: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)+ for index, (item, shared) in enumerate(zip(heard, peerlist.sharing_a_name(heard))):+ self._heard_row(index, item, item["address"] == chosen, shared)if service is not None and service.error:self.heard_empty.set(f"Beamer cannot look for machines: {service.error}", ink="fault")else:@@ -521,7 +521,7 @@ class MachinesPanel:self.chosen = Noneself._heard_key = None- def _heard_row(self, index, item, picked):+ def _heard_row(self, index, item, picked, shared_name):older = item.get("pairing") != pairing.PAIRING_V3showing = item["pair_id"] is not None and not olderrow = widgets.pressable(lambda index=index: self._choose(index), "well" if picked else "ground",@@ -536,7 +536,9 @@ class MachinesPanel: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)+ # A current machine's row always says where it is; an older one's only where its name is shared.+ where = self._shown(item["address"]) if shared_name or not older else ""+ detail = " · ".join(part for part in ("Older Beamer" if older else platform, where) if part)line.addArrangedSubview_(widgets.Label(detail, theme.TYPE["small"], mono=True, ink="amber" if older else "ink_3").view)row.addSubview_(line)widgets.pin(line, row, (7, 10, 7, 10))diff --git a/mac_app/pages.py b/mac_app/pages.pyindex 13e6c20..e2ed9db 100644--- a/mac_app/pages.py+++ b/mac_app/pages.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport refrom core import effects+from core import peerlist# (key, name, SF Symbol, what the page is for), in sidebar order, which is the order a new Mac is# set up in after the Overview; Cmd+1 is the first.@@ -19,10 +20,10 @@ PAGES = (("permissions", "Permissions", "lock.shield","macOS must allow Beamer to read this keyboard and trackpad before it can send them anywhere."),("crossing", "Crossing", "cursorarrow.motionlines",- "Choose how the pointer or a key moves input to the other machine, and how hard the edge pushes back first."),+ "Choose how the pointer or a key moves input to each machine, and how hard the edge pushes back first."),("keyboard", "Keyboard", "keyboard",- "How this Mac's modifier keys arrive on the other machine, which keys and buttons stay on this Mac, "- "and how fast the other machine's pointer moves here. The switch key is on the Crossing page."),+ "How this Mac's modifier keys arrive on other machines, which keys and buttons stay on this Mac, "+ "and how fast another machine's pointer moves here. The switch key is on the Crossing page."),("design", "Design", "paintpalette","How crossing looks and feels on this Mac: the edge, the corner, the notch and the trackpad."),("connection", "Connection", "network",@@ -32,12 +33,13 @@ 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 other# machine's on the Mac: each app sets only its own machine, and the other's are in Beamer there.SCOPE = {- "crossing": "For this Mac only; the other machine keeps its own. Only which side the other machine is on is shared. This "- "Mac's resistance is also what its pointer meets at the other machine's edge on the way back.",- "design": "For this Mac's screen only; the other machine keeps its own.",- "keyboard": "For this Mac's keyboard only; the other machine keeps its own.",+ "crossing": "For this Mac only; every other machine keeps its own. Only which side each machine is on is shared, "+ "with that machine. This Mac's resistance is also what its pointer meets at another machine's edge on "+ "the way back.",+ "design": "For this Mac's screen only; every other machine keeps its own.",+ "keyboard": "For this Mac's keyboard only; every other machine keeps its own.",}-# With Same on both machines on, under each row of the shared pages that stays this Mac's own.+# With Same on all machines on, under each row of the shared pages that stays this Mac's own.OWN_ROW = "This Mac only."OWN_NOTCH = "The notch is this Mac only."# The window's footer, and the pages where its first sentence would be untrue.@@ -180,20 +182,144 @@ MARK = 3.0CORNER_MARK = 12.0+DIAGRAM_SPLIT_GAP = 6.0+DIAGRAM_MARGIN = 12.0+SIDES = ("left", "right", "top", "bottom")+PART_ORDER = ("start", "middle", "end")++def arrangement(width, height, side):- """Where the two screens sit in a diagram `width` by `height`, top left at the origin: (this,- other) as (x, y, w, h), the pair centred with the other screen on `side` of this one."""+ """Where the two screens sit with one machine paired: (this, other) as (x, y, w, h)."""+ this, (other,) = diagram_layout(width, height, [(side, None)])+ return this, other+++def diagram_layout(width, height, machines):+ """Where this Mac and each machine sit in a drawing `width` by `height`, top left at the origin.+ `machines` is (side, first third) per machine: side "" when it is not placed, first third the+ index of its first third when it crosses by Part of the edge, else None. Returns (this, frames),+ a frame (x, y, w, h) or None for each machine. Two or more on one side share it, each as much+ shorter as there are of them, in the order of their thirds when all have some, else of the+ list; the whole is centred, and shrinks to fit only when it must."""tw, th = DIAGRAM_THISow, oh = DIAGRAM_OTHER- if side in ("left", "right"):- left = (width - (tw + DIAGRAM_GAP + ow)) / 2- this_x = left + ow + DIAGRAM_GAP if side == "left" else left- other_x = left if side == "left" else left + tw + DIAGRAM_GAP- return (this_x, (height - th) / 2, tw, th), (other_x, (height - oh) / 2, ow, oh)- top = (height - (th + DIAGRAM_GAP + oh)) / 2- this_y = top + oh + DIAGRAM_GAP if side == "top" else top- other_y = top if side == "top" else top + th + DIAGRAM_GAP- return ((width - tw) / 2, this_y, tw, th), ((width - ow) / 2, other_y, ow, oh)+ placed = [None] * len(machines)+ for side in SIDES:+ at = [index for index, (where, _third) in enumerate(machines) if where == side]+ if at and all(machines[index][1] is not None for index in at):+ at.sort(key=lambda index: machines[index][1])+ count = len(at)+ if not count:+ continue+ w, h = ow / count, oh / count+ upright = side in ("left", "right")+ step = (h if upright else w) + DIAGRAM_SPLIT_GAP+ start = ((th if upright else tw) - (step * count - DIAGRAM_SPLIT_GAP)) / 2+ for order, index in enumerate(at):+ along = start + order * step+ placed[index] = {+ "left": (-DIAGRAM_GAP - w, along), "right": (tw + DIAGRAM_GAP, along),+ "top": (along, -DIAGRAM_GAP - h), "bottom": (along, th + DIAGRAM_GAP),+ }[side] + (w, h)+ frames = [(0.0, 0.0, tw, th)] + [frame for frame in placed if frame is not None]+ left = min(x for x, _y, _w, _h in frames)+ top = min(y for _x, y, _w, _h in frames)+ span_w = max(x + w for x, _y, w, _h in frames) - left+ span_h = max(y + h for _x, y, _w, h in frames) - top+ scale = 1.0+ if span_w > width or span_h > height:+ scale = min((width - 2 * DIAGRAM_MARGIN) / span_w, (height - 2 * DIAGRAM_MARGIN) / span_h)+ dx = (width - span_w * scale) / 2 - left * scale+ dy = (height - span_h * scale) / 2 - top * scale++ def fit(frame):+ x, y, w, h = frame+ return (dx + x * scale, dy + y * scale, w * scale, h * scale)++ return fit(frames[0]), [None if frame is None else fit(frame) for frame in placed]+++def placement(machine):+ """A machine as diagram_layout takes it: its side, and its first third when it crosses by Part+ of the edge."""+ parts = [PART_ORDER.index(part) for part in machine["parts"] if part in PART_ORDER]+ return machine["side"] if machine["side"] in SIDES else "", min(parts) if "part" in machine["methods"] and parts else None+++def diagram_marks(this, machines):+ """What lights on this Mac's screen in the drawing. `machines` are dicts with `key`, `side`,+ `methods`, `parts`, `corner` and `chosen`. Returns (marks, notch): marks maps (key, "edge"),+ (key, "corner") and (key, "part", third) to (frame or None, tone or None), the tone "chosen"+ for the chosen machine's ways, "other" for another's, "track" for a third of the chosen+ machine's edge it does not use and no other machine does, and None for nothing lit; notch is+ the tone of the notch, or None."""+ held = {}+ for machine in machines:+ side, methods = machine["side"], machine["methods"]+ if side in SIDES and ("edge" in methods or "part" in methods):+ for part in PART_ORDER if "edge" in methods else machine["parts"]:+ held.setdefault((side, part), []).append(machine["key"])+ marks = {}+ for machine in machines:+ key, side, methods = machine["key"], machine["side"], machine["methods"]+ tone = "chosen" if machine["chosen"] else "other"+ placed = side in SIDES+ marks[(key, "edge")] = (side_mark(this, side) if placed else None, tone if placed and "edge" in methods else None)+ thirds = third_marks(this, side) if placed else {}+ for part in PART_ORDER:+ lit = None+ if placed and "part" in methods:+ if part in machine["parts"]:+ lit = tone+ elif machine["chosen"] and not held.get((side, part)):+ lit = "track"+ marks[(key, "part", part)] = (thirds.get(part), lit)+ marks[(key, "corner")] = (corner_mark(this, machine["corner"]), tone if "corner" in methods else None)+ notch = [machine["chosen"] for machine in machines if "notch" in machine["methods"]]+ return marks, ("chosen" if any(notch) else "other") if notch else None+++_WHERE = {"left": "to the left of", "right": "to the right of", "top": "above", "bottom": "below"}+++def _joined(names):+ return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]+++def not_placed(machines):+ """The line under the drawing naming the machines with no side yet; "" when every one has one."""+ names = [machine["label"] for machine in machines if machine["side"] not in SIDES]+ return f"Not placed yet: {_joined(names)}" if names else ""+++def arrangement_description(machines, sentence):+ """What VoiceOver reads for the drawing: where every machine is, then the chosen one's ways in."""+ where = [f"{machine['label']} is {_WHERE[machine['side']]} this Mac." if machine["side"] in SIDES+ else f"{machine['label']} is not placed yet." for machine in machines]+ return " ".join(where + [sentence + "." if sentence else "No way in is on."])+++def send_items(peers, on, hide):+ """The menu bar's items for sending input with more than one machine to send to: (id, title)+ for each machine this Mac sends to, "Bring input back" on the one input is on (`on`). [] with+ one or none, where the one Send input item stands as it always has."""+ labels = peerlist.labels(peers)+ targets = [entry for entry in peers if entry.get("id") and entry.get("send") is True and entry.get("port") != 0]+ if len(targets) < 2:+ return []+ return [(entry["id"], "Bring input back" if entry["id"] == on else redact(f"Send input to {labels[entry['token']]}", hide))+ for entry in targets]+++def where_caption(label):+ """The caption of the side control: today's words with one machine, the chosen one's name with several."""+ return f"Where {label} is" if label else "Where the other machine is"+++def shown_side(side, machines):+ """The side the page shows for a machine. With one machine paired, or none, one not placed yet+ shows Right as it always has; with several, nothing, so no two default onto one side."""+ return side or ("right" if machines <= 1 else "")def side_mark(screen, side):@@ -297,10 +423,11 @@ def notch_or_corner_only(methods):return bool(chosen & {"notch", "corner"}) and not chosen & {"edge", "part"}-NOTCH_OR_CORNER_NOTE = (- "With only the notch or a corner on, input arrives by the notch's or corner's own side, so this "- "choice does nothing on this Mac; the other machine's own push still follows it."-)+def notch_or_corner_note(label):+ """The note under the side control while only the notch or a corner leads there; `label` is the+ chosen machine's with several paired, None with one."""+ return ("With only the notch or a corner on, input arrives by the notch's or corner's own side, so this "+ f"choice does nothing on this Mac; {label or 'the other machine'}'s own push still follows it.")def crossing_rows(methods):diff --git a/mac_app/settings_store.py b/mac_app/settings_store.pyindex 1bbb99f..26f80d6 100644--- a/mac_app/settings_store.py+++ b/mac_app/settings_store.py@@ -15,6 +15,7 @@ import osimport secretsimport tempfileimport threading+import timefrom pathlib import Pathimport config as config_module@@ -24,6 +25,7 @@ from core import peerlistfrom core import protocolfrom core import receiverfrom core import return_edge+from core import waysfrom crossing import CORNERS, EDGES, GLOW_COLOURS, GLOW_STYLES, HAPTIC_FEELS, HAPTIC_STEPS, METHODS, NOTCH_STYLESfrom key_codes import KEY_NAME_TO_CODE@@ -239,9 +241,8 @@ 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`."""+def _merge_config(base, cfg):+ """`base` with the values of `cfg` written over it: the pairing fields into peers[0], the rest by name."""settings = copy.deepcopy(base)raw = config_to_raw(cfg)machine_id = settings["machine_id"]@@ -265,15 +266,15 @@ def _merge_config(base, cfg, side_by=None):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)+ # A machine's side and zones are written by `set_ways` and `arrangement` only: the flat view+ # mirrors the first machine's, and one read before another machine's arrangement landed+ # would otherwise put the old side back.+ # Its name and hardware address are learnt on its link: written here only with a new address,+ # which clears what was learnt at the old one, or a save from a window read before one was+ # learnt would put the old one back.+ if cfg.host != peers[0].get("host"):+ peers[0].update(name=cfg.pc_name, hw=cfg.mac_address)+ peers[0].update(host=cfg.host, port=cfg.port, send=cfg.send_to_windows, allow_drive=cfg.allow_windows_to_drive)settings["crossing"] = {name: value for name, value in crossing.items() if not (peers and name in MOVED_CROSSING)}@@ -322,8 +323,8 @@ class SettingsStore: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).+ # The snapshot `replaced` came from was taken before this lock: it may have changed+ # or gone since (WIRE.md section 6, item 4).if held is None or held["id"] != replaced.get("id") or held["linked"] != replaced.get("linked"):raise SettingsError("the machine being replaced changed while pairing")peerlist.add_peer(settings, entry, replaced)@@ -352,7 +353,52 @@ class SettingsStore:self.save_settings(settings)return removed- def save(self, raw, side_by=None):+ def set_ways(self, peer, *, side, methods, parts, corner, default=False):+ """Writes one machine's side and zones, as the Crossing page shows them for it (core/ways.py);+ `default` when the side is only the one the page shows for a machine not placed yet. Returns+ whether its side moved, which the caller sends it as `arrangement`; SettingsError, writing+ nothing, for a machine not in the list or zones that would clash with another's."""+ with self.lock:+ settings = copy.deepcopy(self.current())+ try:+ moved = ways.edit(settings, peer, side=side, methods=methods, parts=parts, corner=corner,+ kinds=ZONE_KINDS, corner_edge=lambda corner, _side: _corner_edge(corner), now=time.time(),+ default=default)+ except KeyError:+ raise SettingsError("that machine is no longer paired with this Mac") from None+ if moved:+ # Moved onto a side another machine's edge holds: the side stands and this machine's+ # way there goes off, as when the side arrives from it; the page says who holds it.+ ways.settle(settings, peer, "this Mac")+ self.save_settings(settings)+ return moved++ def set_hardware(self, peer, address):+ """Writes the hardware address learnt for a machine (wake-on-LAN); True when it changed."""+ address = parse_mac(address)+ if address is None:+ return False+ with self.lock:+ settings = copy.deepcopy(self.current())+ entry = next((item for item in settings["peers"] if item["id"] == peer), None)+ if entry is None or entry["hw"] == address:+ return False+ entry["hw"] = address+ self.save_settings(settings)+ return True++ def arrangement(self, peer, edge, set_at, by, way_back=None):+ """A machine's `arrangement`, kept when it is newer than the side held for that machine, and+ its `way_back` whatever the side (core/ways.py). Returns (changed, notices), a sentence for each+ zone it turned off."""+ with self.lock:+ settings = copy.deepcopy(self.current())+ changed, notices = ways.arrangement(settings, peer, edge, set_at, by, "this Mac", way_back)+ if changed:+ self.save_settings(settings)+ return changed, notices++ def save(self, raw):try:cfg = config_module.parse_config(raw)except (config_module.ConfigError, TypeError, ValueError, OverflowError) as exc:@@ -363,7 +409,7 @@ class SettingsStore: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)))+ return self._config(self.save_settings(_merge_config(base, cfg)))@staticmethoddef _without_stale_pairing(cfg, base, handed):@@ -410,6 +456,7 @@ class SettingsStore:learnt = next((peer for peer in settings["peers"] if peer["token"] == unnamed["token"] and peer["id"]), None)if learnt:settings["zones"] = _rename_zones(settings["zones"], "", learnt["id"])+ self._ensure_zones(settings)self._check(settings)self._write(settings)return settings@@ -444,6 +491,7 @@ class SettingsStore:if not isinstance(settings, dict) or settings.get("schema") != SCHEMA:raise SettingsError(f"{self.path.name} is not a schema {SCHEMA} settings file")settings = self._complete(settings)+ self._ensure_zones(settings)self._check(settings)return settings@@ -466,6 +514,14 @@ class SettingsStore:} if settings["peers"] else {**config_module.DEFAULT_CROSSING, **settings["crossing"]}return settings+ @staticmethod+ def _ensure_zones(settings):+ """A machine paired before beta.5 has no zone at all (pairing made none): it gets its edge.+ Run after a learnt id has renamed the migrated machine's zones, or that machine would look+ bare and get a second edge."""+ if isinstance(settings["zones"], list) and all(isinstance(item, dict) for item in settings["peers"] + settings["zones"]):+ ways.ensure_zones(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")@@ -512,24 +568,11 @@ class SettingsStore: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+ """Two zones in use never cover one stretch (WIRE.md section 8); a corner inside an edge is the+ exception, and the notch stands beside the top edge, as 1.4.x let it, but leads to one machine."""+ sentence = ways.clash(settings, "this Mac")+ if sentence is not None:+ raise SettingsError(sentence)def _write(self, settings):self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)diff --git a/mac_app/tests/bridge_fakes.py b/mac_app/tests/bridge_fakes.pyindex 2006ae0..742d8b6 100644--- a/mac_app/tests/bridge_fakes.py+++ b/mac_app/tests/bridge_fakes.py@@ -6,7 +6,7 @@ import loggingimport timeimport config-from core import protocol+from core.tests import pngsclass FakeQuartz:kCGEventKeyDown = 10@@ -155,7 +155,7 @@ def quiet_logger():return logger-FAKE_PNG = protocol.PNG_SIGNATURE + b"\x00" * 64+FAKE_PNG = pngs.png()class FakeClipboard:diff --git a/mac_app/tests/fake_link.py b/mac_app/tests/fake_link.pyindex 77ab388..8730c0d 100644--- a/mac_app/tests/fake_link.py+++ b/mac_app/tests/fake_link.py@@ -21,13 +21,13 @@ CAPS = ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "setticlass FakeLink:- def __init__(self, token, book, identity, *, state=None, up=None, message=None, notice=None, socket_factory=None,+ def __init__(self, token, book, identity, *, state=None, up=None, message=None, socket_factory=None,tunnel=None, clock=None, reconnect_seconds=2.0, hardware=None, large=None):self.token = tokenself.hardware = hardwareself.large = largeself.book = book- self.callbacks = {"state": state, "up": up, "message": message, "notice": notice}+ self.callbacks = {"state": state, "up": up, "message": message}self.tunnel = tunnelself.started = Falseself.stopped = Falsediff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.pyindex 703e8c9..576e514 100644--- a/mac_app/tests/test_bridge.py+++ b/mac_app/tests/test_bridge.py@@ -18,6 +18,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspaimport configimport media_keysfrom core import protocol+from core.tests import pngsfrom bridge import (CONNECT_TIMEOUT_SECONDS,CROSSING_RETRY_SECONDS,@@ -657,6 +658,10 @@ class ClipboardSyncTests(unittest.TestCase):self._take_with(FakeClipboard("shot.png", big))self.assertEqual(self.link.posted[1], protocol.clipboard_msg("shot.png"))+ def test_an_image_too_large_to_decode_is_dropped_but_the_text_is_sent(self):+ self._take_with(FakeClipboard("shot.png", pngs.png(16384, 16384)))+ self.assertEqual(self.link.posted[1], protocol.clipboard_msg("shot.png"))+def test_an_inbound_clipboard_sets_text_and_image(self):fake = FakeClipboard()self.controller.clipboard = fakediff --git a/mac_app/tests/test_crossing_matrix.py b/mac_app/tests/test_crossing_matrix.pyindex 9443a39..beb9d10 100644--- a/mac_app/tests/test_crossing_matrix.py+++ b/mac_app/tests/test_crossing_matrix.py@@ -11,7 +11,7 @@ import unittestsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))-from bridge_fakes import FakeQuartz, crossing_config+from bridge_fakes import PAIRED_TOKEN, FakeQuartz, crossing_configfrom core import protocolfrom core.tests.responder_harness import HEREfrom crossing import CORNERS, EDGES, OPPOSITE, CrossingEngine@@ -161,41 +161,56 @@ class ArrangementFromEitherSideTests(unittest.TestCase):self.store = SettingsStore(os.path.join(self.dir.name, "settings.json"))self.logged = []+ BY = protocol.id_text(b"\xff" * 16)+ SMALL = protocol.id_text(bytes(15) + b"\x01")+def window(self, edge="right", stamp=0):cfg = crossing_config(edge=edge, arrangement_set_at=stamp)self.store.save(config_to_raw(cfg))cfg = self.store.load()+ self.rebuilt = 0+ self.told = []++ def zones_changed():+ self.rebuilt += 1+return types.SimpleNamespace(- controller=types.SimpleNamespace(cfg=cfg, crossing=None),+ controller=types.SimpleNamespace(cfg=cfg, crossing=None, zones_changed=zones_changed, _alert=lambda *a: None),settings_store=self.store,logger=types.SimpleNamespace(info=lambda *a: self.logged.append(a), exception=lambda *a: None),refresh=lambda: None,+ _load=lambda raw: None,+ _flush=lambda: None,+ _tell=lambda peer: self.told.append(peer),)def test_a_newer_arrangement_from_the_pc_is_applied_with_its_stamp_and_arms_the_new_edge(self):window = self.window("right", stamp=100)- self.apply(window, "left", 200)+ self.apply(window, "", "right", 200, self.BY)self.assertEqual(window.controller.cfg.crossing["edge"], "left")self.assertEqual(window.controller.cfg.crossing["arrangement_set_at"], 200)- self.assertEqual(window.controller.crossing.edge, "left")+ self.assertEqual(self.rebuilt, 1)+ # Answered with this Mac's own, so the PC learns whether a way leads back (WIRE.md section 8).+ self.assertEqual(len(self.told), 1)def test_an_older_one_is_ignored(self):window = self.window("right", stamp=200)- self.apply(window, "left", 100)+ self.apply(window, "", "right", 100, self.BY)self.assertEqual(window.controller.cfg.crossing["edge"], "right")+ self.assertEqual(self.rebuilt, 0)- def test_the_same_one_over_the_second_link_changes_nothing_and_logs_nothing(self):+ def test_the_same_one_over_the_second_link_changes_nothing_the_second_time(self):window = self.window("left", stamp=300)- self.apply(window, "left", 300)- self.assertEqual(self.logged, [])+ self.apply(window, "", "left", 400, self.BY)+ self.apply(window, "", "left", 400, self.BY)+ self.assertEqual(self.rebuilt, 1)- def test_two_different_arrangements_stamped_in_the_same_second_each_keep_their_own(self):- # Pinned known gap, not a rule: a tie-break would flip this.- # Nothing breaks the tie, so the machines stay apart until one is changed again; two- # people changing the same setting on two machines in one second is the only way in.+ def test_two_different_arrangements_stamped_in_the_same_second_settle_on_the_larger_id(self):window = self.window("right", stamp=300)- self.apply(window, "left", 300)+ self.apply(window, "", "right", 300, self.SMALL)self.assertEqual(window.controller.cfg.crossing["edge"], "right")+ self.apply(window, "", "right", 300, self.BY)+ self.assertEqual(window.controller.cfg.crossing["edge"], "left")class ArrangementOverTheLinksTests(unittest.TestCase):@@ -215,7 +230,7 @@ class ArrangementOverTheLinksTests(unittest.TestCase):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(duo.mac.send_arrangement(protocol.id_text(HERE), "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))@@ -223,7 +238,7 @@ class ArrangementOverTheLinksTests(unittest.TestCase):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))+ self.assertTrue(duo.mac_input.send_arrangement(protocol.id_text(HERE), "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))@@ -231,8 +246,8 @@ class ArrangementOverTheLinksTests(unittest.TestCase):duo = self.duo()duo.link_mac_to_pc()duo.link_pc_to_mac()- self.assertFalse(duo.mac_input.send_arrangement("left", 500))- self.assertTrue(duo.mac.send_arrangement("left", 500))+ self.assertFalse(duo.mac_input.send_arrangement(protocol.id_text(HERE), "left", 500))+ self.assertTrue(duo.mac.send_arrangement(protocol.id_text(HERE), "left", 500))self.assertTrue(wait_for(lambda: self.heard(duo, 500)))self.assertIsNone(duo.pc.expect(protocol.MSG_ARRANGEMENT, 0.3))@@ -257,7 +272,7 @@ class ArrangementOverTheLinksTests(unittest.TestCase):duo = self.duo(side="")duo.link_mac_to_pc()# 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(duo.mac.send_arrangement(protocol.id_text(HERE), "left", 9))self.assertTrue(wait_for(lambda: self.heard(duo, 9)))self.assertEqual([read["set_at"] for _, read in duo.pc_responder.arrangements], [9])@@ -268,7 +283,7 @@ class WhatIsSharedTests(unittest.TestCase):line = pages.SCOPE["crossing"]self.assertNotIn("Two are shared", line)- self.assertIn("Only which side the other machine is on is shared", line)+ self.assertIn("Only which side each machine is on is shared", line)def pc_at_edge(duo, edge):@@ -385,7 +400,8 @@ class MacToPcTests(unittest.TestCase):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 = False+ # As the switch does: written to the settings, before the link it no longer wants has gone.+ duo.store.set_peer(PAIRED_TOKEN, send=False)x, y = side_point("right", "middle")self.assertFalse(duo.mac_push(x, y, 30))self.assertFalse(duo.mac.set_redirecting(True))@@ -459,7 +475,10 @@ class MacDrivenTests(unittest.TestCase):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(crossing={"methods": methods, "edge": "top"}, side="left")+ # The edge zone named apart from the methods: its side, not the flat crossing edge,+ # is where the PC's pointer comes home.+ duo = self.duo(crossing={"methods": methods, "edge": "top"}, side="left",+ mac_zones=[{"peer": "pc", "kind": "edge"}])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")diff --git a/mac_app/tests/test_crossing_page_machines.py b/mac_app/tests/test_crossing_page_machines.pynew file mode 100644index 0000000..a90fa94--- /dev/null+++ b/mac_app/tests/test_crossing_page_machines.py@@ -0,0 +1,502 @@+"""The Crossing page with several machines paired, in the real settings window (WIRE.md sections 5+and 8): a machine is chosen at the top of Ways in, everything per machine below it shows and writes+that machine's ways, the drawing places every machine, and the menu bar sends input to each. Built+as the README's screenshots build it, never put on screen, starting no network."""++import base64+import copy+import json+import logging+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++import AppKit # noqa: E402+import rumps.rumps as rumps_module # noqa: E402++AppKit.NSApplication.sharedApplication()++import bridge # noqa: E402+import kvm_bridge_app # noqa: E402+import settings_store # noqa: E402+from bridge_fakes import PAIRED_TOKEN # noqa: E402+from core import protocol, ways # noqa: E402+from fake_link import FakeLink # noqa: E402+from wake import WakingController # noqa: E402++BEE = protocol.id_text(bytes(range(40, 56)))+SEA = protocol.id_text(bytes(range(70, 86)))+OAK = protocol.id_text(bytes(range(90, 106)))+++def token(start):+ return base64.urlsafe_b64encode(bytes(range(start, start + 32))).decode("ascii").rstrip("=")+++def entry(ident, secret, name, side="", own="", **extra):+ return {**settings_store.PEER_DEFAULTS, "id": ident, "name": name, "platform": "windows", "token": secret,+ "host": "192.0.2.30", "port": 24820, "paired_at": 1_700_000_000, "linked": True, "side": side,+ "side_set_at": 100 if side else 0, "side_by": own if side else "", **extra}+++class Page(unittest.TestCase):+ """This Mac with Bee on its right by its edge, and Sea on its left by its top third."""++ def setUp(self):+ self.directory = tempfile.TemporaryDirectory()+ self.addCleanup(self.directory.cleanup)+ path = Path(self.directory.name) / "config.json"+ raw = settings_store.config_to_raw(settings_store.editable_default_config())+ raw.update(host="192.0.2.20", auth_token=PAIRED_TOKEN)+ path.write_text(json.dumps(raw))+ self.store = settings_store.SettingsStore(path)+ self.later = []+ patcher = mock.patch.object(kvm_bridge_app.AppHelper, "callLater", lambda _delay, call: self.later.append(call))+ patcher.start()+ self.addCleanup(patcher.stop)++ def build(self, peers, zones=()):+ settings = copy.deepcopy(self.store.current())+ own = settings["machine_id"]+ settings["peers"] = [entry(*peer[:3], **{"own": own, **(peer[3] if len(peer) > 3 else {})}) for peer in peers]+ settings["zones"] = list(zones)+ self.store.save_settings(settings)+ logger = logging.getLogger("test-crossing-page-machines")+ book, identity = bridge.links_from_store(self.store, "1.5.0")+ self.controller = WakingController(self.store.load(), logger=logger, book=book, identity=identity,+ link_factory=FakeLink)+ with mock.patch.object(kvm_bridge_app, "accessibility_granted", return_value=True), \+ mock.patch.object(kvm_bridge_app, "input_monitoring_granted", return_value=True):+ self.window = kvm_bridge_app.ControlWindow.alloc().initWithController_settingsStore_logger_(+ self.controller, self.store, logger)+ self.addCleanup(self.window.appearance_watch.stop)+ self.window.windows_input = mock.Mock()+ self.window.windows_input.send_arrangement.return_value = True+ self.window.windows_input.server.links.return_value = []+ self.sent = []+ self.sent_by = []+ self.controller.send_arrangement = lambda peer, edge, set_at, by=None: (+ self.sent.append((peer, edge, set_at)) or self.sent_by.append(by) or True)+ return self.window++ def two(self):+ return self.build(+ [(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "left"})],+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "part", "parts": ["start"]},+ {"peer": SEA, "kind": "corner", "corner": "bottom_left", "edge": "left"}])++ def ways_of(self, peer):+ return ways.ways(self.store.current(), peer)++ def methods(self):+ return [name for name, tile in self.window.method_boxes.items() if tile.value]++ def toggle(self, way):+ self.window.method_boxes[way]._toggle()++ def pick(self, peer):+ self.window.machine_select._choose(peer)+++class OneOrNoMachine(Page):+ def test_with_one_machine_there_is_no_picker_and_the_page_reads_as_today(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "left"})], [{"peer": BEE, "kind": "edge"}])+ self.assertTrue(window.machine_row.isHidden())+ self.assertEqual(window.edge_caption.text, "Where the other machine is")+ self.assertEqual(window.edge_select.value, "left")+ self.assertEqual(self.methods(), ["edge", "shortcut"])++ def test_one_machine_with_no_side_shows_right_as_it_always_has(self):+ window = self.build([(BEE, token(100), "Bee")])+ self.assertEqual(window.edge_select.value, "right")++ def test_a_save_with_one_machine_not_placed_writes_the_shown_right_unstamped_so_its_own_side_wins(self):+ window = self.build([(BEE, token(100), "Bee")], [{"peer": BEE, "kind": "edge"}])+ window._apply_settings()+ held = self.store.current()["peers"][0]+ self.assertEqual((held["side"], held["side_set_at"], held["side_by"]), ("right", 0, ""))+ self.assertEqual(self.sent, [(BEE, "right", 0)])+ window.apply_arrangement(BEE, "bottom", 1_790_000_000, BEE, True)+ self.assertEqual(self.ways_of(BEE)["side"], "top")++ def test_with_one_machine_a_change_writes_its_ways_and_sends_it_the_side(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "left"})], [{"peer": BEE, "kind": "edge"}])+ window.edge_select._choose("top")+ window._apply_settings()+ self.assertEqual(self.ways_of(BEE)["side"], "top")+ self.assertEqual([(peer, edge) for peer, edge, _at in self.sent], [(BEE, "top")])++ def test_with_none_paired_the_page_writes_the_flat_settings_as_today(self):+ window = self.build([])+ self.assertTrue(window.machine_row.isHidden())+ self.toggle("corner")+ window._apply_settings()+ self.assertIn("corner", self.store.load().crossing["methods"])+++class ChoosingAMachine(Page):+ def test_with_two_machines_the_picker_names_each_and_starts_on_the_first(self):+ window = self.two()+ self.assertFalse(window.machine_row.isHidden())+ self.assertEqual([title for _value, title in window.machine_select.choices], ["Bee", "Sea"])+ self.assertEqual(window.machine_select.value, BEE)+ self.assertEqual(window.edge_caption.text, "Where Bee is")+ self.assertEqual((window.edge_select.value, self.methods()), ("right", ["edge", "shortcut"]))++ def test_choosing_a_machine_shows_its_ways(self):+ window = self.two()+ self.pick(SEA)+ self.assertEqual(window.edge_caption.text, "Where Sea is")+ self.assertEqual(window.edge_select.value, "left")+ self.assertEqual(self.methods(), ["part", "corner", "shortcut"])+ self.assertEqual([name for name, tile in window.part_boxes.items() if tile.value], ["start"])+ self.assertEqual(window.corner_select.value, "bottom_left")+ self.assertEqual(window.push_strip.other_name, "Sea")++ def test_a_change_writes_the_chosen_machines_ways_and_leaves_the_others_alone(self):+ window = self.two()+ bee = self.ways_of(BEE)+ self.pick(SEA)+ self.toggle("notch")+ window._apply_settings()+ self.assertIn("notch", self.ways_of(SEA)["methods"])+ self.assertEqual(self.ways_of(BEE), bee)+ self.assertEqual(self.sent, [])++ def test_a_new_side_is_sent_to_that_machine_and_over_its_own_link_when_this_macs_is_down(self):+ window = self.two()+ self.pick(SEA)+ window.edge_select._choose("top")+ window._apply_settings()+ stamp = next(peer for peer in self.store.current()["peers"] if peer["id"] == SEA)["side_set_at"]+ self.assertEqual(self.sent, [(SEA, "top", stamp)])+ window.windows_input.send_arrangement.assert_not_called()+ self.controller.send_arrangement = lambda *_args: False+ window.edge_select._choose("bottom")+ window._apply_settings()+ window.windows_input.send_arrangement.assert_called_once()+ self.assertEqual(window.windows_input.send_arrangement.call_args.args[:2], (SEA, "bottom"))++ def test_the_engine_is_built_again_once_a_machines_ways_change(self):+ window = self.two()+ self.pick(SEA)+ with mock.patch.object(self.controller, "zones_changed") as rebuilt:+ self.toggle("notch")+ window._apply_settings()+ rebuilt.assert_called()++ def test_a_clash_is_said_naming_both_and_the_controls_go_back_to_what_is_saved(self):+ window = self.two()+ self.pick(SEA)+ # Moved onto Bee's side, Sea keeps the side and its ways there go off (core/ways.py settle).+ window.edge_select._choose("right")+ window._apply_settings()+ sea = next(entry for entry in self.store.current()["peers"] if entry["id"] == SEA)+ self.assertEqual(sea["side"], "right")+ before = copy.deepcopy(self.store.current())+ methods = self.methods()+ self.toggle("edge")+ window._apply_settings()+ self.assertEqual(window.message_label.ink, "fault")+ self.assertIn("Bee", window.message_label.text)+ self.assertIn("Sea", window.message_label.text)+ self.assertEqual(window.edge_select.value, "right")+ self.assertEqual(self.methods(), methods)+ self.assertEqual(self.store.current()["zones"], before["zones"])++ def test_switching_machines_saves_a_change_still_waiting_first(self):+ window = self.two()+ self.toggle("corner")+ self.assertTrue(self.later)+ self.pick(SEA)+ self.assertIn("corner", self.ways_of(BEE)["methods"])+ sea = self.ways_of(SEA)+ for call in self.later:+ call()+ self.assertEqual(self.ways_of(SEA), sea)+ self.assertEqual(self.methods(), ["part", "corner", "shortcut"])++ def test_the_shortcut_resistance_and_drag_guard_stay_this_macs_own(self):+ window = self.two()+ self.pick(SEA)+ held = (self.ways_of(BEE), self.ways_of(SEA))+ dragging = self.store.load().crossing["block_while_dragging"]+ self.toggle("shortcut")+ window.dragging_box._toggle()+ window._apply_settings()+ self.assertFalse(self.store.current()["shortcut"])+ self.assertNotIn("shortcut", self.store.load().crossing["methods"])+ self.assertEqual(self.store.load().crossing["block_while_dragging"], not dragging)+ self.assertEqual((self.ways_of(BEE), self.ways_of(SEA)), held)+ self.pick(BEE)+ self.assertFalse(window.method_boxes["shortcut"].value)++ def test_a_machine_with_no_side_shows_none_with_several_paired(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}), (OAK, token(200), "Oak")],+ [{"peer": BEE, "kind": "edge"}])+ self.pick(OAK)+ self.assertIsNone(window.edge_select.value or None)+ window._apply_settings()+ self.assertEqual(self.ways_of(OAK)["side"], "")++ def test_removing_the_chosen_machine_falls_back_to_the_first_and_one_left_hides_the_picker(self):+ window = self.two()+ self.pick(SEA)+ self.store.remove_peer(token(150))+ window.peers_changed()+ self.assertTrue(window.machine_row.isHidden())+ self.assertEqual(window.edge_select.value, "right")+ self.assertEqual(window.edge_caption.text, "Where the other machine is")++ def test_a_third_machine_paired_joins_the_picker(self):+ window = self.two()+ self.store.add_peer(entry(OAK, token(200), "Oak"))+ window.peers_changed()+ self.assertEqual([title for _value, title in window.machine_select.choices], ["Bee", "Sea", "Oak"])++ def test_a_name_learnt_on_a_link_reaches_the_picker_on_the_next_tick(self):+ window = self.two()+ settings = copy.deepcopy(self.store.current())+ settings["peers"][1]["name"] = "Sea Studio"+ self.store.save_settings(settings)+ window.refresh()+ self.assertEqual([title for _value, title in window.machine_select.choices], ["Bee", "Sea Studio"])++ def test_an_arrangement_from_the_chosen_machine_moves_its_control(self):+ window = self.two()+ self.pick(SEA)+ window.apply_arrangement(SEA, "top", 5000, SEA)+ self.assertEqual(window.edge_select.value, "bottom")+ self.assertEqual(window.machine_select.value, SEA)++ def test_an_arrangement_arriving_keeps_a_change_still_waiting(self):+ window = self.two()+ self.pick(SEA)+ self.toggle("notch")+ window.apply_arrangement(BEE, "right", 5000, BEE)+ self.assertIn("notch", self.ways_of(SEA)["methods"])+ self.assertTrue(window.method_boxes["notch"].value)+ self.assertEqual(self.ways_of(BEE)["side"], "left")++ def test_a_machine_paired_keeps_a_change_still_waiting(self):+ window = self.two()+ self.pick(SEA)+ self.toggle("notch")+ self.store.add_peer(entry(OAK, token(200), "Oak"))+ window.peers_changed()+ self.assertIn("notch", self.ways_of(SEA)["methods"])+ self.assertTrue(window.method_boxes["notch"].value)++ def test_a_change_waiting_for_a_machine_just_removed_is_dropped_without_a_fault(self):+ window = self.two()+ self.pick(SEA)+ self.toggle("notch")+ self.store.remove_peer(token(150))+ window.peers_changed()+ self.assertNotIn(SEA, [item["id"] for item in self.store.current()["peers"]])+ self.assertEqual(window.machine_select, None)++ def test_a_missing_pairing_is_noted_under_the_ways(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "right", "allow_drive": True, "paired_with": []}),+ (SEA, token(150), "Sea", {"side": "left", "allow_drive": True, "paired_with": [BEE]})],+ [{"peer": BEE, "kind": "edge"}])+ expected = ways.missing_sentence(self.store.current(), SEA, "this Mac")+ self.assertTrue(expected)+ self.assertEqual(window.missing_note.view.isHidden(), not ways.missing_sentence(self.store.current(), BEE, "this Mac"))+ self.pick(SEA)+ self.assertFalse(window.missing_note.view.isHidden())+ self.assertEqual(window.missing_note.text, expected)+++class WayBack(Page):+ """`arrangement`'s `way_back` (WIRE.md section 8): what each machine is told, and what it said."""++ def entry_of(self, peer):+ return next(item for item in self.store.current()["peers"] if item["id"] == peer)++ def test_turning_off_every_way_to_a_machine_tells_it_so_with_its_side_as_it_was(self):+ window = self.two()+ self.pick(SEA)+ self.toggle("part")+ self.toggle("corner")+ window._apply_settings()+ self.assertEqual(self.sent, [(SEA, "left", 100)])+ self.assertEqual(self.sent_by, [self.store.current()["machine_id"]])+ self.toggle("corner")+ window._apply_settings()+ self.assertEqual(len(self.sent), 2)++ def test_an_arrangement_that_changed_something_is_answered_with_this_macs_own(self):+ window = self.two()+ window.apply_arrangement(SEA, "top", 5000, SEA, True)+ self.assertEqual(self.sent, [(SEA, "bottom", 5000)])+ self.assertEqual(self.sent_by, [SEA])+ self.assertIs(self.entry_of(SEA)["way_back"], True)+ window.apply_arrangement(SEA, "top", 5000, SEA, True)+ self.assertEqual(len(self.sent), 1)+ window.apply_arrangement(SEA, "top", 5000, SEA, False)+ self.assertEqual(len(self.sent), 2)+ self.assertIs(self.entry_of(SEA)["way_back"], False)++ def test_the_answer_goes_over_the_link_the_machine_opened_when_this_macs_is_down(self):+ window = self.two()+ self.controller.send_arrangement = lambda *_args: False+ window.apply_arrangement(SEA, "top", 5000, SEA, True)+ window.windows_input.send_arrangement.assert_called_once_with(SEA, "bottom", 5000, SEA)+++class TheNotes(Page):+ """What the page says under the ways about a machine it cannot reach, or that cannot reach back."""++ def test_a_machine_whose_side_another_holds_is_named_with_the_one_that_holds_it(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "right"})],+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge", "off": True}])+ self.pick(SEA)+ expected = ways.blocked_sentence(self.store.current(), SEA, "this Mac")+ self.assertIn("Sea has no way in: Bee already leads from the right edge", expected)+ self.assertFalse(window.blocked_note.view.isHidden())+ self.assertEqual(window.blocked_note.text, expected)+ self.pick(BEE)+ self.assertTrue(window.blocked_note.view.isHidden())++ def test_a_machine_that_said_no_way_leads_back_is_named_until_it_says_one_does(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}),+ (SEA, token(150), "Sea", {"side": "left", "way_back": False})],+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge"}])+ self.assertTrue(window.no_way_back_note.view.isHidden())+ self.pick(SEA)+ self.assertFalse(window.no_way_back_note.view.isHidden())+ self.assertEqual(window.no_way_back_note.text, ways.no_way_back_sentence(self.store.current(), SEA))+ window.apply_arrangement(SEA, "right", 5000, SEA, True)+ self.assertTrue(window.no_way_back_note.view.isHidden())+++class TheOverview(Page):+ def test_the_address_shown_is_the_machine_the_status_speaks_of(self):+ window = self.build([(BEE, token(100), "Bee", {"host": "192.0.2.31"}), (SEA, token(150), "Sea", {"host": "192.0.2.32"})])+ with mock.patch.object(self.controller, "_in_question", return_value=SEA):+ window._show_peer()+ self.assertIn("192.0.2.32", window.peer_footer.text)+++class TheDrawing(Page):+ def test_the_drawing_has_every_machine_with_the_chosen_one_marked(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "top"}),+ (OAK, token(200), "Oak")], [{"peer": BEE, "kind": "edge"}])+ self.pick(SEA)+ machines = window.arrangement_diagram.machines+ self.assertEqual([(m["label"], m["side"], m["chosen"]) for m in machines],+ [("Bee", "right", False), ("Sea", "top", True), ("Oak", "", False)])+ self.assertEqual(machines[0]["methods"], ["edge"])+ label = window.arrangement_diagram.accessibilityLabel()+ for words in ("Bee is to the right of this Mac.", "Sea is above this Mac.", "Oak is not placed yet."):+ self.assertIn(words, label)+ drawing = window.arrangement_diagram+ drawing.setFrame_(((0, 0), (480, drawing.HEIGHT)))+ drawing._draw(False)+ self.assertEqual(drawing.not_placed.string(), "Not placed yet: Oak")+ self.assertTrue(drawing.screens[OAK][0].isHidden())+ self.assertFalse(drawing.screens[SEA][0].isHidden())++ def test_the_chosen_machines_drawing_follows_the_controls_before_the_save(self):+ window = self.two()+ self.pick(SEA)+ window.edge_select._choose("bottom")+ sea = window.arrangement_diagram.machines[1]+ self.assertEqual((sea["side"], sea["chosen"]), ("bottom", True))+++class Wording(Page):+ def test_the_switch_is_same_on_all_machines(self):+ window = self.two()+ self.assertEqual(window.same_switch.words.text, "Same on all machines")+++class TheMenuBar(Page):+ def tray(self):+ tray = mock.Mock()+ tray.controller = self.controller+ tray.control_window = self.window+ return tray++ def test_a_machines_item_sends_input_to_it(self):+ self.two()+ self.controller.event_tap = object()+ self.controller.input_error = None+ with mock.patch.object(self.controller, "set_redirecting", return_value=True) as switch:+ kvm_bridge_app.TrayApp._send_to(self.tray(), SEA)+ switch.assert_called_once_with(True, peer=SEA)++ def test_the_item_of_the_machine_input_is_on_brings_it_back(self):+ self.two()+ self.controller.event_tap = object()+ self.controller.input_error = None+ self.controller.owner.on = SEA+ self.controller.redirecting = True+ with mock.patch.object(self.controller, "set_redirecting", return_value=True) as switch:+ kvm_bridge_app.TrayApp._send_to(self.tray(), SEA)+ switch.assert_called_once_with(False)++ def test_another_machines_item_moves_input_straight_there(self):+ self.two()+ self.controller.event_tap = object()+ self.controller.input_error = None+ self.controller.owner.on = BEE+ self.controller.redirecting = True+ with mock.patch.object(self.controller, "set_redirecting", return_value=True) as switch:+ kvm_bridge_app.TrayApp._send_to(self.tray(), SEA)+ self.assertEqual(switch.call_args_list, [mock.call(True, peer=SEA)])++ def menu_tray(self):+ tray = self.tray()+ # The menu rumps.App keeps, which rumps does not export.+ tray.menu = rumps_module.Menu()+ tray.toggle_item = kvm_bridge_app.rumps.MenuItem(kvm_bridge_app.TOGGLE_ITEM)+ tray.menu.add(tray.toggle_item)+ tray.menu.add(kvm_bridge_app.rumps.MenuItem("Pause crossing"))+ tray._send_keys = []+ return tray++ def titles(self, tray):+ return [item.title for item in tray.menu.values() if not item.hidden]++ def test_with_two_machines_the_menu_has_an_item_each_in_place_of_the_one(self):+ self.two()+ tray = self.menu_tray()+ kvm_bridge_app.TrayApp._machine_items(tray)+ self.assertEqual(self.titles(tray), ["Send input to Bee", "Send input to Sea", "Pause crossing"])+ self.controller.owner.on = SEA+ self.controller.redirecting = True+ kvm_bridge_app.TrayApp._machine_items(tray)+ self.assertEqual(self.titles(tray), ["Send input to Bee", "Bring input back", "Pause crossing"])++ def test_with_one_machine_the_menu_keeps_its_one_item(self):+ self.build([(BEE, token(100), "Bee", {"side": "left"})])+ tray = self.menu_tray()+ kvm_bridge_app.TrayApp._machine_items(tray)+ self.assertEqual(self.titles(tray), [kvm_bridge_app.TOGGLE_ITEM, "Pause crossing"])++ def test_a_machine_switched_off_leaves_the_menu(self):+ self.two()+ tray = self.menu_tray()+ kvm_bridge_app.TrayApp._machine_items(tray)+ self.store.set_peer(token(150), send=False)+ kvm_bridge_app.TrayApp._machine_items(tray)+ self.assertEqual(self.titles(tray), [kvm_bridge_app.TOGGLE_ITEM, "Pause crossing"])++ def test_without_the_permissions_nothing_is_sent_and_it_says_why(self):+ self.two()+ self.controller.event_tap = None+ tray = self.tray()+ with mock.patch.object(self.controller, "set_redirecting") as switch:+ kvm_bridge_app.TrayApp._send_to(tray, SEA)+ switch.assert_not_called()+ tray.notify_user.assert_called_once()+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_crossing_zones.py b/mac_app/tests/test_crossing_zones.pynew file mode 100644index 0000000..5b6a8f7--- /dev/null+++ b/mac_app/tests/test_crossing_zones.py@@ -0,0 +1,112 @@+"""The Mac's crossing engine with zones for several machines (WIRE.md section 8): each push says+which machine its zone leads to, zones are checked corners first, then edges, then thirds, then+the notch, and a machine with no side can still be reached by its corner or the notch."""++import os+import sys+import unittest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from crossing import CrossingEngine++BOUNDS = (0, 0, 1728, 1117)+RIGHT_X, LEFT_X, TOP_Y = 1727.0, 0.0, 0.0+A, B, C = "machine-a", "machine-b", "machine-c"+++def peer(ident, side):+ return {"id": ident, "side": side}+++def engine(peers, zones, **overrides):+ crossing = {"resistance_px": 0, "block_while_dragging": True}+ crossing.update(overrides)+ return CrossingEngine.from_zones(crossing, zones, peers)+++def push(machine, x, y, dx, dy, notch_range=None, displays=None):+ return machine.feed(x, y, dx, dy, BOUNDS, 1.0, notch_range, False, displays)+++class EachZoneSaysItsMachine(unittest.TestCase):+ def test_two_machines_on_two_edges_each_take_their_own_push(self):+ machine = engine([peer(A, "right"), peer(B, "left")],+ [{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])+ right = push(machine, RIGHT_X, 500.0, 20, 0)+ self.assertTrue(right.crossed)+ self.assertEqual((right.peer, right.edge, right.mac_edge), (A, "left", "right"))+ left = push(machine, LEFT_X, 500.0, -20, 0)+ self.assertTrue(left.crossed)+ self.assertEqual((left.peer, left.edge, left.mac_edge), (B, "right", "left"))++ def test_two_machines_share_one_edge_by_thirds(self):+ machine = engine([peer(A, "right"), peer(B, "right")], [+ {"peer": A, "kind": "part", "parts": ["start"]},+ {"peer": B, "kind": "part", "parts": ["end"]},+ ])+ self.assertEqual(push(machine, RIGHT_X, 100.0, 20, 0).peer, A)+ self.assertEqual(push(machine, RIGHT_X, 1000.0, 20, 0).peer, B)+ middle = push(machine, RIGHT_X, 560.0, 20, 0)+ self.assertFalse(middle.crossed)+ self.assertIsNone(middle.peer)++ def test_a_corner_wins_over_another_machines_edge(self):+ machine = engine([peer(A, "right"), peer(B, "top")], [+ {"peer": A, "kind": "edge"},+ {"peer": B, "kind": "corner", "corner": "top_right", "edge": "right"},+ ])+ step = push(machine, RIGHT_X, 2.0, 20, -20)+ self.assertTrue(step.crossed)+ self.assertEqual((step.peer, step.via), (B, "corner"))+ straight = push(machine, RIGHT_X, 2.0, 20, 0)+ self.assertEqual((straight.peer, straight.via), (A, "edge"))++ def test_a_machine_with_no_side_is_reached_by_its_corner_but_never_by_an_edge(self):+ zones = [{"peer": A, "kind": "edge"}, {"peer": A, "kind": "corner", "corner": "bottom_left", "edge": "left"}]+ self.assertFalse(push(engine([peer(A, "")], zones), LEFT_X, 500.0, -20, 0).crossed)+ corner = push(engine([peer(A, "")], zones), LEFT_X, 1115.0, -20, 20)+ self.assertEqual((corner.crossed, corner.peer), (True, A))++ def test_the_notch_leads_to_its_own_machine(self):+ machine = engine([peer(A, "right"), peer(B, "top")], [{"peer": A, "kind": "edge"}, {"peer": B, "kind": "notch"}])+ step = push(machine, 860.0, TOP_Y, 0, -20, notch_range=(800.0, 920.0))+ self.assertEqual((step.crossed, step.peer, step.via), (True, B, "notch"))++ def test_zones_that_are_off_or_name_a_machine_left_out_are_not_armed(self):+ machine = engine([peer(A, "right"), peer(B, "left")], [+ {"peer": A, "kind": "edge", "off": True},+ {"peer": B, "kind": "edge"},+ {"peer": C, "kind": "edge"},+ ])+ self.assertFalse(push(machine, RIGHT_X, 500.0, 20, 0).crossed)+ self.assertTrue(machine.armed)+ self.assertEqual(machine.peers, {B})++ def test_nothing_in_use_is_not_armed(self):+ machine = engine([peer(A, "right")], [{"peer": A, "kind": "edge", "off": True}])+ self.assertFalse(machine.armed)++ def test_each_edge_with_nothing_beyond_its_display_is_a_wall_for_its_own_machine(self):+ # Two displays side by side, the right one shorter: below it, the left display's right edge+ # is not exposed, and the right display's own bottom is.+ displays = [(0, 0, 1000, 1117), (1000, 0, 1728, 600)]+ machine = engine([peer(A, "right"), peer(B, "bottom")],+ [{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])+ step = push(machine, 1727.0, 300.0, 20, 0, displays=displays)+ self.assertEqual((step.crossed, step.peer), (True, A))+ under = push(machine, 1500.0, 599.0, 0, 20, displays=displays)+ self.assertEqual((under.crossed, under.peer), (True, B))+++class OneMachineAsBefore(unittest.TestCase):+ def test_the_old_settings_still_build_an_engine_whose_steps_name_no_machine(self):+ machine = CrossingEngine(methods=("edge",), edge="right", resistance_px=0)+ step = push(machine, RIGHT_X, 500.0, 20, 0)+ self.assertTrue(step.crossed)+ self.assertIsNone(step.peer)+ self.assertEqual(machine.edge, "right")+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_mac_links.py b/mac_app/tests/test_mac_links.pyindex d7aacc6..65fa0b6 100644--- a/mac_app/tests/test_mac_links.py+++ b/mac_app/tests/test_mac_links.py@@ -393,6 +393,29 @@ class GestureThroughAHandOverTests(Base):self.assertEqual(self.link.sent, [])+class AbandonedHandOverTests(Base):+ """A hand-over given up before its answer closes the link to the machine asked, whose accept may+ still be on the way (WIRE.md section 5); the owner's tests cover every way it is given up."""++ def test_the_shortcut_home_while_the_next_machine_is_asked_closes_its_link(self):+ self.up()+ with self.controller.book.lock:+ peers = self.controller.book.data["peers"]+ peers.append({**peers[0], "id": protocol.id_text(OTHER_ID), "token": "second", "send": True})+ self.controller._sync_links()+ mac = self.controller.links["second"]+ mac.up(self.controller, ident=OTHER_ID, name="Laptop", platform="macos")+ self.controller.set_redirecting(True)+ self.link.arrives(self.controller, protocol.accept_msg(1))+ self.link.arrives(self.controller, protocol.switch_v6(1, OTHER_ID))+ self.assertEqual(mac.dropped, [])+ self.controller.set_redirecting(False)+ settle(self.controller)+ self.assertEqual(len(mac.dropped), 1)+ self.assertEqual(self.link.dropped, [])+ self.assertFalse(self.controller.redirecting)++class ChordCutShortTests(Base):def test_a_link_whose_queue_fills_mid_chord_is_dropped_rather_than_left_holding_a_modifier(self):self.up(platform="macos")@@ -581,7 +604,7 @@ class AnnouncementTests(Base):self.controller.book.data["peers"][0]["id"] = self.peerself.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)])+ self.assertEqual(seen, [(self.peer, "right", seen[0][2], self.peer, None)])def test_a_peers_settings_reach_the_app_with_who_sent_them(self):seen = []@@ -597,9 +620,10 @@ class AnnouncementTests(Base):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):+ def test_an_arrangement_made_here_goes_to_the_machine_it_is_for(self):self.up()- self.controller.send_arrangement("top", 12)+ self.assertTrue(self.controller.send_arrangement(self.peer, "top", 12))+ self.assertFalse(self.controller.send_arrangement(protocol.id_text(OTHER_ID), "top", 13))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))diff --git a/mac_app/tests/test_mac_pairing.py b/mac_app/tests/test_mac_pairing.pyindex c8b5a60..8091708 100644--- a/mac_app/tests/test_mac_pairing.py+++ b/mac_app/tests/test_mac_pairing.py@@ -57,7 +57,11 @@ class MacPairingTests(unittest.TestCase):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"], [])+ # The machine at the 1.4.x entry's address on its platform takes over its side and zones.+ zones = self.store.current()["zones"]+ self.assertTrue(zones)+ self.assertEqual({zone["peer"] for zone in zones}, {peers[0]["id"]})+ self.assertEqual((peers[0]["side"], peers[0]["side_set_at"]), (before["side"], before["side_set_at"]))self.assertTrue(wait_until(lambda: self.pc.paired))def test_a_pairing_this_mac_hosts_is_stored_after_the_machines_it_has(self):diff --git a/mac_app/tests/test_mac_review.py b/mac_app/tests/test_mac_review.pyindex eb7c80e..b256701 100644--- a/mac_app/tests/test_mac_review.py+++ b/mac_app/tests/test_mac_review.py@@ -120,7 +120,7 @@ class LinkSetRaceTests(Base):class ArrangementOriginTests(Base):- def test_an_arrangement_from_a_peer_that_is_not_the_first_is_not_applied_to_the_first(self):+ def test_an_arrangement_from_a_peer_that_is_not_the_first_reaches_the_app_with_its_own_id(self):seen = []self.controller.on_arrangement = lambda *args: seen.append(args)with self.controller.book.lock:@@ -130,9 +130,8 @@ class ArrangementOriginTests(Base):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)+ self.assertEqual([args[0] for args in seen], [protocol.id_text(OTHER_ID), protocol.id_text(PEER_ID)])class LetGoWaitTests(Base):diff --git a/mac_app/tests/test_mac_three.py b/mac_app/tests/test_mac_three.pynew file mode 100644index 0000000..59ab6df--- /dev/null+++ b/mac_app/tests/test_mac_three.py@@ -0,0 +1,269 @@+"""The Mac's controller with two machines paired (WIRE.md sections 4, 5 and 8), links faked: a push+through a zone takes the machine that zone leads to, the shortcut goes where input was last or to+the first that can take it, each machine's arrangement is its own, and the window's status follows+the machine in question rather than the first in the list."""++import copy+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 core import protocol, receiver+from bridge_fakes import FakeClipboard, FakeClock, FakeQuartz, make_config, quiet_logger, settle+from fake_link import CAPS, FakeLink+from windows_input import WindowsInput++OWN = bytes(range(1, 17))+BEE, SEA = bytes(range(40, 56)), bytes(range(70, 86))+++def entry(ident, name, secret, side):+ return {"id": protocol.id_text(ident), "name": name, "platform": "windows", "token": secret, "host": "192.0.2.10",+ "port": 24820, "hw": "", "send": True, "allow_drive": True, "side": side, "side_set_at": 100,+ "side_by": protocol.id_text(OWN), "paired_with": [], "paired_at": 1, "linked": True, "from_1_4": False}+++class Three(unittest.TestCase):+ """This Mac with Bee on its right and Sea on its left, an edge zone to each."""++ controller_class = KVMController++ def setUp(self):+ FakeQuartz.reset_cursor_spies()+ self.data = {+ "schema": 6, "machine_id": protocol.id_text(OWN), "name": "This Mac", "port": 24820, "shortcut": True,+ "peers": [entry(BEE, "Bee", "b" * 43, "right"), entry(SEA, "Sea", "s" * 43, "left")],+ "zones": [{"peer": protocol.id_text(BEE), "kind": "edge"}, {"peer": protocol.id_text(SEA), "kind": "edge"}],+ }+ self.saved = []+ book = receiver.PeerBook(lambda: self.data, self._store, threading.RLock())+ identity = lambda: {"id": OWN, "name": "This Mac", "platform": "macos", "app": "1.5.0", "caps": list(CAPS), "port": 24820}+ self.clock = FakeClock()+ self.controller = self.controller_class(+ make_config("b" * 43), logger=quiet_logger(), quartz=FakeQuartz, clock=self.clock,+ clipboard=FakeClipboard("hello"), link_factory=FakeLink, desktop_bounds=lambda: (0, 0, 1920, 1080),+ book=book, identity=identity,+ )+ self.alerts = []+ self.controller.on_user_alert = lambda title, message: self.alerts.append(message)+ self.bee = self.controller.links["b" * 43]+ self.sea = self.controller.links["s" * 43]++ def _store(self, data):+ self.data = copy.deepcopy(data)+ self.saved.append(self.data)++ def up(self, link, ident, name, accepts=True):+ link.up(self.controller, ident=ident, name=name, accepts=accepts)+ settle(self.controller)++ def push(self, x, y, dx, dy=0, times=20):+ for _ in range(times):+ self.clock.value += 0.01+ event = {"location": (x, y), FakeQuartz.kCGMouseEventDeltaX: dx, FakeQuartz.kCGMouseEventDeltaY: dy}+ self.controller._handle_local_mouse(FakeQuartz.kCGEventMouseMoved, event)+ if self.controller.redirecting:+ break+ settle(self.controller)++ def takes(self, link):+ return [m["data"] for m in link.posted if m["type"] == protocol.MSG_FOCUS and m["data"]["target"] == link.peer_id]+++class EachZoneTakesItsMachine(Three):+ def test_the_right_edge_takes_bee_and_the_left_edge_takes_sea(self):+ self.up(self.bee, BEE, "Bee")+ self.up(self.sea, SEA, "Sea")+ self.push(1919, 500, 30)+ self.assertEqual(self.controller.owner.on, protocol.id_text(BEE))+ self.assertEqual(self.takes(self.bee)[-1]["edge"], "left")+ self.assertEqual(self.takes(self.sea), [])+ self.controller.set_redirecting(False)+ settle(self.controller)+ self.push(0, 500, -30)+ self.assertEqual(self.controller.owner.on, protocol.id_text(SEA))+ self.assertEqual(self.takes(self.sea)[-1]["edge"], "right")++ def test_a_machine_whose_link_is_down_has_no_wall_and_the_other_still_crosses(self):+ self.up(self.sea, SEA, "Sea")+ self.push(1919, 500, 30)+ self.assertFalse(self.controller.redirecting)+ self.push(0, 500, -30)+ self.assertEqual(self.controller.owner.on, protocol.id_text(SEA))++ def test_a_machine_that_does_not_accept_input_is_not_taken_and_the_push_says_so(self):+ self.up(self.bee, BEE, "Bee", accepts=False)+ self.up(self.sea, SEA, "Sea")+ self.push(1919, 500, 30)+ self.assertIsNone(self.controller.owner.on)+ self.assertEqual(self.takes(self.bee), [])+ self.assertIn("Bee does not accept input from this Mac", self.alerts[-1])++ def test_a_machine_this_mac_does_not_send_to_has_no_wall(self):+ self.data["peers"][0]["send"] = False+ self.controller.peers_changed()+ self.up(self.sea, SEA, "Sea")+ self.push(1919, 500, 30)+ self.assertFalse(self.controller.redirecting)+ self.push(0, 500, -30)+ self.assertEqual(self.controller.owner.on, protocol.id_text(SEA))+++ def test_a_machine_that_just_refused_stands_down_and_the_other_still_crosses(self):+ self.up(self.bee, BEE, "Bee")+ self.up(self.sea, SEA, "Sea")+ self.push(1919, 500, 30)+ self.bee.arrives(self.controller, protocol.refuse_msg(self.controller.owner.route, "owned"))+ settle(self.controller)+ self.assertFalse(self.controller.redirecting)+ FakeQuartz.reset_cursor_spies()+ self.push(1919, 500, 30)+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(FakeQuartz.warp_calls, [])+ self.push(0, 500, -30)+ self.assertEqual(self.controller.owner.on, protocol.id_text(SEA))+++class TheShortcut(Three):+ def test_it_goes_where_input_was_last(self):+ self.up(self.bee, BEE, "Bee")+ self.up(self.sea, SEA, "Sea")+ self.push(0, 500, -30)+ self.controller.set_redirecting(False)+ settle(self.controller)+ self.assertTrue(self.controller.set_redirecting(True))+ settle(self.controller)+ self.assertEqual(self.controller.owner.on, protocol.id_text(SEA))++ def test_it_goes_to_the_first_that_can_take_input_when_the_first_in_the_list_is_down(self):+ self.up(self.sea, SEA, "Sea")+ self.assertTrue(self.controller.set_redirecting(True))+ settle(self.controller)+ self.assertEqual(self.controller.owner.on, protocol.id_text(SEA))++ def test_a_menu_names_its_machine(self):+ self.up(self.bee, BEE, "Bee")+ self.up(self.sea, SEA, "Sea")+ self.assertTrue(self.controller.set_redirecting(True, peer=protocol.id_text(SEA)))+ settle(self.controller)+ self.assertEqual(self.controller.owner.on, protocol.id_text(SEA))++ def test_a_menu_moves_input_straight_from_one_machine_to_another(self):+ self.up(self.bee, BEE, "Bee")+ self.up(self.sea, SEA, "Sea")+ self.assertTrue(self.controller.set_redirecting(True, peer=protocol.id_text(BEE)))+ settle(self.controller)+ self.assertTrue(self.controller.set_redirecting(True, peer=protocol.id_text(SEA)))+ settle(self.controller)+ self.assertEqual(self.controller.owner.on, protocol.id_text(SEA))+ self.assertTrue(self.controller.redirecting)+ let_go = [m["data"] for m in self.bee.posted if m["type"] == protocol.MSG_FOCUS][-1]+ self.assertEqual(let_go["target"], protocol.id_text(SEA))+ self.assertFalse(self.controller.set_redirecting(True, peer=protocol.id_text(SEA)))++ def test_nothing_up_says_which_machine_it_tried(self):+ self.assertFalse(self.controller.set_redirecting(True))+ self.assertTrue(any("Bee" in alert for alert in self.alerts), self.alerts)+++class TheStatusFollowsTheMachineInQuestion(Three):+ def test_connected_and_the_label_speak_of_the_machine_the_shortcut_would_take(self):+ self.up(self.sea, SEA, "Sea")+ self.assertTrue(self.controller.connected)+ self.assertEqual(self.controller.peer_label, "Sea")++ def test_while_input_is_on_a_machine_the_label_is_that_machine(self):+ self.up(self.bee, BEE, "Bee")+ self.up(self.sea, SEA, "Sea")+ self.controller.set_redirecting(True, peer=protocol.id_text(SEA))+ settle(self.controller)+ self.assertEqual(self.controller.on_label, "Sea")+ self.assertEqual(self.controller.peer_label, "Sea")+++class EachMachinesArrangement(Three):+ def test_an_arrangement_from_the_second_machine_is_handed_on_with_its_id(self):+ heard = []+ self.controller.on_arrangement = lambda peer, edge, set_at, by, way_back: heard.append((peer, edge, set_at, by, way_back))+ self.up(self.sea, SEA, "Sea")+ self.sea.arrives(self.controller, protocol.arrangement_v6("top", 2000, SEA))+ self.sea.arrives(self.controller, protocol.arrangement_v6("top", 2000, SEA, way_back=False))+ self.assertEqual(heard, [(protocol.id_text(SEA), "top", 2000, protocol.id_text(SEA), None),+ (protocol.id_text(SEA), "top", 2000, protocol.id_text(SEA), False)])++ def arrangements(self, link):+ return [m["data"] for m in link.posted if m["type"] == protocol.MSG_ARRANGEMENT]++ def test_each_link_up_says_whether_a_way_leads_to_that_machine(self):+ self.data["zones"][1]["off"] = True+ self.up(self.bee, BEE, "Bee")+ self.up(self.sea, SEA, "Sea")+ self.assertIs(self.arrangements(self.bee)[-1]["way_back"], True)+ self.assertIs(self.arrangements(self.sea)[-1]["way_back"], False)++ def test_a_side_sent_from_here_says_whether_a_way_leads_there_and_who_set_it(self):+ self.up(self.sea, SEA, "Sea")+ self.assertTrue(self.controller.send_arrangement(protocol.id_text(SEA), "top", 3000, protocol.id_text(SEA)))+ sent = self.arrangements(self.sea)[-1]+ self.assertEqual((sent["by"], sent["way_back"]), (protocol.id_text(SEA), True))+ self.data["zones"][1]["off"] = True+ self.assertTrue(self.controller.send_arrangement(protocol.id_text(SEA), "top", 3001))+ sent = self.arrangements(self.sea)[-1]+ self.assertEqual((sent["by"], sent["way_back"]), (protocol.id_text(OWN), False))+++class TheLinkInArrangement(Three):+ """The same over the link a machine opened to this Mac (windows_input.py)."""++ def setUp(self):+ super().setUp()+ self.heard = []+ self.input = WindowsInput(self.controller, arrangement_callback=lambda *args: self.heard.append(args))+ self.addCleanup(self.input.stop)++ def test_a_machine_linked_in_is_told_whether_a_way_leads_to_it(self):+ self.data["zones"][1]["off"] = True+ self.input.server.caps_of = lambda _peer: frozenset()+ told = {name: [m["data"] for m in self.input._announce(ident) if m["type"] == protocol.MSG_ARRANGEMENT]+ for name, ident in (("bee", BEE), ("sea", SEA))}+ self.assertIs(told["bee"][0]["way_back"], True)+ self.assertIs(told["sea"][0]["way_back"], False)++ def test_a_side_sent_over_its_link_says_whether_a_way_leads_there_and_who_set_it(self):+ sent = []+ self.input.server.send = lambda peer, message: sent.append(message["data"]) or True+ self.assertTrue(self.input.send_arrangement(protocol.id_text(SEA), "top", 3000, protocol.id_text(SEA)))+ self.assertEqual((sent[-1]["by"], sent[-1]["way_back"]), (protocol.id_text(SEA), True))++ def test_an_arrangement_over_its_link_reaches_the_app_with_way_back(self):+ self.input._on_arrangement(SEA, {"edge": "top", "set_at": 5, "by": SEA, "way_back": False})+ self.input._on_arrangement(SEA, {"edge": "top", "set_at": 6, "by": SEA})+ self.assertEqual(self.heard, [(protocol.id_text(SEA), "top", 5, protocol.id_text(SEA), False),+ (protocol.id_text(SEA), "top", 6, protocol.id_text(SEA), None)])++ def test_a_side_changed_here_goes_to_that_machine_only(self):+ self.up(self.bee, BEE, "Bee")+ self.up(self.sea, SEA, "Sea")+ before = len(self.bee.posted)+ self.assertTrue(self.controller.send_arrangement(protocol.id_text(SEA), "top", 3000))+ sent = [m for m in self.sea.posted if m["type"] == protocol.MSG_ARRANGEMENT]+ self.assertEqual(sent[-1]["data"]["edge"], "top")+ self.assertEqual(len(self.bee.posted), before)++ def test_the_zones_follow_a_side_that_changed_in_the_settings(self):+ self.up(self.bee, BEE, "Bee")+ self.up(self.sea, SEA, "Sea")+ self.data["peers"][0]["side"] = "top"+ self.controller.zones_changed()+ self.push(1919, 500, 30)+ self.assertFalse(self.controller.redirecting)+ self.push(900, 0, 0, -30)+ self.assertEqual(self.controller.owner.on, protocol.id_text(BEE))+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_mac_wire.py b/mac_app/tests/test_mac_wire.pyindex fe8c173..2565e60 100644--- a/mac_app/tests/test_mac_wire.py+++ b/mac_app/tests/test_mac_wire.py@@ -44,6 +44,10 @@ class Wire(unittest.TestCase):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)+ # A pairing made on 1.5.0, as a flat save with a token is the 1.4.x migration, which never links.+ settings = self.store.current()+ settings["peers"][0].update(id=protocol.id_text(self.machine.own), from_1_4=False)+ self.store.save_settings(settings)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@@ -158,8 +162,7 @@ class DrivenMacTests(unittest.TestCase):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+ settings["peers"][0].update(id=protocol.id_text(PEER), send=False, from_1_4=False)self.store.save_settings(settings)self.controller = KVMController(cfg, logger=quiet_logger(), quartz=FakeQuartz, clipboard=FakeClipboard(),diff --git a/mac_app/tests/test_machines.py b/mac_app/tests/test_machines.pyindex 88911be..8a69821 100644--- a/mac_app/tests/test_machines.py+++ b/mac_app/tests/test_machines.py@@ -46,10 +46,15 @@ class StateTests(unittest.TestCase):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_any_1_4_pairing_is_asked_to_be_paired_again(self):+ # 1.4.x kept no record of whether its token was paired or typed, so a token of pairing's+ # shape is asked again too, and so is one an earlier beta linked.+ for migrated in (entry(token="typed-in-1.4", id="", from_1_4=True), entry(id="", linked=False, from_1_4=True),+ entry(from_1_4=True)):+ with self.subTest(entry=migrated):+ state = row(entry=migrated, kind="failed").state+ self.assertEqual((state.key, state.tone, state.word), ("pair_again", "amber", "Pair again"))+ self.assertEqual(state.detail, "STUDIO-PC was paired on Beamer 1.4. Pair the two again to link them on 1.5.0.")def test_a_machine_linked_in_but_not_dialled_is_linked_too(self):state = row(has_link=False, inbound=True, entry=entry(send=False)).statediff --git a/mac_app/tests/test_machines_panel.py b/mac_app/tests/test_machines_panel.pyindex fee2a57..eab55f0 100644--- a/mac_app/tests/test_machines_panel.py+++ b/mac_app/tests/test_machines_panel.py@@ -123,6 +123,14 @@ class Base(unittest.TestCase):def rows(self):return [view for view in self.panel.list.arrangedSubviews()]+ def texts(self, view):+ found = []+ if isinstance(view, AppKit.NSTextField):+ found.append(view.stringValue())+ for sub in view.subviews():+ found.extend(self.texts(sub))+ return found+class ListTests(Base):def test_the_migrated_machine_is_listed_by_its_name_and_where_it_is(self):@@ -423,6 +431,28 @@ class EnteringACodeTests(Base):self.run_pair()self.assertEqual(self.service.paired, [])+ def test_same_named_older_machines_show_their_addresses(self):+ first = heard(name="Studio", address="192.168.50.22", pairing=2)+ second = heard(name="Studio", address="169.254.3.7", pairing=2)+ self.service.heard = [first, second]+ self.panel._heard_key = None+ self.panel.refresh()+ rows = self.panel.heard_list.arrangedSubviews()+ texts = [" ".join(self.texts(row)) for row in rows]+ self.assertEqual(len(texts), 2)+ self.assertNotEqual(*texts)+ self.assertIn("192.168.50.22", texts[0])+ self.assertIn("169.254.3.7", texts[1])++ def test_shared_older_machine_addresses_follow_the_hide_addresses_setting(self):+ self.controller.cfg.hide_addresses = True+ self.service.heard = [heard(name="Studio", address="192.168.50.22", pairing=2),+ heard(name="Studio", address="169.254.3.7", pairing=2)]+ self.panel._heard_key = None+ self.panel.refresh()+ texts = [" ".join(self.texts(row)) for row in self.panel.heard_list.arrangedSubviews()]+ self.assertTrue(all("192.168.50.22" not in text and "169.254.3.7" not in text for text in texts))+def test_the_chosen_machine_is_paired_with_the_code_and_the_list_updates(self):self.service.result = entry(FIRST, SECOND_TOKEN, "Laptop")self.store.add_peer(self.service.result)diff --git a/mac_app/tests/test_pages.py b/mac_app/tests/test_pages.pyindex 599c25d..e1f6f9e 100644--- a/mac_app/tests/test_pages.py+++ b/mac_app/tests/test_pages.py@@ -209,5 +209,158 @@ class RedactTests(unittest.TestCase):self.assertEqual(pages.redact("", True), "")+def machine(label, side, methods=(), parts=("middle",), corner="top_left", chosen=False, key=None):+ return {"key": key or label, "label": label, "side": side, "methods": list(methods), "parts": list(parts),+ "corner": corner, "chosen": chosen}+++class NeighboursTest(unittest.TestCase):+ """This Mac in the middle of the Crossing page's drawing, every placed machine beside its side."""++ W, H = 520.0, 186.0++ def inside(self, frame):+ x, y, w, h = frame+ self.assertGreaterEqual(x, 0)+ self.assertGreaterEqual(y, 0)+ self.assertLessEqual(x + w, self.W + 1e-6)+ self.assertLessEqual(y + h, self.H + 1e-6)++ def test_one_machine_sits_where_the_one_machine_drawing_put_it(self):+ for side in ("left", "right", "top", "bottom"):+ with self.subTest(side=side):+ this, frames = pages.diagram_layout(self.W, self.H, [(side, None)])+ self.assertEqual((this, frames[0]), pages.arrangement(self.W, self.H, side))++ def test_a_machine_with_no_side_is_not_drawn_and_this_mac_stays_in_the_middle(self):+ this, frames = pages.diagram_layout(self.W, self.H, [("", None)])+ self.assertIsNone(frames[0])+ self.assertAlmostEqual(this[0] + this[2] / 2, self.W / 2)+ self.assertAlmostEqual(this[1] + this[3] / 2, self.H / 2)++ def test_a_row_puts_one_machine_each_side(self):+ this, (left, right) = pages.diagram_layout(self.W, self.H, [("left", None), ("right", None)])+ self.assertAlmostEqual(left[0] + left[2] + pages.DIAGRAM_GAP, this[0])+ self.assertAlmostEqual(this[0] + this[2] + pages.DIAGRAM_GAP, right[0])+ self.assertAlmostEqual(this[0] + this[2] / 2, self.W / 2)+ for frame in (this, left, right):+ self.inside(frame)++ def test_an_l_keeps_both_neighbours_on_their_sides_and_the_whole_inside_the_drawing(self):+ this, (right, top) = pages.diagram_layout(self.W, self.H, [("right", None), ("top", None)])+ self.assertGreater(right[0], this[0] + this[2])+ self.assertLess(top[1] + top[3], this[1])+ for frame in (this, right, top):+ self.inside(frame)++ def test_two_on_one_side_share_it_each_half_as_long_in_the_order_of_their_thirds(self):+ this, (lower, upper) = pages.diagram_layout(self.W, self.H, [("right", 2), ("right", 0)])+ _, (single,) = pages.diagram_layout(self.W, self.H, [("right", None)])+ self.assertAlmostEqual(upper[3], single[3] / 2)+ self.assertAlmostEqual(upper[2], single[2] / 2)+ self.assertLess(upper[1] + upper[3], lower[1])+ self.assertEqual(upper[0], lower[0])+ self.assertGreater(upper[0], this[0] + this[2])++ def test_two_on_one_side_without_thirds_follow_the_list(self):+ _, (first, second) = pages.diagram_layout(self.W, self.H, [("top", None), ("top", 0)])+ self.assertLess(first[0], second[0])++ def test_a_machine_is_placed_by_its_side_and_its_first_third(self):+ self.assertEqual(pages.placement(machine("Bee", "right", ["part"], parts=["end", "middle"])), ("right", 1))+ self.assertEqual(pages.placement(machine("Bee", "right", ["edge"], parts=["end"])), ("right", None))+ self.assertEqual(pages.placement(machine("Bee", "", ["part"])), ("", 1))++ def test_four_sides_shrink_to_fit(self):+ this, frames = pages.diagram_layout(self.W, self.H, [(side, None) for side in ("left", "right", "top", "bottom")])+ for frame in (this, *frames):+ self.inside(frame)+ self.assertLess(this[2], pages.DIAGRAM_THIS[0])+++class MarksTest(unittest.TestCase):+ """What lights on this Mac: the chosen machine's ways strong, the others' quiet."""++ this = (100.0, 50.0, 120.0, 75.0)++ def test_the_chosen_machines_edge_is_strong_and_anothers_quiet(self):+ marks, notch = pages.diagram_marks(self.this, [+ machine("Bee", "right", ["edge"], chosen=True), machine("Sea", "left", ["edge"])])+ self.assertEqual(marks[("Bee", "edge")], (pages.side_mark(self.this, "right"), "chosen"))+ self.assertEqual(marks[("Sea", "edge")], (pages.side_mark(self.this, "left"), "other"))+ self.assertIsNone(notch)++ def test_a_way_that_is_off_or_has_no_side_lights_nothing(self):+ marks, _ = pages.diagram_marks(self.this, [machine("Bee", "", ["edge", "corner"], chosen=True)])+ self.assertEqual(marks[("Bee", "edge")], (None, None))+ self.assertEqual(marks[("Bee", "corner")], (pages.corner_mark(self.this, "top_left"), "chosen"))+ self.assertIsNone(marks[("Bee", "part", "start")][1])++ def test_unchosen_thirds_of_the_chosen_machine_are_a_track_unless_another_machine_has_them(self):+ marks, _ = pages.diagram_marks(self.this, [+ machine("Bee", "right", ["part"], parts=["start"], chosen=True),+ machine("Sea", "right", ["part"], parts=["end"])])+ thirds = pages.third_marks(self.this, "right")+ self.assertEqual(marks[("Bee", "part", "start")], (thirds["start"], "chosen"))+ self.assertEqual(marks[("Bee", "part", "middle")], (thirds["middle"], "track"))+ self.assertEqual(marks[("Bee", "part", "end")][1], None)+ self.assertEqual(marks[("Sea", "part", "end")], (thirds["end"], "other"))+ self.assertIsNone(marks[("Sea", "part", "middle")][1])++ def test_the_notch_lights_for_the_machine_it_leads_to(self):+ _, notch = pages.diagram_marks(self.this, [machine("Bee", "right", chosen=True), machine("Sea", "left", ["notch"])])+ self.assertEqual(notch, "other")+ _, notch = pages.diagram_marks(self.this, [machine("Bee", "right", ["notch"], chosen=True)])+ self.assertEqual(notch, "chosen")+++class MachineWordsTest(unittest.TestCase):+ def test_machines_with_no_side_are_named_under_the_drawing(self):+ self.assertEqual(pages.not_placed([machine("Bee", "right"), machine("Sea", "")]), "Not placed yet: Sea")+ self.assertEqual(pages.not_placed([machine("Oak", ""), machine("Sea", "")]), "Not placed yet: Oak and Sea")+ self.assertEqual(pages.not_placed([machine("Bee", "left")]), "")++ def test_the_description_names_every_machine_and_its_side(self):+ text = pages.arrangement_description(+ [machine("Bee", "right", chosen=True), machine("Sea", "top"), machine("Oak", "")], "Push through the right edge")+ self.assertEqual(text, "Bee is to the right of this Mac. Sea is above this Mac. Oak is not placed yet. "+ "Push through the right edge.")+ self.assertEqual(pages.arrangement_description([machine("Bee", "left", chosen=True)], ""),+ "Bee is to the left of this Mac. No way in is on.")++ def test_one_machine_keeps_todays_words_and_several_name_the_one_chosen(self):+ self.assertEqual(pages.where_caption(None), "Where the other machine is")+ self.assertEqual(pages.where_caption("Bee"), "Where Bee is")+ self.assertEqual(pages.notch_or_corner_note(None), pages.notch_or_corner_note("the other machine"))+ self.assertIn("Bee's own push", pages.notch_or_corner_note("Bee"))++ def test_an_unplaced_machine_shows_no_side_unless_it_is_the_only_one(self):+ self.assertEqual(pages.shown_side("", 1), "right")+ self.assertEqual(pages.shown_side("", 0), "right")+ self.assertEqual(pages.shown_side("", 2), "")+ self.assertEqual(pages.shown_side("top", 3), "top")+++class SendItemsTest(unittest.TestCase):+ """The menu bar's Send input, one per machine once there are several to send to."""++ @staticmethod+ def entry(ident, name, **extra):+ return {"id": ident, "name": name, "token": "t" + ident, "host": "192.0.2.4", "port": 24820, "send": True, **extra}++ def test_one_machine_keeps_the_one_item(self):+ self.assertEqual(pages.send_items([self.entry("A", "Bee")], None, False), [])+ self.assertEqual(pages.send_items([self.entry("A", "Bee"), self.entry("B", "Sea", send=False)], None, False), [])++ def test_each_machine_this_mac_sends_to_has_its_own_and_the_one_input_is_on_brings_it_back(self):+ peers = [self.entry("A", "Bee"), self.entry("B", "Sea"), self.entry("C", "Oak", send=False)]+ self.assertEqual(pages.send_items(peers, None, False), [("A", "Send input to Bee"), ("B", "Send input to Sea")])+ self.assertEqual(pages.send_items(peers, "B", False), [("A", "Send input to Bee"), ("B", "Bring input back")])++ def test_a_nameless_machines_address_is_hidden_when_asked(self):+ peers = [self.entry("A", ""), self.entry("B", "Sea")]+ self.assertEqual(pages.send_items(peers, None, True)[0][1], "Send input to •••")++if __name__ == "__main__":unittest.main()diff --git a/mac_app/tests/test_replay.py b/mac_app/tests/test_replay.pyindex dae0cdf..a73c366 100644--- a/mac_app/tests/test_replay.py+++ b/mac_app/tests/test_replay.py@@ -105,7 +105,7 @@ class WholeConnectionReplayTests(unittest.TestCase):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(duo.mac.send_arrangement(protocol.id_text(HERE), "left", 500))self.assertTrue(wait_for(lambda: any(read["set_at"] == 500 for _, read in pc.arrangements)), "the arrangement never arrived")duo.mac.stop()self.assertTrue(wait_for(lambda: pc.responder.owner is None and not pc.responder.links()))diff --git a/mac_app/tests/test_same_on_both.py b/mac_app/tests/test_same_on_both.pyindex 1c6406a..58ae974 100644--- a/mac_app/tests/test_same_on_both.py+++ b/mac_app/tests/test_same_on_both.py@@ -1,4 +1,4 @@-"""Same on both machines in the real window: the Overview switch, a PC's settings arriving, and a+"""Same on all machines in the real window: the Overview switch, a PC's settings arriving, and achange here going out. Built as test_appearance builds it, never put on screen; the two links'sends are recorded instead."""diff --git a/mac_app/tests/test_settings_sync_link.py b/mac_app/tests/test_settings_sync_link.pyindex c163922..2a13ea8 100644--- a/mac_app/tests/test_settings_sync_link.py+++ b/mac_app/tests/test_settings_sync_link.py@@ -1,4 +1,4 @@-"""Same on both machines over loopback: the Mac's real controller and responder against a PC end+"""Same on all machines over loopback: the Mac's real controller and responder against a PC endmade of core's own link and responder, announcing on connect and carrying each change, with twosmall ends holding each machine's state through settings_sync as the apps' windows do (apply_same onthe Mac, _on_settings on the PC). The Mac's state travels over its own link and over the PC's."""@@ -162,7 +162,7 @@ class Rig: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)+ settings["peers"][0].update(id=protocol.id_text(PC_ID), from_1_4=False)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)diff --git a/mac_app/tests/test_settings_v6.py b/mac_app/tests/test_settings_v6.pyindex 1f787e5..f23fd61 100644--- a/mac_app/tests/test_settings_v6.py+++ b/mac_app/tests/test_settings_v6.py@@ -21,7 +21,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspaimport config as config_moduleimport settings_store-from core import protocol+from core import protocol, receiver, waysfrom settings_store import SettingsError, SettingsStore, config_to_rawFIXTURES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")@@ -481,75 +481,169 @@ class SavingTests(Base):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"))+ # The side is written by set_ways and arrangement only: a flat view read before another+ # machine's arrangement landed must not put the old side back.+ self.assertEqual((first["side"], first["side_set_at"]), ("left", 1790000000))+ self.assertEqual((cfg.host, cfg.crossing["edge"]), ("192.0.2.99", "left"))- def test_the_side_stamp_keeps_its_author_until_it_changes(self):+ def test_a_flat_save_keeps_a_name_and_hardware_address_learnt_since_the_window_read(self):settings = self.settings()+ settings["peers"][0].update(name="Learnt PC", hw="aa:bb:cc:dd:ee:01")+ self.store.save_settings(settings)+ self.store.save(config_to_raw(replace(self.cfg, pointer_speed=2.0)))+ first = self.settings()["peers"][0]+ self.assertEqual((first["name"], first["hw"]), ("Learnt PC", "aa:bb:cc:dd:ee:01"))+ self.assertEqual(self.settings()["pointer_speed"], 2.0)++ def test_a_new_address_clears_what_was_learnt_at_the_old_one(self):+ settings = self.settings()+ settings["peers"][0].update(name="Learnt PC", hw="aa:bb:cc:dd:ee:01")+ self.store.save_settings(settings)+ self.store.save(config_to_raw(replace(self.cfg, host="192.0.2.99", pc_name="", mac_address="")))+ first = self.settings()["peers"][0]+ self.assertEqual((first["host"], first["name"], first["hw"]), ("192.0.2.99", "", ""))++ def with_id(self):+ settings = self.settings()+ settings["peers"][0]["id"] = PEER_ID+ for zone in settings["zones"]:+ zone["peer"] = PEER_ID+ self.write_settings(settings)+ self.store = SettingsStore(self.path)+ return settings++ def test_the_side_stamp_keeps_its_author_until_it_changes(self):+ settings = self.with_id()settings["peers"][0].update(side_by=SECOND_ID)self.write_settings(settings)+ self.store = SettingsStore(self.path)self.store.save(config_to_raw(self.cfg))self.assertEqual(self.settings()["peers"][0]["side_by"], SECOND_ID)- 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"])+ self.assertFalse(self.store.set_ways(PEER_ID, side="left", methods=["edge"], parts=["middle"], corner="top_right"))+ self.assertEqual(self.settings()["peers"][0]["side_by"], SECOND_ID)+ self.assertTrue(self.store.set_ways(PEER_ID, side="top", methods=["edge"], parts=["middle"], corner="top_right"))+ first = self.settings()["peers"][0]+ self.assertEqual((first["side"], first["side_by"]), ("top", self.settings()["machine_id"]))+ self.assertGreater(first["side_set_at"], 1790000000)def test_an_arrangement_from_the_peer_is_stamped_with_the_peers_id_not_this_machines(self):- raw = config_to_raw(self.cfg)- raw["crossing"]["edge"] = "bottom"- raw["crossing"]["arrangement_set_at"] = 1790000500- self.store.save(raw, side_by=SECOND_ID)+ self.with_id()+ self.assertEqual(self.store.arrangement(PEER_ID, "top", 1790000500, SECOND_ID), (True, []))first = self.settings()["peers"][0]self.assertEqual((first["side"], first["side_set_at"], first["side_by"]), ("bottom", 1790000500, SECOND_ID))def test_a_tie_won_on_the_larger_by_stores_the_winners_by(self):- settings = self.settings()+ settings = self.with_id()stamp = settings["peers"][0]["side_set_at"]settings["peers"][0].update(side_by=OTHER_ID_FOR_TIE)self.write_settings(settings)- 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.store = SettingsStore(self.path)+ self.assertEqual(self.store.arrangement(PEER_ID, "left", stamp, SECOND_ID), (False, []))+ self.assertEqual(self.store.arrangement(PEER_ID, "left", stamp, OTHER_ID_FOR_TIE), (False, []))+ larger = base64.urlsafe_b64encode(bytes(range(200, 216))).decode("ascii").rstrip("=")+ self.assertEqual(self.store.arrangement(PEER_ID, "left", stamp, larger), (True, []))+ self.assertEqual(self.settings()["peers"][0]["side_by"], larger)self.assertEqual(self.settings()["peers"][0]["side_set_at"], stamp)+ def test_an_arrangement_for_one_machine_leaves_the_others_side_alone(self):+ settings = self.with_id()+ second = {**copy.deepcopy(settings["peers"][0]), "id": SECOND_ID, "side": "right", "name": "Second"}+ second["token"] = second["token"][::-1]+ settings["peers"].append(second)+ self.write_settings(settings)+ self.store = SettingsStore(self.path)+ self.store.arrangement(SECOND_ID, "right", 1790000900, SECOND_ID)+ after = self.settings()["peers"]+ self.assertEqual((after[0]["side"], after[1]["side"]), ("left", "left"))+def test_the_store_serves_the_settings_it_holds_to_a_peer_book_and_keeps_them_after_a_save(self):book = self.store.book()self.assertEqual(book.peers()[0]["token"], TOKEN)raw = config_to_raw(self.cfg)- raw["pc_name"] = "Renamed"+ raw["host"] = "192.0.2.98"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(book.peers()[0]["host"], "192.0.2.98")+ # The migrated entry never links; as a pairing made on 1.5.0 it does, and what it learns is kept.+ own = protocol.read_id(self.settings()["machine_id"])+ self.assertEqual(book.admit(protocol.key_id(TOKEN), own, protocol.read_id(PEER_ID), {"name": "Learnt"})[0], receiver.GONE)+ settings = self.store.current()+ settings["peers"][0].update(id=PEER_ID, from_1_4=False)+ self.store.save_settings(settings)+ self.assertEqual(book.admit(protocol.key_id(TOKEN), own, protocol.read_id(PEER_ID), {"name": "Learnt"})[0], receiver.ADMITTED)+ self.assertEqual(self.settings()["peers"][0]["name"], "Learnt")self.assertEqual(self.store.current()["peers"][0]["name"], "Learnt")def test_changing_the_methods_turns_zones_on_and_off(self):+ self.with_id()raw = config_to_raw(self.cfg)- raw["crossing"]["methods"] = ["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"]}+ raw["crossing"]["methods"] = ["edge", "corner"]+ self.store.save(raw)+ self.assertFalse(self.settings()["shortcut"])+ self.store.set_ways(PEER_ID, side="left", methods=["part", "notch"], parts=["middle"], corner="top_right")+ zones = {zone["kind"]: zone for zone in self.settings()["zones"]}self.assertTrue(zones["edge"]["off"])self.assertNotIn("off", zones["part"])self.assertEqual(zones["part"]["parts"], ["middle"])self.assertNotIn("off", zones["notch"])- self.assertEqual(cfg.crossing["methods"], ["part", "notch"])+ self.assertEqual(self.store.load().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)+ self.with_id()+ self.store.set_ways(PEER_ID, side="top", methods=["corner"], parts=["middle"], corner="top_right")corner = [z for z in self.settings()["zones"] if z["kind"] == "corner"][0]self.assertEqual((corner["corner"], corner["edge"]), ("top_right", "right"))- raw["crossing"]["corner"] = "bottom_left"- self.store.save(raw)+ self.store.set_ways(PEER_ID, side="top", methods=["corner"], parts=["middle"], corner="bottom_left")corner = [z for z in self.settings()["zones"] if z["kind"] == "corner"][0]self.assertEqual((corner["corner"], corner["edge"]), ("bottom_left", "left"))+ def test_ways_that_would_clash_with_another_machines_are_refused_with_both_named_and_nothing_written(self):+ settings = self.with_id()+ second = {**copy.deepcopy(settings["peers"][0]), "id": SECOND_ID, "side": "right", "name": "Second"}+ second["token"] = second["token"][::-1]+ settings["peers"].append(second)+ settings["zones"].append({"peer": SECOND_ID, "kind": "edge"})+ self.write_settings(settings)+ self.store = SettingsStore(self.path)+ # On the same side as Second, with no way in yet: turning its edge on would cover Second's.+ self.store.set_ways(PEER_ID, side="right", methods=[], parts=["middle"], corner="top_right")+ before = self.settings()+ with self.assertRaises(SettingsError) as raised:+ self.store.set_ways(PEER_ID, side="right", methods=["edge"], parts=["middle"], corner="top_right")+ self.assertIn("Second", str(raised.exception))+ self.assertIn("right edge of this Mac", str(raised.exception))+ self.assertEqual(self.settings(), before)++ def second_machine(self, side, zones=None):+ settings = self.with_id()+ second = {**copy.deepcopy(settings["peers"][0]), "id": SECOND_ID, "side": side, "name": "Second"}+ second["token"] = second["token"][::-1]+ settings["peers"].append(second)+ if zones is not None:+ settings["zones"] += zones+ self.write_settings(settings)+ self.store = SettingsStore(self.path)++ def test_a_machine_paired_with_no_zone_gets_its_edge_when_the_settings_are_read(self):+ # The rig's beta.3 file of 01-10-2026: a second machine's side set, and no zone to cross by.+ self.second_machine("right")+ self.assertIn({"peer": SECOND_ID, "kind": "edge"}, self.store.current()["zones"])++ def test_one_whose_side_is_taken_gets_its_edge_off_and_the_settings_still_read(self):+ self.second_machine("left")+ self.assertIn({"peer": SECOND_ID, "kind": "edge", "off": True}, self.store.current()["zones"])+ self.assertIn("Second has no way in", ways.blocked_sentence(self.store.current(), SECOND_ID, "this Mac"))++ def test_moving_a_machine_onto_a_taken_side_keeps_the_side_and_turns_its_way_there_off(self):+ self.second_machine("right", [{"peer": SECOND_ID, "kind": "edge"}])+ self.assertTrue(self.store.set_ways(SECOND_ID, side="left", methods=["edge"], parts=["middle"], corner="top_right"))+ second = next(entry for entry in self.settings()["peers"] if entry["id"] == SECOND_ID)+ self.assertEqual(second["side"], "left")+ self.assertIn({"peer": SECOND_ID, "kind": "edge", "off": True}, self.settings()["zones"])++ def test_ways_for_a_machine_no_longer_paired_are_refused(self):+ with self.assertRaises(SettingsError):+ self.store.set_ways(SECOND_ID, side="right", methods=["edge"], parts=["middle"], corner="top_right")+def test_the_first_machines_port_is_its_own_and_never_moves_this_macs(self):raw = config_to_raw(self.cfg)raw["port"] = 9000@@ -625,7 +719,8 @@ class PairedAndRemovedTests(Base):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"], [])+ # Only the new machine's own edge, which every machine paired starts with.+ self.assertEqual(after["zones"], [{"peer": PEER_ID, "kind": "edge"}])self.assertEqual(self.store.load().auth_token, OTHER_TOKEN)def test_a_pairing_that_cannot_be_written_raises_and_changes_nothing(self):@@ -647,7 +742,7 @@ class PairedAndRemovedTests(Base):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"], [])+ self.assertEqual(self.settings()["zones"], [{"peer": SECOND_ID, "kind": "edge"}])def test_removing_the_only_machine_leaves_this_one_unpaired_and_it_stays_so(self):self.store.remove_peer(TOKEN)@@ -919,7 +1014,7 @@ class ReimportRefusalsTests(Base):settings["peers"] = [added]settings["zones"] = []self.store.save_settings(settings)- self.assertEqual(self.settings()["zones"], [])+ self.assertEqual(self.settings()["zones"], [{"peer": SECOND_ID, "kind": "edge"}])class OverlapTests(Base):@@ -974,14 +1069,23 @@ class OverlapTests(Base):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"])+ def test_ways_with_the_edge_and_the_thirds_on_write_the_thirds_off(self):+ self.store.set_ways("", side="left", methods=["edge", "part"], parts=["middle"], corner="top_right")+ self.assertEqual(self.store.load().crossing["methods"], ["shortcut", "edge"])zones = {z["kind"]: z for z in self.settings()["zones"]}self.assertTrue(zones["part"]["off"])+ def test_two_machines_on_one_notch_are_refused(self):+ def two_notches(s):+ s["peers"][0]["id"] = PEER_ID+ s["zones"] = [{**z, "peer": PEER_ID} for z in s["zones"]]+ s["zones"][3].pop("off", None)+ second = {**copy.deepcopy(s["peers"][0]), "id": SECOND_ID, "side": "right"}+ second["token"] = second["token"][::-1]+ s["peers"].append(second)+ s["zones"].append({"peer": SECOND_ID, "kind": "notch"})+ self.refused(two_notches)+if __name__ == "__main__":unittest.main()diff --git a/mac_app/tests/test_wake.py b/mac_app/tests/test_wake.pyindex a4ff633..1f0db2b 100644--- a/mac_app/tests/test_wake.py+++ b/mac_app/tests/test_wake.py@@ -103,7 +103,7 @@ class WakingControllerTests(unittest.TestCase):self.controller.WAKE_POLL_SECONDS = 0.01self.alerts = []self.controller.on_user_alert = lambda title, message: self.alerts.append(message)- self.controller.on_mac_learned = self.learned.append+ self.controller.on_mac_learned = lambda peer, mac: self.learned.append(mac)def _wait_for_wake_thread(self):for thread in threading.enumerate():@@ -190,9 +190,12 @@ class WakingControllerTests(unittest.TestCase):newer.reconnect_interval_s = 7.0import bridge as bridge_module+ racing = []+def racing_replace(cfg, **changes):result = real(cfg, **changes)thread = threading.Thread(target=lambda: self.controller.apply_settings(newer))+ racing.append(thread)thread.start()thread.join(0.3)return result@@ -203,6 +206,8 @@ class WakingControllerTests(unittest.TestCase):self.controller.book.data["peers"][0]["host"] = "192.0.2.88"bring_up(self.controller)self._wait_for_learning()+ for thread in racing:+ thread.join(5)self.assertIs(self.controller.cfg, newer)def _wait_for_learning(self):diff --git a/mac_app/tests/test_wake_three.py b/mac_app/tests/test_wake_three.pynew file mode 100644index 0000000..2b94f89--- /dev/null+++ b/mac_app/tests/test_wake_three.py@@ -0,0 +1,83 @@+"""Wake-on-LAN with two machines paired: a switch to a machine that is asleep wakes that machine, at+its own hardware address and host, and a link coming up learns that machine's address for it."""++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 core import protocol+from bridge_fakes import settle+from test_mac_three import BEE, SEA, Three+from wake import WakingController+++class WakingThree(Three):+ controller_class = WakingController++ def setUp(self):+ self.woken = []+ self.looked_up = []+ self.learnt = []+ super().setUp()+ self.controller.wake_sender = lambda mac, host: self.woken.append((mac, host))+ self.controller.mac_lookup = lambda host: self.looked_up.append(host) or "aa:bb:cc:00:00:0" + ("1" if host == "192.0.2.11" else "2")+ self.controller.on_mac_learned = lambda peer, mac: self.learnt.append((peer, mac))+ self.data["peers"][0].update(hw="aa:bb:cc:dd:ee:01", host="192.0.2.11")+ self.data["peers"][1].update(hw="aa:bb:cc:dd:ee:02", host="192.0.2.12")+ self.controller.WAKE_POLL_SECONDS = 0.01++ def test_a_switch_to_a_sleeping_machine_wakes_that_machine(self):+ self.up(self.bee, BEE, "Bee")+ self.assertFalse(self.controller.set_redirecting(True, peer=protocol.id_text(SEA)))+ self.assertTrue(self.controller.waking)+ self.assertTrue(_wait(lambda: self.woken))+ self.assertEqual(self.woken, [("aa:bb:cc:dd:ee:02", "192.0.2.12")])+ self.assertIn("Sea", self.controller.connection_status)+ self.controller.stop_event.set()++ def test_moving_input_on_to_a_sleeping_machine_wakes_it_and_leaves_input_where_it_is(self):+ self.up(self.bee, BEE, "Bee")+ self.assertTrue(self.controller.set_redirecting(True, peer=protocol.id_text(BEE)))+ settle(self.controller)+ self.assertFalse(self.controller.set_redirecting(True, peer=protocol.id_text(SEA)))+ self.assertTrue(_wait(lambda: self.woken))+ self.assertEqual(self.woken, [("aa:bb:cc:dd:ee:02", "192.0.2.12")])+ self.assertTrue(self.controller.redirecting)+ self.controller.stop_event.set()++ def test_the_shortcut_to_nothing_up_wakes_the_first_it_would_send_to(self):+ self.assertFalse(self.controller.set_redirecting(True))+ self.assertTrue(_wait(lambda: self.woken))+ self.assertEqual(self.woken, [("aa:bb:cc:dd:ee:01", "192.0.2.11")])+ self.controller.stop_event.set()++ def test_can_wake_speaks_of_the_machine_in_question(self):+ self.up(self.bee, BEE, "Bee")+ self.assertFalse(self.controller.can_wake)+ self.data["peers"][0]["send"] = False+ self.controller.peers_changed()+ self.assertTrue(self.controller.can_wake)++ def test_every_link_coming_up_learns_its_own_machines_address(self):+ self.bee.dialled = ("192.0.2.11", 24820)+ self.up(self.bee, BEE, "Bee")+ self.up(self.sea, SEA, "Sea")+ self.assertTrue(_wait(lambda: len(self.learnt) == 2), self.learnt)+ self.assertEqual(sorted(self.learnt), sorted([(protocol.id_text(BEE), "aa:bb:cc:00:00:01"),+ (protocol.id_text(SEA), "aa:bb:cc:00:00:02")]))+++def _wait(predicate, timeout=2.0):+ done = threading.Event()+ for _ in range(int(timeout / 0.01)):+ if predicate():+ return True+ done.wait(0.01)+ return predicate()+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_way_home.py b/mac_app/tests/test_way_home.pyindex 92bfc73..3dec684 100644--- a/mac_app/tests/test_way_home.py+++ b/mac_app/tests/test_way_home.py@@ -185,7 +185,7 @@ class ChangesReachTheArmedZonesTests(unittest.TestCase):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["peers"][0].update(id=PEER_TEXT, side="right", send=False, from_1_4=False)settings["zones"] = zones(methods, parts, corner)self.store.save_settings(settings)diff --git a/mac_app/tests/two_machines.py b/mac_app/tests/two_machines.pyindex 511f118..890b5cb 100644--- a/mac_app/tests/two_machines.py+++ b/mac_app/tests/two_machines.py@@ -32,6 +32,7 @@ from bridge import KVMControllerimport bridge_fakesfrom bridge_fakes import PAIRED_TOKEN, FakeClock, FakeQuartz, crossing_config, quiet_loggerfrom core import protocol+from core.return_edge import OPPOSITEfrom core.return_edge import Rectfrom core.tests.responder_harness import HERE, FakeDesktop, FakeInjector, Initiator, Machine, entryfrom settings_store import SettingsStore@@ -102,7 +103,7 @@ class Duo: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"}])+ settings["zones"] = self._named(mac_zones if mac_zones is not None else self._zones_from(cfg.crossing))self.store.save_settings(settings)# The one pasteboard the controller and the Mac's responder share, as on a real Mac.@@ -113,7 +114,7 @@ class Duo:)self.mac.on_crossing = lambda kind, step: self.feedback.append((kind, step))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.on_arrangement = lambda peer, edge, set_at, by, way_back=None: self.mac_arrangements.append((OPPOSITE[edge], set_at, by))self.mac.notch_range = notchleft, top, right, bottom = mac_bounds@@ -124,7 +125,7 @@ class Duo:):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)),+ arrangement_callback=lambda peer, edge, set_at, by, way_back=None: self.mac_arrangements.append((OPPOSITE[edge], set_at, by)),arrival_callback=lambda edge, x, y: self.mac_arrivals.append((edge, x, y)),)self.mac_responder = self.mac_input.server@@ -133,6 +134,20 @@ class Duo:self._started = Falseself._closed = False+ @staticmethod+ def _zones_from(crossing):+ """The Mac's zones for the PC as its crossing methods make them, the one list both its own+ pointer and a driven one cross by (WIRE.md section 8)."""+ methods = crossing["methods"]+ zones = [{"peer": "pc", "kind": "edge"}] if "edge" in methods else []+ if "part" in methods and "edge" not in methods:+ zones.append({"peer": "pc", "kind": "part", "parts": list(crossing["edge_parts"])})+ if "corner" in methods:+ zones.append({"peer": "pc", "kind": "corner", "corner": crossing["corner"], "edge": crossing["corner"].split("_")[1]})+ if "notch" in methods:+ zones.append({"peer": "pc", "kind": "notch"})+ return zones+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}diff --git a/mac_app/wake.py b/mac_app/wake.pyindex 4a70727..d33f4de 100644--- a/mac_app/wake.py+++ b/mac_app/wake.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport threadingfrom bridge import KVMController+from core import protocolfrom core.wol import WAKE_WINDOW_SECONDS, lookup_mac, mac_from_arp_output, magic_packet, parse_mac, send_magic_packet__all__ = [@@ -36,13 +37,14 @@ class WakingController(KVMController):switch 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.- `on_mac_learned(mac)` fires off the connection thread when the ARP table names a different- address from the one stored; the app persists it."""+ `on_mac_learned(peer, mac)` fires off the connection thread when the ARP table names a+ different address for a machine from the one stored for it; the app persists it."""WAKE_POLL_SECONDS = 0.5def __init__(self, cfg, wake_sender=send_magic_packet, mac_lookup=lookup_mac, **kwargs):self._waking = False+ self._waking_peer = Noneself._wake_lock = threading.Lock()self.wake_sender = wake_senderself.mac_lookup = mac_lookup@@ -51,14 +53,31 @@ class WakingController(KVMController):@propertydef connection_status(self):- return waking_status(self._wake_name()) if self._waking else KVMController.connection_status.fget(self)+ if self._waking:+ return waking_status(self._wake_name(self._waking_peer))+ return 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"+ def _wake_name(self, peer=None):+ peer = peer or self._in_question()+ name = self._label(lambda entry: entry.get("id") == peer) if peer else None+ return name or self.peer_label or self.cfg.pc_name or self.cfg.host or "the other machine"++ def _wake_address(self, peer):+ """`peer`'s (hardware address, host): its entry's; a Config-built controller's flat settings'."""+ if self._memory is not None:+ return self.cfg.mac_address, self.cfg.host+ entry = next((item for item in self.book.peers() if item.get("id") == peer), None) or {}+ return entry.get("hw") or "", entry.get("host") or ""++ def _awake(self, peer):+ if self._memory is not None:+ return self.connected+ link = self._peers_up.get(peer) if peer else None+ return link is not None and link.live()@propertydef waking(self) -> bool:@@ -66,43 +85,56 @@ class WakingController(KVMController):@propertydef can_wake(self) -> bool:- return bool(self.cfg.mac_address) and not self.connected-- def set_redirecting(self, value, edge=None, offset=None, came_home=True):- if value and not self.redirecting and not self.connected and self.cfg.mac_address and not self._refused():- self.wake()+ """Whether the machine in question (where input is, else where the shortcut would send it)+ is asleep and can be woken."""+ peer = self._in_question()+ return bool(self._wake_address(peer)[0]) and not self._awake(peer)++ def set_redirecting(self, value, edge=None, offset=None, came_home=True, peer=None):+ target = peer or self._shortcut_peer()+ # From home, or on from the machine input is on to another (a menu naming it): one asleep is woken.+ leaving = not self.redirecting or (peer is not None and peer != self.owner.on)+ if (value and leaving and not self._awake(target) and self._wake_address(target)[0]+ and not self._refused(target)):+ self.wake(target)return False- return super().set_redirecting(value, edge, offset, came_home=came_home)-- def _refused(self) -> bool:- """A PC that answered and refused -- the token, or the protocol version -- is awake, and- waking it would hide why; the switch says the refusal instead."""- return self.status_kind in REFUSED_KINDS-- def wake(self) -> bool:- """Sends the packet and starts waiting, unless a wake is already in flight."""+ return super().set_redirecting(value, edge, offset, came_home=came_home, peer=peer)++ def _refused(self, peer=None) -> bool:+ """A machine that answered and refused -- the pairing, or the protocol version -- is awake,+ and waking it would hide why; the switch says the refusal instead."""+ link = self._link_of(peer) if peer else None+ kind = link.kind if link is not None else self.status_kind+ return kind in REFUSED_KINDS++ def wake(self, peer=None) -> bool:+ """Sends `peer` (the machine in question when not given) the packet and starts waiting,+ unless a wake is already in flight."""+ peer = peer or self._in_question()with self._wake_lock:- if self._waking or self.connected:+ if self._waking or self._awake(peer):return Falseself._waking = True- threading.Thread(target=self._wake_worker, name="wake", daemon=True).start()+ self._waking_peer = peer+ threading.Thread(target=self._wake_worker, args=(peer,), name="wake", daemon=True).start()return True- def _wake_worker(self):+ def _wake_worker(self, peer=None):started = self.clock()- name = self._wake_name()+ name = self._wake_name(peer)+ mac, host = self._wake_address(peer)try:- self.wake_sender(self.cfg.mac_address, self.cfg.host)+ self.wake_sender(mac, host)except (OSError, ValueError) as exc:self.logger.warning("wake-on-LAN packet not sent: %s", exc)self._waking = Falseself.connection_status = not_woken_status(name)self._alert("Beamer", "Could not send the wake-up packet")return- self.logger.info("sent wake-on-LAN to %s", self.cfg.host)+ self.logger.info("sent wake-on-LAN to %s", host)self._alert("Beamer", waking_status(name))while not self.stop_event.wait(self.WAKE_POLL_SECONDS):- if self.connected:+ if self._awake(peer):self._waking = Falseself.logger.info("%s woke and connected", name)self._alert("Beamer", f"{name} is awake — switch again to send input")@@ -114,27 +146,31 @@ class WakingController(KVMController):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 _primary_up(self, link, fields):- super()._primary_up(link, fields)+ def _peer_up(self, link, fields):+ super()._peer_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()+ peer = protocol.id_text(fields["id"])+ threading.Thread(target=self._learn_mac, args=(peer, host), name="Beamer-learn-mac", daemon=True).start()- def _learn_mac(self, host):+ def _learn_mac(self, peer, host):try:mac = self.mac_lookup(host)except Exception:self.logger.exception("hardware address lookup failed")return- with self._cfg_lock:- if not mac or mac == self.cfg.mac_address:- return- self.cfg.mac_address = mac- self.logger.info("learned the PC's hardware address from the ARP table")+ if self._memory is not None:+ with self._cfg_lock:+ if not mac or mac == self.cfg.mac_address:+ return+ self.cfg.mac_address = mac+ elif not mac or mac.lower() == self._wake_address(peer)[0].lower():+ return+ self.logger.info("learned %s's hardware address from the ARP table", self._wake_name(peer))callback = self.on_mac_learnedif callback is not None:try:- callback(mac)+ callback(peer, mac)except Exception:self.logger.exception("on_mac_learned callback failed")diff --git a/mac_app/windows_input.py b/mac_app/windows_input.pyindex 879c0cf..6c65c24 100644--- a/mac_app/windows_input.py+++ b/mac_app/windows_input.py@@ -38,7 +38,7 @@ class WindowsInput:self._logger = logger or LOGGER# 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).+ # handler in the app, called with (peer, edge, set_at, by, way_back).self._arrangement_callback = arrangement_callbackself._lock = threading.RLock()self._running_for = None@@ -68,7 +68,6 @@ class WindowsInput: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.server@@ -136,16 +135,16 @@ class WindowsInput:link = self._controller._peers_up.get(protocol.id_text(peer_id))return link is not None and link.live()- 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+ def send_arrangement(self, peer: str, mac_edge: str, set_at: int, by=None) -> bool:+ """Tell `peer` (a b64 id) which edge of this Mac faces it, as the controller's send_arrangement+ does, over the link it opened to this Mac, when this Mac has none open to it (WIRE.md section 3,+ "Which link"). False when it has no link here either, which is not a failure worth reporting."""+ ident = protocol.read_id(peer)if ident is None or self._outbound_up(ident):return False- own = bytes(self._controller.identity()["id"])- return self.server.send(ident, protocol.arrangement_v6(mac_edge, int(set_at), own))+ author = protocol.read_id(by) or bytes(self._controller.identity()["id"])+ return self.server.send(ident, protocol.arrangement_v6(mac_edge, int(set_at), author,+ way_back=self._controller.way_back(peer)))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@@ -171,7 +170,8 @@ class WindowsInput: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))+ messages.append(protocol.arrangement_v6(entry["side"], entry.get("side_set_at", 0), by,+ way_back=self._controller.way_back(text)))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]@@ -183,7 +183,8 @@ class WindowsInput:def _on_arrangement(self, peer, read) -> None:if self._arrangement_callback is None:return- self._arrangement_callback(crossing.OPPOSITE[read["edge"]], read["set_at"], protocol.id_text(read["by"]))+ self._arrangement_callback(protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]),+ read.get("way_back"))def _on_settings(self, peer, data) -> None:if self.settings_callback is not None:diff --git a/win_app/app_config.py b/win_app/app_config.pyindex 687c749..6f6ed6c 100644--- a/win_app/app_config.py+++ b/win_app/app_config.py@@ -1,10 +1,12 @@"""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."""+and never written back to it. `Config` is the flat view the window, the sender and the receiver have+always read: this PC's own settings, and `peers[0]` as the fields that used to be the Mac's+(`mac_host`, `auth_token`, `send_to_mac` and the rest). Each peer's side and zones are written only by+`set_ways` and `apply_arrangement`, one peer at a time, never by a save of the flat view, so a view read+before another machine sent its side cannot put the old one back. The settings carry whatever else+the file holds through every save untouched."""import base64import binascii@@ -15,6 +17,7 @@ import loggingimport osimport tempfileimport threading+import timefrom dataclasses import dataclass, field, fields, replacefrom pathlib import Path@@ -24,6 +27,7 @@ from core import ignoredfrom core import protocolfrom core import receiverfrom core import return_edge+from core import waysfrom core.pairing import local_address_towardsimport tokens@@ -41,17 +45,13 @@ 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))+# (eight fixed keys, 1.2 to 1.3.1) is still one. Which keys are left out, and which are loaded but+# never offered, are the capture's, in its own key codes.TRIGGER_VKS = {- name: vk for vk, name in capture_win.VK_TO_NAME.items() if vk not in _NOT_TRIGGERS+ name: vk for vk, name in capture_win.VK_TO_NAME.items() if vk not in capture_win.NOT_TRIGGER_VKS}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}+UNRECORDABLE_TRIGGER_VKS = capture_win.UNRECORDABLE_TRIGGER_VKSMODIFIER_STYLES = ("semantic", "positional")@@ -68,6 +68,11 @@ class ConfigError(Exception):pass+class ClashError(ConfigError):+ """Two machines' zones would lead from one stretch of this PC's screen; the message is the+ sentence that names both. Nothing was written."""++class SettingsFileError(ConfigError):"""settings.json exists but this version cannot use it (another schema, a hand edit that brokeit). Nothing is written over it."""@@ -99,7 +104,7 @@ class Config:check_updates: bool = True# Every address the window shows is hidden.hide_addresses: bool = False- # Same on both machines: the Crossing and Design pages kept in step with the Mac's, and the unix+ # Same on all machines: the Crossing and Design pages kept in step with the Mac's, and the unix# seconds of the last change to that or to a shared value; see settings_sync.same_on_both: bool = Falsesame_set_at: int = 0@@ -110,8 +115,9 @@ class Config:scroll_speed: float = 1.0reverse_scroll: bool = Falsesend_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.+ # How input leaves this PC: "shortcut" is this PC's own and is saved from here; the rest, with the+ # corner, the thirds, `mac_return_edge` and `arrangement_set_at`, are the first peer's ways as+ # loaded, never saved from here (set_ways writes each peer's).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.@@ -130,11 +136,6 @@ class Config:# 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@@ -645,7 +646,8 @@ def load_settings(path: Path) -> dict:settings.setdefault("port", protocol.DEFAULT_PORT)settings.setdefault("shortcut", True)settings.setdefault("migrated_token_sha256", "")- if legacy is not None and remigrate(settings, legacy):+ repaired = ways.ensure_zones(settings)+ if (legacy is not None and remigrate(settings, legacy)) or repaired:_write_json(path, settings)return settings@@ -717,9 +719,10 @@ def _flat_from_settings(settings: dict) -> dict: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."""+ """Write a Config's flat fields (from `config_to_dict`) into the settings: this PC's own, and the+ first peer's address, name and switches, never a side or a zone. A token that is not the first+ peer's is a new pairing: it replaces that entry, and its zones point at the empty id until a link+ 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"]@@ -731,6 +734,9 @@ def _apply_flat(settings: dict, flat: dict) -> None: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)+ held = peers[0] if peers else {}+ # The side is the pair's, settled by `arrangement`, and is not the flat view's to set.+ entry.update(side=held.get("side", ""), side_set_at=held.get("side_set_at", 0), side_by=held.get("side_by", ""))if peers:for zone in settings["zones"]:if zone.get("peer") == peers[0].get("id"):@@ -739,34 +745,14 @@ def _apply_flat(settings: dict, flat: dict) -> None: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"],- )+ # Its name and hardware address are learnt on its link: written here only with a new address, which+ # clears what was learnt at the old one, or a save from a window read before one was learnt would+ # put the old one back.+ if flat["mac_host"] != peer.get("host"):+ peer.update(name=flat["paired_with"], hw=flat["mac_hardware_address"])+ peer.update(host=flat["mac_host"], send=flat["send_to_mac"], allow_drive=flat["allow_mac_to_drive"])if flat["port"] != old_port and peer.get("port") == old_port:peer["port"] = flat["port"]- _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@@ -833,8 +819,8 @@ def set_own(path: Path, **fields) -> None: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."""+ """What links write into the first peer's entry, in the flat view's names: its token, address,+ hardware address and name, and the two direction switches."""with SETTINGS_LOCK:flat = _flat_from_settings(load_settings(path))# With no peer there is nothing for links to have written, and the flat view has no such fields.@@ -842,11 +828,8 @@ def learned_fields(path: Path) -> dict: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",-)+# What links and a fold write into the first peer, in the flat view's names.+LEARNED = ("auth_token", "mac_host", "mac_hardware_address", "paired_with", "send_to_mac", "allow_mac_to_drive")# The ones a link writes while the window is not looking, which a save must never overwrite.LINK_WRITTEN = ("mac_host", "mac_hardware_address", "paired_with")@@ -863,50 +846,40 @@ def set_peer_hardware_address(path: Path, peer: str, address: str) -> bool: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."""+def set_ways(path: Path, peer: str, *, side=None, methods, parts, corner) -> bool:+ """Writes one peer's ways across (WIRE.md section 8): its `side`, and its edge, part and corner+ zones, in use when named in `methods`. `side` None keeps the side held now, so a change to a way+ never puts back a side that arrived since the window last read it. Raises ClashError, writing+ nothing, when two machines' zones would then cover one stretch of this PC's screen; ConfigError+ when no entry has `peer`. Returns whether the side moved, which the caller sends as `arrangement`."""with SETTINGS_LOCK:settings = load_settings(path)entry = next((item for item in settings["peers"] if item.get("id") == peer), None)- 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)+ if entry is None:+ raise ConfigError("that machine is not paired with this PC")+ moved = ways.edit(+ settings, peer, side=entry.get("side", "") if side is None else side, methods=methods, parts=parts,+ corner=corner, kinds=KINDS, corner_edge=_corner_edge, now=time.time(),+ )+ if moved:+ # Moved onto a side another machine's edge holds: the side stands and this machine's way+ # there goes off, as when the side arrives from it; the page says which machine holds it.+ ways.settle(settings, peer, "this PC")+ sentence = ways.clash(settings, "this PC")+ if sentence is not None:+ raise ClashError(sentence)_write_json(path, settings)- return True, notices+ return moved-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 notices+def apply_arrangement(path: Path, peer: str, edge: str, set_at: int, by: str, way_back=None):+ """A peer's `arrangement` (WIRE.md section 8), as core.ways takes it: `edge` is the edge of the peer+ that faces this PC, so this PC's side for it is the opposite, and `way_back` is kept whatever the+ side. Returns (changed, notices): whether the file was written, and a sentence for each of that+ peer's zones turned off by a clash."""+ with SETTINGS_LOCK:+ settings = load_settings(path)+ changed, notices = ways.arrangement(settings, peer, edge, set_at, by, "this PC", way_back, _corner_edge)+ if changed:+ _write_json(path, settings)+ return changed, noticesdiff --git a/win_app/autostart_x11.py b/win_app/autostart_x11.pynew file mode 100644index 0000000..902af63--- /dev/null+++ b/win_app/autostart_x11.py@@ -0,0 +1,115 @@+"""Start at login, owned by the app: the autostart entry is the setting, so there is no config+field to disagree with it.++An XDG autostart entry (freedesktop Desktop Application Autostart spec) in+$XDG_CONFIG_HOME/autostart, which every mainstream desktop session runs at login. Unlike the+Windows task it needs no elevation and no service manager.++The spec lets a user or desktop switch an entry off without deleting it, with Hidden=true (or+GNOME's X-GNOME-Autostart-enabled=false), so those read as disabled here; enabling rewrites the+file and so clears them.+"""++from __future__ import annotations++import os+import sys+import tempfile+from pathlib import Path+from typing import Optional++ENTRY_NAME = "beamer.desktop"+COMMENT = "Shares one keyboard and mouse between your computers"+# The spec's reserved characters: an Exec argument holding any of them must be double-quoted.+_RESERVED = set(" \t\n\"'\\<>~|&;$*?#()`")+++def config_home() -> Path:+ """$XDG_CONFIG_HOME, or ~/.config when it is unset, empty or not absolute, as the base+ directory spec says."""+ configured = os.environ.get("XDG_CONFIG_HOME", "")+ return Path(configured) if configured and os.path.isabs(configured) else Path.home() / ".config"+++def _entry_path(base: Optional[os.PathLike]) -> Path:+ return Path(base if base is not None else config_home()) / "autostart" / ENTRY_NAME+++def installed_exe() -> Optional[str]:+ """The exe an entry can start, or None when running from source, where there is none."""+ return sys.executable if getattr(sys, "frozen", False) else None+++def _exec_argument(arg: str) -> str:+ """One argument as the spec's Exec key wants it: %% for a literal percent, double quotes when+ a reserved character is present (with " ` $ and \\ backslash-escaped inside), then the whole+ value escaped again as a string, which doubles every backslash."""+ arg = arg.replace("%", "%%")+ if any(char in _RESERVED for char in arg):+ for char in '\\"`$':+ arg = arg.replace(char, "\\" + char)+ arg = f'"{arg}"'+ return arg.replace("\\", "\\\\").replace("\n", "\\n").replace("\t", "\\t")+++def exec_line(exe: str) -> str:+ return f"{_exec_argument(exe)} --hidden"+++def entry_text(exe: str) -> str:+ return (+ "[Desktop Entry]\n"+ "Type=Application\n"+ "Name=Beamer\n"+ f"Exec={exec_line(exe)}\n"+ "X-GNOME-Autostart-enabled=true\n"+ "NoDisplay=true\n"+ f"Comment={COMMENT}\n"+ )+++def is_enabled(base: Optional[os.PathLike] = None) -> bool:+ try:+ lines = _entry_path(base).read_text(encoding="utf-8", errors="replace").splitlines()+ except OSError:+ return False+ in_entry = False+ for line in lines:+ line = line.strip()+ if line.startswith("["):+ in_entry = line == "[Desktop Entry]"+ elif in_entry:+ key, _, value = line.partition("=")+ key, value = key.strip(), value.strip()+ if (key == "Hidden" and value == "true") or (key == "X-GNOME-Autostart-enabled" and value == "false"):+ return False+ return True+++def set_enabled(enabled: bool, exe: str, base: Optional[os.PathLike] = None) -> None:+ """Raises OSError saying which file could not be written, or removed, and why."""+ path = _entry_path(base)+ if not enabled:+ try:+ path.unlink(missing_ok=True)+ except OSError as error:+ raise OSError(f"could not remove {path}: {error.strerror or error}") from error+ return+ temp = None+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, temp = tempfile.mkstemp(dir=path.parent, prefix=".beamer-", suffix=".tmp")+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ handle.write(entry_text(exe))+ # mkstemp makes the file private; a desktop session reads it as the user, but others expect 0644.+ os.chmod(temp, 0o644)+ os.replace(temp, path)+ temp = None+ except OSError as error:+ raise OSError(f"could not write {path}: {error.strerror or error}") from error+ finally:+ if temp is not None:+ try:+ os.unlink(temp)+ except OSError:+ passdiff --git a/win_app/capture_portal.py b/win_app/capture_portal.pynew file mode 100644index 0000000..2854945--- /dev/null+++ b/win_app/capture_portal.py@@ -0,0 +1,871 @@+"""Keyboard and mouse capture on Wayland, through the InputCapture portal and libei: the twin of+capture_x11.py, with the same Hooks, Trigger and names, so the bridge and the sender drive it.++Wayland lets no app see input meant for another, so capture is the desktop's. Beamer puts pointer+barriers on the outside edges of this machine's zones (the edge, its thirds, or a corner's two+walls) and the compositor, when the pointer pushes through one, captures every keyboard and+pointer and sends their events to Beamer over libei until Beamer lets go (Release). Nothing else+can start a capture, so input leaves this machine only across an edge: the shortcut and the tray+bring it home but cannot send it away, and Beamer sees no key at all while input is here.++A push into a barrier is not yet a crossing. The barrier holds the pointer, as Windows holds it at+the edge of the desktop, and the movement that follows feeds the sender's own zone models, so the+resistance, the corners and the thirds behave as on the other machines. The pointer can slide+along the barrier while held; the desktop shows it still, so where it is lives in desktop_portal+and the pointer is let go there. Any movement back into the screen, a key, a button, or a pause+in the push lets go of it; the key or button that did is lost, since nothing can play it back+here. Once the zone gives, input is away until the sender brings it home, and the pointer is let+go where the sender lands it (it says so through desktop_portal before or just after it reports+input home, so the let-go waits a moment for it).++While input is away, a key the sender hands back (the stays-here list) is lost for the same+reason, and the full-screen hold and the drag guard have nothing to read (desktop_portal).++Every way home is the desktop's: Release, the session closing when its D-Bus connection does+(a stop, an error, the process dying), and a watchdog that ends that connection when the capture+thread stops answering while the desktop holds input for it.++InputCapture v2 (GNOME 51, Plasma 6.7) remembers the user's answer with a restore token, kept in+the state directory; v1 asks at every start."""++import logging+import math+import os+import select+import threading+import time+from typing import Callable, Dict, List, Optional, Tuple++from capture_win import ( # noqa: F401 (re-exported for the bridge, which reads them from here)+ BUTTON_TITLES,+ MODIFIER_NAMES,+ REDIRECT,+ RETURN,+ TOGGLE,+ WHEEL_DELTA,+ WM_MOUSEHWHEEL,+ WM_MOUSEWHEEL,+ Trigger,+ button_of,+ mouse_event,+ wheel_notches,+)+from capture_x11 import ( # noqa: F401 (the same evdev names and titles as X11)+ _BUTTONS,+ CHORD_MASK,+ KEYCODE_OFFSET,+ NOT_TRIGGER_VKS,+ UNRECORDABLE_TRIGGER_VKS,+ VK_TITLES,+ VK_TO_NAME,+ _wheel_data,+ character,+ hook_vk,+ input_title,+)+from core import keytable+from core import return_edge as crossing+import desktop_portal+import portal++LOGGER = logging.getLogger(__name__)++INTERFACE = "org.freedesktop.portal.InputCapture"+CAP_KEYBOARD, CAP_POINTER = 1, 2+TICK_SECONDS = 0.05+STALL_SECONDS = 2.0+# A push that stops for this long is a pointer resting at the edge, which is let go.+IDLE_SECONDS = 0.3+# How long a let-go waits for the sender to say where the pointer lands.+LANDING_SECONDS = 0.15+# How long the portal has to answer a request no user sees (zones, barriers).+REQUEST_SECONDS = 10.0+# After the desktop disables the session, the barriers are set again no sooner than this.+DISABLED_SECONDS = 1.0+# An Activated signal with no activation_id (the portal spec allows it): libei's sequences are not+# checked, and Release names none.+NO_ID = -1+# A push that met two barriers at once is put on the nearest within this many pixels of the pointer.+WALL_PX = 64+# While input is away with nothing captured, the sender is asked to bring it home this often.+HOME_AGAIN_SECONDS = 0.5+# ei events that arrive before the portal's Activated signal says which barrier, held until it does.+EARLY_MAX = 64+EARLY_SECONDS = 1.0+# libei's scroll is in the desktop's pixels; mutter and weston send 10 for one wheel click.+PIXELS_PER_NOTCH = 10.0+# evdev's button codes, as X numbers them for capture_x11's table.+EVDEV_BUTTONS = {0x110: 1, 0x111: 3, 0x112: 2, 0x113: 8, 0x114: 9}++# The core modifier bits a held key sets, for when the desktop does not say (libei sends a+# receiver its modifiers only if the compositor chooses to).+HELD_MODS = {42: 1, 54: 1, 29: 4, 97: 4, 56: 8, 125: 64, 126: 64}++# Wall outward directions.+_NORMAL = {"left": (-1, 0), "right": (1, 0), "top": (0, -1), "bottom": (0, 1)}++# The app's own sentences for what Wayland takes away; the bridge shows them as they are.+NO_PORTAL = ("This desktop does not let apps capture the keyboard and mouse (it has no InputCapture "+ "portal), so this machine cannot drive another one. It can still be driven if the "+ "desktop allows remote control.")+REFUSED = ("Beamer was not allowed to capture the keyboard and mouse, so this machine cannot drive "+ "another one. Turn sending off and on again to be asked again.")+ENDED = "The desktop stopped letting Beamer capture the keyboard and mouse: {detail}"+++class CaptureUnavailable(RuntimeError):+ """Capture cannot happen here; `sentence` says so in the app's words."""++ def __init__(self, sentence: str) -> None:+ super().__init__(sentence)+ self.sentence = sentence+++# -- barriers, pure -------------------------------------------------------+++def _outer(monitors: List[crossing.Rect], monitor: crossing.Rect, edge: str) -> List[Tuple[int, int]]:+ """The stretches of `monitor`'s `edge`, as [start, end) along it, that no other display lies+ beyond: a barrier must sit on the outside of the union of the zones."""+ if edge in ("left", "right"):+ line = monitor.x if edge == "left" else monitor.x + monitor.width+ start, end = monitor.y, monitor.y + monitor.height+ beyond = [(m.y, m.y + m.height) for m in monitors+ if (m.x + m.width == line if edge == "left" else m.x == line)]+ else:+ line = monitor.y if edge == "top" else monitor.y + monitor.height+ start, end = monitor.x, monitor.x + monitor.width+ beyond = [(m.x, m.x + m.width) for m in monitors+ if (m.y + m.height == line if edge == "top" else m.y == line)]+ stretches = [(start, end)]+ for low, high in beyond:+ cut = []+ for a, b in stretches:+ if high <= a or low >= b:+ cut.append((a, b))+ continue+ if a < low:+ cut.append((a, low))+ if high < b:+ cut.append((high, b))+ stretches = cut+ return stretches+++def _line(monitor: crossing.Rect, edge: str) -> int:+ return {"left": monitor.x, "right": monitor.x + monitor.width,+ "top": monitor.y, "bottom": monitor.y + monitor.height}[edge]+++def _segment(monitor: crossing.Rect, edge: str, a: int, b: int) -> Tuple[int, int, int, int]:+ line = _line(monitor, edge)+ if edge in ("left", "right"):+ return (line, a, line, b - 1)+ return (a, line, b - 1, line)+++def _clip(stretches, low: int, high: int) -> List[Tuple[int, int]]:+ return [(max(a, low), min(b, high)) for a, b in stretches if min(b, high) > max(a, low)]+++def _thirds(monitor: crossing.Rect, edge: str) -> List[Tuple[int, int]]:+ """Each third of `monitor` along `edge`, as [start, end), split where return_edge.part_of+ splits a fraction of the display."""+ start, length = (monitor.y, monitor.height) if edge in ("left", "right") else (monitor.x, monitor.width)+ cuts = [start + math.ceil(i * length / 3) for i in range(3)] + [start + length]+ return [(cuts[i], cuts[i + 1]) for i in range(3)]+++def barriers(models: list, monitors: List[crossing.Rect]) -> List[Tuple[str, Tuple[int, int, int, int]]]:+ """(wall, position) for every barrier the sender's zone models need on these displays, in the+ portal's coordinates, each once: a whole edge, the chosen thirds of it, or a corner's two walls+ of CORNER_PX + 1 pixels. A notch stretch (SpanEdge) is the Mac's and has none here."""+ found: List[Tuple[str, Tuple[int, int, int, int]]] = []++ def add(wall, position):+ if (wall, position) not in found:+ found.append((wall, position))++ for model in models:+ if isinstance(model, crossing.SpanEdge):+ continue+ for monitor in monitors:+ if isinstance(model, crossing.CornerPush):+ for wall in (model.vertical, model.horizontal):+ along_far = wall in ("left", "right")+ other = model.horizontal if wall in ("top", "bottom") else model.vertical+ if along_far: # a side wall runs along y, from the corner's top or bottom+ low = monitor.y if other == "top" else monitor.y + monitor.height - 1 - crossing.CORNER_PX+ else:+ low = monitor.x if other == "left" else monitor.x + monitor.width - 1 - crossing.CORNER_PX+ for a, b in _clip(_outer(monitors, monitor, wall), low, low + crossing.CORNER_PX + 1):+ add(wall, _segment(monitor, wall, a, b))+ continue+ stretches = _outer(monitors, monitor, model.edge)+ if isinstance(model, crossing.PartEdge):+ thirds = _thirds(monitor, model.edge)+ chosen = [thirds[crossing.PARTS.index(part)] for part in crossing.PARTS if part in model.parts]+ stretches = [piece for low, high in chosen for piece in _clip(stretches, low, high)]+ for a, b in stretches:+ add(model.edge, _segment(monitor, model.edge, a, b))+ return found+++def model_key(models: list) -> tuple:+ """What about the models places barriers, so they are set again only when it changes."""+ return tuple((type(m).__name__, m.edge, tuple(sorted(getattr(m, "parts", ()))), getattr(m, "corner", None))+ for m in models)+++class Press:+ """The pointer held at a barrier while input is still here: where it is, sliding along the+ wall, and whether the movement is still a push."""++ def __init__(self, wall: str, point: Tuple[int, int], displays: List[crossing.Rect], clock=time.monotonic) -> None:+ self.wall = wall+ self._displays = displays+ self.point = desktop_portal.clamp_to(displays, *point)+ self._clock = clock+ self._last_push = clock()+ self._exact = [float(self.point[0]), float(self.point[1])]++ def feed(self, dx: float, dy: float) -> bool:+ """True while the movement pushes outward or slides along the wall; False once it comes+ back into the screen, with `point` where it then is."""+ nx, ny = _NORMAL[self.wall]+ outward = dx * nx + dy * ny+ if outward < 0:+ self._move(dx, dy)+ return False+ # Only the part along the wall moves the pointer; the barrier holds the rest.+ self._move(dx * (1 - abs(nx)), dy * (1 - abs(ny)))+ if outward > 0:+ self._last_push = self._clock()+ return True++ def _move(self, dx: float, dy: float) -> None:+ self._exact[0] += dx+ self._exact[1] += dy+ self.point = desktop_portal.clamp_to(self._displays, *self._exact)+ # Travel past the display is not kept: the pointer cannot be there.+ for axis in (0, 1):+ if self.point[axis] != round(self._exact[axis]):+ self._exact[axis] = float(self.point[axis])++ def idle(self) -> bool:+ return self._clock() - self._last_push > IDLE_SECONDS+++# -- the session ----------------------------------------------------------+++class _Session:+ """The InputCapture session and its libei receiver, on the capture thread only."""++ def __init__(self, bus_factory, ei_factory, tokens, stopping) -> None:+ self.portal = portal.Portal(bus_factory(), stopping)+ self._ei_factory = ei_factory+ self._tokens = tokens+ self.handle = None+ self.ei = None+ self.zone_set = None+ self.enabled = False++ def check(self) -> None:+ preflight = getattr(self._ei_factory, "preflight", None)+ if preflight is not None:+ preflight()+ self.version = self.portal.version(INTERFACE)+ if self.version < 1:+ raise CaptureUnavailable(NO_PORTAL)++ def open(self) -> None:+ """Make and start the session; the user may be asked, for as long as they take."""+ try:+ if self.version >= 2:+ results = portal.plain(self.portal.call(INTERFACE, "CreateSession2", "a{sv}",+ ({"session_handle_token": ("s", self.portal.token())},)))+ self.handle = results[0]["session_handle"]+ options = {"capabilities": ("u", CAP_KEYBOARD | CAP_POINTER), "persist_mode": ("u", 2)}+ token = self._tokens.read()+ if token:+ options["restore_token"] = ("s", token)+ started = self.portal.request(INTERFACE, "Start", "osa{sv}", lambda handle_token: (+ self.handle, "", dict(options, handle_token=("s", handle_token))))+ if started.get("restore_token"):+ self._tokens.write(started["restore_token"])+ else:+ results = self.portal.request(INTERFACE, "CreateSession", "sa{sv}", lambda handle_token: ("", {+ "handle_token": ("s", handle_token),+ "session_handle_token": ("s", self.portal.token()),+ "capabilities": ("u", CAP_KEYBOARD | CAP_POINTER),+ }))+ self.handle = results["session_handle"]+ except portal.Refused:+ self._tokens.write("")+ raise CaptureUnavailable(REFUSED) from None+ fd = self.portal.call(INTERFACE, "ConnectToEIS", "oa{sv}", (self.handle, {}))[0]+ try:+ self.ei = self._ei_factory(fd)+ except Exception:+ os.close(fd)+ raise++ def zones(self) -> List[crossing.Rect]:+ results = self.portal.request(INTERFACE, "GetZones", "oa{sv}", lambda token: (self.handle, {"handle_token": ("s", token)}),+ timeout=REQUEST_SECONDS)+ self.zone_set = results.get("zone_set")+ return [crossing.Rect(x, y, width, height) for width, height, x, y in results.get("zones", [])]++ def set_barriers(self, positions: List[Tuple[int, int, int, int]]) -> List[int]:+ """Barrier i + 1 for each position; the ids the desktop refused. Setting them suspends+ the session, so it is enabled again after, when there are any."""+ self.enabled = False+ listed = [{"barrier_id": ("u", index + 1), "position": ("(iiii)", tuple(position))}+ for index, position in enumerate(positions)]+ results = self.portal.request(INTERFACE, "SetPointerBarriers", "oa{sv}aa{sv}u", lambda token: (+ self.handle, {"handle_token": ("s", token)}, listed, self.zone_set or 0), timeout=REQUEST_SECONDS)+ if positions:+ self.enable()+ return list(results.get("failed_barriers", []))++ def enable(self) -> None:+ self.portal.call(INTERFACE, "Enable", "oa{sv}", (self.handle, {}))+ self.enabled = True++ def disable(self) -> None:+ if self.enabled:+ self.portal.call(INTERFACE, "Disable", "oa{sv}", (self.handle, {}))+ self.enabled = False++ def release(self, activation_id: int, point: Tuple[int, int]) -> None:+ options = {"cursor_position": ("(dd)", (float(point[0]), float(point[1])))}+ if activation_id != NO_ID:+ options["activation_id"] = ("u", int(activation_id))+ self.portal.call(INTERFACE, "Release", "oa{sv}", (self.handle, options))++ def close(self) -> None:+ try:+ if self.ei is not None:+ self.ei.close()+ finally:+ self.ei = None+ self.portal.close()+++class Hooks:+ """The capture thread and the session it owns, with capture_x11.Hooks' callbacks:+ `on_key(name, down, vk, us)`, `on_mouse(message, x, y, mouse_data)` and `on_motion(dx, dy)`,+ `vk` the evdev code. `grab_while(predicate)` says when input is away; `barriers_from(models)`+ gives the sender's zone models, empty while the edges are held. `on_home` is called on the+ capture thread when the desktop ends a capture while input is away (so it comes home), and+ `on_failure(exc)` when capture stops on its own after it started."""++ def __init__(self, on_key, on_mouse, on_motion, connect: Optional[Callable[[], object]] = None,+ ei: Optional[Callable[[int], object]] = None, tokens=None, clock=time.monotonic) -> None:+ self._on_key = on_key+ self._on_mouse = on_mouse+ self._on_motion = on_motion+ self._connect = connect or portal.JeepneyBus+ self._ei_factory = ei or _ei_receiver+ self._tokens = tokens or portal.TokenStore("input-capture")+ self._clock = clock+ self._thread: Optional[threading.Thread] = None+ self._ready = threading.Event()+ self._stopping = threading.Event()+ self._failure: Optional[BaseException] = None+ self._predicate: Optional[Callable[[], bool]] = None+ self._models: Callable[[], list] = lambda: []+ self.on_home: Optional[Callable[[], None]] = None+ self.on_failure: Optional[Callable[[BaseException], None]] = None+ self._session: Optional[_Session] = None+ self._beat = clock()+ self._reset()++ def _reset(self) -> None:+ self._activation: Optional[int] = None+ self._press: Optional[Press] = None+ self._away = False+ self._home_since: Optional[float] = None+ self._early: List[tuple] = []+ self._early_at = 0.0+ self._walls: Dict[int, str] = {}+ self._placed: List[Tuple[str, Tuple[int, int, int, int]]] = []+ self._sequences: Dict[object, int] = {} # libei device: the sequence it emulates under+ self._disabled_at: Optional[float] = None+ self._sent_home_at: Optional[float] = None+ self._key = None+ self._zones: List[crossing.Rect] = []+ self._keymap = None+ self._mods = (0, 0, 0, 0)+ self._names_down: Dict[int, str] = {}+ self._carry = [0.0, 0.0]+ self._scroll_carry = [0.0, 0.0]+ self._frame: List[tuple] = []++ def grab_while(self, predicate: Callable[[], bool]) -> None:+ """Hold input for as long as `predicate` is true, once the desktop has captured it. Asked on+ the capture thread after every batch, so cheap and never blocking."""+ self._predicate = predicate++ def barriers_from(self, models: Callable[[], list]) -> None:+ self._models = models++ @property+ def grabbed(self) -> bool:+ return self._activation is not None++ @property+ def holding(self) -> bool:+ """Whether the desktop has captured input for Beamer now: only then can it go away."""+ return self._activation is not None++ def start(self) -> None:+ if self._thread is not None and self._thread.is_alive():+ if self._stopping.is_set():+ raise RuntimeError("The last capture thread has not stopped yet")+ return+ self._ready.clear()+ self._stopping.clear()+ self._failure = None+ self._thread = threading.Thread(target=self._run, name="Beamer-hooks", daemon=True)+ self._thread.start()+ if not self._ready.wait(timeout=5.0):+ raise RuntimeError("The input capture did not start within five seconds")+ if self._failure is not None:+ raise self._failure++ def stop(self) -> None:+ self._stopping.set()+ thread = self._thread+ if thread is None:+ return+ thread.join(timeout=2.0)+ if thread.is_alive():+ LOGGER.error("The capture thread did not stop within two seconds; ending its connection")+ self._abort()+ thread.join(timeout=1.0)+ if not thread.is_alive():+ self._thread = None++ def _abort(self) -> None:+ session = self._session+ if session is not None:+ abort = getattr(session.portal.bus, "abort", None)+ if abort is not None:+ abort()++ # -- the thread ----------------------------------------------------------++ def _run(self) -> None:+ session = None+ try:+ session = self._session = _Session(self._connect, self._ei_factory, self._tokens, self._stopping.is_set)+ session.check()+ self._beat = self._clock()+ threading.Thread(target=self._watch, name="Beamer-hooks-watch", daemon=True).start()+ self._ready.set()+ session.open()+ self._set_zones(session.zones())+ while not self._stopping.is_set():+ self._beat = self._clock()+ self._wait(session)+ self._beat = self._clock()+ for path, interface, member, body in session.portal.signals():+ if interface == INTERFACE and body and body[0] == session.handle:+ self._signal(member, body[1] if len(body) > 1 else {})+ elif interface == portal.SESSION and member == "Closed" and path == session.handle:+ raise CaptureUnavailable(ENDED.format(detail="the session was closed"))+ events = session.ei.events()+ for event in events:+ self._beat = self._clock()+ try:+ self._ei_event(event)+ except CaptureUnavailable:+ raise+ except Exception:+ LOGGER.exception("An input event could not be read; carrying on")+ self._tick()+ except Exception as exc:+ if not self._stopping.is_set():+ LOGGER.exception("Keyboard and mouse capture stopped")+ started = self._ready.is_set()+ self._failure = exc if not started else None+ self._ready.set()+ if started and not self._stopping.is_set() and self.on_failure is not None:+ try:+ self.on_failure(exc)+ except Exception:+ LOGGER.exception("Could not report that capture stopped")+ finally:+ self._end(session)+ self._stopping.set()++ def _end(self, session) -> None:+ """The way home on every exit: let go of a capture, then end the connection, which closes+ the session even if the Release could not be sent."""+ try:+ if session is not None and self._activation is not None:+ session.release(self._activation, desktop_portal.cursor_position())+ except Exception:+ LOGGER.exception("Could not let go of the captured input; closing the session lets go of it")+ finally:+ self._activation = None+ desktop_portal.set_captured(False)+ if session is not None:+ try:+ session.close()+ except Exception:+ LOGGER.exception("The capture session did not close cleanly")+ self._session = None+ self._reset()++ def _wait(self, session) -> None:+ if session.portal.pending():+ return+ try:+ select.select([session.portal.fileno(), session.ei.fileno()], [], [], TICK_SECONDS)+ except (OSError, ValueError) as exc:+ raise CaptureUnavailable(ENDED.format(detail=exc)) from exc++ def _watch(self) -> None:+ """The safety net under a capture thread stuck while the desktop holds input for it:+ nothing else can let go, so its connection is ended and the portal closes the session."""+ while not self._stopping.wait(STALL_SECONDS / 8):+ if self._activation is not None and self._clock() - self._beat > STALL_SECONDS:+ LOGGER.error("The capture thread has not answered for %s s while the keyboard and mouse are captured; "+ "ending its connection to free them", STALL_SECONDS)+ self._abort()+ return++ # -- portal signals --------------------------------------------------------++ def _signal(self, member: str, options: dict) -> None:+ if member == "Activated":+ self._activated(options)+ elif member in ("Deactivated", "Disabled"):+ point = options.get("cursor_position")+ was_away = self._away+ self._activation = None+ self._press = None+ self._away = False+ self._frame = []+ desktop_portal.set_captured(False)+ if point is not None:+ desktop_portal.note_position(*point)+ if member == "Disabled":+ self._session.enabled = False+ self._key = None # set the barriers and enable again, after DISABLED_SECONDS+ self._disabled_at = self._clock()+ # Asked of the sender too: a tray switch may have sent input away a moment ago.+ if was_away or self._away_wanted():+ LOGGER.info("The desktop ended the capture while input was away; bringing it home")+ self._home()+ elif member == "ZonesChanged":+ self._set_zones(self._session.zones())++ def _activated(self, options: dict) -> None:+ activation = options.get("activation_id", NO_ID)+ point = options.get("cursor_position") or desktop_portal.cursor_position()+ barrier = options.get("barrier_id")+ # 0 is a push that met two barriers at once (a corner's two walls); the pointer says which.+ wall = self._walls.get(barrier) if barrier else self._wall_at(point)+ self._activation = activation+ self._frame = []+ desktop_portal.set_captured(True)+ if wall is None:+ LOGGER.info("Captured at a barrier Beamer does not know; letting go")+ self._let_go(desktop_portal.clamp_to(self._zones, *point))+ return+ self._press = Press(wall, point, self._zones, self._clock)+ desktop_portal.note_position(*self._press.point)+ early, self._early = self._early, []+ for event, sequence in early:+ if self._current(sequence):+ self._ei_event(event)++ def _wall_at(self, point) -> Optional[str]:+ """The wall of the placed barrier nearest the pointer, within WALL_PX: the desktop reports+ the pointer on the screen's side of a barrier, or past it by the push."""+ x, y = point+ best = None+ for index, (wall, (x1, y1, x2, y2)) in enumerate(self._placed):+ if index + 1 not in self._walls:+ continue+ distance = max(x1 - x, 0, x - x2) + max(y1 - y, 0, y - y2)+ if distance <= WALL_PX and (best is None or distance < best[0]):+ best = (distance, wall)+ return best[1] if best else None++ def _let_go_unannounced(self) -> None:+ """The desktop started sending input for a capture it never announced (no Activated):+ after EARLY_SECONDS it is let go under its libei sequence, which is its activation id."""+ if not self._early or self._clock() - self._early_at <= EARLY_SECONDS:+ return+ sequence = self._early[-1][1]+ self._early = []+ LOGGER.warning("The desktop captured input without saying so; letting go")+ self._activation = sequence+ self._let_go(desktop_portal.cursor_position())++ def _current(self, sequence: Optional[int]) -> bool:+ """Whether input emulated under `sequence` belongs to the capture now held: libei's start+ sequence is the portal's activation id."""+ return self._activation == NO_ID or sequence is None or sequence == self._activation++ def _home(self) -> None:+ if self.on_home is not None:+ self.on_home()++ def _let_go(self, point: Tuple[int, int]) -> None:+ """Release at `point`. Input counts as held until the Release has gone, and a Release that+ fails ends the session, whose closing lets go of input whatever else has failed."""+ activation = self._activation+ self._press = None+ self._away = False+ self._home_since = None+ self._frame = []+ desktop_portal.note_position(*point)+ try:+ if activation is not None and self._session is not None:+ self._session.release(activation, point)+ except Exception as exc:+ raise CaptureUnavailable(ENDED.format(detail=f"letting go failed: {exc}")) from exc+ finally:+ self._activation = None+ desktop_portal.set_captured(False)+ # The sender may have landed the pointer while the Release was on its way.+ landed = desktop_portal.position()+ if landed is not None and landed != desktop_portal.clamp_to(self._zones, *point):+ desktop_portal.set_cursor_position(*landed)++ # -- the tick --------------------------------------------------------------++ def _away_wanted(self) -> bool:+ predicate = self._predicate+ if predicate is None:+ return False+ try:+ return bool(predicate())+ except Exception:+ LOGGER.exception("Could not tell whether input is away; bringing it home")+ return False++ def _tick(self) -> None:+ session = self._session+ if self._activation is None:+ # Input away with nothing captured (a switch that passed input_held() just before a+ # let-go): no key can reach the peer, so it comes home.+ if self._away_wanted():+ now = self._clock()+ if self._sent_home_at is None or now - self._sent_home_at >= HOME_AGAIN_SECONDS:+ if self._sent_home_at is None:+ LOGGER.info("Input went away with nothing captured; bringing it home")+ self._sent_home_at = now+ self._home()+ else:+ self._sent_home_at = None+ self._let_go_unannounced()+ if self._disabled_at is None or self._clock() - self._disabled_at >= DISABLED_SECONDS:+ self._place_barriers(session)+ return+ if self._press is not None:+ if self._away_wanted():+ self._press = None+ self._away = True+ elif self._press.idle() or not self._models():+ self._let_go(self._press.point)+ return+ if self._away_wanted():+ self._home_since = None+ return+ now = self._clock()+ if self._home_since is None:+ self._home_since = now+ return+ if now - self._home_since >= LANDING_SECONDS:+ self._let_go(desktop_portal.cursor_position())++ def _set_zones(self, zones: List[crossing.Rect]) -> None:+ self._zones = zones+ desktop_portal.set_zones(zones)+ self._key = None++ def _place_barriers(self, session) -> None:+ try:+ models = list(self._models())+ except Exception:+ LOGGER.exception("Could not read the zones; no barriers until the next change")+ models = []+ key = (model_key(models), tuple(self._zones))+ if key == self._key:+ if models and not session.enabled:+ session.enable()+ return+ self._key = key+ placed = self._placed = barriers(models, self._zones)+ failed = session.set_barriers([position for _wall, position in placed])+ self._walls = {index + 1: wall for index, (wall, _position) in enumerate(placed) if index + 1 not in failed}+ if failed:+ LOGGER.warning("The desktop refused %d of %d edge barriers", len(failed), len(placed))++ # -- ei events -------------------------------------------------------------++ def _ei_event(self, event: tuple) -> None:+ kind = event[0]+ if kind == "device_added":+ device = event[1]+ if hasattr(device, "keymap") and 4 in getattr(device, "caps", ()): # libei.CAP_KEYBOARD+ self._read_keymap(device)+ return+ if kind == "disconnect":+ raise CaptureUnavailable(ENDED.format(detail="its input connection closed"))+ if kind == "modifiers":+ self._mods = tuple(event[2:6])+ return+ if kind == "start":+ self._sequences[event[1]] = event[2]+ return+ if kind == "stop":+ # What arrives between a let-go and the desktop ending the capture belongs to nobody.+ self._sequences.pop(event[1], None)+ if not self._sequences:+ self._early = []+ return+ if kind not in ("motion", "button", "key", "scroll", "scroll_discrete", "frame"):+ return+ sequence = self._sequences.get(event[1]) if len(event) > 1 else None+ if self._activation is None:+ # Ahead of the Activated signal that says which barrier.+ if sequence is not None and len(self._early) < EARLY_MAX:+ if not self._early:+ self._early_at = self._clock()+ self._early.append((event, sequence))+ return+ if not self._current(sequence):+ if sequence > self._activation and len(self._early) < EARLY_MAX:+ # The next capture's, ahead of its Activated signal.+ if not self._early:+ self._early_at = self._clock()+ self._early.append((event, sequence))+ return # else an earlier capture's+ if self._press is not None and self._away_wanted():+ # Sent away from another thread since the last look (the tray, a driven machine).+ self._press = None+ self._away = True+ if self._press is not None:+ self._pressing(event)+ return+ if kind == "frame":+ self._end_frame()+ else:+ self._frame.append(event)++ def _read_keymap(self, device) -> None:+ try:+ text = device.keymap()+ if text:+ import xkb_x11++ if self._keymap is not None:+ self._keymap.close()+ self._keymap = xkb_x11.Keymap.from_text(text)+ except Exception:+ LOGGER.exception("Could not read the captured keyboard's layout; keys with no fixed name are dropped")++ def _pressing(self, event: tuple) -> None:+ kind = event[0]+ if kind in ("key", "button"):+ if event[3]:+ LOGGER.info("A key or button at the edge lets go of the pointer; it does not reach an app")+ self._let_go(self._press.point)+ return+ if kind != "motion":+ return+ press = self._press+ if not press.feed(event[2], event[3]):+ self._let_go(press.point)+ return+ desktop_portal.note_position(*press.point)+ self._motion(event[2], event[3])+ if self._away_wanted():+ self._press = None+ self._away = True++ def _end_frame(self) -> None:+ events, self._frame = self._frame, []+ discrete = any(event[0] == "scroll_discrete" for event in events)+ for event in events:+ kind = event[0]+ if kind == "motion":+ self._motion(event[2], event[3])+ elif kind == "key":+ self._key_event(event[2], event[3])+ elif kind == "button":+ self._button(event[2], event[3])+ elif kind == "scroll_discrete":+ self._wheel(event[2] / 120.0 * WHEEL_DELTA, event[3] / 120.0 * WHEEL_DELTA)+ elif kind == "scroll" and not discrete:+ self._wheel(event[2] / PIXELS_PER_NOTCH * WHEEL_DELTA, event[3] / PIXELS_PER_NOTCH * WHEEL_DELTA)++ def _motion(self, dx: float, dy: float) -> None:+ carry = self._carry+ carry[0] += dx+ carry[1] += dy+ whole_x, whole_y = int(carry[0]), int(carry[1])+ carry[0] -= whole_x+ carry[1] -= whole_y+ if whole_x or whole_y:+ self._on_motion(whole_x, whole_y)++ def _wheel(self, units_x: float, units_y: float) -> None:+ """libei scrolls positive down and right; Windows' wheel is positive up, its horizontal+ wheel positive right."""+ carry = self._scroll_carry+ carry[0] += units_x+ carry[1] -= units_y+ for index, message in ((1, WM_MOUSEWHEEL), (0, WM_MOUSEHWHEEL)):+ whole = int(carry[index])+ carry[index] -= whole+ if whole:+ self._on_mouse(message, 0, 0, _wheel_data(whole))++ def _button(self, code: int, down: bool) -> None:+ fixed = _BUTTONS.get(EVDEV_BUTTONS.get(code))+ if fixed is None:+ return+ press, release, data = fixed+ # An answer of False, the button kept here, cannot be played back on Wayland.+ self._on_mouse(press if down else release, 0, 0, data)++ def _key_event(self, code: int, down: bool) -> None:+ name = self._names_down.get(code) if down else self._names_down.pop(code, None)+ if name is None:+ name = VK_TO_NAME.get(code)+ if name is None and self._keymap is not None:+ depressed, latched, locked, group = self._mods+ mods = self._keymap.core_mods(depressed | latched | locked)+ for held in self._names_down:+ mods |= HELD_MODS.get(held, 0)+ name = character(code + KEYCODE_OFFSET, mods, group, self._keymap)+ if name is None:+ return+ if down:+ self._names_down[code] = name+ self._on_key(name, down, code, keytable.EVDEV_US.get(code))+++def _ei_receiver(fd: int):+ import libei++ return libei.Context(fd, sender=False)+++def _libei_present() -> None:+ import libei++ libei._load()+++# Checked before the session is asked for, so the desktop never asks for something Beamer cannot use.+_ei_receiver.preflight = _libei_presentdiff --git a/win_app/capture_win.py b/win_app/capture_win.pyindex b17e158..f889041 100644--- a/win_app/capture_win.py+++ b/win_app/capture_win.py@@ -246,6 +246,14 @@ for _index in range(1, 13):for _index in range(13, 21):VK_TO_NAME[0x7C + (_index - 13)] = f"f{_index}"+# Media and browser keys are never the trigger: they are what the stays-on-this-PC list is for.+# The undifferentiated 0x10-0x12 never reach the hook.+NOT_TRIGGER_VKS = {0x10, 0x11, 0x12} | set(range(0xA6, 0xB4))+# 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_NAMES = {"shift","shift_r",diff --git a/win_app/capture_x11.py b/win_app/capture_x11.pynew file mode 100644index 0000000..a51636d--- /dev/null+++ b/win_app/capture_x11.py@@ -0,0 +1,763 @@+"""Keyboard and mouse capture on X11: the twin of capture_win.py, with the same Hooks, Trigger and+names, so the bridge and the sender drive it unchanged.++X has no per-event swallow, so capture is two things. A listener: XInput2 raw events, selected on+the root window, report every key, button and movement whoever has focus. And, while input is on+another machine, an active grab of every master device, which keeps their events from every other+client until it is let go. The grab is the capture thread's alone, taken and let go between+bounded batches of events as `grab_while`'s predicate says; it lives on this thread's own+connection, so a process that dies takes it with its socket, and a watchdog closes that socket if+the thread stops answering while it holds the grab, as Windows removes a hook that stops answering.++Raw events reach a client that holds a grab only through the grab's own event mask (proved on+Xvfb on 01-10-2026: with an empty mask, a grabbed pointer's motion stopped arriving), so each grab+asks for them again.++Keys from inside a grab come from the grab's XI2 key events, which carry the state at the moment+of the key: modifiers, layout group and the auto-repeat flag. Raw key events are used for keys+from outside one. Which side of a grab an event came from is read from its sequence number against+the grab's request, not from whether the grab is held when the event is read: a release queued+just before the grab would otherwise be lost, and one queued inside it read twice. A key's release+and repeats go out under the name its press went out under.++An event inside a grab that the sender hands back (an input on the stays-here list, a key at the+moment input came home) is played to this machine through XTest with the grab let go around it,+since the grab has already kept it from every app.++Movement is the mouse's own unaccelerated counts from raw motion, as Windows reads WM_INPUT, and+each one is also reported as a WM_MOUSEMOVE so the sender's pin warps the pointer back while input+is away: XWarpPointer makes no raw event, as SetCursorPos makes no WM_INPUT. No confine_to: a+confined pointer would swallow the sender's arrival warp when input comes home by a crossing. The+wheel is the scroll valuators of a smooth-scrolling device (libinput), whose emulated buttons 4 to+7 are skipped, and buttons 4 to 7 of any other.++Events from the XTEST devices are this machine's own injection, dropped as capture_win drops+LLKHF_INJECTED. A pointer that reports absolute positions (a tablet, a VM's pointer) moves the pin+but gives no pressure, as on Windows.++python-xlib and libxkbcommon are reached only when the hooks start, so this module imports+anywhere."""++import collections+import ctypes+import ctypes.util+import logging+import select+import socket+import struct+import threading+import time+from typing import Callable, Dict, List, Optional, Tuple++# The pure pieces are Windows' own: the sender and the bridge read Windows mouse messages, and the+# trigger is platform-free.+from capture_win import ( # noqa: F401 (re-exported for the bridge, which reads them from here)+ BUTTON_TITLES,+ MODIFIER_NAMES,+ REDIRECT,+ RETURN,+ TOGGLE,+ WHEEL_DELTA,+ WM_LBUTTONDOWN,+ WM_LBUTTONUP,+ WM_MBUTTONDOWN,+ WM_MBUTTONUP,+ WM_MOUSEHWHEEL,+ WM_MOUSEMOVE,+ WM_MOUSEWHEEL,+ WM_RBUTTONDOWN,+ WM_RBUTTONUP,+ WM_XBUTTONDOWN,+ WM_XBUTTONUP,+ Trigger,+ button_of,+ mouse_event,+ wheel_notches,+)+from core import keytable++LOGGER = logging.getLogger(__name__)++# XI2.h, so nothing here needs Xlib to import.+XI_KEY_PRESS, XI_KEY_RELEASE = 2, 3+XI_HIERARCHY_CHANGED = 11+XI_RAW_KEY_PRESS, XI_RAW_KEY_RELEASE = 13, 14+XI_RAW_BUTTON_PRESS, XI_RAW_BUTTON_RELEASE = 15, 16+XI_RAW_MOTION = 17+XI_ALL_DEVICES, XI_ALL_MASTER_DEVICES = 0, 1+XI_MASTER_POINTER, XI_MASTER_KEYBOARD, XI_SLAVE_POINTER = 1, 2, 3+XI_KEY_REPEAT = 1 << 16+XI_POINTER_EMULATED = 1 << 16+XI_MODE_ABSOLUTE = 1+XI_SCROLL_VERTICAL = 1+GENERIC_EVENT = 35+MAPPING_NOTIFY = 34+MAPPING_POINTER = 2++RAW_MASK = sum(1 << kind for kind in (XI_RAW_KEY_PRESS, XI_RAW_KEY_RELEASE, XI_RAW_BUTTON_PRESS, XI_RAW_BUTTON_RELEASE, XI_RAW_MOTION))+POINTER_GRAB_MASK = sum(1 << kind for kind in (XI_RAW_BUTTON_PRESS, XI_RAW_BUTTON_RELEASE, XI_RAW_MOTION))+KEYBOARD_GRAB_MASK = sum(1 << kind for kind in (XI_KEY_PRESS, XI_KEY_RELEASE, XI_RAW_KEY_PRESS, XI_RAW_KEY_RELEASE))++# Core modifier bits. Control, Mod1 (Alt) and Mod4 (Super) are where every desktop maps them.+SHIFT_MASK, LOCK_MASK, CONTROL_MASK, MOD1_MASK, MOD2_MASK, MOD4_MASK = 1, 2, 4, 8, 16, 64+CHORD_MASK = CONTROL_MASK | MOD1_MASK | MOD4_MASK+NUM_LOCK_MASK = MOD2_MASK++KEYCODE_OFFSET = 8 # an X keycode is the evdev code plus 8, on every server that uses evdev or libinput+TICK_SECONDS = 0.05+MAX_BATCH = 128 # events read before the grab is looked at again, however fast they come+STALL_SECONDS = 2.0+# How long a let-go grab's span is kept: every event from inside it has been read long before, and a+# span kept for ever would match again once the 16-bit sequence number came round.+SPAN_KEEP_SECONDS = 5.0++# Wire names by evdev code, Mac-shaped as capture_win's: this keyboard's Ctrl is "cmd" and its Super+# key "ctrl", the Semantic style the sender swaps back to physical names.+VK_TO_NAME: Dict[int, str] = {+ code: keytable.wire_name(physical, "linux", "macos", "semantic") for code, physical in keytable.EVDEV_NAMES.items()+}++# The keypad with Num Lock off moves, as Windows' VK_HOME and the rest do.+KEYPAD_NAMES = {0xFF95: "home", 0xFF96: "left", 0xFF97: "up", 0xFF98: "right", 0xFF99: "down",+ 0xFF9A: "page_up", 0xFF9B: "page_down", 0xFF9C: "end", 0xFF9E: "insert", 0xFF9F: "delete"}++_TITLES = {+ "shift": "Left Shift", "shift_r": "Right Shift", "ctrl": "Left Ctrl", "ctrl_r": "Right Ctrl",+ "alt": "Left Alt", "alt_r": "Right Alt", "cmd": "Left Super", "cmd_r": "Right Super", "caps_lock": "Caps Lock",+ "backspace": "Backspace", "tab": "Tab", "enter": "Enter", "esc": "Esc", "space": "Space", "delete": "Delete",+ "insert": "Insert", "home": "Home", "end": "End", "page_up": "Page Up", "page_down": "Page Down", "left": "Left",+ "right": "Right", "up": "Up", "down": "Down", "menu": "Menu", "print_screen": "Print Screen", "pause": "Pause",+ "num_lock": "Num Lock", "scroll_lock": "Scroll Lock", "browser_back": "Browser Back",+ "browser_forward": "Browser Forward", "volume_mute": "Mute", "volume_down": "Volume Down", "volume_up": "Volume Up",+ "media_next": "Next Track", "media_prev": "Previous Track", "media_stop": "Stop", "media_play_pause": "Play/Pause",+}+_TITLES.update({f"f{index}": f"F{index}" for index in range(1, 25)})+VK_TITLES: Dict[int, str] = {code: _TITLES[physical] for code, physical in keytable.EVDEV_NAMES.items()}+VK_TITLES[96] = "Num Enter"++# Offered by the recorder or not, as app_config reads capture_win's: media and browser keys are for+# the stays-here list, and typing keys a double-tap or a hold would take from every app. On X the+# trigger also reaches apps at home, so Print Screen stays out as on Windows.+NOT_TRIGGER_VKS = {code for code, physical in keytable.EVDEV_NAMES.items() if physical.startswith(("media_", "volume_", "browser_"))}+UNRECORDABLE_TRIGGER_VKS = {code for code, physical in keytable.EVDEV_NAMES.items()+ if physical in ("backspace", "tab", "enter", "esc", "space", "print_screen")}+++def hook_vk(vk: int, scan: int) -> int:+ """The evdev code of a key a Qt window saw: Qt on X11 gives the X keycode as the native scan+ code, and the native virtual key is a keysym, which names the character rather than the key."""+ return scan - KEYCODE_OFFSET if scan > KEYCODE_OFFSET else 0+++def input_title(entry: str) -> str:+ """The name an ignored-inputs entry is shown under."""+ kind, _, value = entry.partition(":")+ if kind == "button":+ return BUTTON_TITLES.get(value, f"Button {value}")+ if kind == "key" and value.isdigit():+ code = int(value)+ if code in VK_TITLES:+ return VK_TITLES[code]+ if code in keytable.EVDEV_US:+ return keytable.EVDEV_US[code].upper()+ return f"Key {code}"+ return entry+++def parse_raw(data: bytes) -> Tuple[int, int, int, int, Dict[int, float]]:+ """(deviceid, detail, sourceid, flags, raw valuators) from the bytes of an XI2 raw event after+ its first ten, which is what python-xlib hands over: it registers no parser for raw events.+ The raw values are the device's own, unaccelerated; the accelerated ones before them are+ skipped."""+ deviceid, _time, detail, sourceid, mask_len, flags = struct.unpack_from("=HIIHHI", data, 0)+ offset = 22+ mask = data[offset:offset + mask_len * 4]+ offset += mask_len * 4+ numbers = [bit for bit in range(mask_len * 32) if mask[bit // 8] >> (bit % 8) & 1]+ offset += 8 * len(numbers)+ raw = {}+ for number in numbers:+ integral, fraction = struct.unpack_from("=iI", data, offset)+ offset += 8+ raw[number] = integral + fraction / 2 ** 32+ return deviceid, detail, sourceid, flags, raw+++_xkb = []+++def _keysym_to_utf32():+ if not _xkb:+ function = None+ name = ctypes.util.find_library("xkbcommon")+ if name:+ try:+ function = ctypes.CDLL(name).xkb_keysym_to_utf32+ function.restype = ctypes.c_uint32+ function.argtypes = [ctypes.c_uint32]+ except (OSError, AttributeError):+ function = None+ _xkb.append(function)+ return _xkb[0]+++_KEYPAD_TEXT = {0xFFAA: "*", 0xFFAB: "+", 0xFFAC: ",", 0xFFAD: "-", 0xFFAE: ".", 0xFFAF: "/"}+_KEYPAD_TEXT.update({0xFFB0 + digit: str(digit) for digit in range(10)})+++def keysym_text(keysym: int) -> Optional[str]:+ """The character a keysym types, or None. libxkbcommon knows every keysym; without it (the+ tests on the Mac), Latin-1, the keypad and the Unicode keysyms."""+ if not keysym:+ return None+ convert = _keysym_to_utf32()+ if convert is not None:+ point = convert(keysym)+ return chr(point) if point else None+ if 0x20 <= keysym <= 0x7E or 0xA0 <= keysym <= 0xFF:+ return chr(keysym)+ if keysym in _KEYPAD_TEXT:+ return _KEYPAD_TEXT[keysym]+ if keysym & 0xFF000000 == 0x01000000:+ return chr(keysym & 0x00FFFFFF)+ return None+++def character(keycode: int, mods: int, group: int, keymap) -> Optional[str]:+ """What a key with no fixed name sends (WIRE.md section 7): the character with Shift, Caps Lock+ and Num Lock applied as the layout applies them, or, while Ctrl, Alt or Super is held, the+ key's own unshifted character, so a chord arrives as a modifier and the plain key. A keypad+ key with Num Lock off is the key it moves by. None for a key that types nothing printable (a+ dead key). AltGr selects nothing here, as on Windows. `keymap` is an xkb_x11.Keymap."""+ if mods & CHORD_MASK:+ use = mods & NUM_LOCK_MASK+ else:+ use = mods & (SHIFT_MASK | LOCK_MASK | NUM_LOCK_MASK)+ keysym = keymap.keysym(keycode, use, group)+ named = KEYPAD_NAMES.get(keysym)+ if named is not None:+ return named+ text = keymap.text(keysym)+ return text if text and text.isprintable() else None+++# A button's logical number to the Windows messages the bridge reads. 4 to 7 are the wheel.+_BUTTONS = {+ 1: (WM_LBUTTONDOWN, WM_LBUTTONUP, 0),+ 2: (WM_MBUTTONDOWN, WM_MBUTTONUP, 0),+ 3: (WM_RBUTTONDOWN, WM_RBUTTONUP, 0),+ 8: (WM_XBUTTONDOWN, WM_XBUTTONUP, 1 << 16),+ 9: (WM_XBUTTONDOWN, WM_XBUTTONUP, 2 << 16),+}+_WHEEL = {4: (WM_MOUSEWHEEL, WHEEL_DELTA), 5: (WM_MOUSEWHEEL, -WHEEL_DELTA),+ 6: (WM_MOUSEHWHEEL, -WHEEL_DELTA), 7: (WM_MOUSEHWHEEL, WHEEL_DELTA)}+++def _wheel_data(units: int) -> int:+ return (max(-0x8000, min(0x7FFF, units)) & 0xFFFF) << 16+++def _at_or_after(sequence: int, serial: int) -> bool:+ """Sequence numbers are 16 bits and wrap: `sequence` is at or after `serial` when it is less+ than half the circle ahead of it."""+ return ((sequence - serial) & 0xFFFF) < 0x8000+++class Device:+ def __init__(self, deviceid: int, use: int, name: str, absolute: bool = False, scrolls=None) -> None:+ self.deviceid, self.use, self.name, self.absolute = deviceid, use, name, absolute+ # Valuator number to (vertical, increment) for a smooth-scrolling device.+ self.scrolls: Dict[int, Tuple[bool, float]] = scrolls or {}+++class _Connection:+ """The capture thread's own X connection, and an XKB view of the layout beside it: everything+ here speaks to the server, so what the hooks decide can be driven by a fake in tests. Events+ come out as plain tuples."""++ def __init__(self) -> None:+ from Xlib import X, display+ from Xlib.ext import xinput, xtest++ import xkb_x11++ self._X, self._xinput, self._xtest = X, xinput, xtest+ self.display = display.Display()+ try:+ if not self.display.has_extension("XInputExtension"):+ raise RuntimeError("This X server has no XInput extension")+ if not self.display.has_extension("XTEST"):+ raise RuntimeError("This X server has no XTEST extension")+ self._opcode = self.display.display.get_extension_major("XInputExtension")+ # python-xlib's xinput_query_version announces 2.0, and a 2.0 client is sent raw events+ # only while nothing is grabbed.+ reply = xinput.XIQueryVersion(display=self.display.display, opcode=self._opcode, major_version=2, minor_version=2)+ if (reply.major_version, reply.minor_version) < (2, 1):+ raise RuntimeError(f"This X server has XInput {reply.major_version}.{reply.minor_version}; Beamer needs 2.1")+ self.keymap = xkb_x11.Keymap(self.display.get_display_name())+ self.root = self.display.screen().root+ self.root.xinput_select_events([(XI_ALL_MASTER_DEVICES, RAW_MASK), (XI_ALL_DEVICES, 1 << XI_HIERARCHY_CHANGED)])+ # An invisible cursor for the pointer grab: a 1x1 pixmap with an empty mask.+ pixmap = self.root.create_pixmap(1, 1, 1)+ gc = pixmap.create_gc(foreground=0)+ pixmap.fill_rectangle(gc, 0, 0, 1, 1)+ self._cursor = pixmap.create_cursor(pixmap, (0, 0, 0), (0, 0, 0), 0, 0)+ gc.free()+ pixmap.free()+ self.display.sync()+ except Exception:+ self.display.close()+ raise++ def events(self, timeout: float) -> list:+ display = self.display+ if not display.pending_events():+ select.select([display.fileno()], [], [], timeout)+ found = []+ while len(found) < MAX_BATCH and display.pending_events():+ event = display.next_event()+ kind = event.type+ if kind == MAPPING_NOTIFY:+ display.refresh_keyboard_mapping(event)+ if event.request != MAPPING_POINTER:+ try:+ self.keymap.reload()+ except Exception:+ # A keymap changing as it is read: the old one serves until the next change.+ LOGGER.exception("The keyboard layout could not be read again; keeping the last one")+ found.append(("mapping", event.request))+ elif kind == GENERIC_EVENT and event.extension == self._opcode:+ found.extend(self._generic(event))+ return found++ def _generic(self, event) -> list:+ kind = event.evtype+ if XI_RAW_KEY_PRESS <= kind <= XI_RAW_MOTION:+ deviceid, detail, sourceid, flags, raw = parse_raw(event.data)+ return [("raw", kind, detail, sourceid, flags, raw, deviceid, event.sequence_number)]+ if kind in (XI_KEY_PRESS, XI_KEY_RELEASE):+ data = event.data+ return [("key", kind == XI_KEY_PRESS, data.detail, data.sourceid, data.flags,+ data.mods.effective_mods, data.groups.effective_group, data.deviceid, event.sequence_number)]+ if kind == XI_HIERARCHY_CHANGED:+ return [("hierarchy",)]+ return []++ def devices(self) -> List[Device]:+ xinput = self._xinput+ found = []+ for info in self.display.xinput_query_device(XI_ALL_DEVICES).devices:+ name = info.name.decode("utf-8", "replace") if isinstance(info.name, bytes) else str(info.name)+ absolute = False+ scrolls = {}+ for item in info.classes:+ kind = getattr(item, "type", None)+ if kind == xinput.ValuatorClass and item.number in (0, 1) and item.mode == XI_MODE_ABSOLUTE:+ absolute = True+ elif kind == xinput.ScrollClass and item.increment:+ scrolls[item.number] = (item.scroll_type == XI_SCROLL_VERTICAL, float(item.increment))+ found.append(Device(info.deviceid, info.use, name, absolute, scrolls))+ return found++ def grab(self, device: Device) -> Optional[int]:+ """The grab request's serial when it was granted, None when another client holds the device."""+ keyboard = device.use == XI_MASTER_KEYBOARD+ request = self._xinput.XIGrabDevice(+ display=self.display.display, opcode=self._opcode, deviceid=device.deviceid, grab_window=self.root,+ time=self._X.CurrentTime, cursor=self._X.NONE if keyboard else self._cursor,+ grab_mode=self._xinput.GrabModeAsync, paired_device_mode=self._xinput.GrabModeAsync, owner_events=False,+ mask=KEYBOARD_GRAB_MASK if keyboard else POINTER_GRAB_MASK,+ )+ return request._serial if request.status == 0 else None++ def ungrab(self, device: Device) -> int:+ request = self.display.xinput_ungrab_device(device.deviceid, self._X.CurrentTime)+ self.display.sync()+ return request._serial++ def fake_key(self, keycode: int, down: bool) -> None:+ self._xtest.fake_input(self.display, self._X.KeyPress if down else self._X.KeyRelease, keycode)+ self.display.sync()++ def fake_button(self, button: int, down: bool) -> None:+ self._xtest.fake_input(self.display, self._X.ButtonPress if down else self._X.ButtonRelease, button)+ self.display.sync()++ def pointer_mapping(self) -> List[int]:+ return list(self.display.get_pointer_mapping())++ def state(self) -> Tuple[int, int]:+ """(modifier bits, layout group) now. The core state carries the group in bits 13 and 14+ for any client, XKB-aware or not."""+ mask = self.root.query_pointer().mask+ return mask & 0xFF, (mask >> 13) & 3++ def abort(self) -> None:+ """From another thread: end the connection under the capture thread, which the server+ answers by releasing every grab it holds."""+ try:+ self.display.display.socket.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass++ def close(self) -> None:+ try:+ self.keymap.close()+ finally:+ self.display.close()+++class Hooks:+ """The listener, the grab and the thread that owns both, with capture_win.Hooks' callbacks:+ `on_key(name, down, vk, us)`, `on_mouse(message, x, y, mouse_data)` and `on_motion(dx, dy)`.+ `vk` is the evdev code. An answer of False to a key or button from inside a grab means it was+ this machine's, and it is played here."""++ def __init__(self, on_key, on_mouse, on_motion, connect: Optional[Callable[[], object]] = None) -> None:+ self._on_key = on_key+ self._on_mouse = on_mouse+ self._on_motion = on_motion+ self._connect = connect or _Connection+ self._connection = None+ self._thread: Optional[threading.Thread] = None+ self._ready = threading.Event()+ self._stopping = threading.Event()+ self._failure: Optional[BaseException] = None+ self._predicate: Optional[Callable[[], bool]] = None+ # The proof harness turns this off to read its own injection back.+ self.drop_injected = True+ self._masters: List[Device] = []+ self._xtest: set = set()+ self._absolute: set = set()+ self._scrolls: Dict[int, Dict[int, Tuple[bool, float]]] = {}+ self._buttons: List[int] = []+ self._grabbed: List[Device] = []+ self._taking = False+ # Per master device, the (first, after-last) request serials of its recent grabs; the+ # after-last is None while it is held.+ self._spans: Dict[int, collections.deque] = {}+ self._names_down: Dict[int, str] = {}+ # Keys and buttons this machine was given through XTest after a grab kept them from it,+ # held until their own release arrives, whichever way it comes.+ self._played_keys: set = set()+ self._played_buttons: set = set()+ # Called on the capture thread with the exception when capture stops on its own after it+ # started (the X server gone, the watchdog), so input can come home.+ self.on_failure: Optional[Callable[[BaseException], None]] = None+ self._refused_said = False+ self._carry = [0.0, 0.0]+ self._scroll_carry: Dict[Tuple[int, int], float] = {}+ self._beat = time.monotonic()++ def grab_while(self, predicate: Callable[[], bool]) -> None:+ """Hold every master device for as long as `predicate` is true: asked after every batch of+ events and at least every TICK_SECONDS. It runs on the capture thread, so it must be cheap+ and never block."""+ self._predicate = predicate++ @property+ def grabbed(self) -> bool:+ return bool(self._grabbed)++ def start(self) -> None:+ if self._thread is not None and self._thread.is_alive():+ if self._stopping.is_set():+ # A stop that timed out: a second thread would share this one's bookkeeping while+ # its connection may still hold the grab.+ raise RuntimeError("The last capture thread has not stopped yet")+ return+ self._ready.clear()+ self._stopping.clear()+ self._failure = None+ self._thread = threading.Thread(target=self._run, name="Beamer-hooks", daemon=True)+ self._thread.start()+ if not self._ready.wait(timeout=5.0):+ raise RuntimeError("The input hooks did not start within five seconds")+ if self._failure is not None:+ raise self._failure++ def stop(self) -> None:+ self._stopping.set()+ thread = self._thread+ if thread is None:+ return+ thread.join(timeout=2.0)+ if thread.is_alive():+ LOGGER.error("The capture thread did not stop within two seconds; closing its connection")+ connection = self._connection+ if connection is not None:+ connection.abort()+ thread.join(timeout=1.0)+ if not thread.is_alive():+ self._thread = None++ def _run(self) -> None:+ connection = None+ try:+ connection = self._connection = self._connect()+ self._read_devices()+ self._buttons = connection.pointer_mapping()+ self._beat = time.monotonic()+ threading.Thread(target=self._watch, args=(connection,), name="Beamer-hooks-watch", daemon=True).start()+ self._ready.set()+ while not self._stopping.is_set():+ self._beat = time.monotonic()+ for event in connection.events(TICK_SECONDS):+ self._beat = time.monotonic()+ try:+ self._handle(event)+ except Exception:+ LOGGER.exception("An input event could not be read; carrying on")+ self._beat = time.monotonic()+ self._tick()+ except Exception as exc:+ LOGGER.exception("Keyboard and mouse capture stopped")+ started = self._ready.is_set()+ self._failure = exc+ self._ready.set()+ if started and not self._stopping.is_set() and self.on_failure is not None:+ try:+ self.on_failure(exc)+ except Exception:+ LOGGER.exception("Could not report that capture stopped")+ finally:+ self._let_go()+ self._release_played()+ if connection is not None:+ try:+ connection.close()+ except Exception:+ LOGGER.exception("The capture connection did not close cleanly")+ self._connection = None+ self._stopping.set()++ def _watch(self, connection) -> None:+ """The safety net under a capture thread stuck in a callback or a round trip while it+ holds the grab: nothing else can let go of it, so its connection is ended."""+ while not self._stopping.wait(STALL_SECONDS / 8):+ holding = self._grabbed or self._taking+ if holding and time.monotonic() - self._beat > STALL_SECONDS:+ LOGGER.error("The capture thread has not answered for %s s while holding the keyboard and mouse; "+ "closing its connection to free them", STALL_SECONDS)+ connection.abort()+ return++ # The grab++ def _tick(self) -> None:+ want = False+ predicate = self._predicate+ if predicate is not None:+ try:+ want = bool(predicate())+ except Exception:+ LOGGER.exception("Could not tell whether input is away; letting go")+ if want and not self._grabbed:+ self._take()+ elif not want and self._grabbed:+ self._let_go()++ def _take(self) -> None:+ self._taking = True+ try:+ for device in self._masters:+ if not self._grab_one(device):+ # All or nothing: half a grab sends keys away while the pointer works here.+ # Another client's grab (an open menu) refuses ours; it is asked again next tick.+ if not self._refused_said:+ self._refused_said = True+ LOGGER.warning("Another app holds %s; trying again until it lets go", device.name)+ self._let_go()+ return+ self._refused_said = False+ finally:+ self._taking = False++ def _grab_one(self, device: Device) -> bool:+ self._beat = time.monotonic()+ try:+ serial = self._connection.grab(device)+ except Exception:+ LOGGER.exception("Grabbing %s failed", device.name)+ return False+ if serial is None:+ return False+ spans = self._spans.setdefault(device.deviceid, collections.deque(maxlen=8))+ spans.append([serial, None, None])+ self._grabbed.append(device)+ return True++ def _let_go_of(self, device: Device) -> None:+ self._beat = time.monotonic()+ try:+ serial = self._connection.ungrab(device)+ except Exception:+ LOGGER.exception("Letting go of %s failed", device.name)+ serial = None+ # Only now: the watchdog watches for as long as anything is held, the ungrab's round trip too.+ if device in self._grabbed:+ self._grabbed.remove(device)+ spans = self._spans.get(device.deviceid)+ if spans and spans[-1][1] is None:+ spans[-1][1] = serial+ spans[-1][2] = time.monotonic()++ def _let_go(self) -> None:+ for device in list(self._grabbed):+ self._let_go_of(device)++ def _inside(self, master: int, sequence: int) -> bool:+ """Whether an event from `master` stamped `sequence` was made while this client held it."""+ spans = self._spans.get(master)+ if not spans:+ return False+ now = time.monotonic()+ while spans and spans[0][2] is not None and now - spans[0][2] > SPAN_KEEP_SECONDS:+ spans.popleft()+ for first, after, _closed in spans:+ if _at_or_after(sequence, first) and (after is None or not _at_or_after(sequence, after)):+ return True+ return False++ def _play_key(self, keycode: int, down: bool) -> None:+ if down:+ self._played_keys.add(keycode)+ else:+ self._played_keys.discard(keycode)+ self._replay(XI_MASTER_KEYBOARD, lambda connection: connection.fake_key(keycode, down))++ def _play_button(self, button: int, down: bool) -> None:+ if down:+ self._played_buttons.add(button)+ else:+ self._played_buttons.discard(button)+ self._replay(XI_MASTER_POINTER, lambda connection: connection.fake_button(button, down))++ def _release_played(self) -> None:+ """XTest holds a played key until told otherwise, and the server would repeat it for ever."""+ for keycode in sorted(self._played_keys):+ self._play_key(keycode, False)+ for button in sorted(self._played_buttons):+ self._play_button(button, False)++ def _replay(self, device_use: int, play: Callable[[object], None]) -> None:+ """Play one event here that a grab kept from every app: the grab is let go around it, so+ XTest's copy reaches the focused window, then taken again, all of it or none."""+ held = next((device for device in self._grabbed if device.use == device_use), None)+ if held is not None:+ self._let_go_of(held)+ try:+ play(self._connection)+ except Exception:+ LOGGER.exception("Could not play an input on this machine")+ finally:+ if held is not None and not self._grab_one(held):+ self._let_go()++ # Events++ def _read_devices(self) -> None:+ devices = self._connection.devices()+ before = {device.deviceid for device in self._masters}+ self._masters = [device for device in devices if device.use in (XI_MASTER_POINTER, XI_MASTER_KEYBOARD)]+ self._xtest = {device.deviceid for device in devices if "XTEST" in device.name}+ self._absolute = {device.deviceid for device in devices if device.use == XI_SLAVE_POINTER and device.absolute}+ self._scrolls = {device.deviceid: device.scrolls for device in devices if device.scrolls}+ if self._grabbed and {device.deviceid for device in self._masters} != before:+ # A master added or gone: what is held is no longer every device; the next tick takes them all.+ self._let_go()++ def _handle(self, event: tuple) -> None:+ kind = event[0]+ if kind == "raw":+ _, evtype, detail, sourceid, flags, raw, master, sequence = event+ if self.drop_injected and sourceid in self._xtest:+ return+ if evtype in (XI_RAW_KEY_PRESS, XI_RAW_KEY_RELEASE):+ if not self._inside(master, sequence): # inside a grab, its key event says it+ self._key(detail, evtype == XI_RAW_KEY_PRESS, None, None, False)+ elif evtype in (XI_RAW_BUTTON_PRESS, XI_RAW_BUTTON_RELEASE):+ self._button(detail, evtype == XI_RAW_BUTTON_PRESS, flags, self._inside(master, sequence))+ elif evtype == XI_RAW_MOTION:+ self._motion(sourceid, raw)+ elif kind == "key":+ _, down, detail, sourceid, _flags, mods, group, _master, _sequence = event+ if self.drop_injected and sourceid in self._xtest:+ return+ self._key(detail, down, mods, group, True)+ elif kind == "hierarchy":+ self._read_devices()+ elif kind == "mapping" and event[1] == MAPPING_POINTER:+ self._buttons = self._connection.pointer_mapping()++ def _key(self, keycode: int, down: bool, mods: Optional[int], group: Optional[int], swallowed: bool) -> None:+ code = keycode - KEYCODE_OFFSET+ name = self._names_down.get(code) if down else self._names_down.pop(code, None)+ if name is None:+ name = VK_TO_NAME.get(code)+ if name is None:+ if mods is None:+ # Outside a grab an event carries no state: one round trip, for character keys only.+ mods, group = self._connection.state()+ name = character(keycode, mods, group, self._connection.keymap)+ if name is None:+ return+ if down:+ self._names_down[code] = name+ answer = self._on_key(name, down, code, keytable.EVDEV_US.get(code))+ if not down and keycode in self._played_keys:+ self._play_key(keycode, False) # its press was played here, whatever is answered now+ elif answer is False and swallowed:+ self._play_key(keycode, down)++ def _button(self, physical: int, down: bool, flags: int, swallowed: bool) -> None:+ buttons = self._buttons+ logical = buttons[physical - 1] if 0 < physical <= len(buttons) else physical+ wheel = _WHEEL.get(logical)+ if wheel is not None:+ if not down or flags & XI_POINTER_EMULATED:+ return # a smooth-scrolling device's wheel is its scroll valuators+ message, delta = wheel+ answer = self._on_mouse(message, 0, 0, _wheel_data(delta))+ if answer is False and swallowed:+ self._play_button(logical, True)+ self._play_button(logical, False)+ return+ fixed = _BUTTONS.get(logical)+ if fixed is not None:+ press, release, data = fixed+ answer = self._on_mouse(press if down else release, 0, 0, data)+ if not down and logical in self._played_buttons:+ self._play_button(logical, False)+ elif answer is False and swallowed:+ self._play_button(logical, down)++ def _motion(self, sourceid: int, raw: Dict[int, float]) -> None:+ scrolls = self._scrolls.get(sourceid)+ if scrolls:+ for number, value in raw.items():+ axis = scrolls.get(number)+ if axis is None:+ continue+ vertical, increment = axis+ key = (sourceid, number)+ # One increment is one notch, positive down and right; Windows' wheel is positive+ # up, its horizontal wheel positive right.+ carry = self._scroll_carry.get(key, 0.0) + (-value if vertical else value) / increment * WHEEL_DELTA+ whole = int(carry)+ self._scroll_carry[key] = carry - whole+ if whole:+ self._on_mouse(WM_MOUSEWHEEL if vertical else WM_MOUSEHWHEEL, 0, 0, _wheel_data(whole))+ if 0 not in raw and 1 not in raw:+ return+ self._on_mouse(WM_MOUSEMOVE, 0, 0, 0)+ if sourceid in self._absolute:+ return+ carry = self._carry+ carry[0] += raw.get(0, 0.0)+ carry[1] += raw.get(1, 0.0)+ dx, dy = int(carry[0]), int(carry[1])+ carry[0] -= dx+ carry[1] -= dy+ if dx or dy:+ self._on_motion(dx, dy)diff --git a/win_app/clipboard_portal.py b/win_app/clipboard_portal.pynew file mode 100644index 0000000..77572da--- /dev/null+++ b/win_app/clipboard_portal.py@@ -0,0 +1,146 @@+"""The clipboard on Wayland, through the portal Clipboard on inject_portal's RemoteDesktop session:+the same four functions as clipboard_x11.py.++A Wayland desktop gives the clipboard only to the focused app, so a background app reaches it+through the portal, which GNOME ties to a remote control session: the one the injector opens,+which the desktop asks about once. Without that session (refused, or a desktop with no portal)+the clipboard reads as empty and nothing is written, and the app says why (inject_portal).++Another app's copy is read from an fd the portal hands over, on the caller's thread, so a slow+app costs one clipboard sync and never the injector. Beamer's own copy is offered as text and PNG+and written to each app that pastes it (inject_portal's transfer). The portal says whether the+clipboard is Beamer's own, so its echo is never sent back."""++import logging+import os+import select+import time+from typing import Optional, Tuple++import inject_portal++LOGGER = logging.getLogger(__name__)++TEXT_MIMES = ("text/plain;charset=utf-8", "text/plain", "UTF8_STRING", "STRING", "TEXT")+PNG_MIME = "image/png"+TIMEOUT_SECONDS = 2.0+MAX_BYTES = 64 * 1024 * 1024++_synced: Optional[int] = None+++def _read_fd(fd: int, timeout: float = TIMEOUT_SECONDS) -> Optional[bytes]:+ """All an app writes into `fd` until it closes it, within `timeout`; None if it did not finish."""+ chunks = []+ size = 0+ deadline = time.monotonic() + timeout+ try:+ while True:+ left = deadline - time.monotonic()+ if left <= 0:+ LOGGER.warning("The app holding the clipboard did not hand it over in time")+ return None+ ready, _, _ = select.select([fd], [], [], left)+ if not ready:+ continue+ chunk = os.read(fd, 65536)+ if not chunk:+ return b"".join(chunks)+ size += len(chunk)+ if size > MAX_BYTES:+ LOGGER.warning("The clipboard is larger than Beamer sends; leaving it")+ return None+ chunks.append(chunk)+ finally:+ os.close(fd)+++def _read(mime: str) -> Optional[bytes]:+ fd = inject_portal.remote().ask(lambda session: session.open_selection(mime), discard=os.close)+ if fd is None:+ return None+ return _read_fd(fd)+++def _offered() -> Tuple[list, bool, int]:+ return inject_portal.remote().ask(lambda session: (list(session.offered), session.ours, session.changes),+ default=([], False, 0))+++def _contents(offered: list) -> Tuple[Optional[str], Optional[bytes]]:+ text = png = None+ mime = next((m for m in TEXT_MIMES if m in offered), None)+ if mime is not None:+ data = _read(mime)+ if data:+ text = data.decode("utf-8", "replace").replace("\r\n", "\n")+ if PNG_MIME in offered:+ png = _read(PNG_MIME) or None+ return text or None, png+++def get_contents() -> Tuple[Optional[str], Optional[bytes]]:+ """(text, png) another app has on the clipboard, either None when absent; both None when it+ is Beamer's own, or the clipboard cannot be reached. Never raises."""+ try:+ offered, ours, _changes = _offered()+ if ours:+ return None, None+ return _contents(offered)+ except Exception:+ LOGGER.exception("Could not read the clipboard")+ return None, None+++def changed_contents() -> Tuple[Optional[str], Optional[bytes]]:+ """get_contents(), or (None, None) when no other app has copied since the clipboard was last+ sent or written. Either way it counts as sent from here on."""+ global _synced+ try:+ offered, ours, changes = _offered()+ if ours or changes == _synced:+ return None, None+ text, png = _contents(offered)+ if text is not None or png is not None:+ _synced = changes+ return text, png+ except Exception:+ LOGGER.exception("Could not read the clipboard")+ return None, None+++def change_stamp() -> Optional[int]:+ """A number that moves whenever the clipboard changes, Beamer's own writes included, or None+ while the session is not up. Read without waiting: the sender asks under its lock."""+ session = inject_portal._remote+ if session is None or not session.ready.is_set():+ return None+ return session.stamp+++def forget_sync() -> None:+ global _synced+ _synced = None+++def set_contents(text: Optional[str], png: Optional[bytes]) -> bool:+ """Offer `text` and/or `png` as this machine's clipboard. False when there is nothing to set or+ the clipboard cannot be reached. Never raises."""+ global _synced+ offer = {}+ if text is not None:+ data = text.replace("\r\n", "\n").encode("utf-8")+ offer.update({"text/plain;charset=utf-8": data, "text/plain": data, "UTF8_STRING": data})+ if png is not None:+ offer[PNG_MIME] = png+ if not offer:+ return False+ try:+ written = bool(inject_portal.remote().ask(lambda session: session.set_selection(offer), default=False))+ except Exception:+ LOGGER.exception("Could not set the clipboard")+ return False+ if written:+ changes = inject_portal.remote().ask(lambda session: session.changes, default=None)+ _synced = changes+ return writtendiff --git a/win_app/clipboard_x11.py b/win_app/clipboard_x11.pynew file mode 100644index 0000000..56b41db--- /dev/null+++ b/win_app/clipboard_x11.py@@ -0,0 +1,216 @@+"""Linux X11 clipboard access through Qt's QClipboard, the same four functions as clipboard_win.py.++On X11 a clipboard is not a store but a promise: the owner keeps the data and answers other+apps' requests for it from its own event loop. QClipboard therefore must only be touched on the+GUI thread, which owns the selection; touched from elsewhere it reads stale data or never answers+a paste. Beamer's callers are the network receiver and sender threads, so every call here runs on+the GUI thread, directly when already on it and otherwise queued to it and waited on. The wait is+bounded: a wedged GUI thread costs one clipboard sync, never the link.++PNG crosses the wire as it lives on the clipboard, so the raw image/png data is handed on+untouched when the source offers it; only an image offered in another form is encoded.+"""++import logging+import threading+from typing import Optional, Tuple++from PySide6.QtCore import QBuffer, QIODevice, QMimeData, QObject, Qt, QThread, Signal+from PySide6.QtGui import QGuiApplication, QImage++LOGGER = logging.getLogger(__name__)++PNG_MIME = "image/png"+# Stamped on everything Beamer writes, with a token per write, so dataChanged can tell the echo of+# Beamer's own write from another app's copy.+OWN_FORMAT = "application/x-beamer-own"+TIMEOUT_SECONDS = 2.0++# Counts dataChanged signals. _synced_counter is its value when the clipboard was last sent to the+# other machine or written from it; None until then and after forget_sync. A switch sends the+# clipboard only when the counter has moved since, so an unchanged screenshot is not pushed across+# on every switch.+_change_counter = 0+_synced_counter = None+_own_token = 0+_connected_to = None++_runner = None+_runner_app = None+_runner_lock = threading.Lock()+++class _Job:+ def __init__(self, fn, args, default):+ self.fn = fn+ self.args = args+ self.result = default+ self.done = threading.Event()+ self.cancelled = False+++class _Runner(QObject):+ """Lives on the GUI thread; a queued signal is how a worker gets code run there."""++ run = Signal(object)++ def __init__(self):+ super().__init__()+ self.run.connect(self._execute, Qt.ConnectionType.QueuedConnection)++ def _execute(self, job):+ try:+ # A caller that timed out has been told False, so its write must not land late.+ if not job.cancelled:+ job.result = job.fn(*job.args)+ except Exception:+ LOGGER.exception("clipboard call failed on the GUI thread")+ finally:+ job.done.set()+++def _runner_for(app):+ global _runner, _runner_app+ with _runner_lock:+ if _runner is None or _runner_app is not app:+ runner = _Runner()+ runner.moveToThread(app.thread())+ _runner, _runner_app = runner, app+ return _runner+++def _on_gui(fn, *args, default):+ app = QGuiApplication.instance()+ if app is None:+ return default+ if QThread.currentThread() == app.thread():+ try:+ return fn(*args)+ except Exception:+ LOGGER.exception("clipboard call failed")+ return default+ job = _Job(fn, args, default)+ _runner_for(app).run.emit(job)+ if not job.done.wait(TIMEOUT_SECONDS):+ job.cancelled = True+ LOGGER.warning("the GUI thread did not answer a clipboard call within %s s; skipping it", TIMEOUT_SECONDS)+ return default+ return job.result+++def _owns(clipboard) -> bool:+ return clipboard.ownsClipboard()+++def _is_own_write(clipboard) -> bool:+ # Ownership first: asking a foreign owner for its formats is a blocking round trip to that app.+ if not _owns(clipboard):+ return False+ mime = clipboard.mimeData()+ return mime is not None and mime.hasFormat(OWN_FORMAT) and bytes(mime.data(OWN_FORMAT)) == str(_own_token).encode()+++def _on_data_changed() -> None:+ global _change_counter, _synced_counter+ was_synced = _synced_counter == _change_counter+ _change_counter += 1+ # dataChanged may be delivered during setMimeData or later from the event loop: _write covers+ # the first, this covers the second, carrying the marker forward only if nothing else changed.+ if was_synced and _is_own_write(QGuiApplication.clipboard()):+ _synced_counter = _change_counter+++def _connect() -> None:+ global _connected_to+ app = QGuiApplication.instance()+ if _connected_to is not app:+ QGuiApplication.clipboard().dataChanged.connect(_on_data_changed)+ _connected_to = app+++def _image_to_png(image: QImage) -> Optional[bytes]:+ buffer = QBuffer()+ buffer.open(QIODevice.OpenModeFlag.WriteOnly)+ if not image.save(buffer, "PNG"):+ return None+ return bytes(buffer.data())+++def _read() -> Tuple[Optional[str], Optional[bytes]]:+ _connect()+ clipboard = QGuiApplication.clipboard()+ mime = clipboard.mimeData()+ if mime is None:+ return None, None+ text = mime.text() if mime.hasText() else None+ png = None+ if mime.hasFormat(PNG_MIME):+ png = bytes(mime.data(PNG_MIME)) or None+ elif mime.hasImage():+ image = clipboard.image()+ if not image.isNull():+ png = _image_to_png(image)+ return text or None, png+++def _changed() -> Tuple[Optional[str], Optional[bytes]]:+ global _synced_counter+ _connect()+ counter = _change_counter+ if counter == _synced_counter:+ return None, None+ text, png = _read()+ # Only what was read counts as sent: a failed read must not hold this clipboard back.+ if text is not None or png is not None:+ _synced_counter = counter+ return text, png+++def _write(text: Optional[str], png: Optional[bytes]) -> bool:+ global _own_token, _synced_counter+ _connect()+ mime = QMimeData()+ if text is not None:+ # X11 text is LF; a Windows peer's CRLF would show as stray carriage returns.+ mime.setText(text.replace("\r\n", "\n"))+ if png is not None:+ mime.setData(PNG_MIME, png)+ _own_token += 1+ mime.setData(OWN_FORMAT, str(_own_token).encode())+ QGuiApplication.clipboard().setMimeData(mime)+ _synced_counter = _change_counter+ return True+++def get_contents() -> Tuple[Optional[str], Optional[bytes]]:+ """(text, png) from the X11 clipboard, either None when absent, both None if there is no Qt+ application or reading failed for any reason. Never raises."""+ return _on_gui(_read, default=(None, None))+++def changed_contents() -> Tuple[Optional[str], Optional[bytes]]:+ """get_contents(), or (None, None) when the clipboard has not changed since it was last sent+ to or written from the other machine. Either way the current contents count as sent from here+ on."""+ return _on_gui(_changed, default=(None, None))+++def forget_sync() -> None:+ """A new link: the other machine may have lost what it was sent, so the next switch sends again."""+ global _synced_counter+ _synced_counter = None+++def set_contents(text: Optional[str], png: Optional[bytes]) -> bool:+ """Replace the X11 clipboard with `text` and/or `png`. Returns True when at least one was set,+ False if there is no Qt application or the write failed. Never raises."""+ try:+ if png is not None and QImage.fromData(png, "PNG").isNull():+ LOGGER.warning("inbound clipboard image did not decode; setting the text only")+ png = None+ if text is None and png is None:+ return False+ except Exception:+ LOGGER.exception("failed to check an inbound clipboard image")+ return False+ return _on_gui(_write, text, png, default=False)diff --git a/win_app/desktop_portal.py b/win_app/desktop_portal.pynew file mode 100644index 0000000..05eade3--- /dev/null+++ b/win_app/desktop_portal.py@@ -0,0 +1,141 @@+"""Desktop geometry and the pointer on Wayland: the twin of desktop_x11.py, with the same functions.++Wayland tells no app where the pointer is, and lets none move it. Beamer knows it only where it+puts it or is told: the InputCapture portal says where the pointer met a barrier, and every move+Beamer plays for a peer through RemoteDesktop is an absolute position it chose. So this module+keeps the last position as the truth, and the capture and injection modules keep it current:++- capture_portal, while the desktop holds the pointer at a barrier, moves it along the barrier+ and lets go of it at `position()` when input comes home;+- inject_portal registers a mover, which places the pointer with libei's absolute pointer while+ a peer drives this machine (and while nothing is captured).++The displays are the portal's zones when the InputCapture session has them, else the regions of+the RemoteDesktop absolute pointer, else what Qt says, all in the desktop's logical pixels. If+someone moves this machine's own mouse while a peer drives it, the position here is stale until+the peer's next move puts it back: no portal reports the local pointer.++A full-screen app cannot be seen and no button can be asked after (button_down is False), so the+full-screen hold and the drag guard have nothing to go on here."""++import logging+import threading+from typing import Callable, List, Optional, Tuple++from core.return_edge import Rect++LOGGER = logging.getLogger(__name__)++_lock = threading.Lock()+_position: Optional[Tuple[int, int]] = None+_zones: List[Rect] = [] # the InputCapture session's+_regions: List[Rect] = [] # the RemoteDesktop absolute pointer's+_mover: Optional[Callable[[int, int], None]] = None+_captured = False+++def set_zones(zones: List[Rect]) -> None:+ global _zones+ with _lock:+ _zones = list(zones)+++def set_regions(regions: List[Rect]) -> None:+ global _regions+ with _lock:+ _regions = list(regions)+++def set_mover(mover: Optional[Callable[[int, int], None]]) -> None:+ """The injector's absolute move, or None when its session is gone."""+ global _mover+ with _lock:+ _mover = mover+++def set_captured(captured: bool) -> None:+ """Whether the InputCapture session holds the pointer: then nothing is moved for real, and the+ position is where the pointer is let go."""+ global _captured+ with _lock:+ _captured = captured+++def note_position(x: float, y: float) -> None:+ """Where the pointer is, as the desktop or Beamer's own last move says, held on a display."""+ global _position+ point = clamp_to(_displays(), x, y)+ with _lock:+ _position = point+++def position() -> Optional[Tuple[int, int]]:+ with _lock:+ return _position+++def clamp_to(displays: List[Rect], x: float, y: float) -> Tuple[int, int]:+ """The nearest point to (x, y) that is on a display: a barrier sits one pixel beyond the last+ one, and a staggered arrangement has gaps."""+ x, y = int(round(x)), int(round(y))+ if not displays:+ return x, y+ best = None+ for rect in displays:+ point = (min(max(x, rect.x), rect.right), min(max(y, rect.y), rect.bottom))+ distance = (point[0] - x) ** 2 + (point[1] - y) ** 2+ if best is None or distance < best[0]:+ best = (distance, point)+ return best[1]+++def _qt_screens() -> List[Rect]:+ try:+ from PySide6.QtGui import QGuiApplication++ if QGuiApplication.instance() is None:+ return []+ return [Rect(g.x(), g.y(), g.width(), g.height()) for g in (screen.geometry() for screen in QGuiApplication.screens())]+ except Exception:+ LOGGER.exception("Could not read the displays from Qt")+ return []+++def _displays() -> List[Rect]:+ with _lock:+ known = list(_zones or _regions)+ return known or _qt_screens()+++def monitors() -> List[Rect]:+ return _displays() or [Rect(0, 0, 1920, 1080)]+++def cursor_position() -> Tuple[int, int]:+ found = position()+ if found is not None:+ return found+ first = monitors()[0]+ return first.x + first.width // 2, first.y + first.height // 2+++def set_cursor_position(x: int, y: int) -> None:+ """The position the pointer is at from now: placed there by the injector while nothing is+ captured, else where the capture lets it go when input comes home."""+ note_position(x, y)+ with _lock:+ mover = None if _captured else _mover+ point = _position+ if mover is not None:+ try:+ mover(*point)+ except Exception:+ LOGGER.exception("Could not place the pointer")+++def button_down(name: str) -> bool:+ return False+++def full_screen_app() -> Optional[str]:+ return Nonediff --git a/win_app/desktop_x11.py b/win_app/desktop_x11.pynew file mode 100644index 0000000..b452f8f--- /dev/null+++ b/win_app/desktop_x11.py@@ -0,0 +1,130 @@+"""X11 pointer and monitor geometry, the Linux twin of desktop_win.++Monitors come from RandR 1.5 rather than Qt's screens: the sender asks from the capture thread,+where Qt's screen list is not safe to read, and RandR reports X root pixels, the pointer's own+space, which effect_overlay.logical_point already maps to Qt's. There is no work area here+because nothing reads one.++python-xlib is imported inside _connect, never at module import, so this module imports on the+Mac and on Windows, where the test suite loads every test module without it installed. One X+connection serves the module, opened on first use from $DISPLAY and guarded by one lock: the+capture and link threads call in alongside the GUI thread's full_screen_app, and a python-xlib+connection is not safe to share across threads."""++import threading+from contextlib import contextmanager+from types import SimpleNamespace+from typing import List, Optional, Tuple++from core.return_edge import Rect++_lock = threading.Lock()+_conn = None++# Core pointer-state mask bits; X has none for the back and forward buttons.+_BUTTON_MASKS = {"left": 1 << 8, "middle": 1 << 9, "right": 1 << 10}+# Xlib.X.AnyPropertyType, spelled out so the property reads need no import.+_ANY_PROPERTY_TYPE = 0+++def _connect():+ from Xlib import display, error++ opened = display.Display()+ return SimpleNamespace(+ display=opened,+ root=opened.screen().root,+ x_error=error.XError,+ closed=(error.ConnectionClosedError, OSError),+ )+++def _drop() -> None:+ global _conn+ dead, _conn = _conn, None+ try:+ dead.display.close()+ except Exception:+ pass+++def _reset() -> None:+ with _lock:+ if _conn is not None:+ _drop()+++@contextmanager+def _session():+ global _conn+ with _lock:+ if _conn is None:+ _conn = _connect()+ conn = _conn+ try:+ yield conn+ except conn.closed:+ # A dead socket never recovers, so the next call reconnects; this one reports it.+ _drop()+ raise+++def monitors() -> List[Rect]:+ with _session() as conn:+ try:+ if conn.display.has_extension("RANDR"):+ version = conn.display.xrandr_query_version()+ if (version.major_version, version.minor_version) >= (1, 5):+ found = [+ Rect(m.x, m.y, m.width_in_pixels, m.height_in_pixels)+ for m in conn.root.xrandr_get_monitors(is_active=True).monitors+ ]+ if found:+ return found+ except conn.x_error:+ pass+ geometry = conn.root.get_geometry()+ return [Rect(0, 0, geometry.width, geometry.height)]+++def cursor_position() -> Tuple[int, int]:+ with _session() as conn:+ pointer = conn.root.query_pointer()+ return pointer.root_x, pointer.root_y+++def set_cursor_position(x: int, y: int) -> None:+ """Called on every pointer move while input is away, so one warp and one flush, no round trip.+ XWarpPointer produces no XInput2 raw motion, which is what keeps the sender's pin from+ feeding itself back."""+ with _session() as conn:+ conn.root.warp_pointer(int(x), int(y))+ conn.display.flush()+++def button_down(name: str) -> bool:+ mask = _BUTTON_MASKS.get(name)+ if mask is None:+ return False+ with _session() as conn:+ return bool(conn.root.query_pointer().mask & mask)+++def full_screen_app() -> Optional[str]:+ """The name of the foreground app while it is full screen, else None. GUI thread, once a+ second, as the Mac checks."""+ with _session() as conn:+ display = conn.display+ try:+ active = conn.root.get_full_property(display.intern_atom("_NET_ACTIVE_WINDOW"), _ANY_PROPERTY_TYPE)+ if active is None or not len(active.value) or not active.value[0]:+ return None+ window = display.create_resource_object("window", active.value[0])+ state = window.get_full_property(display.intern_atom("_NET_WM_STATE"), _ANY_PROPERTY_TYPE)+ if state is None or display.intern_atom("_NET_WM_STATE_FULLSCREEN") not in state.value:+ return None+ wm_class = window.get_wm_class()+ except conn.x_error:+ # The window can vanish between the two reads.+ return None+ return (wm_class[1] if wm_class else "") or "An app"diff --git a/win_app/diagram.py b/win_app/diagram.pyindex 6ce0e80..1f9fecd 100644--- a/win_app/diagram.py+++ b/win_app/diagram.py@@ -17,8 +17,12 @@ SCREEN = (120.0, 75.0)GAP = 14.0PAD = 8.0CAP_ROW = 34.0+NOTE_ROW = 22.0LIT = 3.0CORNER = 16.0+# The marks of the machines the page is not showing: there, but not the ones being edited.+QUIET = "ink_3"+QUIET_ALPHA = 0.55def _colour(name: str, alpha: float = 1.0) -> QColor:@@ -27,77 +31,143 @@ def _colour(name: str, alpha: float = 1.0) -> QColor:return colour-def _marks(edge, methods, parts, corner, shortcut) -> dict:- """Each mark the diagram can draw, keyed (kind, detail), at 1 when the settings light it."""- methods = set(methods)- marks = {}- for side in pages_win.SIDE_ANGLE:- marks[("edge", side)] = 1.0 if "edge" in methods and side == edge else 0.0- marks[("track", side)] = 1.0 if "part" in methods and side == edge else 0.0- for part in pages_win.PART_SPANS:- marks[("part", side, part)] = 1.0 if "part" in methods and side == edge and part in parts else 0.0- for name in pages_win.CORNER_NAMES:- marks[("corner", name)] = 1.0 if "corner" in methods and name == corner else 0.0- marks[("cap",)] = 1.0 if shortcut else 0.0+def _lit(lead: float, level: float) -> QColor:+ """A mark on this PC's screen: the signal colour for the machine shown, quieter for the rest."""+ lead = max(0.0, min(1.0, lead))+ return _blend(QUIET, "signal", lead, level * (QUIET_ALPHA + (1.0 - QUIET_ALPHA) * lead))+++def _blend(quiet: str, strong: str, level: float, alpha: float = 1.0) -> QColor:+ """`quiet` at 0, `strong` at 1, so a machine chosen or left eases between the two."""+ one, two = QColor(theme.colour(quiet)), QColor(theme.colour(strong))+ level = max(0.0, min(1.0, level))+ mixed = QColor.fromRgbF(*(a + (b - a) * level for a, b in zip(one.getRgbF()[:3], two.getRgbF()[:3])))+ mixed.setAlphaF(max(0.0, min(1.0, alpha)))+ return mixed+++def _drawn_side(machine: dict, alone: bool) -> str:+ # One machine with no side is drawn on the right, as the one-machine page always drew it.+ return machine.get("side") or ("right" if alone else "")+++def _marks(machines, shortcut) -> dict:+ """Each mark the diagram can draw, keyed (kind, machine, detail), at 1 when the settings light it;+ ("lead", machine) at 1 lights its marks in the signal colour, ("named", machine) its name in ink."""+ alone = len(machines) == 1+ marks = {("cap",): 1.0 if shortcut else 0.0}+ for machine in machines:+ key, methods, edge = machine["key"], set(machine["methods"]), _drawn_side(machine, alone)+ for side in pages_win.SIDE_ANGLE:+ marks[("edge", key, side)] = 1.0 if "edge" in methods and side == edge else 0.0+ marks[("track", key, side)] = 1.0 if "part" in methods and side == edge else 0.0+ for part in pages_win.PART_SPANS:+ lit = "part" in methods and side == edge and part in machine["parts"]+ marks[("part", key, side, part)] = 1.0 if lit else 0.0+ for name in pages_win.CORNER_NAMES:+ marks[("corner", key, name)] = 1.0 if "corner" in methods and name == machine["corner"] else 0.0+ marks[("lead", key)] = 1.0 if machine["chosen"] or alone else 0.0+ marks[("named", key)] = 1.0 if machine["chosen"] and not alone else 0.0return marksclass ArrangementDiagram(QWidget):- """This PC's screen with the other machine's beside it on the chosen side, and on this PC's screen,- lit, whatever crosses; the shortcut as a key cap underneath."""+ """This PC's screen in the middle and each paired machine's beside the side it is on, two on one+ side sharing it; on this PC's screen, lit, whatever crosses to each, the chosen machine's in the+ signal colour and the rest quieter; the machines with no side named underneath; the shortcut as a+ key cap below that."""def __init__(self, parent: QWidget | None = None) -> None:super().__init__(parent)self.setAccessibleName("Arrangement")self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)self._state = None- self._angle = pages_win.SIDE_ANGLE["right"]- self._marks = _marks("right", (), (), "", False)+ self._machines: list = []+ # Where each machine's screen is drawn now, by key: [angle, start, end, shown], moving between states.+ self._places: dict = {}+ self._labels: dict = {}+ self._marks = _marks([], False)+ self._unplaced = ""self._cap_text = ""- self._other = OTHERself.setFixedHeight(self._height())- def set_other_name(self, name: str) -> None:- name = name or OTHER- if name != self._other:- self._other = name- self.update()-def sizeHint(self) -> QSize:return QSize(2 * round(SCREEN[0]) + round(GAP) + 2 * round(PAD), self._height())def minimumSizeHint(self) -> QSize:return QSize(2 * round(SCREEN[0]) + round(GAP), self._height())- def _height(self) -> int:- _pc, _mac, pair_h = pages_win.arrangement_rects(100.0, 0.0, self._angle, SCREEN, GAP)- return round(PAD + pair_h + PAD + CAP_ROW * self._marks[("cap",)])+ def _drawing(self, width: float):+ keys = [key for key, place in self._places.items() if place[3] > 0.001]+ placed = [tuple(self._places[key][:3]) for key in keys]+ pc, rects, height = pages_win.layout_rects(max(1.0, width - 2 * PAD), PAD, placed, SCREEN, GAP,+ centre_pc=len(self._machines) > 1)+ return (pc[0] + PAD, pc[1], pc[2], pc[3]), {key: (rect[0] + PAD, *rect[1:]) for key, rect in zip(keys, rects)}, height- def set_state(self, edge, methods, parts, corner, key_name, style) -> None:- state = (edge, tuple(methods), tuple(parts), corner, key_name, style)+ def _height(self) -> int:+ _pc, _rects, height = self._drawing(float(self.width() or 2 * SCREEN[0] + GAP + 2 * PAD))+ return round(PAD + height + PAD + (NOTE_ROW if self._unplaced else 0.0) + CAP_ROW * self._marks[("cap",)])++ def resizeEvent(self, event) -> None:+ super().resizeEvent(event)+ # A narrow page shrinks the drawing, and the widget's height follows it.+ height = self._height()+ if height != self.height():+ self.setFixedHeight(height)++ def set_machines(self, machines, key_name, style, shortcut) -> None:+ """Each machine a dict: `key`, `label` ("" for the placeholder of an unpaired PC), `side` (""+ when not placed), `methods`, `parts`, `corner` and `chosen`."""+ machines = [dict(machine, methods=list(machine["methods"]), parts=list(machine["parts"])) for machine in machines]+ state = (repr(machines), key_name, style, shortcut)if state == self._state:returnfirst = self._state is Noneself._state = state- shortcut = "shortcut" in methods+ self._machines = machines+ alone = len(machines) == 1+ self._labels = {machine["key"]: machine["label"] or OTHER for machine in machines}if shortcut:self._cap_text = pages_win.trigger_phrase(key_name, style)- self.setAccessibleDescription(pages_win.ways_summary(methods, edge, parts, corner, key_name, style))- targets = _marks(edge, methods, parts, corner, shortcut)+ self._unplaced = "" if alone else pages_win.unplaced_line(+ [machine["label"] for machine in machines if not machine.get("side")])+ self.setAccessibleDescription(pages_win.diagram_description(+ [dict(machine, label=self._labels[machine["key"]], side=_drawn_side(machine, alone)) for machine in machines],+ key_name, style, shortcut))+ targets = _marks(machines, shortcut)+ slots = pages_win.side_slots([dict(machine, side=_drawn_side(machine, alone)) for machine in machines])+ ends = {}+ for machine, slot in zip(machines, slots):+ held = self._places.get(machine["key"])+ if slot is None:+ ends[machine["key"]] = list(held[:3]) + [0.0] if held else [0.0, 0.0, 1.0, 0.0]+ continue+ side, start, end = slot+ # A machine already drawn goes round to its new side; one just placed fades in there.+ drawn = held is not None and held[3] > 0.0 and not first+ angle = pages_win.turn_to(held[0], side) if drawn else pages_win.SIDE_ANGLE[side]+ ends[machine["key"]] = [angle, start, end, 1.0]+ for key, held in self._places.items():+ # A machine removed or no longer placed fades where it was.+ ends.setdefault(key, list(held[:3]) + [0.0])+ starts = {}+ for key, end in ends.items():+ held = self._places.get(key)+ starts[key] = list(held) if held is not None and held[3] > 0.0 else end[:3] + [0.0]start_marks = dict(self._marks)- start_angle = self._angle- end_angle = pages_win.turn_to(start_angle, edge)- if first:- end_angle = pages_win.SIDE_ANGLE[edge]def apply(t):- self._angle = start_angle + (end_angle - start_angle) * t- self._marks = {key: start_marks[key] + (targets[key] - start_marks[key]) * t for key in targets}+ self._places = {key: [a + (b - a) * t for a, b in zip(starts[key], end)] for key, end in ends.items()}+ self._marks = {key: start_marks.get(key, 0.0) + (targets.get(key, 0.0) - start_marks.get(key, 0.0)) * t+ for key in set(targets) | set(start_marks)}self.setFixedHeight(self._height())self.update()def settle():- self._angle = end_angle % 360.0+ self._places = {key: [end[0] % 360.0, end[1], end[2], end[3]] for key, end in ends.items() if end[3] > 0.0+ or key in self._labels}+ self._marks = {key: level for key, level in targets.items()}+ self.setFixedHeight(self._height())self.update()if first:@@ -109,39 +179,62 @@ class ArrangementDiagram(QWidget):def paintEvent(self, _event) -> None:painter = QPainter(self)painter.setRenderHint(QPainter.RenderHint.Antialiasing)- pc, mac, pair_h = pages_win.arrangement_rects(self.width(), PAD, self._angle, SCREEN, GAP)+ pc, rects, height = self._drawing(float(self.width()))radius = tokens.RADIUS["field"]- self._screen(painter, QRectF(*mac), self._other, "panel", "edge", "ink_3", radius)- self._screen(painter, QRectF(*pc), "This PC", "well", "edge", "ink_2", radius)- for key, level in self._marks.items():- if level <= 0.001:+ for key, rect in rects.items():+ painter.setOpacity(self._places[key][3])+ named = self._marks.get(("named", key), 0.0)+ self._screen(painter, QRectF(*rect), self._labels.get(key, OTHER), "panel", _blend("edge", "ink_3", named),+ _blend("ink_3", "ink", named), radius)+ painter.setOpacity(1.0)+ self._screen(painter, QRectF(*pc), "This PC", "well", _colour("edge"), _colour("ink_2"), radius)+ # The machines not shown first, so the chosen one's marks lie over theirs where they meet.+ for key, level in sorted(self._marks.items(), key=lambda item: self._marks.get(("lead", item[0][1]), 0.0)+ if len(item[0]) > 1 else 0.0):+ if level <= 0.001 or key[0] in ("cap", "lead", "named"):continue- kind = key[0]+ kind, lead = key[0], self._marks.get(("lead", key[1]), 0.0)if kind == "edge":- self._segment(painter, pc, key[1], 0.0, 1.0, level, "signal", LIT)+ self._segment(painter, pc, key[2], 0.0, 1.0, level, lead, LIT)elif kind == "track":- self._track(painter, pc, key[1], level)+ self._track(painter, pc, key[2], level)elif kind == "part":- start, end = pages_win.PART_SPANS[key[2]]- self._segment(painter, pc, key[1], start, end, level, "signal", LIT, gap=2.0)+ start, end = pages_win.PART_SPANS[key[3]]+ self._segment(painter, pc, key[2], start, end, level, lead, LIT, gap=2.0)elif kind == "corner":- self._corner(painter, pc, key[1], level)+ self._corner(painter, pc, key[2], level, lead)+ top = PAD + height + PAD+ if self._unplaced:+ painter.setPen(_colour("ink_3"))+ painter.setFont(theme.font(tokens.TYPE["note"]))+ line = QRectF(PAD, top, self.width() - 2 * PAD, NOTE_ROW)+ painter.drawText(line, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop,+ painter.fontMetrics().elidedText(self._unplaced, Qt.TextElideMode.ElideRight, int(line.width())))+ top += NOTE_ROWlevel = self._marks[("cap",)]if level > 0.001 and self._cap_text:- self._cap(painter, PAD + pair_h + PAD, level)+ self._cap(painter, top, level)painter.end()- def _screen(self, painter, rect: QRectF, name, fill, line, ink, radius) -> None:- painter.setPen(QPen(_colour(line), 1.0))+ def _screen(self, painter, rect: QRectF, name, fill, line: QColor, ink: QColor, radius) -> None:+ painter.setPen(QPen(line, 1.0))painter.setBrush(_colour(fill))painter.drawRoundedRect(rect.adjusted(0.5, 0.5, -0.5, -0.5), radius, radius)- painter.setPen(_colour(ink))+ painter.setPen(ink)painter.setFont(theme.font(tokens.TYPE["small"], 600))- name = painter.fontMetrics().elidedText(name, Qt.TextElideMode.ElideRight, int(rect.width()) - 8)- painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, name)+ metrics = painter.fontMetrics()+ room = rect.adjusted(4, 2, -4, -2)+ wrapped = Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWordWrap+ needed = metrics.boundingRect(room.toRect(), wrapped, name)+ if metrics.horizontalAdvance(name) > room.width() and needed.width() <= room.width() and needed.height() <= room.height():+ # A screen sharing its side is half as wide: a two-word name goes onto two lines there.+ painter.drawText(room, wrapped, name)+ return+ painter.drawText(rect, Qt.AlignmentFlag.AlignCenter,+ metrics.elidedText(name, Qt.TextElideMode.ElideRight, int(rect.width()) - 8))@staticmethod- def _segment(painter, rect, side, start, end, level, colour, width, gap=0.0) -> None:+ def _segment(painter, rect, side, start, end, level, lead, width, gap=0.0) -> None:# Grows from its middle as it comes in.middle = (start + end) / 2.0half = (end - start) / 2.0 * level@@ -151,14 +244,18 @@ class ArrangementDiagram(QWidget):y1, y2 = y1 + gap, y2 - gapelse:x1, x2 = x1 + gap, x2 - gap- pen = QPen(_colour(colour, level), width)+ pen = QPen(_lit(lead, level), width)pen.setCapStyle(Qt.PenCapStyle.RoundCap)painter.setPen(pen)painter.drawLine(QPointF(x1, y1), QPointF(x2, y2))def _track(self, painter, rect, side, level) -> None:"""Part of the edge: the whole side as a dim track, with a divider between the thirds."""- self._segment(painter, rect, side, 0.0, 1.0, level, "off", LIT)+ pen = QPen(_colour("off", level), LIT)+ pen.setCapStyle(Qt.PenCapStyle.RoundCap)+ painter.setPen(pen)+ x1, y1, x2, y2 = pages_win.side_segment(rect, side, 0.5 - 0.5 * level, 0.5 + 0.5 * level, inset=LIT / 2.0 + 1.0)+ painter.drawLine(QPointF(x1, y1), QPointF(x2, y2))pen = QPen(_colour("edge", level), 1.0)painter.setPen(pen)for fraction in (1.0 / 3.0, 2.0 / 3.0):@@ -169,12 +266,12 @@ class ArrangementDiagram(QWidget):painter.drawLine(QPointF(x1, y1 - 5), QPointF(x1, y1 + 5))@staticmethod- def _corner(painter, rect, corner, level) -> None:+ def _corner(painter, rect, corner, level, lead) -> None:size = CORNER * (0.4 + 0.6 * level)x, y, w, h = pages_win.corner_box(rect, corner, size)box = QRectF(x, y, w, h).adjusted(2, 2, -2, -2)- painter.setPen(QPen(_colour("signal", level), 1.5))- painter.setBrush(_colour("signal", 0.35 * level))+ painter.setPen(QPen(_lit(lead, level), 1.5))+ painter.setBrush(_lit(lead, 0.35 * level))painter.drawRoundedRect(box, 2, 2)def _cap(self, painter, top, level) -> None:diff --git a/win_app/inject_portal.py b/win_app/inject_portal.pynew file mode 100644index 0000000..6448f9a--- /dev/null+++ b/win_app/inject_portal.py@@ -0,0 +1,757 @@+"""Keyboard and mouse injection on Wayland, through the RemoteDesktop portal and libei: the twin of+inject_x11.py, with the same functions, so the receiver drives it unchanged. The portal clipboard+rides on the same session (clipboard_portal), since GNOME offers its clipboard to a background app+only there.++One thread owns the session: its D-Bus connection, the libei sender and the clipboard's transfers.+The functions here hand it work and return; only a clipboard read waits for an answer. The session+starts when start() is called (the app does so when it can be driven or shares a clipboard) or at+the first event, and the desktop asks the user once: the answer is remembered with a restore+token (persist_mode 2), kept in the state directory, so later starts ask nothing.++Keys are pressed by evdev code on the keyboard the desktop gives, whose layout it hands over with+the device and whose locks and group it reports as they change. A character is typed as on X11+(inject_x11.plan_key: the layout's own key, Shift worked around it, the US place under a chord),+with two differences. The desktop's keymap cannot be changed, so a character the layout has no key+for is not typed (logged once). And a held key is repeated by the app it reaches, not the server,+so a key typed with Shift changed around it is let go at once and each of the peer's repeats types+it again.++The pointer is moved with libei's absolute pointer where the desktop offers one (GNOME does), at+a position Beamer keeps in desktop_portal, since no Wayland app can ask where the pointer is."""++import logging+import os+import queue+import select+import threading+import time+from typing import Callable, Dict, List, Optional, Set, Tuple++import desktop_portal+import portal+from capture_x11 import KEYCODE_OFFSET, LOCK_MASK, NUM_LOCK_MASK+from core.return_edge import Rect+from inject_x11 import (+ MAP,+ NO_REPEAT,+ PRESS,+ RELEASE,+ REPEAT,+ KeyState,+ Layout,+ plan_key,+ plan_text,+)++LOGGER = logging.getLogger(__name__)++INTERFACE = "org.freedesktop.portal.RemoteDesktop"+CLIPBOARD = "org.freedesktop.portal.Clipboard"+DEVICE_KEYBOARD, DEVICE_POINTER = 1, 2+TICK_SECONDS = 0.1+CALL_SECONDS = 2.0+# How long the portal has to answer a request no user sees.+REQUEST_SECONDS = 10.0+# After a session ends (not a refusal), the next one is opened no sooner than this.+RETRY_SECONDS = 5.0+# How long the desktop has, once connected, to offer the devices input waits for.+DEVICE_SECONDS = 2.0+# Input waiting for the session beyond this is dropped, not queued without end.+MAX_PENDING = 512+# How long an app pasting Beamer's clipboard has to take it.+WRITE_SECONDS = 5.0+# libei's capabilities (libei.py), here so this module imports without libei.+CAP_POINTER, CAP_POINTER_ABSOLUTE, CAP_KEYBOARD, CAP_SCROLL, CAP_BUTTON = 1, 2, 4, 16, 32++# evdev button codes.+BUTTONS = {"left": 0x110, "right": 0x111, "middle": 0x112, "back": 0x113, "forward": 0x114}+# A wheel click as libei counts it, and the pixels the PC reckons a click scrolls (inject_x11).+DISCRETE_PER_CLICK = 120+PIXELS_PER_CLICK = 40.0++NO_PORTAL = ("This desktop does not let apps control the keyboard and mouse (it has no RemoteDesktop "+ "portal with libei), so another machine cannot drive this one and the clipboard is not shared.")+REFUSED = ("Beamer was not allowed to control this machine, so another machine cannot drive it and the "+ "clipboard is not shared. Restart Beamer to be asked again.")+ENDED = "The desktop stopped letting Beamer control this machine: {detail}"+CLOSED = ("Remote control was stopped from the desktop, so another machine cannot drive this one and the "+ "clipboard is not shared until Beamer restarts.")+MISSING = "Beamer cannot control this machine: {detail}"++# Called with one of the sentences above when the session cannot start or ends; set by the app.+on_problem: Optional[Callable[[str], None]] = None+++class WaylandLayout(Layout):+ """inject_x11's Layout over the desktop's keymap, which cannot be changed: no spare keys."""++ def spare(self) -> List[int]:+ return []+++def wayland_steps(steps: list) -> List[Tuple[int, bool]]:+ """plan_key's or plan_text's steps as (evdev code, down). A key after NO_REPEAT is let go as soon+ as it is pressed; REPEAT, the X server's, means nothing here, and MAP cannot be planned with no+ spare keys."""+ out: List[Tuple[int, bool]] = []+ quick: Set[int] = set()+ for step in steps:+ kind, keycode = step[0], step[1]+ if kind == NO_REPEAT:+ quick.add(keycode)+ elif kind == PRESS:+ out.append((keycode - KEYCODE_OFFSET, True))+ if keycode in quick:+ out.append((keycode - KEYCODE_OFFSET, False))+ elif kind == RELEASE:+ out.append((keycode - KEYCODE_OFFSET, False))+ elif kind not in (REPEAT, MAP):+ LOGGER.warning("Unknown key step %r", step)+ return out+++def scroll_steps(dy: float, dx: float, mode: str, carry: List[float]) -> Tuple[str, float, float]:+ """One scroll message as libei's: ("discrete", x, y) in 120ths of a click for the wheel's lines,+ the fraction carried in `carry` ([y, x]); ("pixels", x, y) for a pixel scroll. The wire's y is+ positive away from the hand, libei's positive down."""+ if mode == "pixel":+ return "pixels", float(dx), -float(dy)+ carry[0] += float(dy) * DISCRETE_PER_CLICK+ carry[1] += float(dx) * DISCRETE_PER_CLICK+ whole_y, whole_x = int(carry[0]), int(carry[1])+ carry[0] -= whole_y+ carry[1] -= whole_x+ return "discrete", whole_x, -whole_y+++def _keymap_from_text(text: str):+ import xkb_x11++ return xkb_x11.Keymap.from_text(text)+++def _ei_sender(fd: int):+ import libei++ return libei.Context(fd, sender=True)+++def _libei_present() -> None:+ import libei++ libei._load()+++# Checked before the session is asked for, so the desktop never asks for something Beamer cannot use.+_ei_sender.preflight = _libei_present+++class Remote:+ """The RemoteDesktop session's thread. `submit(fn)` runs fn(self) there once the desktop's+ devices are up; `ask(fn)` runs it there at once and returns its answer.++ A refusal, or a desktop with no portal for it, stands until Beamer restarts, and no work is+ queued meanwhile. A session that ends any other way opens again at the next input, after+ RETRY_SECONDS, without asking: its restore token says the user already said yes."""++ def __init__(self, connect: Callable[[], object] = None, ei: Callable[[int], object] = None, tokens=None,+ keymap: Callable[[str], object] = None) -> None:+ self._connect = connect or portal.JeepneyBus+ self._ei_factory = ei or _ei_sender+ self._keymap = keymap or _keymap_from_text+ self._tokens = tokens or portal.TokenStore("remote-desktop")+ self._commands: "queue.Queue" = queue.Queue()+ self._wake_read, self._wake_write = os.pipe()+ os.set_blocking(self._wake_read, False)+ os.set_blocking(self._wake_write, False)+ self._thread: Optional[threading.Thread] = None+ self._stopping = threading.Event()+ self._lock = threading.Lock()+ self.ready = threading.Event()+ self.problem: Optional[str] = None+ self._terminal = False # refused or impossible: never asked again this run+ self._closed = False # stopped for good (Beamer quitting)+ self._retry_at = 0.0+ self._said_full = False+ self._generation = 0+ self.stamp = 0 # never reset, so a new session cannot repeat a stamp a caller holds+ self._reset()++ def _reset(self) -> None:+ self.portal = None+ self.ei = None+ self.handle = None+ self.clipboard_enabled = False+ self._devices: List[object] = [] # resumed, in the order they came+ self._added: List[object] = []+ self._sequence = 0+ self._eis_at: Optional[float] = None+ self._held: List[Callable] = [] # input waiting for the devices to resume+ self.layout: Optional[WaylandLayout] = None+ self.group = 0+ self.locks = 0+ self.state = KeyState()+ self.pressed: Set[int] = set()+ self.buttons: Dict[int, object] = {}+ self.scroll_carry = [0.0, 0.0]+ # The clipboard: what another app offers, what Beamer offers, and a count of other apps'+ # copies. `stamp` moves at every change, Beamer's own writes included (clipboard_portal).+ self.offered: List[str] = []+ self.ours = False+ self.changes = 0+ self.offer: Dict[str, bytes] = {}++ # -- from any thread ---------------------------------------------------------++ def _admits(self) -> bool:+ return not (self._closed or self._terminal)++ def start(self) -> None:+ with self._lock:+ if not self._admits():+ return+ if self._thread is not None and self._thread.is_alive():+ return+ if time.monotonic() < self._retry_at:+ return+ self._stopping.clear()+ self.ready.clear()+ self._thread = threading.Thread(target=self._run, name="Beamer-remote", daemon=True)+ self._thread.start()++ def stop(self) -> None:+ """For good: nothing after it opens the session again."""+ with self._lock:+ self._closed = True+ self._stopping.set()+ self._wake()+ thread = self._thread+ if thread is not None:+ thread.join(timeout=2.0)+ session = self.portal+ if thread.is_alive() and session is not None:+ abort = getattr(session.bus, "abort", None)+ if abort is not None:+ abort()++ def submit(self, work: Callable[["Remote"], None], release: bool = False) -> None:+ """`release` work (a key or button let go) is never dropped for a full queue: dropping it+ would leave the press held on this machine."""+ if not self._admits():+ return+ self.start()+ if self._commands.qsize() >= MAX_PENDING and not release:+ if not self._said_full:+ self._said_full = True+ LOGGER.warning("Remote control is not keeping up; input from the peer is dropped until it does")+ return+ self._said_full = False+ thread = self._thread+ if thread is None or not thread.is_alive():+ return # between sessions: input that late would play stale+ self._commands.put((work, None, None))+ self._wake()++ def ask(self, work: Callable[["Remote"], object], default=None, timeout: float = CALL_SECONDS,+ discard: Optional[Callable[[object], None]] = None):+ """Run `work` on the session's thread and return what it answers, or `default` when the+ session is not up or does not answer in time; an answer that comes after that is handed+ to `discard` (an fd is closed, say)."""+ if not self._admits():+ return default+ self.start()+ if not self.ready.wait(timeout):+ return default+ answer = _Answer(discard)+ self._commands.put((work, answer, None))+ self._wake()+ return answer.wait(timeout, default)++ def _wake(self) -> None:+ try:+ os.write(self._wake_write, b"x")+ except (BlockingIOError, OSError):+ pass++ # -- the thread --------------------------------------------------------------++ def _run(self) -> None:+ ended = False+ try:+ preflight = getattr(self._ei_factory, "preflight", None)+ try:+ if preflight is not None:+ preflight()+ bus = self._connect()+ except Exception as exc:+ # Missing libei or jeepney, or no session bus: no retry would find them.+ raise _Problem(MISSING.format(detail=exc), terminal=True) from exc+ self.portal = portal.Portal(bus, self._stopping.is_set)+ self._open()+ while not self._stopping.is_set():+ self._wait()+ for path, interface, member, body in self.portal.signals():+ self._signal(path, interface, member, body)+ for event in self.ei.events():+ self._ei_event(event)+ self._run_commands()+ except _Problem as problem:+ ended = not problem.terminal+ self._terminal = problem.terminal+ self._report(problem.sentence)+ except Exception as exc:+ if not self._stopping.is_set():+ LOGGER.exception("Remote control stopped")+ ended = True+ self._report(ENDED.format(detail=exc))+ finally:+ if ended:+ if self._tokens.read():+ self._retry_at = time.monotonic() + RETRY_SECONDS+ else:+ # Opened again it would ask again, prompted by the peer's input: it waits for a restart.+ self._terminal = True+ self._end()++ def _report(self, sentence: str) -> None:+ if sentence == self.problem:+ return # said already, and no session has opened since+ self.problem = sentence+ LOGGER.warning("%s", sentence)+ if on_problem is not None:+ try:+ on_problem(sentence)+ except Exception:+ LOGGER.exception("Could not report a remote control problem")++ def _open(self) -> None:+ portal_ = self.portal+ if portal_.version(INTERFACE) < 2:+ raise _Problem(NO_PORTAL, terminal=True)+ created = portal_.request(INTERFACE, "CreateSession", "a{sv}", lambda token: (+ {"handle_token": ("s", token), "session_handle_token": ("s", portal_.token())},), timeout=REQUEST_SECONDS)+ self.handle = created["session_handle"]+ options = {"types": ("u", DEVICE_KEYBOARD | DEVICE_POINTER), "persist_mode": ("u", 2)}+ token = self._tokens.read()+ if token:+ options["restore_token"] = ("s", token)+ portal_.request(INTERFACE, "SelectDevices", "oa{sv}", lambda handle_token: (+ self.handle, dict(options, handle_token=("s", handle_token))), timeout=REQUEST_SECONDS)+ if portal_.version(CLIPBOARD) >= 1:+ try:+ portal_.call(CLIPBOARD, "RequestClipboard", "oa{sv}", (self.handle, {}))+ except portal.PortalError:+ LOGGER.info("The desktop offers no clipboard with remote control")+ try:+ started = portal_.request(INTERFACE, "Start", "osa{sv}", lambda handle_token: (+ self.handle, "", {"handle_token": ("s", handle_token)}))+ except portal.Refused:+ self._tokens.write("")+ raise _Problem(REFUSED, terminal=True) from None+ self._tokens.write(started.get("restore_token", ""))+ self.clipboard_enabled = bool(started.get("clipboard_enabled"))+ fd = portal_.call(INTERFACE, "ConnectToEIS", "oa{sv}", (self.handle, {}))[0]+ try:+ self.ei = self._ei_factory(fd)+ except Exception:+ os.close(fd)+ raise+ self._generation += 1+ self._eis_at = time.monotonic()+ self.problem = None+ self.ready.set()+ desktop_portal.set_mover(lambda x, y: self.submit(lambda remote: remote.place(x, y)))++ def _wait(self) -> None:+ if self.portal.pending() or (not self._commands.empty() and self._input_ready()):+ return+ try:+ ready, _, _ = select.select([self.portal.fileno(), self.ei.fileno(), self._wake_read], [], [], TICK_SECONDS)+ except (OSError, ValueError) as exc:+ raise _Problem(ENDED.format(detail=exc)) from exc+ if self._wake_read in ready:+ try:+ while os.read(self._wake_read, 256):+ pass+ except BlockingIOError:+ pass++ def _input_ready(self) -> bool:+ """Whether input can be played: a keyboard and a pointer are up, or the desktop has had+ DEVICE_SECONDS to offer them and what is up is all there will be."""+ if self._with(CAP_KEYBOARD) is not None and (self._with(CAP_POINTER_ABSOLUTE) or self._with(CAP_POINTER)):+ return True+ return self._eis_at is not None and time.monotonic() - self._eis_at >= DEVICE_SECONDS++ def _run_commands(self) -> None:+ while True:+ try:+ work, answer, _ = self._commands.get_nowait()+ except queue.Empty:+ break+ if answer is None:+ self._held.append(work)+ continue+ try:+ answer.give(True, work(self))+ except Exception:+ LOGGER.exception("Could not answer a clipboard request")+ answer.give(False, None)+ if not self._held or not self._input_ready():+ return+ held, self._held = self._held, []+ for work in held:+ try:+ work(self)+ except Exception:+ LOGGER.exception("Could not play an input from the peer")++ def _end(self) -> None:+ desktop_portal.set_mover(None)+ self.ready.clear()+ try:+ if self.ei is not None:+ self.release_held()+ except Exception:+ LOGGER.exception("Could not let go of what was held for the peer")+ try:+ if self.ei is not None:+ self.ei.close()+ finally:+ if self.portal is not None:+ self.portal.close()+ self._reset()+ # Work still queued answers nothing; the next start begins clean.+ while True:+ try:+ _work, answer, _ = self._commands.get_nowait()+ except queue.Empty:+ break+ if answer is not None:+ answer.give(False, None)++ # -- signals and devices -----------------------------------------------------++ def _signal(self, path, interface, member, body) -> None:+ if interface == portal.SESSION and member == "Closed" and path == self.handle:+ # The user stopped it from the desktop's indicator: it is not opened again behind them.+ raise _Problem(CLOSED, terminal=True)+ if interface != CLIPBOARD or not body or body[0] != self.handle:+ return+ if member == "SelectionOwnerChanged":+ options = body[1] if len(body) > 1 else {}+ self.ours = bool(options.get("session_is_owner"))+ if not self.ours:+ self.offered = list(options.get("mime_types", []))+ self.changes += 1+ self.stamp += 1+ elif member == "SelectionTransfer":+ try:+ self._transfer(body[1], body[2])+ except portal.PortalError:+ # One paste lost; the session and the clipboard carry on.+ LOGGER.exception("Could not hand the clipboard to the app pasting it")+ self._write_done(body[2], False)++ def _write_done(self, serial: int, ok: bool) -> None:+ try:+ self.portal.call(CLIPBOARD, "SelectionWriteDone", "oub", (self.handle, serial, ok))+ except portal.PortalError:+ LOGGER.exception("Could not tell the desktop a paste has finished")++ def _ei_event(self, event: tuple) -> None:+ kind = event[0]+ if kind == "device_added":+ self._add(event[1])+ elif kind == "device_removed":+ device = event[1]+ for listed in (self._devices, self._added):+ if device in listed:+ listed.remove(device)+ # Buttons it held went with it: the desktop lets go of a removed device's input.+ self.buttons = {code: held for code, held in self.buttons.items() if held is not device}+ elif kind == "device_resumed":+ device = event[1]+ if device not in self._devices:+ self._devices.append(device)+ self._sequence += 1+ self.ei.start(device, self._sequence)+ elif kind == "device_paused":+ if event[1] in self._devices:+ self._devices.remove(event[1])+ elif kind == "modifiers" and self.layout is not None:+ _device, _depressed, _latched, locked, group = event[1:6]+ self.group = group+ self.locks = self.layout.keymap.core_mods(locked) & (LOCK_MASK | NUM_LOCK_MASK)+ elif kind == "disconnect":+ raise _Problem(ENDED.format(detail="its input connection closed"))++ def _add(self, device) -> None:+ self._added.append(device)+ if device.has(CAP_POINTER_ABSOLUTE):+ regions = [Rect(x, y, width, height) for x, y, width, height, _scale in device.regions()]+ if regions:+ desktop_portal.set_regions(regions)+ if device.has(CAP_KEYBOARD) and self.layout is None:+ try:+ text = device.keymap()+ if text:+ self.layout = WaylandLayout(self._keymap(text))+ except Exception:+ LOGGER.exception("Could not read this desktop's keyboard layout; characters cannot be typed")++ def _with(self, cap: int):+ """The first resumed device with `cap`, or None."""+ return next((device for device in self._devices if device.has(cap)), None)++ # -- playing input, on the thread ---------------------------------------------++ def keys(self, presses: List[Tuple[int, bool]]) -> None:+ device = self._with(CAP_KEYBOARD)+ if device is None:+ return+ for code, down in presses:+ if down:+ self.pressed.add(code)+ elif code in self.pressed:+ self.pressed.discard(code)+ else:+ continue+ self.ei.key(device, code, down)+ self.ei.frame(device)++ def move_by(self, dx: float, dy: float) -> None:+ x, y = desktop_portal.cursor_position()+ if self._with(CAP_POINTER_ABSOLUTE) is not None:+ self.place(x + dx, y + dy)+ return+ device = self._with(CAP_POINTER)+ if device is not None:+ self.ei.motion(device, dx, dy)+ self.ei.frame(device)+ desktop_portal.note_position(x + dx, y + dy)++ def place(self, x: float, y: float) -> None:+ desktop_portal.note_position(x, y)+ point = desktop_portal.position()+ device = self._with(CAP_POINTER_ABSOLUTE)+ if device is not None:+ self.ei.absolute(device, float(point[0]), float(point[1]))+ self.ei.frame(device)++ def button(self, code: int, down: bool) -> None:+ if down:+ device = self._with(CAP_BUTTON)+ if device is None:+ return+ self.buttons[code] = device+ else:+ device = self.buttons.pop(code, None)+ if device is None:+ return+ self.ei.button(device, code, down)+ self.ei.frame(device)++ def scroll(self, dy: float, dx: float, mode: str) -> None:+ device = self._with(CAP_SCROLL)+ if device is None:+ return+ kind, x, y = scroll_steps(dy, dx, mode, self.scroll_carry)+ if kind == "pixels":+ self.ei.scroll(device, x, y)+ elif x or y:+ self.ei.scroll_discrete(device, int(x), int(y))+ else:+ return+ self.ei.frame(device)++ def release_held(self) -> None:+ self.keys([(code, False) for code in sorted(self.pressed)])+ for code in sorted(self.buttons):+ self.button(code, False)+ self.state = KeyState()+ self.scroll_carry = [0.0, 0.0]++ # -- the clipboard, on the thread ----------------------------------------------++ def set_selection(self, offer: Dict[str, bytes]) -> bool:+ if not self.clipboard_enabled:+ return False+ self.offer = dict(offer)+ self.portal.call(CLIPBOARD, "SetSelection", "oa{sv}", (self.handle, {"mime_types": ("as", list(offer))}))+ self.ours = True+ self.stamp += 1+ return True++ def open_selection(self, mime: str) -> Optional[int]:+ """An fd the owning app writes `mime`'s data into, for the caller to read and close."""+ if not self.clipboard_enabled:+ return None+ return self.portal.call(CLIPBOARD, "SelectionRead", "os", (self.handle, mime))[0]++ def _transfer(self, mime: str, serial: int) -> None:+ """Another app pastes what Beamer put on the clipboard: its data goes down an fd the portal+ gives, written on a helper thread so a slow reader never holds this one, within+ WRITE_SECONDS, and the portal is told it is done from here, by this session only."""+ data = self.offer.get(mime)+ if data is None:+ self._write_done(serial, False)+ return+ fd = self.portal.call(CLIPBOARD, "SelectionWrite", "ou", (self.handle, serial))[0]+ generation = self._generation+ stopping = self._stopping++ def write() -> None:+ ok = _write_all(fd, data, WRITE_SECONDS, stopping)++ def done(remote: "Remote") -> None:+ if remote._generation == generation and remote.portal is not None:+ remote._write_done(serial, ok)++ self._commands.put((done, _Answer(None), None))+ self._wake()++ threading.Thread(target=write, name="Beamer-clipboard-write", daemon=True).start()+++def _write_all(fd: int, data: bytes, seconds: float, stopping: threading.Event) -> bool:+ """Write `data` to `fd` and close it, giving up after `seconds` or when the session stops."""+ deadline = time.monotonic() + seconds+ try:+ os.set_blocking(fd, False)+ view = memoryview(data)+ while view:+ left = deadline - time.monotonic()+ if left <= 0 or stopping.is_set():+ LOGGER.warning("The app pasting the clipboard did not take it in time")+ return False+ _, ready, _ = select.select([], [fd], [], min(left, 0.2))+ if ready:+ view = view[os.write(fd, view):]+ return True+ except OSError:+ LOGGER.exception("Could not hand the clipboard to the app pasting it")+ return False+ finally:+ try:+ os.close(fd)+ except OSError:+ pass+++class _Answer:+ """One answer from the session's thread to a caller who waits a bounded time; an answer that+ comes after the caller gave up is handed to `discard`."""++ def __init__(self, discard: Optional[Callable[[object], None]]) -> None:+ self._discard = discard+ self._lock = threading.Lock()+ self._event = threading.Event()+ self._gave_up = False+ self._value = (False, None)++ def give(self, ok: bool, value) -> None:+ with self._lock:+ if not self._gave_up:+ self._value = (ok, value)+ self._event.set()+ return+ if ok and self._discard is not None and value is not None:+ try:+ self._discard(value)+ except Exception:+ LOGGER.exception("Could not discard a late answer")++ def wait(self, timeout: float, default):+ self._event.wait(timeout)+ with self._lock:+ if not self._event.is_set():+ self._gave_up = True+ return default+ ok, value = self._value+ return value if ok else default+++class _Problem(Exception):+ def __init__(self, sentence: str, terminal: bool = False) -> None:+ super().__init__(sentence)+ self.sentence = sentence+ self.terminal = terminal+++_remote: Optional[Remote] = None+_remote_lock = threading.Lock()+++def remote() -> Remote:+ global _remote+ with _remote_lock:+ if _remote is None:+ _remote = Remote()+ return _remote+++def start() -> None:+ """Open the session now, so the desktop asks while the user is at this machine."""+ remote().start()+++def stop() -> None:+ if _remote is not None:+ _remote.stop()+++def _warn_once(message: str, item: str, _said: Set[str] = set()) -> None:+ if item not in _said:+ _said.add(item)+ LOGGER.warning(message, item)+++def inject_key(name: str, down: bool, us: Optional[str] = None) -> None:+ def go(session: Remote) -> None:+ if session.layout is None and len(name) == 1:+ return # a named key needs no layout; a character does+ session.keys(wayland_steps(plan_key(name, down, us, session.state, session.layout, session.group, session.locks)))++ remote().submit(go, release=not down)+++def inject_text(text: str) -> None:+ def go(session: Remote) -> None:+ if session.layout is None:+ return+ session.keys(wayland_steps(plan_text(text, session.state, session.layout, session.group, session.locks)))++ remote().submit(go)+++def inject_mouse_move(dx: int, dy: int) -> None:+ remote().submit(lambda session: session.move_by(dx, dy))+++def move_to(x: int, y: int) -> None:+ remote().submit(lambda session: session.place(x, y))+++def inject_mouse_button(button: str, down: bool) -> None:+ code = BUTTONS.get(button)+ if code is None:+ _warn_once("Unknown mouse button ignored: %r", button)+ return+ remote().submit(lambda session: session.button(code, down), release=not down)+++def inject_scroll(dy, dx=0.0, mode: str = "line") -> None:+ remote().submit(lambda session: session.scroll(dy, dx, mode))+++def inject_gesture(name: str, swipe=None) -> None:+ """As on X11: a Linux machine does not offer `gestures`."""+ _warn_once("Gestures are not yet on Linux; %r dropped", name)+++def release_all() -> None:+ """Let go of every key and button held for the peer."""+ if _remote is not None:+ _remote.submit(lambda session: session.release_held(), release=True)diff --git a/win_app/inject_x11.py b/win_app/inject_x11.pynew file mode 100644index 0000000..ee5f4f5--- /dev/null+++ b/win_app/inject_x11.py@@ -0,0 +1,571 @@+"""Keyboard and mouse injection on X11 through XTest: the twin of input_injector.py, with the same+functions, so the receiver drives it unchanged.++Named keys are pressed by evdev code (an X keycode is the code plus 8), the same codes the X11+capture reads. A character is typed as WIRE.md section 7 says: on the key that types it in the+current layout group, read through XKB (xkb_x11), with Shift pressed or let go around it as the+layout needs; when this layout has no key for it, on its US place under a chord or for a letter of+another script, as input_injector._by_place; otherwise on a spare keycode mapped to it, which stays+mapped so a second press needs no remap (every remap makes each client reread the keymap).++Auto-repeat is the server's, as for a key held on this machine's own keyboard: the server repeats+a key XTest holds (measured on Xvfb, 01-10-2026), so the peer's repeats of a held key are not+pressed again, or every held key would repeat twice as fast. The exception is a key typed with+Shift changed around it, whose server repeats would come out under the Shift the user holds: its+server repeat is turned off while it is held and each of the peer's repeats is typed again.++Planning is pure, as plan_key_inputs is on Windows: plan_key and plan_text take the layout and+the held-key state and return steps, so the rules are tested without a server.++One connection and one lock, as input_injector has one lock: a session thread injecting while a+reconnect's release_all clears would otherwise press a key nothing then remembers to release.+python-xlib and libxkbcommon are reached only when the first event is injected, so this module+imports anywhere."""++import atexit+import functools+import logging+import os+import threading+import time+from pathlib import Path+from typing import Dict, List, Optional, Set, Tuple++from capture_x11 import KEYCODE_OFFSET, LOCK_MASK, NUM_LOCK_MASK, SHIFT_MASK+from core import keytable+from input_injector import CHORD_KEYS, MODIFIER_KEYS, SHIFT_KEYS, _by_place++LOGGER = logging.getLogger(__name__)++SHIFT_L = 42 + KEYCODE_OFFSET++# Wire names to evdev codes: EVDEV_NAMES turned round, the main Enter for "enter".+NAME_TO_CODE: Dict[str, int] = {name: code for code, name in keytable.EVDEV_NAMES.items() if code != 96}+NAME_TO_CODE.update({"return": 28, "escape": 1})+US_TO_CODE: Dict[str, int] = {char: code for code, char in keytable.EVDEV_US.items()}++BUTTONS = {"left": 1, "middle": 2, "right": 3, "back": 8, "forward": 9}+# A wheel click scrolls about three lines, which the PC reckons as 40 pixels; a pixel delta from a+# trackpad becomes clicks at that rate, its remainder carried.+PIXELS_PER_CLICK = 40.0+# Before a spare keycode is mapped to another character, the clients get this long to read the+# press it just made: each reads the keymap again only when it handles the MappingNotify.+REMAP_PAUSE_SECONDS = 0.05++PRESS, RELEASE, MAP, NO_REPEAT, REPEAT = "press", "release", "map", "no_repeat", "repeat"+++def repeat_state_file() -> Path:+ """Where the keycodes whose auto-repeat this module turned off are written: it is the X+ server's state and outlives the process, so a Beamer that was killed turns them on again when+ it next starts."""+ base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state")+ return Path(base) / "beamer" / "x11-repeat-off"+++def keysym_for(character: str) -> int:+ """The keysym for a character: Latin-1 as itself, anything else as its Unicode keysym."""+ point = ord(character)+ if 0x20 <= point <= 0x7E or 0xA0 <= point <= 0xFF:+ return point+ return 0x01000000 | point+++class Layout:+ """The layout as typing reads it, over an xkb_x11.Keymap: which key types a character in a+ group and whether it needs Shift with the locks (Caps Lock, Num Lock) as they are, and what the+ key at a US place types there. `mapped` holds the spare keycodes this module mapped since the+ keymap was last read."""++ def __init__(self, keymap) -> None:+ self.keymap = keymap+ self.mapped: Dict[int, int] = {}+ self._found: Dict[Tuple[int, int], Dict[str, Tuple[int, bool]]] = {}++ def find(self, character: str, group: int, locks: int) -> Optional[Tuple[int, bool]]:+ """(keycode, shift) for the key typing `character`, without Shift preferred, or None."""+ table = self._found.get((group, locks))+ if table is None:+ table = {}+ keymap = self.keymap+ for keycode in range(keymap.max_keycode, keymap.min_keycode - 1, -1):+ for shift in (True, False):+ text = keymap.text(keymap.keysym(keycode, locks | (SHIFT_MASK if shift else 0), group))+ if text:+ table[text] = (keycode, shift)+ self._found[(group, locks)] = table+ found = table.get(character)+ if found is None:+ keycode = next((code for code, keysym in self.mapped.items() if keysym == keysym_for(character)), None)+ if keycode is not None:+ return keycode, False+ return found++ def place(self, us: str, group: int) -> Optional[Tuple[int, Optional[str]]]:+ """The keycode at `us`'s place and what it types there unshifted, the shape+ input_injector._by_place asks for."""+ code = US_TO_CODE.get(us)+ if code is None:+ return None+ keycode = code + KEYCODE_OFFSET+ return keycode, self.keymap.text(self.keymap.keysym(keycode, 0, group))++ def holds(self, keycode: int, keysym: int) -> bool:+ """Whether a spare keycode still types `keysym`: a new keymap (setxkbmap, a layout switch+ that loads one) wipes what was mapped."""+ if self.mapped.get(keycode) == keysym:+ return True+ return self.keymap.keysym(keycode, 0, 0) == keysym++ def spare(self) -> List[int]:+ """Keycodes with nothing on them, highest first, as xdotool takes them: the low ones are+ real keys a layout may still name, and 8 is evdev's reserved code 0."""+ keymap = self.keymap+ return [code for code in range(keymap.max_keycode, KEYCODE_OFFSET, -1) if keymap.empty(code) and code not in self.mapped]++ def map(self, keycode: int, keysym: int) -> None:+ self.mapped[keycode] = keysym+ self._found.clear()+++class KeyState:+ """What this machine holds down for the peer, and the spare keycodes it has mapped."""++ def __init__(self) -> None:+ self.mods_down: Set[str] = set()+ self.named_down: Set[int] = set()+ # A held character: its keycode, and for one typed with Shift changed around it, whether+ # it needs Shift, for each repeat to be typed again (None when the server repeats it).+ self.chars_down: Dict[str, Tuple[int, Optional[bool]]] = {}+ self.spares: Dict[int, int] = {} # keysym to keycode, least recently used first++ def held_shift(self) -> List[int]:+ return [NAME_TO_CODE[name] + KEYCODE_OFFSET for name in sorted(self.mods_down & SHIFT_KEYS)]+++def _spare_steps(character: str, layout: Layout, state: KeyState) -> Optional[Tuple[int, list]]:+ """A spare keycode typing `character` on both levels, and the steps that map it, or None when+ every spare is held."""+ keysym = keysym_for(character)+ keycode = state.spares.pop(keysym, None)+ if keycode is not None and layout.holds(keycode, keysym):+ state.spares[keysym] = keycode # most recent last+ return keycode, []+ evicting = False+ if keycode is None:+ free = [code for code in layout.spare() if code not in state.spares.values()]+ if free:+ keycode = free[0]+ else:+ held = {code for code, _again in state.chars_down.values()}+ reusable = [(sym, code) for sym, code in state.spares.items() if code not in held]+ if not reusable:+ return None+ old_sym, keycode = reusable[0]+ del state.spares[old_sym]+ evicting = True+ # else a new keymap wiped it: it is mapped again where it was.+ state.spares[keysym] = keycode+ layout.map(keycode, keysym)+ return keycode, [(MAP, keycode, keysym, evicting)]+++def _shift_around(keycode: int, shift: bool, state: KeyState) -> list:+ """Press `keycode` with Shift as `shift` says, pressing or letting go of it around the key."""+ held = state.held_shift()+ if shift and not held:+ return [(PRESS, SHIFT_L), (PRESS, keycode), (RELEASE, SHIFT_L)]+ if not shift and held:+ return [(RELEASE, code) for code in held] + [(PRESS, keycode)] + [(PRESS, code) for code in held]+ return [(PRESS, keycode)]+++_warned: Set[str] = set()+++def _warn_once(message: str, item: str) -> None:+ if item not in _warned:+ _warned.add(item)+ LOGGER.warning(message, item)+++def plan_key(name: str, down: bool, us: Optional[str], state: KeyState, layout: Layout, group: int, locks: int) -> list:+ """Steps for one key message: (PRESS, keycode), (RELEASE, keycode), (MAP, keycode, keysym,+ evicting), (NO_REPEAT, keycode) or (REPEAT, keycode). `locks` is the Caps Lock and Num Lock+ bits as they are. Updates `state`. Empty for a name this machine cannot press, and for the+ peer's repeat of a key the server is already repeating."""+ lowered = name.lower() if len(name) > 1 else name+ if lowered in MODIFIER_KEYS:+ if down:+ state.mods_down.add(lowered)+ else:+ state.mods_down.discard(lowered)+ code = NAME_TO_CODE.get(lowered) if len(name) > 1 else None+ if code is not None:+ keycode = code + KEYCODE_OFFSET+ if not down:+ state.named_down.discard(keycode)+ return [(RELEASE, keycode)]+ if keycode in state.named_down:+ return []+ state.named_down.add(keycode)+ return [(PRESS, keycode)]+ if len(name) != 1:+ _warn_once("Unknown key name ignored: %r", name)+ return []+ character = name+ held = state.chars_down.get(character)+ if not down:+ if held is None:+ found = layout.find(character, group, locks)+ return [] if found is None else [(RELEASE, found[0])]+ del state.chars_down[character]+ keycode, again = held+ return [(RELEASE, keycode)] + ([(REPEAT, keycode)] if again is not None else [])+ if held is not None:+ keycode, shift = held+ # Shift is worked out again: the peer may have pressed or let go of its own since.+ return [] if shift is None else [(RELEASE, keycode)] + _shift_around(keycode, shift, state)+ chord = bool(state.mods_down & CHORD_KEYS)+ found = layout.find(character, group, locks)+ if found is not None:+ keycode, shift = found+ # Under a chord the peer's own Shift is part of the shortcut; it is never touched.+ steps = [(PRESS, keycode)] if chord else _shift_around(keycode, shift, state)+ if len(steps) == 1:+ state.chars_down[character] = (keycode, None)+ return steps+ state.chars_down[character] = (keycode, shift)+ return [(NO_REPEAT, keycode)] + steps+ place = _by_place(character, us, state.mods_down, lambda key: layout.place(key, group))+ if place is not None:+ state.chars_down[character] = (place[0], None)+ return [(PRESS, place[0])]+ spare = _spare_steps(character, layout, state)+ if spare is None:+ _warn_once("No spare key left to type %r", character)+ return []+ keycode, steps = spare+ state.chars_down[character] = (keycode, None)+ return steps + [(PRESS, keycode)]+++def plan_text(text: str, state: KeyState, layout: Layout, group: int, locks: int) -> list:+ """Steps typing `text` as it stands (WIRE.md section 10): every modifier the peer holds is let+ go first and pressed again after, so neither they nor the layout play a part."""+ held = [NAME_TO_CODE[name] + KEYCODE_OFFSET for name in sorted(state.mods_down) if name in NAME_TO_CODE]+ steps = [(RELEASE, code) for code in held]+ bare = KeyState()+ bare.spares, bare.chars_down = state.spares, state.chars_down+ for character in text:+ found = layout.find(character, group, locks)+ if found is not None:+ keycode, shift = found+ steps += _shift_around(keycode, shift, bare)+ else:+ spare = _spare_steps(character, layout, bare)+ if spare is None:+ _warn_once("No spare key left to type %r", character)+ continue+ keycode, mapped = spare+ steps += mapped + [(PRESS, keycode)]+ steps.append((RELEASE, keycode))+ return steps + [(PRESS, code) for code in held]+++def plan_scroll(dy, dx, mode: str, carry: List[float]) -> Tuple[int, int]:+ """Whole wheel clicks (vertical, horizontal) for one scroll message, the remainder carried in+ `carry` ([y, x]) as plan_scroll_units carries Windows' wheel units. Positive y is away from+ the hand, positive x is right, as on Windows."""+ scale = 1.0 / PIXELS_PER_CLICK if mode == "pixel" else 1.0+ carry[0] += float(dy) * scale+ carry[1] += float(dx) * scale+ whole_y, whole_x = int(carry[0]), int(carry[1])+ carry[0] -= whole_y+ carry[1] -= whole_x+ return whole_y, whole_x+++def scroll_buttons(whole_y: int, whole_x: int) -> List[int]:+ buttons = [4 if whole_y > 0 else 5] * abs(whole_y)+ return buttons + [7 if whole_x > 0 else 6] * abs(whole_x)+++class _Connection:+ """The injector's X connection: XTest, the keymap and per-key auto-repeat."""++ def __init__(self) -> None:+ from Xlib import X, display+ from Xlib.ext import xtest++ import xkb_x11++ self._X, self._xtest = X, xtest+ self.display = display.Display()+ try:+ if not self.display.has_extension("XTEST"):+ raise RuntimeError("This X server has no XTEST extension")+ self.keymap = xkb_x11.Keymap(self.display.get_display_name())+ except Exception:+ self.display.close()+ raise+ self.root = self.display.screen().root+ self._repeat_off: Set[int] = set()+ self._restore_left_over()+ atexit.register(self._restore_at_exit)++ def _restore_left_over(self) -> None:+ try:+ left = [int(word) for word in repeat_state_file().read_text().split()]+ except (OSError, ValueError):+ return+ for keycode in left:+ self.display.change_keyboard_control(key=keycode, auto_repeat_mode=self._X.AutoRepeatModeOn)+ self.display.sync()+ self._write_repeat_off()++ def _write_repeat_off(self) -> None:+ path = repeat_state_file()+ try:+ if self._repeat_off:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(" ".join(str(keycode) for keycode in sorted(self._repeat_off)))+ else:+ path.unlink(missing_ok=True)+ except OSError:+ LOGGER.exception("Could not record which keys have auto-repeat off")++ def _restore_at_exit(self) -> None:+ try:+ self.restore_repeat()+ except Exception:+ pass++ def layout(self) -> Layout:+ return Layout(self.keymap)++ def mapping_changed(self) -> bool:+ """Whether a MappingNotify has arrived since the last look; the keymap is read again."""+ changed = False+ while self.display.pending_events():+ event = self.display.next_event()+ if event.type == self._X.MappingNotify and event.request in (self._X.MappingKeyboard, self._X.MappingModifier):+ changed = True+ if changed:+ self.keymap.reload()+ return changed++ def state(self) -> Tuple[int, int]:+ """(layout group, the Caps Lock and Num Lock bits) now."""+ mask = self.root.query_pointer().mask+ return (mask >> 13) & 3, mask & (LOCK_MASK | NUM_LOCK_MASK)++ def run(self, steps) -> None:+ X, fake = self._X, self._xtest.fake_input+ for step in steps:+ kind = step[0]+ if kind == MAP:+ if step[3]:+ self.display.sync()+ time.sleep(REMAP_PAUSE_SECONDS)+ self.display.change_keyboard_mapping(step[1], [(step[2], step[2])])+ self.display.sync()+ elif kind == NO_REPEAT:+ repeats = self.display.get_keyboard_control().auto_repeats+ if repeats[step[1] // 8] >> (step[1] % 8) & 1:+ self._repeat_off.add(step[1])+ self._write_repeat_off() # before the change, so a crash after it is undone next start+ self.display.change_keyboard_control(key=step[1], auto_repeat_mode=X.AutoRepeatModeOff)+ elif kind == REPEAT:+ if step[1] in self._repeat_off:+ self.display.change_keyboard_control(key=step[1], auto_repeat_mode=X.AutoRepeatModeOn)+ self._repeat_off.discard(step[1])+ self._write_repeat_off()+ else:+ fake(self.display, X.KeyPress if kind == PRESS else X.KeyRelease, step[1])+ self.display.flush()++ def restore_repeat(self) -> None:+ if not self._repeat_off:+ return+ for keycode in sorted(self._repeat_off):+ self.display.change_keyboard_control(key=keycode, auto_repeat_mode=self._X.AutoRepeatModeOn)+ self.display.sync()+ self._repeat_off.clear()+ self._write_repeat_off()++ def button(self, button: int, down: bool) -> None:+ self._xtest.fake_input(self.display, self._X.ButtonPress if down else self._X.ButtonRelease, button)+ self.display.flush()++ def move(self, dx: int, dy: int) -> None:+ self._xtest.fake_input(self.display, self._X.MotionNotify, detail=1, x=int(dx), y=int(dy))+ self.display.flush()++ def move_to(self, x: int, y: int) -> None:+ self._xtest.fake_input(self.display, self._X.MotionNotify, detail=0, root=self.root.id, x=int(x), y=int(y))+ self.display.flush()++ def close(self) -> None:+ atexit.unregister(self._restore_at_exit)+ try:+ self.restore_repeat()+ self.keymap.close()+ finally:+ self.display.close()+++_connect = _Connection+_connection = None+_layout: Optional[Layout] = None+_state = KeyState()+_buttons_down: Set[str] = set()+_scroll_carry = [0.0, 0.0]+_lock = threading.RLock()+++def _locked(function):+ @functools.wraps(function)+ def wrapper(*args, **kwargs):+ with _lock:+ return function(*args, **kwargs)++ return wrapper+++def _open():+ global _connection, _layout+ if _connection is None:+ _connection = _connect()+ _layout = None+ return _connection+++def _drop() -> None:+ """After a failed request the connection is closed and opened again on the next one: a dead X+ socket never recovers."""+ global _connection, _layout+ dead, _connection, _layout = _connection, None, None+ if dead is not None:+ try:+ dead.close()+ except Exception:+ pass+++def _talk(function):+ """Runs `function(connection)` under the lock, dropping the connection if it fails."""+ with _lock:+ connection = _open()+ try:+ return function(connection)+ except Exception:+ _drop()+ raise+++def _current_layout(connection) -> Layout:+ global _layout+ if connection.mapping_changed() or _layout is None:+ _layout = connection.layout()+ return _layout+++@_locked+def inject_key(name: str, down: bool, us: Optional[str] = None) -> None:+ def go(connection):+ layout = _current_layout(connection)+ group, locks = connection.state() if len(name) == 1 else (0, 0)+ steps = plan_key(name, down, us, _state, layout, group, locks)+ if steps:+ connection.run(steps)++ _talk(go)+++@_locked+def inject_text(text: str) -> None:+ def go(connection):+ layout = _current_layout(connection)+ group, locks = connection.state()+ steps = plan_text(text, _state, layout, group, locks)+ if steps:+ connection.run(steps)++ _talk(go)+++def inject_mouse_move(dx: int, dy: int) -> None:+ _talk(lambda connection: connection.move(dx, dy))+++def move_to(x: int, y: int) -> None:+ """An absolute XTest move, for the proof harness."""+ _talk(lambda connection: connection.move_to(x, y))+++@_locked+def inject_mouse_button(button: str, down: bool) -> None:+ number = BUTTONS.get(button)+ if number is None:+ _warn_once("Unknown mouse button ignored: %r", button)+ return+ if down:+ _buttons_down.add(button)+ else:+ _buttons_down.discard(button)+ _talk(lambda connection: connection.button(number, down))+++@_locked+def inject_scroll(dy, dx=0.0, mode: str = "line") -> None:+ buttons = scroll_buttons(*plan_scroll(dy, dx, mode, _scroll_carry))+ if buttons:+ def go(connection):+ for button in buttons:+ connection.button(button, True)+ connection.button(button, False)++ _talk(go)+++def inject_gesture(name: str, swipe=None) -> None:+ """Linux desktops share no shortcut for a swipe, so none is pressed; a Linux machine does not+ offer the `gestures` capability, and a peer that sends one anyway gets this."""+ _warn_once("Gestures are not yet on Linux; %r dropped", name)+++@_locked+def release_all() -> None:+ """Let go of every key and button held for the peer, the twin of input_injector.release_all:+ the receiver calls it when the peer's input goes home or its link dies."""+ for name in sorted(_state.mods_down):+ try:+ inject_key(name, down=False)+ except Exception:+ LOGGER.exception("Could not release %r", name)+ for keycode in sorted(_state.named_down):+ try:+ _talk(lambda connection, keycode=keycode: connection.run([(RELEASE, keycode)]))+ except Exception:+ LOGGER.exception("Could not release keycode %s", keycode)+ for character in sorted(_state.chars_down):+ try:+ inject_key(character, down=False)+ except Exception:+ LOGGER.exception("Could not release %r", character)+ for button in sorted(_buttons_down):+ try:+ inject_mouse_button(button, down=False)+ except Exception:+ LOGGER.exception("Could not release the %s mouse button", button)+ if _connection is not None:+ try:+ _connection.restore_repeat()+ except Exception:+ LOGGER.exception("Could not turn auto-repeat back on")+ _state.mods_down.clear()+ _state.named_down.clear()+ _state.chars_down.clear()+ _buttons_down.clear()+ _scroll_carry[0] = _scroll_carry[1] = 0.0diff --git a/win_app/input_injector.py b/win_app/input_injector.pyindex 1ef9cbc..3032548 100644--- a/win_app/input_injector.py+++ b/win_app/input_injector.py@@ -10,6 +10,8 @@ import timeimport unicodedatafrom typing import Callable, Dict, List, Optional, Set, Tuple+from core.keytable import EVDEV_US+LOGGER = logging.getLogger(__name__)@@ -43,11 +45,8 @@ INJECTED_MARK = 0xBEA3# What each key types on a US keyboard, by scan code, which names the key's place rather than its# label. Key messages carry it as `us` both ways, and a character this layout cannot type lands on-# its place when it has to (_by_place).-SCAN_TO_US: Dict[int, str] = dict(zip(range(0x02, 0x0E), "1234567890-="))-SCAN_TO_US.update(zip(range(0x10, 0x1C), "qwertyuiop[]"))-SCAN_TO_US.update(zip(range(0x1E, 0x2A), "asdfghjkl;'`"))-SCAN_TO_US.update(zip(range(0x2B, 0x36), "\\zxcvbnm,./"))+# its place when it has to (_by_place). Set-1 scan codes are evdev codes, so it is the key table's.+SCAN_TO_US: Dict[int, str] = EVDEV_USUS_SCAN_CODES = {char: scan for scan, char in SCAN_TO_US.items()}MAPVK_VSC_TO_VK = 1diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.pyindex b5acd03..f2f649d 100644--- a/win_app/kvm_bridge_win.py+++ b/win_app/kvm_bridge_win.py@@ -13,7 +13,7 @@ import timefrom typing import Optionalfrom PySide6.QtCore import QEvent, QObject, QRectF, QSize, QTimer, Qt, QUrl, Signal-from PySide6.QtGui import QColor, QDesktopServices, QIcon, QKeySequence, QPainter, QPixmap, QShortcut+from PySide6.QtGui import QAction, QColor, QDesktopServices, QIcon, QKeySequence, QPainter, QPixmap, QShortcutfrom PySide6.QtWidgets import (QApplication,QCheckBox,@@ -72,7 +72,8 @@ from core import receiverfrom core.receiver import LinkResponder, ServerStatefrom core import return_edgefrom core import settings_sync-from sender import LinkSender+from core import ways+from sender import OWN_PLATFORM, LinkSenderimport themeimport tokensfrom core import updates@@ -143,7 +144,7 @@ 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).+# the X11 or the portal back ends (platform_parts).autostart_win = platform_parts.autostartcapture_win = platform_parts.capturedesktop_win = platform_parts.desktop@@ -227,13 +228,11 @@ class StatusBridge(QObject):# 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)+ # peer's edge that faces this PC, stamp, the machine that made the change, its way_back or None).+ arrangement = Signal(str, str, int, str, object)# Either link, carrying a peer's Same on all machines state: (peer id, data).settings = Signal(str, object)alert = Signal(str, 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.@@ -264,7 +263,6 @@ class WindowsApplication(QWidget):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 = None@@ -276,6 +274,12 @@ class WindowsApplication(QWidget):self._pairing_machine = Noneself._pairing_target = ""self._peer_entries: list = []+ self._zone_entries: list = []+ # The machine the Crossing page shows and edits, by id; the first paired one until a choice.+ self._chosen: Optional[str] = None+ self._crossing_seen = None+ self._machine_items: tuple = ()+ self.machine_actions: dict = {}self._labels_by_id: dict = {}self._peers_tick = 0self._firewall_advice: Optional[firewall_win.Advice] = None@@ -305,11 +309,10 @@ class WindowsApplication(QWidget):),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"])+ protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back")),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,@@ -341,10 +344,9 @@ class WindowsApplication(QWidget):# 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"])+ protocol.id_text(peer), read["edge"], read["set_at"], protocol.id_text(read["by"]), read.get("way_back"))self.sender.link_callback = lambda peer, up: self.bridge.peers_changed.emit()- self.sender.notice_callback = self.bridge.notice.emitself.sender.paired_callback = self._store_pairedself.sender.hw_learned = self._learn_peer_hardwareself.sender.announce = self._announce@@ -357,6 +359,20 @@ class WindowsApplication(QWidget):self.sender.on_alert = self.bridge.alert.emitself.bridge.alert.connect(self._on_alert)self.hooks = capture_win.Hooks(self._on_hook_key, self._on_hook_mouse, self.sender.on_motion)+ # X11 cannot swallow one event, only grab the devices; the capture thread holds the grab+ # for as long as input is away.+ grab_while = getattr(self.hooks, "grab_while", None)+ if grab_while is not None:+ grab_while(lambda: self.sender.redirecting)+ self.hooks.on_failure = self._capture_stopped+ # Wayland: only the desktop captures input, at barriers on this machine's zones, and it+ # may end a capture itself, which brings input home.+ if hasattr(self.hooks, "barriers_from"):+ self.hooks.barriers_from(self.sender.zone_models)+ self.hooks.on_home = lambda: self.sender.set_redirecting(False)+ self.sender.input_held = lambda: self.hooks.holding+ if hasattr(platform_parts.injector, "on_problem"):+ platform_parts.injector.on_problem = lambda sentence: self.bridge.alert.emit("Beamer", sentence)self._trigger = capture_win.Trigger()self._sending_detail = "Not connected"self.update_checker = updates.Checker(@@ -637,14 +653,28 @@ class WindowsApplication(QWidget):self.hold_switch.setChecked(self._config.hold_full_screen if self._config else True)self.hold_switch.toggled.connect(self._set_hold_full_screen)module.body.addWidget(self.hold_switch)- module.body.addWidget(self._own_note())- module.body.addWidget(widgets.label(+ own_note = self._own_note()+ module.body.addWidget(own_note)+ hold_note = widgets.label("Off, your pointer can leave a full-screen game or video, and another machine's pointer can come "- "home through this PC's edge. Useful if your keyboard has no key for the shortcut.", "note", wrap=True))+ "home through this PC's edge. Useful if your keyboard has no key for the shortcut.", "note", wrap=True)+ module.body.addWidget(hold_note)+ self.wayland_crossing_note = widgets.label(+ "On Wayland Beamer cannot see a full-screen app, or a mouse button held before the pointer reaches an "+ "edge, so the edges are never held for one and a drag can cross.", "note", wrap=True)+ module.body.addWidget(self.wayland_crossing_note)+ for widget in (self.hold_switch, own_note, hold_note):+ widget.setVisible(not platform_parts.WAYLAND)+ self.wayland_crossing_note.setVisible(platform_parts.WAYLAND)return moduledef _redirect_text(self) -> str:+ """Names the machine the button sends input to, which is the one the shortcut would pick."""+ target = self.sender.shortcut_target()+ if target is not None and target in self._labels_by_id:+ return f"Send input to {self._labels_by_id[target]}"sendable = [entry for entry in self._peer_entries if entry.get("send")]+ # The entry migrated from 1.4.x has no id to pick it by until its first link.return f"Send input to {self._shown(peerlist.labels(self._peer_entries)[sendable[0]['token']])}" if len(sendable) == 1 else "Send input across"def toggle_redirect(self) -> None:@@ -656,10 +686,9 @@ class WindowsApplication(QWidget):def _crossing_state_args(self) -> tuple:entries = self._peer_entries- methods = set(self._config.crossing_methods) if self._config is not None else set()return (bool(entries), any(entry.get("host") for entry in entries), self._any_send(),- bool(self.sender.peers_up()), bool(methods & {"edge", "part", "corner"}),+ bool(self.sender.peers_up()), bool(self._ways_in()),self.sender.crossing_paused, self.sender.full_screen_app, self._machines_name(),)@@ -687,12 +716,9 @@ class WindowsApplication(QWidget):QApplication.beep()self.tray.showMessage(title, self._shown(message), QIcon(str(ICON_PATH)), 4000)- def _on_alert_text(self, message: str) -> None:- self._on_alert("Beamer", message)-def _same_module(self, current: Config) -> QWidget:module = widgets.Module("Settings")- self.same_switch = widgets.Switch("Same on both machines")+ self.same_switch = widgets.Switch("Same on all machines")self.same_switch.setFont(theme.font(theme.TYPE["body"]))self.same_switch.setChecked(current.same_on_both)self.same_switch.toggled.connect(self._set_same)@@ -777,7 +803,8 @@ class WindowsApplication(QWidget):messages = []author = protocol.read_id(entry.get("side_by")) or protocol.read_id(config.machine_id)if entry.get("side") in return_edge.EDGES and entry.get("side_set_at") and author is not None:- messages.append(protocol.arrangement_v6(entry["side"], entry["side_set_at"], author))+ way_back = ways.has_way({"peers": peers, "zones": self.book.zones()}, entry["id"])+ messages.append(protocol.arrangement_v6(entry["side"], entry["side_set_at"], author, way_back=way_back))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]))@@ -801,9 +828,11 @@ class WindowsApplication(QWidget):return {"id": protocol.read_id(config.machine_id) or b"","name": name,- "platform": "windows",+ "platform": OWN_PLATFORM,"app": VERSION[:32] if VERSION.isascii() and VERSION.isprintable() else "dev",- "caps": ["clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings"],+ # A swipe has no shortcut every Linux desktop shares, so Linux does not offer gestures.+ "caps": [cap for cap in ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings")+ if not (cap == "gestures" and OWN_PLATFORM == "linux")],"port": self._settings_port,}@@ -920,6 +949,18 @@ class WindowsApplication(QWidget):def _ways_module(self, current: Config) -> QWidget:module = widgets.Module("Ways in")+ # Which machine everything below shows and edits; only there with more than one paired.+ holder = QWidget()+ holder.setProperty("vernier", "plain")+ self._machine_slot = QVBoxLayout(holder)+ self._machine_slot.setContentsMargins(0, 0, 0, 0)+ self.machine_choice = widgets.Choice((), 1, "")+ self._machine_slot.addWidget(self.machine_choice.view)+ self.machine_row = self._row(widgets.label("Machine", "key"), holder)+ # A wider step under the choice than between the rows it governs, so it reads as their heading.+ self.machine_row.layout().setContentsMargins(0, 0, 0, 8)+ self.machine_row.setVisible(False)+ module.body.addWidget(self.machine_row)self.ways_summary = widgets.label("", "note", wrap=True)module.body.addWidget(self.ways_summary)self.arrangement_diagram = ArrangementDiagram()@@ -927,7 +968,6 @@ class WindowsApplication(QWidget):self.way_boxes: dict = {}for value, text, detail in pages_win.WAY_ROWS:box = QCheckBox(text)- box.setChecked(value in current.crossing_methods)box.toggled.connect(lambda on, v=value: self._ways_changed(v, on))self.way_boxes[value] = boxif not detail:@@ -940,24 +980,26 @@ class WindowsApplication(QWidget):line.addWidget(widgets.label(detail, "small"))line.addStretch(1)module.body.addLayout(line)-- self.edge_choice = widgets.Choice(- EDGE_CHOICES, columns=4, current=current.mac_return_edge, on_change=self._set_arrangement- )- self.edge_choice.set_names("Where the other machine is")- self.edge_unlearned = widgets.label(pages_win.NOT_LEARNED_EDGE, "note", wrap=True)- self.edge_unlearned.setVisible(not current.mac_return_edge)+ # A way refused because it would share a stretch of this screen with another machine's.+ self.clash_note = widgets.label("", "note-amber", wrap=True)+ self.clash_note.setVisible(False)+ module.body.addWidget(self.clash_note)+ # What stops a way working, under the ways it is about: a side another machine's edge holds,+ # a machine that may drive this PC and is not paired with the chosen one, and the chosen one+ # saying none of its own ways leads back here.+ self.blocked_note = widgets.label("", "note-amber", wrap=True)+ self.missing_note = widgets.label("", "note", wrap=True)+ self.no_way_back_note = widgets.label("", "note", wrap=True)+ for note in (self.blocked_note, self.missing_note, self.no_way_back_note):+ note.setVisible(False)+ module.body.addWidget(note)++ self.edge_choice = widgets.Choice(EDGE_CHOICES, columns=4, current="", on_change=self._set_arrangement)+ self.edge_heading = widgets.label("", "key")+ self.edge_note = widgets.label("", "note", wrap=True)+ self.edge_unlearned = widgets.label(pages_win.not_learned_edge(), "note", wrap=True)self.crossing_rows = {- "edge": self._row(- widgets.label("Where the other machine is", "key"),- widgets.label(- "One border, walked both ways, so changing it here moves it on the other machine too.",- "note",- wrap=True,- ),- self.edge_choice.view,- self.edge_unlearned,- ),+ "edge": self._row(self.edge_heading, self.edge_note, self.edge_choice.view, self.edge_unlearned),}chips = QHBoxLayout()@@ -969,16 +1011,13 @@ class WindowsApplication(QWidget):button.setCheckable(True)button.setMinimumHeight(widgets.MIN_TARGET)button.setCursor(Qt.CursorShape.PointingHandCursor)- button.setChecked(part in current.crossing_edge_parts)button.clicked.connect(lambda on, p=part: self._set_part(p, on))chips.addWidget(button, 1)self.part_buttons[part] = buttonself.parts_note = widgets.label("", "note", wrap=True)self.crossing_rows["parts"] = self._row(widgets.label("Parts", "key"), chips, self.parts_note)- self.corner_choice = widgets.Choice(- CORNER_CHOICES, columns=2, current=current.crossing_corner, on_change=self._set_corner- )+ self.corner_choice = widgets.Choice(CORNER_CHOICES, columns=2, current="", on_change=self._set_corner)self.corner_choice.set_names("Corner")self.crossing_rows["corner"] = self._row(widgets.label("Corner", "key"), self.corner_choice.view)@@ -992,77 +1031,191 @@ class WindowsApplication(QWidget):return module- def _ways_changed(self, way: str, on: bool) -> None:- if self._config is None:- return- self._config.crossing_methods = pages_win.toggle_way(self._config.crossing_methods, way, on)- self._persist()- self.sender.update_config(self._config)+ # -- the machine the Crossing page shows --++ def _crossing_settings(self) -> dict:+ """The peers and zones as last read, in the shape core.ways reads them."""+ own = self._config.machine_id if self._config is not None else ""+ return {"machine_id": own, "peers": self._peer_entries, "zones": self._zone_entries}++ def _read_crossing(self) -> None:+ try:+ self._peer_entries, self._zone_entries = self.book.peers(), self.book.zones()+ except (ConfigError, OSError):+ LOGGER.exception("The peers could not be read")++ def _crossing_machines(self) -> list:+ return [(ident, self._shown(label)) for ident, label in pages_win.crossing_machines(self._peer_entries)]++ def _chosen_machine(self) -> Optional[str]:+ ids = [ident for ident, _label in self._crossing_machines()]+ return self._chosen if self._chosen in ids else (ids[0] if ids else None)++ def _ways_in(self) -> set:+ """The kinds of zone in use towards any machine: what Pause holds and the Design page previews."""+ settings = self._crossing_settings()+ found = set()+ for ident, _label in self._crossing_machines():+ if ways.has_way(settings, ident):+ found.update(ways.ways(settings, ident)["methods"])+ return found++ def _choose_machine(self, peer: str) -> None:+ self._chosen = peer+ self._show_clash("")self._reflect_ways()- # The Design page's preview opens where the pointer crosses and says when a place is not a way in.self._reflect_look()- def _set_part(self, part: str, on: bool) -> None:- if self._config is None:- return- self._config.crossing_edge_parts = pages_win.toggle_part(self._config.crossing_edge_parts, part, on)- self._persist()- self.sender.update_config(self._config)+ def _show_clash(self, sentence: str) -> None:+ self.clash_note.setText(sentence)+ motion.set_shown(self.clash_note, bool(sentence))++ def _rebuild_machine_choice(self, machines: list) -> None:+ """The machine choice again when the paired machines or their names change."""+ items = tuple(machines)+ if items == self._machine_items:+ return+ self._machine_items = items+ old = self.machine_choice.view+ # Three names fit a row at the narrowest window; four or more go two to a row.+ columns = len(items) if len(items) <= 3 else 2+ self.machine_choice = widgets.Choice(items, max(1, columns), "", on_change=self._choose_machine)+ self.machine_choice.set_names("Machine")+ self._machine_slot.replaceWidget(old, self.machine_choice.view)+ old.deleteLater()++ def _write_ways(self, **changes) -> bool:+ """One change to the chosen machine's ways, written for that machine alone. A side that moved,+ or a way there that opened or closed, goes to it as `arrangement` (`_tell`); a change that would+ share a stretch of this screen with another machine's zone is refused, said, and every control+ goes back."""+ peer = self._chosen_machine()+ if self._config is None or peer is None:+ self._reflect_ways()+ return False+ self._read_crossing()+ had_way = ways.has_way(self._crossing_settings(), peer)+ held = ways.ways(self._crossing_settings(), peer)+ held.update(changes)+ try:+ moved = app_config.set_ways(self.config_path, peer, side=changes.get("side"), methods=held["methods"],+ parts=held["parts"], corner=held["corner"])+ except app_config.ClashError as exc:+ self._show_clash(self._shown(str(exc)))+ self._reflect_ways()+ return False+ except (ConfigError, OSError):+ LOGGER.exception("A machine's ways could not be saved")+ self._reflect_ways()+ return False+ self._show_clash("")+ self._read_crossing()+ if moved or ways.has_way(self._crossing_settings(), peer) != had_way:+ # One border, walked both ways: the machine on the other side of it moves its own side to match.+ self._tell(peer)+ # A change on the Crossing page reaches a peer's pointer while it is here, not at its next crossing.+ self.server.peers_changed()+ self.sender.refresh()self._reflect_ways()# The Design page's preview opens where the pointer crosses and says when a place is not a way in.self._reflect_look()+ return True++ def _ways_changed(self, way: str, on: bool) -> None:+ if self._config is None:+ return+ if way == "shortcut":+ # The shortcut is this PC's own, whichever machine the page shows.+ self._config.crossing_methods = pages_win.toggle_way(self._config.crossing_methods, way, on)+ self._persist()+ self.sender.update_config(self._config)+ self._reflect_ways()+ self._reflect_look()+ return+ held = ways.ways(self._crossing_settings(), self._chosen_machine())["methods"]+ self._write_ways(methods=[kind for kind in pages_win.toggle_way(held, way, on) if kind != "shortcut"])++ def _set_part(self, part: str, on: bool) -> None:+ held = ways.ways(self._crossing_settings(), self._chosen_machine())["parts"]+ self._write_ways(parts=pages_win.toggle_part(held, part, on))def _reflect_ways(self) -> None:- """The ways' boxes, the parts' chips and which rows show, from the config: a row a chosen- way does not use is hidden, not dimmed, and comes back the moment one does."""+ """The machine choice, the ways' boxes, the parts' chips and which rows show, for the chosen+ machine: a row a chosen way does not use is hidden, not dimmed, and comes back the moment one+ does."""config = self._config or default_config()+ settings = self._crossing_settings()+ machines = self._crossing_machines()+ chosen = self._chosen_machine()+ several = len(machines) > 1+ self._rebuild_machine_choice(machines if several else [])+ self.machine_choice.set_value(chosen)+ motion.set_shown(self.machine_row, several)+ name = dict(machines).get(chosen) if several else None+ name = name or "the other machine"+ held = ways.ways(settings, chosen)+ shortcut = "shortcut" in config.crossing_methods+ methods = held["methods"] + (["shortcut"] if shortcut else [])for value, box in self.way_boxes.items():- if box.isChecked() != (value in config.crossing_methods):+ if box.isChecked() != (value in methods):box.blockSignals(True)- box.setChecked(value in config.crossing_methods)+ box.setChecked(value in methods)box.blockSignals(False)- edge = config.mac_return_edge or "right"+ side = held["side"]+ self.edge_choice.set_value(side)+ self.edge_choice.set_names(f"Where {name} is")+ self.edge_heading.setText(f"Where {name} is")+ self.edge_note.setText(f"One border, walked both ways, so changing it here moves it on {name} too.")+ self.edge_unlearned.setText(pages_win.not_learned_edge(name))+ self.corner_choice.set_value(held["corner"])+ edge = side or "right"names = pages_win.part_names(edge)for part, button in self.part_buttons.items():button.setText(names[part])- button.setChecked(part in config.crossing_edge_parts)+ button.setChecked(part in held["parts"])self.parts_note.setText(- f"Crosses only along {pages_win.parts_phrase(edge, config.crossing_edge_parts)}; the rest of "+ f"Crosses only along {pages_win.parts_phrase(edge, held['parts'])}; the rest of ""it is a wall. Choose any, but at least one.")- shown = pages_win.crossing_rows(config.crossing_methods)+ # Resistance and the drag guard are this PC's own, there while any machine has a zone.+ own = {"dragging", "resistance"} & pages_win.crossing_rows(self._ways_in() | set(methods))+ shown = (pages_win.crossing_rows(methods) - {"dragging", "resistance"}) | ownfor key, row in self.crossing_rows.items():- motion.set_shown(row, key in shown)+ # Wayland shows no button held before the pointer meets the edge (wayland_crossing_note).+ motion.set_shown(row, key in shown and not (key == "dragging" and platform_parts.WAYLAND))motion.set_shown(self.resistance_module, "resistance" in shown)motion.set_shown(self.shortcut_module, "shortcut" in shown)key_name = TRIGGER_KEYS.get(config.trigger_key, config.trigger_key)- summary = pages_win.ways_summary(config.crossing_methods, config.mac_return_edge, config.crossing_edge_parts,- config.crossing_corner, key_name, config.trigger_style)+ summary = pages_win.ways_summary(methods, side, held["parts"], held["corner"], key_name, config.trigger_style,+ name, several)if summary != self.ways_summary.text():shot = motion.snapshot(self.ways_summary)self.ways_summary.setText(summary)motion.fade_from(self.ways_summary, shot)- motion.set_shown(self.edge_unlearned, not config.mac_return_edge)- self.arrangement_diagram.set_state(edge, config.crossing_methods, config.crossing_edge_parts,- config.crossing_corner, key_name, config.trigger_style)+ motion.set_shown(self.edge_unlearned, not side)+ for note, sentence in (+ (self.blocked_note, ways.blocked_sentence(settings, chosen, "this PC") if chosen else ""),+ (self.missing_note, ways.missing_sentence(settings, chosen, "this PC") if chosen else ""),+ (self.no_way_back_note, ways.no_way_back_sentence(settings, chosen) if chosen else "")):+ sentence = self._shown(sentence)+ if sentence != note.text():+ note.setText(sentence)+ motion.set_shown(note, bool(sentence))+ drawn = []+ for ident, label in machines or [("", "")]:+ found = ways.ways(settings, ident) if ident or machines else {"side": "", "methods": [], "parts": ["middle"],+ "corner": "top_left"}+ drawn.append(dict(found, key=ident, label=label, chosen=ident == chosen or not machines))+ self.arrangement_diagram.set_machines(drawn, key_name, config.trigger_style, shortcut)self.resistance_strip.set_edge(edge)def _set_arrangement(self, pc_edge: str) -> None:- """The edge of THIS PC that leads to the Mac -- one border, walked either way. Not an- ordinary save: both machines have to agree on it, so this end's change is timestamped- and sent over whichever link is up."""- if self._config is None or pc_edge == self._config.mac_return_edge:+ """The edge of THIS PC that leads to the chosen machine -- one border, walked either way. Not+ an ordinary change: both machines have to agree on it, so this end's change is stamped and+ sent to that machine over whichever link is up."""+ if ways.ways(self._crossing_settings(), self._chosen_machine())["side"] == pc_edge:return- self._config.mac_return_edge = pc_edge- self._config.arrangement_set_at = settings_sync.next_stamp(self._config.arrangement_set_at, time.time())- self._persist()- 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()+ self._write_ways(side=pc_edge)def _set_hold_full_screen(self, enabled: bool) -> None:if self._config is None:@@ -1079,29 +1232,32 @@ class WindowsApplication(QWidget):self.sender.update_config(self._config)def _set_corner(self, corner: str) -> None:- if self._config is None:- return- self._config.crossing_corner = corner- self._persist()- self.sender.update_config(self._config)- self._reflect_ways()+ self._write_ways(corner=corner)- def _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 _tell(self, peer: str) -> None:+ """This PC's side for `peer` as held, stamped as held, with whether a way leads there (WIRE.md+ section 8), over whichever link is up. Nothing while no side is set."""+ settings = self._crossing_settings()+ entry = next((item for item in settings["peers"] if item.get("id") == peer), None)+ if entry is None or entry.get("side") not in return_edge.EDGES or not entry.get("side_set_at"):+ return+ author = protocol.read_id(entry.get("side_by")) or protocol.read_id(self._config.machine_id)+ target = protocol.read_id(peer)+ if author is None or target is None:+ return+ self._send_to(target, protocol.arrangement_v6(entry["side"], entry["side_set_at"], author,+ way_back=ways.has_way(settings, peer)))- def _on_arrangement(self, peer: str, edge: str, set_at: int, by: str) -> None:+ def _on_arrangement(self, peer: str, edge: str, set_at: int, by: str, way_back=None) -> None:"""A peer changed the arrangement, over either link. `edge` is the edge of the PEER thatfaces 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."""+ side that makes two zones cover one stretch turns the peer's clashing zones off. `way_back`+ is kept whatever the side; a message that changed anything here is answered with this PC's+ own, and one that changed nothing is not, so two machines never answer in turn."""if self._config is None:returntry:- changed, notices = app_config.apply_arrangement(self.config_path, peer, edge, set_at, by)+ changed, notices = app_config.apply_arrangement(self.config_path, peer, edge, set_at, by, way_back)except (ConfigError, OSError):LOGGER.exception("An arrangement could not be saved")return@@ -1112,9 +1268,11 @@ class WindowsApplication(QWidget):self._pull_peer_fields()self.sender.refresh()self.server.peers_changed()+ self._tell(peer)def _pull_peer_fields(self) -> None:- """What links and arrangements wrote into the first peer, into the window's flat view."""+ """What links wrote into the first peer, into the window's flat view, and every machine's side+ and zones as links and arrangements left them, into the Crossing page."""if self._config is None:returntry:@@ -1125,14 +1283,14 @@ class WindowsApplication(QWidget):for name, value in learned.items():setattr(self._config, name, value)self.sender.update_config(self._config)- self.edge_choice.set_value(self._config.mac_return_edge)+ self._read_crossing()self._reflect_look()self._reflect_ways()def _resistance_module(self, current: Config) -> QWidget:module = widgets.Module("Resistance")self.resistance_strip = PushStrip()- self.resistance_strip.set_edge(current.mac_return_edge or "right")+ self.resistance_strip.set_edge("right")self.resistance_strip.set_value(current.crossing_resistance_px)module.body.addWidget(self.resistance_strip)row = QHBoxLayout()@@ -1177,9 +1335,9 @@ class WindowsApplication(QWidget):layout.addWidget(self._speed_module(current))def _speed_module(self, current: Config) -> QWidget:- """How the other machine's pointer feels on this PC: it sends what its own acceleration made of+ """How a driving machine's pointer feels on this PC: it sends what its own acceleration made ofthe hand's movement, and this PC's settings decide the rest."""- module = widgets.Module("The other machine's pointer here")+ module = widgets.Module("Another machine's pointer here")self.speed_sliders = {}self.speed_readouts = {}for key, name, value in (("pointer_speed", "Pointer speed", current.pointer_speed),@@ -1196,9 +1354,9 @@ class WindowsApplication(QWidget):module.body.addLayout(row)self.speed_sliders[key], self.speed_readouts[key] = slider, readoutmodule.body.addWidget(widgets.label(- "For the other machine's trackpad or mouse while it drives this PC.", "note", wrap=True+ "For the trackpad or mouse of whichever machine drives this PC.", "note", wrap=True))- self.reverse_scroll_switch = widgets.Switch("Reverse the other machine's scrolling")+ self.reverse_scroll_switch = widgets.Switch("Reverse scrolling from other machines")self.reverse_scroll_switch.setFont(theme.font(theme.TYPE["body"]))self.reverse_scroll_switch.setChecked(current.reverse_scroll)self.reverse_scroll_switch.toggled.connect(self._reverse_scroll_changed)@@ -1279,7 +1437,7 @@ class WindowsApplication(QWidget):"These keep working on this PC while its input is on another machine: a mouse's back button for ""this PC's browser, say, or a volume key for its speakers."if entries- else "Nothing yet. Every key and button goes to the other machine while it has input. Add one to keep "+ else "Nothing yet. Every key and button goes to the machine that has input. Add one to keep ""it here: a mouse's back button for this PC's browser, say, or a volume key for its speakers.")self.ignored_note.setText(text)@@ -1318,9 +1476,15 @@ class WindowsApplication(QWidget):module = widgets.Module("Shortcut")module.body.addWidget(widgets.label(- "Use this key to send input to the other machine, and to bring it back.", "note", wrap=True+ "Use this key to send input to another machine, and to bring it back.", "note", wrap=True))+ self.wayland_shortcut_note = widgets.label(+ "On Wayland the shortcut only brings input back: the desktop lets input go to another machine only "+ "when the pointer pushes through an edge, and keys on the Stays on this PC list cannot stay here "+ "while input is away.", "note", wrap=True)+ self.wayland_shortcut_note.setVisible(platform_parts.WAYLAND)+ module.body.addWidget(self.wayland_shortcut_note)self.trigger_recorder = widgets.InputRecorder(TRIGGER_KEYS.get(current.trigger_key, current.trigger_key),self._record_trigger,@@ -1394,7 +1558,7 @@ class WindowsApplication(QWidget):def _update_style_hint(self, style: str) -> None:text = (- "Input is on the other machine for as long as the key is held."+ "Input is on another machine for as long as the key is held."if style == "hold"else "Tap twice to switch; tap twice again to come back.")@@ -1449,7 +1613,7 @@ class WindowsApplication(QWidget):module.body.addWidget(self._own_note())module.body.addWidget(widgets.label(- "Lights this PC as you push toward the other machine. Switched off, crossing still works. "+ "Lights this PC as you push toward another machine. Switched off, crossing still works. ""Each machine sets how its own edge looks.","note",wrap=True,@@ -1475,7 +1639,6 @@ class WindowsApplication(QWidget):def _edge_look_module(self, current: Config) -> QWidget:module = widgets.Module("Style and colour")- edge = current.mac_return_edge or "right"colours = app_config.palette_colours(current.glow_colour)# Which animation the tiles below choose. Not saved: it only says which one is being worked on.self.design_mode_choice = widgets.Choice(@@ -1587,9 +1750,9 @@ class WindowsApplication(QWidget):self.design_mode_choice.set_value("crossing")switching = landing and self.design_mode_choice.value == "switch"style = self.glow_style_choice.value- edge = (self._config.mac_return_edge if self._config is not None else "") or "right"+ edge = ways.ways(self._crossing_settings(), self._chosen_machine())["side"] or "right"colour = self.glow_colour_choice.value or "signal"- methods = self._config.crossing_methods if self._config is not None else ()+ methods = sorted(self._ways_in())if not self._place_chosen:# Until a place is picked here, the preview opens where the pointer actually crosses.self.effect_method_choice.set_value(pages_win.preview_place(methods))@@ -1630,7 +1793,10 @@ class WindowsApplication(QWidget):else effects.CLASSIC.get(style)) or effects.CLASSIC["glow"]self.effect_name.setText(f"{fx.name}, {fx.intensity}")self.effect_note.setText(- "The effects stopped working and are off until Beamer restarts, so crossings show Glow in "+ "On Wayland the desktop does not let Beamer draw at the edges of the screen, so crossings show no "+ "effect on this machine. The other machines still show theirs."+ if platform_parts.WAYLAND+ else "The effects stopped working and are off until Beamer restarts, so crossings show Glow in ""the same colours. The log says why."if self._effects_failedelse f"{fx.blurb} It plays around the pointer when the shortcut or a menu brings input to this PC."@@ -1672,7 +1838,7 @@ class WindowsApplication(QWidget):def _persist(self) -> bool:if self._config is None:return False- # A change to a shared setting while Same on both machines is on is stamped here, where+ # A change to a shared setting while Same on all machines is on is stamped here, where# every page's changes are saved, and sent once saved.fields = self._same_fields()shared = self._same_seen is not None and fields != self._same_seen and self._config.same_on_both@@ -1726,7 +1892,7 @@ class WindowsApplication(QWidget):return Nonename = settings.get("name") or pairing.machine_name()return PairingService(- name, identity, "windows", self._announced_port, self.book.peers, self._store_peer,+ name, identity, OWN_PLATFORM, self._announced_port, self.book.peers, self._store_peer,on_paired=self.bridge.paired.emit, logger=LOGGER,)@@ -1737,8 +1903,8 @@ class WindowsApplication(QWidget):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).+ # `replaced` was read before this lock: it may have changed or gone since+ # (WIRE.md section 6, item 4).held = next((peer for peer in settings["peers"] if peer.get("token") == replaced.get("token")), None)if held is None or held.get("id") != replaced.get("id") or held.get("linked") != replaced.get("linked"):raise ConfigError("the machine being replaced changed while pairing")@@ -1773,18 +1939,22 @@ class WindowsApplication(QWidget):def _refresh_peers(self) -> None:try:- peers = self.book.peers()+ peers, zones = self.book.peers(), self.book.zones()except (ConfigError, OSError):LOGGER.exception("The peers could not be read")- peers = []- self._peer_entries = peers+ peers, zones = [], []+ self._peer_entries, self._zone_entries = peers, zonesself.machines.set_peers(self._peer_items(peers))if hasattr(self, "arrangement_diagram"):self._reflect_other_name()+ # A machine paired, removed or renamed, or a side or zone a link wrote: the Crossing page follows.+ seen = repr((peers, zones, self._hide_addresses()))+ if seen != self._crossing_seen:+ self._crossing_seen = seen+ self._reflect_ways()def _reflect_other_name(self) -> None:name = self._machines_name() if len(self._peer_entries) == 1 else ""- self.arrangement_diagram.set_other_name(name)self.resistance_strip.set_other_name(name)def _refresh_peer_states(self) -> None:@@ -1792,10 +1962,10 @@ class WindowsApplication(QWidget):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)+ return any(entry.get("send") and protocol.linkable(entry) 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 ""+ return self._labels_by_id.get(peer, "another machine") if peer is not None else ""def _edit_peer(self, token: str, **fields) -> bool:try:@@ -1866,6 +2036,28 @@ class WindowsApplication(QWidget):if action.isChecked() != on:action.setChecked(on)+ def _refresh_tray_machines(self) -> None:+ """With more than one machine to send to, the tray has "Send input to" for each, and the toggle+ is only there to bring input back; with one, the toggle names it, as it always did."""+ labels = peerlist.labels(self._peer_entries)+ sendable = [(entry["id"], f"Send input to {self._shown(labels[entry['token']])}") for entry in self._peer_entries+ if entry.get("send") and entry.get("port") and protocol.read_id(entry.get("id")) is not None]+ items = sendable if len(sendable) > 1 else []+ if items != [(ident, action.text()) for ident, action in self.machine_actions.items()]:+ for action in self.machine_actions.values():+ self.tray_menu.removeAction(action)+ action.deleteLater()+ self.machine_actions = {}+ for ident, text in items:+ action = QAction(text, self.tray_menu)+ action.triggered.connect(lambda _checked=False, peer=protocol.read_id(ident): self.sender.go(peer))+ self.tray_menu.insertAction(self.pause_action, action)+ self.machine_actions[ident] = action+ on = self.sender.owner+ for ident, action in self.machine_actions.items():+ action.setEnabled(protocol.read_id(ident) != on)+ self.redirect_action.setVisible(not self.machine_actions or self.sender.redirecting)+def _after_peers_edit(self) -> None:"""Whatever changed the peers list: the flat view and the links follow, and the machines are listed again."""if self._config is not None and not self._paired:@@ -1977,7 +2169,7 @@ class WindowsApplication(QWidget):if service is None:returnif self._pairing_open:- self.sheet.set_machines(service.machines())+ self.sheet.set_machines(service.machines(), self._shown)code = service.codeif code is not None:hide = self._hide_addresses()@@ -2336,6 +2528,7 @@ class WindowsApplication(QWidget):self.open_action.triggered.connect(self.show_window)self.status_action = menu.addAction(self._title())self.status_action.setEnabled(False)+ self.tray_menu = menuself.redirect_action = menu.addAction("Send input across")self.redirect_action.triggered.connect(self.toggle_redirect)self.pause_action = menu.addAction("Pause crossing")@@ -2400,8 +2593,6 @@ class WindowsApplication(QWidget):self.double_tap_readout.setText(f"{config.double_tap_ms} ms")self.resistance_strip.set_value(config.crossing_resistance_px)motion.set_shown(self.double_tap_row, config.trigger_style != "hold")- self.corner_choice.set_value(config.crossing_corner)- self.edge_choice.set_value(config.mac_return_edge)self.trigger_recorder.set_title(TRIGGER_KEYS.get(config.trigger_key, config.trigger_key))self.trigger_style_choice.set_value(config.trigger_style)self._update_style_hint(config.trigger_style)@@ -2435,12 +2626,9 @@ class WindowsApplication(QWidget):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))- return- self.update_checker.start()+ if not sys.platform.startswith("linux"):+ # No release has a Linux build yet, so a newer one is nothing this machine can install.+ self.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# it ask, and a click on Allow there writes rules for every network, public ones too,@@ -2468,6 +2656,11 @@ class WindowsApplication(QWidget):if self._config is not None and self._paired:self._start_receiver(self._config)self._start_sending(self._config)+ # Wayland's remote control session, opened now so the desktop asks while someone is at+ # this machine; the clipboard rides on it.+ start_injector = getattr(platform_parts.injector, "start", None)+ if start_injector is not None:+ start_injector()# 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.self._check_firewall()@@ -2476,8 +2669,6 @@ class WindowsApplication(QWidget):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:- returnif self.server.listening and self._receiver_port != config.port:self.server.stop()self._receiver_port = config.port@@ -2488,7 +2679,7 @@ class WindowsApplication(QWidget):when 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 self._any_send() or platform_parts.NOT_YET:+ if not self._any_send():returnself._configure_trigger(config)try:@@ -2499,6 +2690,15 @@ class WindowsApplication(QWidget):returnself.sender.start(config)+ def _capture_stopped(self, error: BaseException) -> None:+ """On the capture thread, when capture ended on its own (the X server gone, a stalled+ thread's connection ended, the desktop refusing or ending a portal session): nothing holds+ this machine's keyboard any more, so input comes home rather than staying on a peer no key+ can reach. A portal's error carries the whole sentence."""+ self.sender.set_redirecting(False)+ sentence = getattr(error, "sentence", None) or f"This machine's keyboard and mouse are no longer captured: {error}"+ self.bridge.alert.emit("Beamer", sentence)+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 neutralcall. True when the event belongs to a peer and Windows must not see it."""@@ -2632,6 +2832,9 @@ class WindowsApplication(QWidget):self.pairing.stop()self.server.stop()self._stop_sending()+ stop_injector = getattr(platform_parts.injector, "stop", None)+ if stop_injector is not None:+ stop_injector()self._hide_crossing()self.tray.hide()QApplication.quit()@@ -2674,7 +2877,7 @@ class WindowsApplication(QWidget):return self.effectsdef _on_pressure(self, edge: str, pressure: float, crossed: bool, part=None) -> None:- if self._closing or self._config is None or not self._config.edge_glow:+ if self._closing or self._config is None or not self._config.edge_glow or platform_parts.WAYLAND:returnoverlay = self._effect_overlay()if overlay is not None:@@ -2691,6 +2894,8 @@ class WindowsApplication(QWidget):def _on_arrival(self, method: str, edge: str, x: float, y: float) -> None:"""A crossing landed the pointer on `edge`, or with method "switch" input came here by aswitch and the pointer is wherever it was left."""+ if platform_parts.WAYLAND:+ returnif method == "switch":overlay = self._switch_overlay()if overlay is not None:@@ -2820,6 +3025,7 @@ class WindowsApplication(QWidget):else:self._refresh_peer_states()self._refresh_tray_directions()+ self._refresh_tray_machines()self._refresh_pairing()def _title(self) -> str:@@ -2842,9 +3048,21 @@ def _windows_kernel32():kernel32.CloseHandle.argtypes = [ctypes.c_void_p]kernel32.GetCurrentProcess.restype = ctypes.c_void_pkernel32.SetPriorityClass.argtypes = [ctypes.c_void_p, ctypes.c_ulong]+ kernel32.SetProcessInformation.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_ulong]return kernel32+def _stay_unthrottled(kernel32) -> None:+ """Opts out of Windows' power throttling (EcoQoS), the counterpart of the Mac's App Nap+ activity. Beamer sits in the tray with no window in front, which is what Windows' heuristics+ throttle, and a throttled Beamer sends its pings and acks late enough for the far side to give+ the link up. ProcessPowerThrottling (4) with execution speed in the control mask and not in+ the state mask: never throttled, whatever the power plan."""+ state = (ctypes.c_uint32 * 3)(1, 0x1, 0) # Version, ControlMask, StateMask+ if not kernel32.SetProcessInformation(kernel32.GetCurrentProcess(), 4, ctypes.byref(state), ctypes.sizeof(state)):+ LOGGER.warning("Could not opt Beamer out of power throttling: %s", ctypes.WinError(ctypes.get_last_error()))++def _claim_instance():"""The single-instance lock: the function that gives it back, or None when another Beameralready holds it."""@@ -2887,6 +3105,7 @@ def main() -> None:kernel32 = _windows_kernel32()if not kernel32.SetPriorityClass(kernel32.GetCurrentProcess(), 0x8000): # ABOVE_NORMAL_PRIORITY_CLASSLOGGER.warning("Could not raise Beamer's priority: %s", ctypes.WinError(ctypes.get_last_error()))+ _stay_unthrottled(kernel32)try:app = QApplication(sys.argv)app.setApplicationName("Beamer")diff --git a/win_app/libei.py b/win_app/libei.pynew file mode 100644index 0000000..4867638--- /dev/null+++ b/win_app/libei.py@@ -0,0 +1,368 @@+"""Beamer's own small ctypes layer over libei, the input emulation library the Wayland portals hand+input over: a receiver for InputCapture (this machine's own keys and pointer while they are away)+and a sender for RemoteDesktop (a peer's input played here). Only the calls Beamer makes are bound;+Peter Hutterer's snegg is the reference for the shapes, not a dependency (its API is not stable and+it has no release).++`Context.events()` turns libei's events into plain tuples, so the capture and injection modules+read them without ctypes and their tests feed tuples of their own:++ ("connect",) ("disconnect",)+ ("seat",) a seat, already bound to every capability it has+ ("device_added", device) ("device_removed", device)+ ("device_resumed", device) ("device_paused", device)+ ("start", device, sequence) ("stop", device)+ ("frame", device, time_us)+ ("motion", device, dx, dy)+ ("absolute", device, x, y)+ ("button", device, code, down) an evdev button code (BTN_LEFT is 0x110)+ ("scroll", device, dx, dy) in logical pixels+ ("scroll_discrete", device, dx, dy) in 120ths of a notch, as libei counts them+ ("scroll_stop", device)+ ("key", device, code, down) an evdev key code+ ("modifiers", device, depressed, latched, locked, group)++A device is a `Device`, which holds its own reference and says its name, capabilities, regions and+keymap; a removed one lets go of its reference at the next events(), once its removal has been+read. A seat is bound here, while its event still holds it, so no seat pointer leaves this module.+libei is reached only when a Context is made, so this module imports anywhere."""++import ctypes+import ctypes.util+import logging+import os+from typing import List, Optional, Tuple++LOGGER = logging.getLogger(__name__)++CAP_POINTER = 1 << 0+CAP_POINTER_ABSOLUTE = 1 << 1+CAP_KEYBOARD = 1 << 2+CAP_TOUCH = 1 << 3+CAP_SCROLL = 1 << 4+CAP_BUTTON = 1 << 5+CAP_TEXT = 1 << 6+CAPS = (CAP_POINTER, CAP_POINTER_ABSOLUTE, CAP_KEYBOARD, CAP_TOUCH, CAP_SCROLL, CAP_BUTTON)++KEYMAP_XKB = 1++EV_CONNECT = 1+EV_DISCONNECT = 2+EV_SEAT_ADDED = 3+EV_SEAT_REMOVED = 4+EV_DEVICE_ADDED = 5+EV_DEVICE_REMOVED = 6+EV_DEVICE_PAUSED = 7+EV_DEVICE_RESUMED = 8+EV_KEYBOARD_MODIFIERS = 9+EV_FRAME = 100+EV_START_EMULATING = 200+EV_STOP_EMULATING = 201+EV_POINTER_MOTION = 300+EV_POINTER_MOTION_ABSOLUTE = 400+EV_BUTTON = 500+EV_SCROLL_DELTA = 600+EV_SCROLL_STOP = 601+EV_SCROLL_CANCEL = 602+EV_SCROLL_DISCRETE = 603+EV_KEYBOARD_KEY = 700++_lib = None+++def _load():+ global _lib+ if _lib is not None:+ return _lib+ path = ctypes.util.find_library("ei") or "libei.so.1"+ try:+ lib = ctypes.CDLL(path)+ except OSError as exc:+ raise RuntimeError("libei is not installed; Beamer needs it to capture and play input on Wayland") from exc+ p, u32, i32, dbl, b = ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int32, ctypes.c_double, ctypes.c_bool+ signatures = {+ "ei_new_sender": (p, [p]),+ "ei_new_receiver": (p, [p]),+ "ei_unref": (p, [p]),+ "ei_configure_name": (None, [p, ctypes.c_char_p]),+ "ei_setup_backend_fd": (ctypes.c_int, [p, ctypes.c_int]),+ "ei_get_fd": (ctypes.c_int, [p]),+ "ei_dispatch": (None, [p]),+ "ei_get_event": (p, [p]),+ "ei_now": (ctypes.c_uint64, [p]),+ "ei_disconnect": (None, [p]),+ "ei_event_unref": (p, [p]),+ "ei_event_get_type": (ctypes.c_int, [p]),+ "ei_event_get_device": (p, [p]),+ "ei_event_get_seat": (p, [p]),+ "ei_event_get_time": (ctypes.c_uint64, [p]),+ "ei_seat_ref": (p, [p]),+ "ei_seat_unref": (p, [p]),+ "ei_seat_has_capability": (b, [p, ctypes.c_int]),+ "ei_device_ref": (p, [p]),+ "ei_device_unref": (p, [p]),+ "ei_device_get_name": (ctypes.c_char_p, [p]),+ "ei_device_has_capability": (b, [p, ctypes.c_int]),+ "ei_device_get_region": (p, [p, ctypes.c_size_t]),+ "ei_device_keyboard_get_keymap": (p, [p]),+ "ei_device_start_emulating": (None, [p, u32]),+ "ei_device_stop_emulating": (None, [p]),+ "ei_device_frame": (None, [p, ctypes.c_uint64]),+ "ei_device_pointer_motion": (None, [p, dbl, dbl]),+ "ei_device_pointer_motion_absolute": (None, [p, dbl, dbl]),+ "ei_device_button_button": (None, [p, u32, b]),+ "ei_device_scroll_delta": (None, [p, dbl, dbl]),+ "ei_device_scroll_discrete": (None, [p, i32, i32]),+ "ei_device_scroll_stop": (None, [p, b, b]),+ "ei_device_keyboard_key": (None, [p, u32, b]),+ "ei_region_get_x": (u32, [p]),+ "ei_region_get_y": (u32, [p]),+ "ei_region_get_width": (u32, [p]),+ "ei_region_get_height": (u32, [p]),+ "ei_region_get_physical_scale": (dbl, [p]),+ "ei_keymap_get_size": (ctypes.c_size_t, [p]),+ "ei_keymap_get_type": (ctypes.c_int, [p]),+ "ei_keymap_get_fd": (ctypes.c_int, [p]),+ "ei_event_emulating_get_sequence": (u32, [p]),+ "ei_event_keyboard_get_xkb_mods_depressed": (u32, [p]),+ "ei_event_keyboard_get_xkb_mods_latched": (u32, [p]),+ "ei_event_keyboard_get_xkb_mods_locked": (u32, [p]),+ "ei_event_keyboard_get_xkb_group": (u32, [p]),+ "ei_event_pointer_get_dx": (dbl, [p]),+ "ei_event_pointer_get_dy": (dbl, [p]),+ "ei_event_pointer_get_absolute_x": (dbl, [p]),+ "ei_event_pointer_get_absolute_y": (dbl, [p]),+ "ei_event_button_get_button": (u32, [p]),+ "ei_event_button_get_is_press": (b, [p]),+ "ei_event_scroll_get_dx": (dbl, [p]),+ "ei_event_scroll_get_dy": (dbl, [p]),+ "ei_event_scroll_get_discrete_dx": (i32, [p]),+ "ei_event_scroll_get_discrete_dy": (i32, [p]),+ "ei_event_keyboard_get_key": (u32, [p]),+ "ei_event_keyboard_get_key_is_press": (b, [p]),+ }+ for name, (restype, argtypes) in signatures.items():+ function = getattr(lib, name)+ function.restype = restype+ function.argtypes = argtypes+ # Variadic, ended by a zero: its arguments are given types at the call, never in argtypes.+ lib.ei_seat_bind_capabilities.restype = None+ _lib = lib+ return lib+++class Device:+ """A libei device, holding a reference of its own until close()."""++ def __init__(self, lib, pointer: int) -> None:+ self._lib = lib+ self.pointer = lib.ei_device_ref(pointer)+ raw = lib.ei_device_get_name(self.pointer)+ self.name = raw.decode("utf-8", "replace") if raw else ""+ self.caps = {cap for cap in CAPS if lib.ei_device_has_capability(self.pointer, cap)}++ def has(self, cap: int) -> bool:+ return cap in self.caps++ def regions(self) -> List[Tuple[int, int, int, int, float]]:+ """(x, y, width, height, scale) for each region of a virtual device, in the compositor's+ logical pixels: where an absolute position lands."""+ found = []+ index = 0+ while True:+ region = self._lib.ei_device_get_region(self.pointer, index)+ if not region:+ return found+ found.append((self._lib.ei_region_get_x(region), self._lib.ei_region_get_y(region),+ self._lib.ei_region_get_width(region), self._lib.ei_region_get_height(region),+ self._lib.ei_region_get_physical_scale(region)))+ index += 1++ def keymap(self) -> Optional[str]:+ """The XKB keymap the compositor gave this keyboard, as text, or None. The fd is libei's and+ stays open; it is read with pread so its offset is never moved."""+ keymap = self._lib.ei_device_keyboard_get_keymap(self.pointer)+ if not keymap or self._lib.ei_keymap_get_type(keymap) != KEYMAP_XKB:+ return None+ size = self._lib.ei_keymap_get_size(keymap)+ fd = self._lib.ei_keymap_get_fd(keymap)+ if fd < 0 or size <= 0:+ return None+ data = os.pread(fd, size, 0)+ return data.rstrip(b"\0").decode("utf-8", "replace")++ def close(self) -> None:+ if self.pointer:+ self._lib.ei_device_unref(self.pointer)+ self.pointer = None+++class Context:+ """One libei connection over an fd a portal's ConnectToEIS gave. `sender` False for capture.+ Not thread-safe: one thread dispatches and sends."""++ def __init__(self, fd: int, sender: bool, name: str = "Beamer") -> None:+ lib = self._lib = _load()+ self.sender = sender+ self._ei = lib.ei_new_sender(None) if sender else lib.ei_new_receiver(None)+ if not self._ei:+ raise RuntimeError("libei could not make a context")+ lib.ei_configure_name(self._ei, name.encode())+ result = lib.ei_setup_backend_fd(self._ei, fd)+ if result != 0:+ lib.ei_unref(self._ei)+ self._ei = None+ raise OSError(-result, f"libei refused the portal's connection: {os.strerror(-result)}")+ self._devices = {}+ self._removed = []++ def fileno(self) -> int:+ return self._lib.ei_get_fd(self._ei)++ def now(self) -> int:+ return self._lib.ei_now(self._ei)++ def _bind(self, seat: int) -> None:+ """Ask the seat for every capability it has: a receiver gets whatever the compositor+ captures, a sender every device it may emulate."""+ lib = self._lib+ caps = [ctypes.c_int(cap) for cap in CAPS if lib.ei_seat_has_capability(seat, cap)]+ lib.ei_seat_bind_capabilities(ctypes.c_void_p(seat), *caps, ctypes.c_void_p(None))++ def _device(self, pointer: int) -> Device:+ device = self._devices.get(pointer)+ if device is None:+ device = self._devices[pointer] = Device(self._lib, pointer)+ return device++ def events(self) -> list:+ """Dispatch what the fd holds and return every event as a tuple (see the module's)."""+ lib = self._lib+ for device in self._removed:+ device.close()+ self._removed = []+ lib.ei_dispatch(self._ei)+ found = []+ while True:+ event = lib.ei_get_event(self._ei)+ if not event:+ return found+ try:+ item = self._read(event)+ finally:+ lib.ei_event_unref(event)+ if item is not None:+ found.append(item)++ def _read(self, event) -> Optional[tuple]:+ lib = self._lib+ kind = lib.ei_event_get_type(event)+ if kind == EV_CONNECT:+ return ("connect",)+ if kind == EV_DISCONNECT:+ return ("disconnect",)+ if kind == EV_SEAT_ADDED:+ self._bind(lib.ei_event_get_seat(event))+ return ("seat",)+ if kind == EV_SEAT_REMOVED:+ return None+ pointer = lib.ei_event_get_device(event)+ if not pointer:+ return None+ device = self._device(pointer)+ if kind == EV_DEVICE_ADDED:+ return ("device_added", device)+ if kind == EV_DEVICE_REMOVED:+ self._removed.append(self._devices.pop(pointer, device))+ return ("device_removed", device)+ if kind == EV_DEVICE_RESUMED:+ return ("device_resumed", device)+ if kind == EV_DEVICE_PAUSED:+ return ("device_paused", device)+ if kind == EV_START_EMULATING:+ return ("start", device, lib.ei_event_emulating_get_sequence(event))+ if kind == EV_STOP_EMULATING:+ return ("stop", device)+ if kind == EV_FRAME:+ return ("frame", device, lib.ei_event_get_time(event))+ if kind == EV_POINTER_MOTION:+ return ("motion", device, lib.ei_event_pointer_get_dx(event), lib.ei_event_pointer_get_dy(event))+ if kind == EV_POINTER_MOTION_ABSOLUTE:+ return ("absolute", device, lib.ei_event_pointer_get_absolute_x(event), lib.ei_event_pointer_get_absolute_y(event))+ if kind == EV_BUTTON:+ return ("button", device, lib.ei_event_button_get_button(event), bool(lib.ei_event_button_get_is_press(event)))+ if kind == EV_SCROLL_DELTA:+ return ("scroll", device, lib.ei_event_scroll_get_dx(event), lib.ei_event_scroll_get_dy(event))+ if kind == EV_SCROLL_DISCRETE:+ return ("scroll_discrete", device, lib.ei_event_scroll_get_discrete_dx(event), lib.ei_event_scroll_get_discrete_dy(event))+ if kind in (EV_SCROLL_STOP, EV_SCROLL_CANCEL):+ return ("scroll_stop", device)+ if kind == EV_KEYBOARD_KEY:+ return ("key", device, lib.ei_event_keyboard_get_key(event), bool(lib.ei_event_keyboard_get_key_is_press(event)))+ if kind == EV_KEYBOARD_MODIFIERS:+ return ("modifiers", device, lib.ei_event_keyboard_get_xkb_mods_depressed(event),+ lib.ei_event_keyboard_get_xkb_mods_latched(event), lib.ei_event_keyboard_get_xkb_mods_locked(event),+ lib.ei_event_keyboard_get_xkb_group(event))+ return None++ # Sending. A device the desktop removed has let go of its reference; sending on it does nothing.++ def start(self, device: Device, sequence: int) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_start_emulating(device.pointer, sequence)++ def stop(self, device: Device) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_stop_emulating(device.pointer)++ def frame(self, device: Device) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_frame(device.pointer, self.now())++ def motion(self, device: Device, dx: float, dy: float) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_pointer_motion(device.pointer, dx, dy)++ def absolute(self, device: Device, x: float, y: float) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_pointer_motion_absolute(device.pointer, x, y)++ def button(self, device: Device, code: int, down: bool) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_button_button(device.pointer, code, down)++ def scroll(self, device: Device, dx: float, dy: float) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_scroll_delta(device.pointer, dx, dy)++ def scroll_discrete(self, device: Device, dx: int, dy: int) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_scroll_discrete(device.pointer, dx, dy)++ def scroll_stop(self, device: Device) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_scroll_stop(device.pointer, True, True)++ def key(self, device: Device, code: int, down: bool) -> None:+ if not device.pointer:+ return+ self._lib.ei_device_keyboard_key(device.pointer, code, down)++ def close(self) -> None:+ if self._ei:+ for device in list(self._devices.values()) + self._removed:+ device.close()+ self._devices.clear()+ self._removed = []+ self._lib.ei_disconnect(self._ei)+ self._lib.ei_unref(self._ei)+ self._ei = Nonediff --git a/win_app/linux_stand_ins.py b/win_app/linux_stand_ins.pyindex 6de412f..9a40ad3 100644--- a/win_app/linux_stand_ins.py+++ b/win_app/linux_stand_ins.py@@ -1,96 +1,17 @@-"""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.+"""The OS parts Linux has no back end for, on X11 and Wayland alike: the firewall check and the+lock screen. Each answers as a machine that has nothing and does nothing, mirroring only the names+the shell reaches through platform_parts, with the Windows module's signatures."""-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 loggingfrom dataclasses import dataclassfrom types import SimpleNamespacefrom 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:diff --git a/win_app/machines_win.py b/win_app/machines_win.pyindex 4b2b89a..fdff7c0 100644--- a/win_app/machines_win.py+++ b/win_app/machines_win.py@@ -21,7 +21,7 @@ from PySide6.QtWidgets import (import peers_viewimport themeimport widgets-from core import pairing+from core import pairing, peerlistKEEP_NOTE = "It stays paired on that machine until you remove this one there too."EMPTY = "No machines paired yet."@@ -344,12 +344,16 @@ class PairingSheet(widgets.Module):# The requester half.- def set_machines(self, machines: list) -> None:+ def set_machines(self, machines: list, shown: Callable[[str], str] = lambda text: text) -> None:"""What discovery hears: dicts with name, address, platform and pairing, and `pair_id` while acode 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."""+ is listed too, as Older Beamer, so it is not mistaken for missing. A machine heard on two+ interfaces is two rows of one name, so where names are shared each row says its address, as+ `shown` (the window's Hide addresses) lets it."""listed = [item for item in machines if item.get("pair_id") or item.get("pairing") != pairing.PAIRING_V3]- key = tuple((item["address"], item["name"], item.get("platform"), item.get("pairing"), item.get("pair_id")) for item in listed)+ wheres = [shown(item["address"]) if shared else "" for item, shared in zip(listed, peerlist.sharing_a_name(listed))]+ key = tuple((item["address"], item["name"], item.get("platform"), item.get("pairing"), item.get("pair_id"), where)+ for item, where in zip(listed, wheres))if key == self._listed:returnself._listed = key@@ -360,9 +364,10 @@ class PairingSheet(widgets.Module):self.heard_layout.removeWidget(button)button.hide()button.deleteLater()- for item in listed:+ for item, where in zip(listed, wheres):version = item.get("pairing") == pairing.PAIRING_V3- text = f"{item['name']} · {peers_view.platform_name(item)} · " + ("showing a code" if version else OLDER)+ parts = (item["name"], peers_view.platform_name(item), where, "showing a code" if version else OLDER)+ text = " · ".join(part for part in parts if part)button = _button(text, "choice")button.setCheckable(True)button.setMinimumHeight(widgets.MIN_TARGET)diff --git a/win_app/pages_win.py b/win_app/pages_win.pyindex a3aafb8..7db4599 100644--- a/win_app/pages_win.py+++ b/win_app/pages_win.py@@ -8,6 +8,7 @@ from __future__ import annotationsimport refrom core import effects+from core import peerlist# (key, name, what the page is for), in sidebar order, which is setup order; Ctrl+1 is the first.PAGES = (@@ -15,28 +16,29 @@ PAGES = ("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 the other machine, and how hard the edge "+ "Choose how the pointer or a key moves input to another machine, and how hard the edge ""pushes back first."),("keyboard", "Keyboard",- "How this PC's Ctrl and Windows keys arrive on the other machine, the keys and buttons that stay "- "here, and how fast the other machine's pointer moves here."),+ "How this PC's Ctrl and Windows keys arrive on another machine, the keys and buttons that stay "+ "here, and how fast another machine's pointer moves here."),("design", "Design",- "How crossing looks on this PC: the light as you push toward the other machine, and where the "+ "How crossing looks on this PC: the light as you push toward another machine, and where the ""pointer lands."),("connection", "Connection","Whether Windows Firewall lets your other machines in, this PC's address, port and shared token, "- "and the other machine's IP address, which pairing learns."),+ "and each paired machine's IP address, which pairing learns."),)KEYS = tuple(page[0] for page in PAGES)-# Under the purpose on the pages whose settings are this PC's alone, so nobody looks for the other+# Under the purpose on the pages whose settings are this PC's alone, so nobody looks for another# machine's on the PC: each app sets only its own machine.SCOPE = {- "crossing": "For this PC only; the other machine keeps its own. Only which side the other machine is on is shared. This PC's "- "resistance is also what its pointer meets at the other machine's edge on the way back.",- "design": "For this PC's screen only; the other machine keeps its own.",- "keyboard": "For this PC's keyboard only; the other machine keeps its own.",+ "crossing": "For this PC only; every other machine keeps its own. Only which side a machine is on is shared, "+ "with that machine. This PC's resistance is also what its pointer meets at another machine's edge "+ "on the way back.",+ "design": "For this PC's screen only; every other machine keeps its own.",+ "keyboard": "For this PC's keyboard only; every other machine keeps its own.",}-# With Same on both machines on, under each row of the shared pages that stays this PC's own.+# With Same on all machines on, under each row of the shared pages that stays this PC's own.OWN_ROW = "This PC only."# The window's footer; the first sentence goes on Connection, whose changes wait for its button.FOOTER_APPLY = "Changes apply as you make them."@@ -173,7 +175,16 @@ def toggle_part(parts, part, on) -> list:return [candidate for candidate in ("start", "middle", "end") if candidate in chosen]-NOT_LEARNED_EDGE = "Not learned yet: choose a side here or on the other machine."+def not_learned_edge(name: str = "the other machine") -> str:+ """Under Where it is, while this PC holds no side for the machine named."""+ return f"Not learned yet: choose a side here or on {name}."+++def crossing_machines(peers: list) -> list:+ """(id, label) for every paired machine a zone can lead to, in the list's order: never a phone,+ which is never dialled (WIRE.md section 5). The entry migrated from 1.4.x has the id ""."""+ labels = peerlist.labels(peers)+ return [(entry.get("id") or "", labels[entry["token"]]) for entry in peers if entry.get("port") != 0]def crossing_state_sentence(paired, heard, sending, connected, armed, paused, full_screen_app, name="the other machine") -> str:@@ -256,10 +267,19 @@ def trigger_phrase(key_name: str, style: str) -> str:return f"{key_name}, {'held' if style == 'hold' else 'twice'}"-def ways_summary(methods, edge, parts, corner, key_name, style) -> str:- """The Ways in module's first line: every way input leaves for the Mac, in one sentence."""+SHORTCUT_SEVERAL = "The shortcut takes input to the machine it was last on."+++def _joined(items) -> str:+ return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]+++def ways_summary(methods, edge, parts, corner, key_name, style, name="the other machine", several=False) -> str:+ """The Ways in module's first line: every way input leaves for the machine `name`, in one+ sentence. With `several` machines paired the shortcut is not this one's, so it gets a sentence of+ its own."""if not edge:- return "Nothing moves input to the other machine until this PC knows which side it is on."+ return f"Nothing moves input to {name} until this PC knows which side it is on."methods = set(methods)ways = []if "edge" in methods:@@ -268,17 +288,24 @@ def ways_summary(methods, edge, parts, corner, key_name, style) -> str:ways.append(f"push through {parts_phrase(edge, parts)}")if "corner" in methods:ways.append(f"push diagonally into the {CORNER_NAMES.get(corner, corner)} corner")- if "shortcut" in methods:+ shortcut = "shortcut" in methods+ if shortcut and not several:ways.append(f"hold {key_name}" if style == "hold" else f"press {key_name} twice")+ after = f" {SHORTCUT_SEVERAL}" if shortcut and several else ""+ if not ways and several:+ return f"No edge or corner leads to {name} yet: choose one below.{after}"if not ways:- return "Nothing moves input to the other machine: choose at least one way below."+ return f"Nothing moves input to {name}: choose at least one way below."joined = ways[0] if len(ways) == 1 else ", ".join(ways[:-1]) + " or " + ways[-1]- return f"Input moves to the other machine when you {joined}."+ return f"Input moves to {name} when you {joined}.{after}"-# The arrangement diagram. Each side of this PC has an angle, and the Mac's screen travels round+# The arrangement diagram. Each side of this PC has an angle, and a machine's screen travels round# this PC's between them: through a corner position, never across it.SIDE_ANGLE = {"right": 0.0, "top": 90.0, "left": 180.0, "bottom": 270.0}+SIDE_WORDS = {"right": "to the right of this PC", "left": "to the left of this PC", "top": "above this PC",+ "bottom": "below this PC"}+PART_ORDER = ("start", "middle", "end")def turn_to(angle: float, side: str) -> float:@@ -305,17 +332,99 @@ def square_point(angle: float) -> tuple:return round(x / scale, 9), round(y / scale, 9)-def arrangement_rects(width: float, top: float, angle: float, screen: tuple, gap: float) -> tuple:- """(this PC's screen, your Mac's screen, the pair's height) as (x, y, w, h) rects, the pair- centred across `width` and starting at `top`, the Mac's screen at `angle` from this PC's."""+def _thirds_rank(machine: dict) -> int:+ parts = machine.get("parts") or ()+ if "part" in (machine.get("methods") or ()) and any(part in PART_ORDER for part in parts):+ return min(PART_ORDER.index(part) for part in parts if part in PART_ORDER)+ return PART_ORDER.index("middle")+++def side_slots(machines: list) -> list:+ """Where each machine's screen sits beside this PC's: (side, start, end), the fractions of that+ side it takes, or None when it has no side. Machines that share a side share its length equally,+ in the order of the thirds they cross by, then of the list."""+ slots = [None] * len(machines)+ by_side: dict = {}+ for index, machine in enumerate(machines):+ if machine.get("side") in SIDE_ANGLE:+ by_side.setdefault(machine["side"], []).append(index)+ for side, indexes in by_side.items():+ order = sorted(indexes, key=lambda index: (_thirds_rank(machines[index]), index))+ for slot, index in enumerate(order):+ slots[index] = (side, slot / len(order), (slot + 1) / len(order))+ return slots+++def neighbour_offset(angle: float, start: float, end: float, screen: tuple, gap: float) -> tuple:+ """(centre x, centre y, w, h) of a machine's screen from the centre of this PC's, y down: at `angle`+ round this PC's as `arrangement` placed one, scaled to the share of the side from `start` to `end`+ and moved along it to that share. Through a corner the share's offset fades out, so the screen+ goes round this PC's, never across it."""w, h = screen+ share = end - start+ nw, nh = w * share, h * sharesx, sy = square_point(angle)- dx, dy = sx * (w + gap), -sy * (h + gap)- pair_h = h + abs(dy)- cx, cy = width / 2.0, top + pair_h / 2.0- pc = (cx - dx / 2.0 - w / 2.0, cy - dy / 2.0 - h / 2.0, w, h)- mac = (cx + dx / 2.0 - w / 2.0, cy + dy / 2.0 - h / 2.0, w, h)- return pc, mac, pair_h+ along = (start + end) / 2.0 - 0.5+ cx = sx * (w / 2.0 + gap + nw / 2.0) + along * w * (1.0 - abs(sx))+ cy = -sy * (h / 2.0 + gap + nh / 2.0) + along * h * (1.0 - abs(sy))+ return cx, cy, nw, nh+++def layout_rects(width: float, top: float, placed: list, screen: tuple, gap: float, centre_pc: bool = False) -> tuple:+ """(this PC's screen, [each machine's screen], the drawing's height) as (x, y, w, h) rects, for+ `placed` as (angle, start, end) per machine. The drawing is centred across `width` from `top`, or+ with `centre_pc` this PC's screen is, so it stays put while the machines round it move; either way+ it is shrunk whole when it would not fit."""++ def rects(scale):+ w, h, g = screen[0] * scale, screen[1] * scale, gap * scale+ others = []+ for angle, start, end in placed:+ cx, cy, nw, nh = neighbour_offset(angle, start, end, (w, h), g)+ others.append((cx - nw / 2.0, cy - nh / 2.0, nw, nh))+ return (-w / 2.0, -h / 2.0, w, h), others++ def span(pc, others):+ left = min(rect[0] for rect in [pc, *others])+ right = max(rect[0] + rect[2] for rect in [pc, *others])+ # This PC's centre is 0, so centred on it the drawing needs its wider half twice over.+ return (-max(-left, right), max(-left, right)) if centre_pc else (left, right)++ pc, others = rects(1.0)+ left, right = span(pc, others)+ if right - left > width > 0:+ pc, others = rects(width / (right - left))+ left, right = span(pc, others)+ upper = min(rect[1] for rect in [pc, *others])+ lower = max(rect[1] + rect[3] for rect in [pc, *others])+ dx, dy = width / 2.0 - (left + right) / 2.0, top - upper++ def moved(rect):+ return rect[0] + dx, rect[1] + dy, rect[2], rect[3]++ return moved(pc), [moved(rect) for rect in others], lower - upper+++def unplaced_line(labels: list) -> str:+ """The line under the diagram naming the machines that have no side yet; "" when none."""+ return f"Not placed yet: {_joined(labels)}" if labels else ""+++def diagram_description(machines: list, key_name: str, style: str, shortcut: bool) -> str:+ """The diagram's accessible description: where every machine is, then the chosen one's ways in.+ Each machine is a dict with `label`, `side`, `methods`, `parts`, `corner` and `chosen`."""+ placed = [f"{machine['label']} is {SIDE_WORDS[machine['side']]}" for machine in machines+ if machine.get("side") in SIDE_WORDS]+ sentences = [_joined(placed) + "."] if placed else []+ line = unplaced_line([machine["label"] for machine in machines if machine.get("side") not in SIDE_WORDS])+ if line:+ sentences.append(line + ".")+ chosen = next((machine for machine in machines if machine.get("chosen")), machines[0] if machines else None)+ if chosen is not None:+ methods = list(chosen.get("methods") or ()) + (["shortcut"] if shortcut else [])+ sentences.append(ways_summary(methods, chosen.get("side") or "", chosen.get("parts") or (), chosen.get("corner") or "",+ key_name, style, chosen["label"], several=len(machines) > 1))+ return " ".join(sentences)def side_segment(rect: tuple, side: str, start: float = 0.0, end: float = 1.0, inset: float = 0.0) -> tuple:diff --git a/win_app/peers_view.py b/win_app/peers_view.pyindex 61d49e8..3d673e6 100644--- a/win_app/peers_view.py+++ b/win_app/peers_view.py@@ -48,9 +48,9 @@ def describe(entry: dict, label: str, *, up: bool, driving: bool, input_there: bif 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")):+ if not protocol.linkable(entry):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.")+ f"{label} was paired on Beamer 1.4. Pair the two again to link them on 1.5.0.")if up:return PeerState("signal", "Linked", f"Connected to {label}.")if waking:diff --git a/win_app/platform_parts.py b/win_app/platform_parts.pyindex 230a578..d8c8137 100644--- a/win_app/platform_parts.py+++ b/win_app/platform_parts.py@@ -2,23 +2,60 @@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+Linux on X11 gets the X11 back ends for capture, injection, the clipboard, desktop geometry and+autostart; Linux on Wayland gets the portal back ends (InputCapture, RemoteDesktop and its+clipboard, over libei) and the same XDG autostart; both get linux_stand_ins for the firewall and+unlock, and no Windows module beyond the pure pieces capture_x11 and inject_x11 borrow. 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 osimport sysfrom types import SimpleNamespacePARTS = ("capture", "desktop", "clipboard", "autostart", "firewall", "unlock", "injector")-def load(platform: str) -> SimpleNamespace:+def session(environ) -> str:+ """"x11" or "wayland": which display server a Linux desktop runs. XDG_SESSION_TYPE says when it+ says either; `startx` from a console leaves it "tty", so then an X display with no Wayland one+ is X11. Under Wayland, DISPLAY is XWayland's, which cannot capture or inject for other apps."""+ kind = environ.get("XDG_SESSION_TYPE", "").lower()+ if kind in ("x11", "wayland"):+ return kind+ if environ.get("DISPLAY") and not environ.get("WAYLAND_DISPLAY"):+ return "x11"+ return "wayland"+++def load(platform: str, environ=os.environ) -> 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})+ stand_ins = {"firewall": linux_stand_ins.firewall, "unlock": linux_stand_ins.unlock}+ if session(environ) != "x11":+ import autostart_x11+ import capture_portal+ import clipboard_portal+ import desktop_portal+ import inject_portal++ return SimpleNamespace(**dict(+ stand_ins, capture=capture_portal, desktop=desktop_portal, clipboard=clipboard_portal,+ autostart=autostart_x11, injector=inject_portal,+ ))+ import autostart_x11+ import capture_x11+ import clipboard_x11+ import desktop_x11+ import inject_x11++ return SimpleNamespace(**dict(+ stand_ins, capture=capture_x11, desktop=desktop_x11, clipboard=clipboard_x11, autostart=autostart_x11,+ injector=inject_x11,+ ))import autostart_winimport capture_winimport clipboard_win@@ -28,14 +65,17 @@ def load(platform: str) -> SimpleNamespace:import unlock_winreturn SimpleNamespace(- not_yet=None, capture=capture_win, desktop=desktop_win, clipboard=clipboard_win, autostart=autostart_win,+ 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+# Wayland lets no app draw at the screen's edges, see a full-screen app or a button held before+# the pointer met a barrier, and lets input leave only across an edge: the app says so where it applies.+WAYLAND = sys.platform.startswith("linux") and session(os.environ) != "x11"+capture = _parts.capturedesktop = _parts.desktopclipboard = _parts.clipboarddiff --git a/win_app/portal.py b/win_app/portal.pynew file mode 100644index 0000000..651a3e6--- /dev/null+++ b/win_app/portal.py@@ -0,0 +1,254 @@+"""The desktop portals over D-Bus, for the Wayland back ends.++One `Portal` per thread that uses it: the capture thread has its own and the injector's thread has+its own, each on its own connection to the session bus. A connection is the session's life: when+it closes, by a stop or by the process dying, the portal closes every session it opened, and the+compositor lets go of input it had captured. That is the way home that needs nothing to run.++The bus is a seam (`JeepneyBus` for real): the request and response matching here is tested with+a fake one on any machine. jeepney is pure Python and is reached only when a JeepneyBus is made,+so this module imports anywhere. Not QtDBus: it would tie both threads to Qt's event loop, where+the capture thread must select on the bus and libei's fd together, as the X11 one selects on its+X connection.++Portal methods that may ask the user (CreateSession, Start) answer through a Request object's+Response signal: 0 granted, 1 refused by the user, 2 ended another way."""++import collections+import logging+import os+import socket+import time+from pathlib import Path+from typing import Callable, Optional++LOGGER = logging.getLogger(__name__)++BUS_NAME = "org.freedesktop.portal.Desktop"+OBJECT_PATH = "/org/freedesktop/portal/desktop"+REQUEST = "org.freedesktop.portal.Request"+SESSION = "org.freedesktop.portal.Session"+PROPERTIES = "org.freedesktop.DBus.Properties"+CALL_SECONDS = 10.0+TICK_SECONDS = 0.1+++class Refused(Exception):+ """The user said no in the desktop's dialog."""+++class PortalError(Exception):+ """The portal failed or is missing; the text says which."""+++def plain(value):+ """A message body as plain values: jeepney gives each value of an a{sv} as its variant, a+ (signature, value) pair."""+ if isinstance(value, dict):+ return {key: plain(unvariant(item)) for key, item in value.items()}+ if isinstance(value, list):+ return [plain(item) for item in value]+ if isinstance(value, tuple):+ return tuple(plain(item) for item in value)+ return value+++def unvariant(value):+ if isinstance(value, tuple) and len(value) == 2 and isinstance(value[0], str):+ return value[1]+ return value+++class TokenStore:+ """A portal's restore token, kept between runs in the state directory, readable by this user+ only: it lets this app skip the desktop's question. Each token is used once and replaced by+ the one the next start returns; an empty one is forgotten."""++ def __init__(self, name: str, base: Optional[Path] = None) -> None:+ if base is None:+ configured = os.environ.get("XDG_STATE_HOME", "")+ base = Path(configured) if configured and os.path.isabs(configured) else Path.home() / ".local" / "state"+ base = base / "beamer"+ self.path = Path(base) / f"{name}-token"++ def read(self) -> str:+ try:+ return self.path.read_text(encoding="utf-8").strip()+ except OSError:+ return ""++ def write(self, token: str) -> None:+ try:+ if not token:+ self.path.unlink(missing_ok=True)+ return+ self.path.parent.mkdir(parents=True, exist_ok=True)+ temporary = self.path.with_suffix(".tmp")+ descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:+ handle.write(token)+ os.replace(temporary, self.path)+ except OSError:+ LOGGER.exception("Could not keep the desktop's permission for next time")+++class Portal:+ """Calls and requests on the portal over `bus`, keeping every other signal for the owner to+ read with signals(). `stopping()` ends a wait for the user early."""++ def __init__(self, bus, stopping: Callable[[], bool] = lambda: False) -> None:+ self.bus = bus+ self._stopping = stopping+ self._waiting = collections.deque()+ self._count = 0+ self._sender = bus.unique_name.lstrip(":").replace(".", "_")++ def token(self) -> str:+ self._count += 1+ return f"beamer{self._count}"++ def call(self, interface: str, method: str, signature: str = "", body: tuple = (), path: str = OBJECT_PATH):+ return self.bus.call(path, interface, method, signature, body)++ def version(self, interface: str) -> int:+ """The portal interface's version, 0 when the portal does not have it."""+ try:+ return int(unvariant(self.call(PROPERTIES, "Get", "ss", (interface, "version"))[0]))+ except PortalError:+ return 0++ def request(self, interface: str, method: str, signature: str, make_body: Callable[[str], tuple],+ timeout: Optional[float] = None) -> dict:+ """Call a method answered by a Response, wait for it and return its results. `make_body`+ gets the handle_token to put in the options. No timeout by default: a dialog waits for the+ user for as long as it takes, though a stop ends the wait."""+ token = self.token()+ path = f"/org/freedesktop/portal/desktop/request/{self._sender}/{token}"+ self.call(interface, method, signature, make_body(token))+ deadline = None if timeout is None else time.monotonic() + timeout+ while True:+ for item in list(self._waiting):+ _kind, at, iface, member, body = item+ if at == path and iface == REQUEST and member == "Response":+ self._waiting.remove(item)+ code, results = body[0], plain(body[1]) if len(body) > 1 else {}+ if code == 0:+ return results+ if code == 1:+ raise Refused(f"{method} was refused")+ raise PortalError(f"{method} ended without an answer ({code})")+ if self._stopping():+ raise PortalError(f"{method} was abandoned: Beamer is stopping")+ wait = TICK_SECONDS+ if deadline is not None:+ wait = min(wait, deadline - time.monotonic())+ if wait <= 0:+ raise PortalError(f"{method} had no answer")+ self._waiting.extend(self.bus.receive(wait))++ def signals(self, timeout: float = 0.0) -> list:+ """Every signal received since the last call, after waiting up to `timeout` for one, as+ (path, interface, member, body) with the body's variants made plain."""+ if not self._waiting:+ self._waiting.extend(self.bus.receive(timeout))+ found = [(at, iface, member, plain(body)) for _kind, at, iface, member, body in self._waiting]+ self._waiting.clear()+ return found++ def fileno(self) -> int:+ return self.bus.fileno()++ def pending(self) -> bool:+ """Whether signals are waiting, here or already read off the socket by the bus, so a+ select() on its fd would wait for nothing."""+ if not self._waiting:+ pending = getattr(self.bus, "pending", None)+ if pending is not None and pending():+ self._waiting.extend(self.bus.receive(0))+ return bool(self._waiting)++ def close(self) -> None:+ self.bus.close()+++class JeepneyBus:+ """The session bus through jeepney's blocking connection, with fd passing. Signals from the+ portal are matched once and kept until receive() hands them over, those that arrive while a+ call waits for its reply included."""++ def __init__(self) -> None:+ try:+ from jeepney.bus_messages import MatchRule, message_bus+ from jeepney.io.blocking import open_dbus_connection+ except ImportError as exc:+ raise PortalError("jeepney is not installed; Beamer needs it to reach the desktop portals") from exc+ try:+ self._conn = open_dbus_connection(bus="SESSION", enable_fds=True)+ except Exception as exc:+ raise PortalError(f"Could not reach the session bus: {exc}") from exc+ self._signals = collections.deque()+ # The bus routes only the portal's signals here; the local filter takes every signal, since+ # a message names its sender by unique name, which a well-known name in it never matches.+ self._filter = self._conn.filter(MatchRule(type="signal"), queue=self._signals)+ self._conn.send_and_get_reply(message_bus.AddMatch(MatchRule(type="signal", sender=BUS_NAME)), timeout=CALL_SECONDS)+ self.unique_name = self._conn.unique_name++ def call(self, path: str, interface: str, method: str, signature: str, body: tuple) -> tuple:+ from jeepney import DBusAddress, MessageType, new_method_call++ message = new_method_call(DBusAddress(path, BUS_NAME, interface), method, signature or None, body)+ try:+ reply = self._conn.send_and_get_reply(message, timeout=CALL_SECONDS)+ except TimeoutError as exc:+ raise PortalError(f"{interface}.{method} did not answer") from exc+ if reply.header.message_type == MessageType.error:+ name = reply.header.fields.get(4, "an error") # HeaderFields.error_name+ raise PortalError(f"{interface}.{method}: {name}: {' '.join(map(str, reply.body))}")+ return tuple(_raw_fds(reply.body))++ def receive(self, timeout: float) -> list:+ if not self._signals and timeout >= 0:+ try:+ self._conn.recv_messages(timeout=max(timeout, 0.0))+ except TimeoutError:+ pass+ found = []+ while self._signals:+ message = self._signals.popleft()+ fields = message.header.fields+ # HeaderFields: 1 path, 2 interface, 3 member.+ found.append(("signal", fields.get(1), fields.get(2), fields.get(3), tuple(_raw_fds(message.body))))+ return found++ def pending(self) -> bool:+ if not self._signals:+ try:+ self._conn.recv_messages(timeout=0)+ except TimeoutError:+ pass+ return bool(self._signals)++ def fileno(self) -> int:+ return self._conn.sock.fileno()++ def abort(self) -> None:+ """End the connection from another thread: the thread waiting on it wakes, and the portal+ closes this connection's sessions."""+ try:+ self._conn.sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass++ def close(self) -> None:+ try:+ self._conn.close()+ except Exception:+ LOGGER.exception("The portal connection did not close cleanly")+++def _raw_fds(body):+ """jeepney hands fds over as FileDescriptor objects that close themselves when dropped; each is+ taken as a plain fd the caller now owns."""+ for item in body:+ to_raw = getattr(item, "to_raw_fd", None)+ yield to_raw() if to_raw is not None else itemdiff --git a/win_app/requirements-linux.txt b/win_app/requirements-linux.txtnew file mode 100644index 0000000..daa86a0--- /dev/null+++ b/win_app/requirements-linux.txt@@ -0,0 +1,11 @@+PySide6-Essentials>=6.11.1+PyNaCl>=1.6+# The X11 back ends talk to the X server through python-xlib (pure Python, LGPL-2.1+, fine beside+# GPL). Pinned exactly: capture_x11 parses XInput2 raw events itself and relies on 0.33's request+# classes. six is its one dependency.+python-xlib==0.33+six==1.17.0+# The Wayland back ends reach the desktop portals over D-Bus through jeepney (pure Python, MIT, no+# dependencies), with fd passing for libei's connection and the clipboard's transfers. libei and+# libxkbcommon are the system's, reached through ctypes (win_app/libei.py, xkb_x11.py).+jeepney==0.9.0diff --git a/win_app/sender.py b/win_app/sender.pyindex 1e70d8f..fc3948f 100644--- a/win_app/sender.py+++ b/win_app/sender.py@@ -13,14 +13,16 @@ shell reaches the same code. Keys arrive with the names Windows capture gives thkey as "ctrl" and Ctrl as "cmd", and leave as the physical key (`PHYSICAL`) before core/keytable.pynames 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.+The shortcut and the Send button pick the machine core.ways.shortcut_peer names: the one input was+last on while it can take input, else the first that can. A tray item per machine picks its own,+and a push through a zone picks that zone's peer."""import collectionsimport ipaddressimport loggingimport queue+import sysimport threadingimport timefrom typing import Callable, Optional@@ -32,6 +34,7 @@ from core import peerlistfrom core import protocolfrom core import receiverfrom core import return_edge+from core import waysfrom core import wolLOGGER = logging.getLogger(__name__)@@ -54,7 +57,8 @@ 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"+# What this machine tells its peers it is (WIRE.md section 2); Linux and Windows read keys alike.+OWN_PLATFORM = "linux" if sys.platform.startswith("linux") else "windows"INPUT_TYPES = protocol.INPUT_TYPES# What the owner's reasons for bringing input home say, naming the machine (WIRE.md section 5).@@ -109,8 +113,8 @@ class LinkSender:`book` is a `receiver.PeerBook` over the app's settings and `zones()` gives this PC's zones assettings.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+ from a worker thread (a GUI marshals them): `status_callback(connected, detail)` for the machine+ the shortcut would pick, `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 bothhalves. `desktop` and `clipboard` are the platform's modules. `hardware(host)` is this PC's@@ -172,12 +176,16 @@ class LinkSender:self._monitors = Noneself._monitors_at = 0.0self._clipboard_stamp = None+ # The machine this PC's input last landed on, as an id text, for the shortcut's choice.+ self._last_on: Optional[str] = Noneself._reported_redirecting = Falseself._followed_at = 0.0self._overflowed = Falseself._armed_for = frozenset()self._clip_wait: dict = {} # peer: actions held back while its clipboard is readself._clip_lock = threading.Lock()+ self._clip_jobs = collections.deque()+ self._clip_busy = Falseself._statuses: dict = {}self._waking = set()self._wake_lock = threading.Lock()@@ -196,6 +204,10 @@ class LinkSender:# changed (section 6); the pairing window supplies it.self.machines: Callable[[], list] = lambda: []self.hw_learned: Optional[Callable[[bytes, str], None]] = None+ # Whether this machine's input can be taken now. Always, except where only the desktop can+ # capture it (Wayland), which it does at an edge barrier: there the shortcut and the tray+ # cannot send input away, only an edge push can.+ self.input_held: Callable[[], bool] = lambda: True# The responder's: whether a peer's input is on this PC, and sending it home.self.driven: Callable[[], bool] = lambda: Falseself.send_peer_home: Callable[[], bool] = lambda: False@@ -205,7 +217,6 @@ class LinkSender:self.arrangement_callback: Optional[Callable] = Noneself.settings_callback: Optional[Callable] = Noneself.paired_callback: Optional[Callable] = None- self.notice_callback: Optional[Callable[[str], None]] = Noneself.link_callback: Optional[Callable[[bytes, bool], None]] = Noneself.links = links(self) if links is not None else _default_links(self)@@ -231,13 +242,26 @@ class LinkSender:@propertydef connected(self) -> bool:- peer = self._primary()+ peer = self.shortcut_target()return peer is not None and self.links.up(peer)@propertydef status(self) -> str:- peer = self._primary_key()- return self._statuses.get(peer) or NOT_CONNECTED_STATUS+ """The link status of the machine the shortcut would take input to; before any entry has an+ id (the one migrated from 1.4.x), of the first this PC dials, by its token."""+ peer = self.shortcut_target()+ entry = self._peers.get(peer) if peer is not None else next(+ (item for item in self._entries if item.get("send") and item.get("host") and item.get("port")), None)+ return (self._statuses.get(self.links.key_of(entry)) if entry is not None else None) or NOT_CONNECTED_STATUS++ def shortcut_target(self) -> Optional[bytes]:+ """Where the shortcut, the Send button and the tray's toggle send this PC's input (WIRE.md+ section 5, core.ways.shortcut_peer); None when this PC sends to no machine."""+ def ready(ident) -> bool:+ peer = protocol.read_id(ident)+ return peer is not None and self.links.up(peer) and self._accepts.get(peer) is True++ return protocol.read_id(ways.shortcut_peer(self._entries, self._last_on, ready))@propertydef waking(self) -> bool:@@ -294,7 +318,7 @@ class LinkSender: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:+ while self._threads and (not self._outbound.empty() or self._clip_wait or self._clip_busy) and self._clock() < deadline:time.sleep(0.01)self._stop_event.set()self.links.stop()@@ -489,6 +513,13 @@ class LinkSender:# border, read from the other end.self._go(target, outcome.edge, offset)+ def zone_models(self) -> list:+ """The models of this PC's ways out, where a desktop that captures input at barriers puts+ them; none while the edges are held."""+ if self.edges_held or self._owner is None:+ return []+ return [model for _peer, model in list(self._models)]+def _still_dragging(self) -> bool:"""A release the hook never saw -- let go over the secure desktop or an elevated window --would otherwise hold the edge shut for good, so each button is asked of Windows again."""@@ -504,12 +535,12 @@ class LinkSender:# -- switching ----------------------------------------------------------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."""+ """Moves this PC's input to the shortcut's machine, or home, as the shortcut, the Send button,+ the tray and the direction switch do. False when nothing moved."""if value:if self.redirecting:return False- peer = self._primary()+ peer = self.shortcut_target()if peer is None:self._alert(f"Cannot switch — {self.status}")return False@@ -534,6 +565,10 @@ class LinkSender:owner = self._ownerif owner is None:return False+ if not self.input_held():+ self._alert("Cannot switch — on this desktop input goes to another machine only by pushing the pointer "+ "through an edge")+ return Falseif 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.@@ -672,13 +707,19 @@ class LinkSender:"""Hands what the owner answered to the outbound worker, in order. Called with the lock stillheld, in the same step as the decision, so two threads' decisions cannot reach the worker theother 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)):+ for index, action in enumerate(actions):+ if isinstance(action, (owner_module.Send, owner_module.SendClipboard, owner_module.SetClipboard, owner_module.Drop)):try:self._outbound.put_nowait(action)except queue.Full:LOGGER.error("the outbound queue filled up; input returns to this PC")self._overflowed = True+ # What is lost with the rest can be sent again, but a link the owner has+ # already counted as closed must still close, or that machine stays owned.+ for lost in actions[index:]:+ if isinstance(lost, owner_module.Drop):+ self._forget_held(lost.peer)+ self.links.close(lost.peer, owner_module.DROPPED)returndef _report(self, actions) -> None:@@ -712,11 +753,19 @@ class LinkSender:def _deliver(self, action) -> None:"""Sends in the order the owner gave them, except that reading the clipboard (which can beslow) never holds up another peer's messages: what follows a clipboard read for the same- peer waits for it, and everything else goes on."""+ peer waits for it, and everything else goes on. The clipboard's reads and writes go one at a+ time, in the order decided, on a thread of their own, so a read never overtakes a write+ decided before it."""if isinstance(action, owner_module.SetClipboard):- self._set_clipboard(action.message)+ self._on_clipboard(lambda message=action.message: self._set_clipboard(message))returnpeer = action.peer+ if isinstance(action, owner_module.Drop):+ # A hand-over given up before its answer: closing the link ends any ownership a late+ # accept began there, and it reconnects (WIRE.md section 5).+ self._forget_held(peer)+ self.links.close(peer, owner_module.DROPPED)+ returnwith self._clip_lock:waiting = self._clip_wait.get(peer)if waiting is not None:@@ -725,7 +774,7 @@ class LinkSender:if isinstance(action, owner_module.SendClipboard):waiting = self._clip_wait[peer] = collections.deque()try:- threading.Thread(target=self._clipboard_then_rest, args=(peer, waiting), name="Beamer-links-clipboard", daemon=True).start()+ self._on_clipboard_locked(lambda peer=peer: self._clipboard_then_rest(peer, waiting))except RuntimeError:# No thread at shutdown: nothing must wait behind a read that never starts.del self._clip_wait[peer]@@ -736,7 +785,8 @@ class LinkSender:def _clipboard_then_rest(self, peer: bytes, waiting) -> None:"""The clipboard for `peer`, then what `waiting` held behind it, in order. `waiting` belongs tothe link it was made on: once that link is lost (`_forget_held`) none of it is sent, as the- machine that reconnects will be taken afresh."""+ machine that reconnects will be taken afresh. A clipboard asked for again takes its turn+ among the clipboard's other work, behind any write decided before it."""try:self._send_clipboard(peer, waiting)except Exception:@@ -749,14 +799,43 @@ class LinkSender:del self._clip_wait[peer]returnaction = waiting.popleft()- try:if isinstance(action, owner_module.SendClipboard):- self._send_clipboard(peer, waiting)- else:- self._send(peer, action.message)+ self._on_clipboard_locked(lambda peer=peer: self._clipboard_then_rest(peer, waiting))+ return+ try:+ self._send(peer, action.message)except Exception:LOGGER.exception("A message held behind the clipboard could not be sent")+ def _on_clipboard(self, job) -> None:+ with self._clip_lock:+ self._on_clipboard_locked(job)++ def _on_clipboard_locked(self, job) -> None:+ """Under `_clip_lock`: `job` done after every clipboard job before it, on the one thread+ that does them, started when there is none."""+ self._clip_jobs.append(job)+ if self._clip_busy:+ return+ try:+ threading.Thread(target=self._clipboard_worker, name="Beamer-links-clipboard", daemon=True).start()+ except RuntimeError:+ self._clip_jobs.pop()+ raise+ self._clip_busy = True++ def _clipboard_worker(self) -> None:+ while True:+ with self._clip_lock:+ if not self._clip_jobs:+ self._clip_busy = False+ return+ job = self._clip_jobs.popleft()+ try:+ job()+ except Exception:+ LOGGER.exception("Clipboard work failed")+def _forget_held(self, peer: bytes) -> None:"""`peer`'s link is lost: what waited for its clipboard is for a link that is gone."""with self._clip_lock:@@ -839,7 +918,7 @@ class LinkSender: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):+ if image is not None and ("clipboard_image" not in caps or not protocol.png_fits(image)):image = Noneif not text and image is None:return@@ -860,6 +939,7 @@ class LinkSender:def _moved(self, moved: owner_module.Moved) -> None:if moved.to is not None:+ self._last_on = protocol.id_text(moved.to)if self._pin_point is None:self._pin_point = self._desktop_module().cursor_position()LOGGER.info("input is on %s", self._name(moved.to))@@ -943,7 +1023,7 @@ class LinkSender: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 isalready in flight."""- peer = peer or self._primary()+ peer = peer or self.shortcut_target()entry = self._peers.get(peer) if peer is not None else Noneaddress = (entry or {}).get("hw") or ""if not address or self.links.up(peer) or self.links.refused(peer):@@ -1023,21 +1103,6 @@ class LinkSender: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-- 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 _status_of(self, peer) -> str:entry = self._peers.get(peer) or {}return self._statuses.get(self.links.key_of(entry)) or NOT_CONNECTED_STATUS@@ -1117,8 +1182,8 @@ class LinkSender: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+ """One core.link.OutboundLink for each peer entry this PC dials, keyed by the entry's token and+ found by peer id once up. What`LinkSender` asks of its links, and what each tells it back."""REFUSALS = ("older", "newer", "wrong_id", "unauthenticated", "different")@@ -1154,7 +1219,7 @@ class LinkSet: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 "")+ if protocol.linkable(entry) and not self._is_local(entry.get("host") or "")}with self._lock:gone = [token for token in self._links if token not in wanted]@@ -1174,7 +1239,7 @@ class LinkSet: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,+ state=self._state, up=self._up, message=self._message, **hooks,)self._links[token] = linkfresh.append(link)@@ -1218,10 +1283,10 @@ class LinkSet:link = self._link(peer)return link is not None and link.send_input(message)- def close(self, peer) -> None:+ def close(self, peer, reason="The link went quiet") -> None:link = self._link(peer)if link is not None:- link.drop("The link went quiet")+ link.drop(reason)def round_trip_ms(self, peer) -> Optional[int]:"""The upper median of the last few trips, with the time the peer held each ACK taken off, or@@ -1286,11 +1351,6 @@ class LinkSet: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 linkdiff --git a/win_app/tests/links_rig.py b/win_app/tests/links_rig.pyindex de2a06d..3600825 100644--- a/win_app/tests/links_rig.py+++ b/win_app/tests/links_rig.py@@ -4,6 +4,7 @@ what one event did and in what order."""import osimport sys+import threadingimport timesys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))@@ -19,6 +20,29 @@ MONITORS = [Rect(0, 0, 1920, 1080)]CAPS = frozenset({"clipboard", "clipboard_image", "settings", "media_keys"})+class FakeClipboard(harness.FakeClipboard):+ def __init__(self, text="here"):+ super().__init__(text)+ self.get_started = threading.Event()+ self.release_get = threading.Event()+ self.set_started = threading.Event()+ self.release_set = threading.Event()+ self.block_get = False+ self.block_set = False++ def get_contents(self):+ self.get_started.set()+ if self.block_get:+ self.release_get.wait(3)+ return super().get_contents()++ def set_contents(self, text, image):+ self.set_started.set()+ if self.block_set:+ self.release_set.wait(3)+ return super().set_contents(text, image)++def make_config(**overrides):values = dict(host="", port=24820, auth_token="", machine_id=protocol.id_text(HERE), name="This PC",@@ -83,7 +107,7 @@ class FakeLinks:self.sent.append((peer, message))return True- def close(self, peer):+ def close(self, peer, reason=None):self.closed.append(peer)self.up_set.discard(peer)@@ -97,7 +121,7 @@ class FakeLinks: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.clipboard = 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)],@@ -143,7 +167,7 @@ class Rig:while time.monotonic() < deadline:while not self.sender._outbound.empty():self.sender._deliver(self.sender._outbound.get_nowait())- if not self.sender._clip_wait:+ if not self.sender._clip_wait and not self.sender._clip_busy:returntime.sleep(0.002)diff --git a/win_app/tests/portal_fakes.py b/win_app/tests/portal_fakes.pynew file mode 100644index 0000000..c45947f--- /dev/null+++ b/win_app/tests/portal_fakes.py@@ -0,0 +1,185 @@+"""Fakes for the Wayland back ends' seams: a session bus with a scripted desktop portal on it, and a+libei context the test feeds events into. Neither needs D-Bus, libei or Qt, so the portal modules'+tests run on every machine."""++import os+import threading+import time++import portal+++def variant(value):+ """A value as jeepney hands over each entry of an a{sv}: (signature, value)."""+ return ("v", value)+++def vardict(values: dict) -> dict:+ return {key: variant(value) for key, value in values.items()}+++class FakeBus:+ """The portal as a script: `answers[method]` is (code, results) for a method answered by a+ Response, or a callable taking the body and returning one; `returns[method]` is the body a+ plain call returns. Every call is recorded in `calls` as (interface, method, body)."""++ REQUESTS = {"CreateSession", "SelectDevices", "Start", "GetZones", "SetPointerBarriers"}++ def __init__(self, versions=None) -> None:+ self.unique_name = ":1.42"+ self.versions = versions or {}+ self.answers = {}+ self.returns = {}+ self.calls = []+ self.closed = False+ self.aborted = False+ self._signals = []+ self._lock = threading.Lock()+ self._read, self._write = os.pipe()++ def call(self, path, interface, method, signature, body):+ if self.closed:+ raise portal.PortalError("the connection is closed")+ with self._lock:+ self.calls.append((interface, method, body))+ if interface == portal.PROPERTIES and method == "Get":+ version = self.versions.get(body[0])+ if version is None:+ raise portal.PortalError("No such interface")+ return (("u", version),)+ if method in self.REQUESTS:+ options = next(item for item in body if isinstance(item, dict))+ token = options["handle_token"][1]+ request = f"/org/freedesktop/portal/desktop/request/1_42/{token}"+ answer = self.answers.get(method, (0, {}))+ if callable(answer):+ answer = answer(body)+ if answer is not None:+ code, results = answer+ self.emit(request, portal.REQUEST, "Response", (code, vardict(results)))+ return (request,)+ returned = self.returns.get(method, ())+ return returned(body) if callable(returned) else returned++ def emit(self, path, interface, member, body) -> None:+ with self._lock:+ self._signals.append(("signal", path, interface, member, body))+ os.write(self._write, b"x")++ def receive(self, timeout):+ with self._lock:+ found, self._signals = self._signals, []+ if not found and timeout > 0:+ time.sleep(min(timeout, 0.01))+ return found++ def made(self, method):+ with self._lock:+ return [body for _interface, name, body in self.calls if name == method]++ def fileno(self):+ return self._read++ def abort(self):+ self.aborted = True+ self.closed = True++ def close(self):+ self.closed = True+++class FakeDevice:+ def __init__(self, name, caps, regions=(), keymap=None) -> None:+ self.name = name+ self.caps = set(caps)+ self._regions = list(regions)+ self._keymap = keymap++ def has(self, cap):+ return cap in self.caps++ def regions(self):+ return list(self._regions)++ def keymap(self):+ return self._keymap++ def __repr__(self):+ return f"FakeDevice({self.name})"+++class FakeEi:+ """A libei context: `feed(*events)` queues events for the next events(); what is sent is in+ `sent`, as (call, device name, *args)."""++ def __init__(self, fd=None) -> None:+ self.fd = fd+ self._events = []+ self._lock = threading.Lock()+ self.sent = []+ self.bound = []+ self.closed = False+ self._read, self._write = os.pipe()++ def feed(self, *events) -> None:+ with self._lock:+ self._events.extend(events)+ os.write(self._write, b"x")++ def events(self):+ with self._lock:+ found, self._events = self._events, []+ return found++ def fileno(self):+ return self._read++ def bind(self, seat):+ self.bound.append(seat)++ def _record(self, call, device, *args):+ with self._lock:+ self.sent.append((call, device.name) + args)++ def start(self, device, sequence):+ self._record("start", device, sequence)++ def stop(self, device):+ self._record("stop", device)++ def frame(self, device):+ self._record("frame", device)++ def motion(self, device, dx, dy):+ self._record("motion", device, dx, dy)++ def absolute(self, device, x, y):+ self._record("absolute", device, x, y)++ def button(self, device, code, down):+ self._record("button", device, code, down)++ def scroll(self, device, dx, dy):+ self._record("scroll", device, dx, dy)++ def scroll_discrete(self, device, dx, dy):+ self._record("scroll_discrete", device, dx, dy)++ def key(self, device, code, down):+ self._record("key", device, code, down)++ def sends(self, call=None):+ with self._lock:+ return [item for item in self.sent if call is None or item[0] == call]++ def close(self):+ self.closed = True+++def wait_for(condition, timeout=3.0, what="the condition"):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if condition():+ return+ time.sleep(0.01)+ raise AssertionError(f"timed out waiting for {what}")diff --git a/win_app/tests/test_arrangement.py b/win_app/tests/test_arrangement.pyindex 743146f..78219ae 100644--- a/win_app/tests/test_arrangement.py+++ b/win_app/tests/test_arrangement.py@@ -85,16 +85,16 @@ class LearnedTests(Folder):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))+ # A side is no longer the flat view's: no save writes one back (set_ways and apply_arrangement do).+ self.assertNotIn("mac_return_edge", learned)- def test_the_token_and_the_ways_come_back_too_so_a_fold_cannot_be_undone_by_a_save(self):+ def test_the_token_comes_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"])+ self.assertEqual(learned["paired_with"], "Other")def test_the_stamps_author_for_same_on_all_machines_is_kept(self):config = app_config.load_config(self.path)diff --git a/win_app/tests/test_autostart_x11.py b/win_app/tests/test_autostart_x11.pynew file mode 100644index 0000000..09a6be9--- /dev/null+++ b/win_app/tests/test_autostart_x11.py@@ -0,0 +1,188 @@+import os+import stat+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++import autostart_x11++EXE = "/home/alex/Beamer/beamer"+++def read_exec(path: Path) -> list:+ """The Exec value as the spec's reader would see it: the string-type escapes undone first, then+ the quoting rules, then %% as a literal percent. Kept apart from the writer's code on purpose."""+ value = next(line[5:] for line in path.read_text(encoding="utf-8").splitlines() if line.startswith("Exec="))+ unescaped, i = [], 0+ while i < len(value):+ if value[i] == "\\" and i + 1 < len(value):+ unescaped.append({"n": "\n", "t": "\t", "r": "\r", "s": " ", "\\": "\\"}.get(value[i + 1], value[i + 1]))+ i += 2+ else:+ unescaped.append(value[i])+ i += 1+ value, args, current, quoted, have, i = "".join(unescaped), [], [], False, False, 0+ while i < len(value):+ char = value[i]+ if quoted:+ if char == "\\" and i + 1 < len(value):+ current.append(value[i + 1])+ i += 1+ elif char == '"':+ quoted = False+ else:+ current.append(char)+ elif char == '"':+ quoted, have = True, True+ elif char == " ":+ if have or current:+ args.append("".join(current))+ current, have = [], False+ else:+ current.append(char)+ i += 1+ if have or current:+ args.append("".join(current))+ return [arg.replace("%%", "%") for arg in args]+++class AutostartX11Test(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.base = Path(self.tmp.name)+ self.entry = self.base / "autostart" / "beamer.desktop"++ def enable(self, exe=EXE):+ autostart_x11.set_enabled(True, exe, base=self.base)++ def test_enable_writes_the_exact_file(self):+ self.enable()+ self.assertEqual(+ self.entry.read_text(encoding="utf-8"),+ "[Desktop Entry]\n"+ "Type=Application\n"+ "Name=Beamer\n"+ f"Exec={EXE} --hidden\n"+ "X-GNOME-Autostart-enabled=true\n"+ "NoDisplay=true\n"+ "Comment=Shares one keyboard and mouse between your computers\n",+ )++ def test_enabled_after_enable_and_disabled_after_disable(self):+ self.assertFalse(autostart_x11.is_enabled(base=self.base))+ self.enable()+ self.assertTrue(autostart_x11.is_enabled(base=self.base))+ autostart_x11.set_enabled(False, EXE, base=self.base)+ self.assertFalse(self.entry.exists())+ self.assertFalse(autostart_x11.is_enabled(base=self.base))++ def test_disabling_when_absent_is_a_no_op(self):+ autostart_x11.set_enabled(False, EXE, base=self.base)+ self.assertFalse((self.base / "autostart").exists())++ def test_enabling_twice_rewrites_in_place(self):+ self.enable()+ self.enable("/opt/beamer/beamer")+ self.assertEqual(read_exec(self.entry), ["/opt/beamer/beamer", "--hidden"])+ self.assertEqual(os.listdir(self.entry.parent), ["beamer.desktop"])++ def test_hidden_true_reads_as_disabled(self):+ self.enable()+ text = self.entry.read_text(encoding="utf-8")+ self.entry.write_text(text + "Hidden=true\n", encoding="utf-8")+ self.assertFalse(autostart_x11.is_enabled(base=self.base))+ self.entry.write_text(text + "Hidden=false\n", encoding="utf-8")+ self.assertTrue(autostart_x11.is_enabled(base=self.base))++ def test_gnome_switch_off_reads_as_disabled(self):+ self.enable()+ text = self.entry.read_text(encoding="utf-8").replace("Autostart-enabled=true", "Autostart-enabled=false")+ self.entry.write_text(text, encoding="utf-8")+ self.assertFalse(autostart_x11.is_enabled(base=self.base))++ def test_hidden_in_another_group_does_not_count(self):+ self.enable()+ text = self.entry.read_text(encoding="utf-8")+ self.entry.write_text(text + "\n[Desktop Action x]\nHidden=true\n", encoding="utf-8")+ self.assertTrue(autostart_x11.is_enabled(base=self.base))++ def test_enable_after_hidden_restores_it(self):+ self.enable()+ self.entry.write_text(self.entry.read_text(encoding="utf-8") + "Hidden=true\n", encoding="utf-8")+ self.enable()+ self.assertTrue(autostart_x11.is_enabled(base=self.base))++ def test_plain_path_is_not_quoted(self):+ self.assertEqual(autostart_x11.exec_line(EXE), f"{EXE} --hidden")++ def test_path_with_a_space_is_quoted(self):+ self.assertEqual(autostart_x11.exec_line("/opt/My Apps/beamer"), '"/opt/My Apps/beamer" --hidden')+ self.enable("/opt/My Apps/beamer")+ self.assertEqual(read_exec(self.entry), ["/opt/My Apps/beamer", "--hidden"])++ def test_dollar_is_escaped_for_both_layers(self):+ # Quoting layer \$, then the string layer doubles its backslash.+ self.assertEqual(autostart_x11.exec_line("/opt/a$b/beamer"), '"/opt/a\\\\$b/beamer" --hidden')+ self.enable("/opt/a$b/beamer")+ self.assertEqual(read_exec(self.entry), ["/opt/a$b/beamer", "--hidden"])++ def test_every_reserved_character_survives(self):+ for char in " \t\"'\\<>~|&;$*?#()`":+ with self.subTest(char=repr(char)):+ exe = f"/opt/a{char}b/beamer"+ self.enable(exe)+ self.assertEqual(read_exec(self.entry), [exe, "--hidden"])++ def test_percent_is_doubled(self):+ self.assertEqual(autostart_x11.exec_line("/opt/100%/beamer"), "/opt/100%%/beamer --hidden")+ self.enable("/opt/100%/beamer")+ self.assertEqual(read_exec(self.entry), ["/opt/100%/beamer", "--hidden"])++ @unittest.skipIf(sys.platform == "win32", "Windows has no POSIX permission bits")+ def test_the_file_is_readable_by_other_programs(self):+ self.enable()+ self.assertEqual(stat.S_IMODE(self.entry.stat().st_mode), 0o644)++ def test_xdg_config_home_is_honoured(self):+ with mock.patch.dict(os.environ, {"XDG_CONFIG_HOME": str(self.base / "xdg")}):+ autostart_x11.set_enabled(True, EXE)+ self.assertTrue((self.base / "xdg" / "autostart" / "beamer.desktop").exists())+ self.assertTrue(autostart_x11.is_enabled())+ autostart_x11.set_enabled(False, EXE)+ self.assertFalse(autostart_x11.is_enabled())++ def test_config_home_defaults_to_dot_config(self):+ env = {k: v for k, v in os.environ.items() if k != "XDG_CONFIG_HOME"}+ with mock.patch.dict(os.environ, env, clear=True), mock.patch("pathlib.Path.home", return_value=self.base):+ self.assertEqual(autostart_x11.config_home(), self.base / ".config")+ with mock.patch.dict(os.environ, {"XDG_CONFIG_HOME": ""}), mock.patch("pathlib.Path.home", return_value=self.base):+ self.assertEqual(autostart_x11.config_home(), self.base / ".config")+ with mock.patch.dict(os.environ, {"XDG_CONFIG_HOME": "relative/dir"}), mock.patch("pathlib.Path.home", return_value=self.base):+ self.assertEqual(autostart_x11.config_home(), self.base / ".config")++ def test_an_unwritable_folder_raises_oserror_with_a_reason(self):+ (self.base / "autostart").write_text("in the way", encoding="utf-8")+ with self.assertRaises(OSError) as caught:+ self.enable()+ self.assertIn("autostart", str(caught.exception))+ self.assertEqual(os.listdir(self.base), ["autostart"])++ def test_a_failed_write_leaves_no_temp_file(self):+ self.enable()+ with mock.patch("os.replace", side_effect=PermissionError(13, "Permission denied")):+ with self.assertRaises(OSError):+ self.enable("/opt/other/beamer")+ self.assertEqual(os.listdir(self.entry.parent), ["beamer.desktop"])+ self.assertEqual(read_exec(self.entry), [EXE, "--hidden"])++ def test_installed_exe_is_only_set_when_frozen(self):+ self.assertIsNone(autostart_x11.installed_exe())+ with mock.patch.object(sys, "frozen", True, create=True):+ self.assertEqual(autostart_x11.installed_exe(), sys.executable)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_capture_portal.py b/win_app/tests/test_capture_portal.pynew file mode 100644index 0000000..d6b1748--- /dev/null+++ b/win_app/tests/test_capture_portal.py@@ -0,0 +1,535 @@+"""Wayland capture on fakes: the barriers that stand for each kind of zone, the press at a barrier+(push, slide, back into the screen), and the capture thread against a scripted InputCapture portal+and libei: a push that crosses, input while away, and every way home (the sender bringing it home,+a move back, a key at the edge, a pause, the desktop ending it, a stop, a dead connection, a+stalled thread)."""++import os+import sys+import time+import unittest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import capture_portal+import desktop_portal+import portal+from core import return_edge+from core.return_edge import Rect+from portal_fakes import FakeBus, FakeDevice, FakeEi, vardict, wait_for++ONE = [Rect(0, 0, 1920, 1080)]+SESSION = "/org/freedesktop/portal/desktop/session/1_42/beamer2"+++class BarrierTest(unittest.TestCase):+ def test_a_whole_edge_on_one_display(self):+ self.assertEqual(capture_portal.barriers([return_edge.ReturnEdge("right")], ONE), [("right", (1920, 0, 1920, 1079))])+ self.assertEqual(capture_portal.barriers([return_edge.ReturnEdge("top")], ONE), [("top", (0, 0, 1919, 0))])++ def test_an_edge_between_two_displays_has_no_barrier(self):+ side_by_side = [Rect(0, 0, 1920, 1080), Rect(1920, 0, 1920, 1080)]+ self.assertEqual(capture_portal.barriers([return_edge.ReturnEdge("right")], side_by_side), [("right", (3840, 0, 3840, 1079))])+ self.assertEqual(capture_portal.barriers([return_edge.ReturnEdge("top")], side_by_side),+ [("top", (0, 0, 1919, 0)), ("top", (1920, 0, 3839, 0))])++ def test_a_staggered_display_leaves_the_uncovered_stretch_of_its_neighbour(self):+ staggered = [Rect(0, 0, 1920, 1080), Rect(1920, 200, 1280, 1024)]+ self.assertEqual(capture_portal.barriers([return_edge.ReturnEdge("right")], staggered),+ [("right", (1920, 0, 1920, 199)), ("right", (3200, 200, 3200, 1223))])++ def test_thirds_are_split_where_part_of_splits_them(self):+ found = capture_portal.barriers([return_edge.PartEdge("left", {"middle"})], ONE)+ self.assertEqual(found, [("left", (0, 360, 0, 719))])+ self.assertEqual(return_edge.part_of(359 / 1080), "start")+ self.assertEqual(return_edge.part_of(360 / 1080), "middle")+ self.assertEqual(return_edge.part_of(720 / 1080), "end")+ both = capture_portal.barriers([return_edge.PartEdge("bottom", {"start", "end"})], ONE)+ self.assertEqual(both, [("bottom", (0, 1080, 639, 1080)), ("bottom", (1280, 1080, 1919, 1080))])++ def test_a_corner_is_its_two_walls_as_far_as_the_corner_push_reaches(self):+ found = capture_portal.barriers([return_edge.CornerPush("top_right", "right")], ONE)+ self.assertEqual(sorted(found), [("right", (1920, 0, 1920, 8)), ("top", (1911, 0, 1919, 0))])+ model = return_edge.CornerPush("top_right", "right")+ self.assertTrue(model._at_edge(ONE, (1919, 8)) and model._at_edge(ONE, (1911, 0)))+ self.assertFalse(model._at_edge(ONE, (1919, 9)) or model._at_edge(ONE, (1910, 0)))++ def test_a_notch_stretch_has_none_and_a_repeat_is_placed_once(self):+ models = [return_edge.SpanEdge("top", lambda: (100, 200)), return_edge.ReturnEdge("left"), return_edge.ReturnEdge("left")]+ self.assertEqual(capture_portal.barriers(models, ONE), [("left", (0, 0, 0, 1079))])+++class Clock:+ def __init__(self):+ self.now = 100.0++ def __call__(self):+ return self.now+++class PressTest(unittest.TestCase):+ def test_a_push_holds_a_slide_moves_along_and_a_move_back_lets_go_where_it_ends(self):+ clock = Clock()+ press = capture_portal.Press("right", (1920.0, 500.0), ONE, clock)+ self.assertEqual(press.point, (1919, 500))+ self.assertTrue(press.feed(6, 0))+ self.assertEqual(press.point, (1919, 500))+ self.assertTrue(press.feed(3, -10))+ self.assertEqual(press.point, (1919, 490))+ self.assertTrue(press.feed(0, 4))+ self.assertEqual(press.point, (1919, 494))+ self.assertFalse(press.feed(-5, 2))+ self.assertEqual(press.point, (1914, 496))++ def test_travel_past_the_display_is_not_kept(self):+ press = capture_portal.Press("right", (1920.0, 1075.0), ONE, Clock())+ press.feed(0, 100)+ self.assertEqual(press.point, (1919, 1079))+ press.feed(0, -10)+ self.assertEqual(press.point, (1919, 1069))++ def test_a_pause_in_the_push_is_idle(self):+ clock = Clock()+ press = capture_portal.Press("left", (0.0, 10.0), ONE, clock)+ press.feed(-4, 0)+ clock.now += capture_portal.IDLE_SECONDS / 2+ self.assertFalse(press.idle())+ press.feed(0, 3) # a slide is not a push+ clock.now += capture_portal.IDLE_SECONDS+ self.assertTrue(press.idle())+++class MemoryTokens:+ def __init__(self, token=""):+ self.token = token++ def read(self):+ return self.token++ def write(self, token):+ self.token = token+++class Harness:+ """A Hooks on a fake portal, its callbacks recorded, and a sender stand-in that crosses after+ `push_to_cross` pushes, as the zone model does."""++ def __init__(self, version=1, models=None, push_to_cross=2, tokens=None):+ self.bus = FakeBus(versions={capture_portal.INTERFACE: version})+ self.bus.answers["CreateSession"] = (0, {"session_handle": SESSION, "capabilities": 3})+ self.bus.answers["GetZones"] = (0, {"zones": [(1920, 1080, 0, 0)], "zone_set": 7})+ self.bus.answers["SetPointerBarriers"] = (0, {"failed_barriers": []})+ self.bus.returns["CreateSession2"] = (vardict({"session_handle": SESSION}),)+ self.bus.returns["ConnectToEIS"] = (99,)+ self.ei = FakeEi()+ self.keys, self.mice, self.motions, self.homes, self.failures = [], [], [], [], []+ self.away = False+ self.models = models if models is not None else [return_edge.ReturnEdge("right")]+ self.push_to_cross = push_to_cross+ self.tokens = tokens or MemoryTokens()+ self.hooks = capture_portal.Hooks(self._key, self._mouse, self._motion, connect=lambda: self.bus,+ ei=lambda fd: self.ei, tokens=self.tokens)+ self.hooks.grab_while(lambda: self.away)+ self.hooks.barriers_from(lambda: self.models)+ self.hooks.on_home = lambda: self.homes.append(True) or setattr(self, "away", False)+ self.hooks.on_failure = self.failures.append+ self.pointer = FakeDevice("captured relative pointer", {1, 16, 32})+ self.keyboard = FakeDevice("captured keyboard", {4})++ def _key(self, name, down, vk, us):+ self.keys.append((name, down, vk))+ return True++ def _mouse(self, message, x, y, data):+ self.mice.append((message, data))+ return True++ def _motion(self, dx, dy):+ self.motions.append((dx, dy))+ if len(self.motions) >= self.push_to_cross:+ self.away = True++ def start(self):+ self.hooks.start()+ wait_for(lambda: self.bus.made("Enable"), what="the session to be enabled")++ def activate(self, x=1920.0, y=500.0, barrier=1, activation=3):+ # libei's start sequence is the portal's activation id.+ self.ei.feed(("start", self.pointer, activation), ("start", self.keyboard, activation))+ self.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"activation_id": activation, "cursor_position": (x, y), "barrier_id": barrier})))+ wait_for(lambda: self.hooks.holding, what="the capture to begin")++ def cross(self):+ self.activate()+ self.ei.feed(*[("motion", self.pointer, 10.0, 0.0)] * self.push_to_cross)+ wait_for(lambda: self.away and self.hooks._away, what="input to go away")++ def releases(self):+ return [(body[1]["activation_id"][1], body[1]["cursor_position"][1]) for body in self.bus.made("Release")]++[email protected](sys.platform == "win32", "the Wayland back ends select on pipes, which Windows cannot; they run only on Linux")+class HooksTest(unittest.TestCase):+ def setUp(self):+ desktop_portal._position = None+ desktop_portal._zones = []+ desktop_portal._regions = []+ desktop_portal._captured = False+ self.harness = None++ def tearDown(self):+ if self.harness is not None:+ self.harness.hooks.stop()++ def make(self, **kwargs):+ self.harness = Harness(**kwargs)+ return self.harness++ def test_the_barriers_go_on_the_zones_and_the_session_is_enabled(self):+ h = self.make()+ h.start()+ listed = h.bus.made("SetPointerBarriers")[0][2]+ self.assertEqual([item["position"] for item in listed], [("(iiii)", (1920, 0, 1920, 1079))])+ self.assertEqual(h.bus.made("SetPointerBarriers")[0][3], 7)+ self.assertEqual(desktop_portal.monitors(), ONE)++ def test_a_push_crosses_input_goes_away_and_comes_home_where_the_sender_lands_it(self):+ h = self.make()+ h.start()+ h.cross()+ self.assertEqual(h.motions, [(10, 0), (10, 0)])+ self.assertEqual(desktop_portal.position(), (1919, 500))+ h.ei.feed(("key", h.keyboard, 1, True), ("frame", h.keyboard, 0), ("key", h.keyboard, 1, False), ("frame", h.keyboard, 0),+ ("button", h.pointer, 0x110, True), ("scroll_discrete", h.pointer, 0, 120), ("frame", h.pointer, 0),+ ("motion", h.pointer, 2.5, -1.5), ("motion", h.pointer, 0.5, 0.5), ("frame", h.pointer, 0))+ wait_for(lambda: len(h.motions) >= 3 and len(h.keys) == 2, what="the input away")+ self.assertEqual(h.keys, [("esc", True, 1), ("esc", False, 1)])+ self.assertEqual(h.mice, [(capture_portal._BUTTONS[1][0], 0),+ (capture_portal.WM_MOUSEWHEEL, capture_portal._wheel_data(-capture_portal.WHEEL_DELTA))])+ self.assertEqual(h.motions[2:], [(2, -1), (1, 0)])+ self.assertEqual(h.releases(), [])+ desktop_portal.set_cursor_position(0, 300)+ h.away = False+ wait_for(lambda: h.releases(), what="the let-go")+ self.assertEqual(h.releases(), [(3, (0.0, 300.0))])+ self.assertFalse(h.hooks.holding)++ def test_a_let_go_waits_a_moment_for_the_landing_the_sender_reports_after_input_comes_home(self):+ h = self.make()+ h.start()+ h.cross()+ h.away = False+ time.sleep(capture_portal.LANDING_SECONDS / 3)+ desktop_portal.set_cursor_position(0, 777)+ wait_for(lambda: h.releases(), what="the let-go")+ self.assertEqual(h.releases(), [(3, (0.0, 777.0))])++ def test_moving_back_into_the_screen_lets_go_there_and_sends_nothing(self):+ h = self.make()+ h.start()+ h.activate()+ h.ei.feed(("motion", h.pointer, -5.0, 2.0))+ wait_for(lambda: h.releases(), what="the let-go")+ self.assertEqual(h.releases(), [(3, (1914.0, 502.0))])+ self.assertEqual(h.motions, [])+ self.assertFalse(h.hooks.holding)++ def test_a_key_at_the_edge_lets_go_and_reaches_nobody(self):+ h = self.make()+ h.start()+ h.activate()+ h.ei.feed(("key", h.keyboard, 30, True), ("frame", h.keyboard, 0))+ wait_for(lambda: h.releases(), what="the let-go")+ self.assertEqual(h.keys, [])++ def test_a_pause_in_the_push_lets_go_where_it_rests(self):+ h = self.make(push_to_cross=99)+ h.start()+ h.activate(y=40.0)+ h.ei.feed(("motion", h.pointer, 4.0, 0.0))+ wait_for(lambda: h.releases(), timeout=capture_portal.IDLE_SECONDS + 1, what="the let-go")+ self.assertEqual(h.releases(), [(3, (1919.0, 40.0))])+ self.assertEqual(h.motions, [(4, 0)])++ def test_events_ahead_of_the_activation_are_read_once_it_says_which_barrier(self):+ h = self.make()+ h.start()+ h.ei.feed(("start", h.pointer, 5), ("motion", h.pointer, 10.0, 0.0))+ time.sleep(0.15)+ self.assertEqual(h.motions, [])+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"activation_id": 5, "cursor_position": (1920.0, 9.0), "barrier_id": 1})))+ wait_for(lambda: h.motions, what="the early push")+ self.assertEqual(h.motions, [(10, 0)])++ def test_what_arrives_after_a_let_go_is_not_replayed_into_the_next_capture(self):+ h = self.make()+ h.start()+ h.activate()+ h.ei.feed(("motion", h.pointer, -5.0, 0.0))+ wait_for(lambda: h.releases(), what="the let-go")+ h.ei.feed(("motion", h.pointer, 7.0, 0.0), ("stop", h.pointer), ("stop", h.keyboard))+ time.sleep(0.15)+ h.activate(activation=4)+ time.sleep(0.15)+ self.assertEqual(h.motions, [])++ def test_a_barrier_it_does_not_know_is_let_go_at_once(self):+ h = self.make()+ h.start()+ h.ei.feed(("start", h.pointer, 1))+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"activation_id": 8, "cursor_position": (1920.0, 9.0), "barrier_id": 77})))+ wait_for(lambda: h.releases(), what="the let-go")+ self.assertEqual(h.releases(), [(8, (1919.0, 9.0))])++ def test_the_desktop_ending_a_capture_while_input_is_away_brings_it_home(self):+ h = self.make()+ h.start()+ h.cross()+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Deactivated",+ (SESSION, vardict({"activation_id": 3, "cursor_position": (1000.0, 10.0)})))+ wait_for(lambda: h.homes, what="input home")+ self.assertFalse(h.hooks.holding)+ self.assertEqual(desktop_portal.position(), (1000, 10))+ self.assertEqual(h.releases(), [])++ def test_disabled_sets_the_barriers_again_and_enables_the_session(self):+ h = self.make()+ h.start()+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Disabled", (SESSION, {}))+ wait_for(lambda: len(h.bus.made("Enable")) >= 2, what="the session enabled again")+ self.assertEqual(len(h.bus.made("SetPointerBarriers")), 2)++ def test_held_edges_take_the_barriers_away_and_their_return_puts_them_back(self):+ h = self.make()+ h.start()+ models = h.models+ h.models = []+ wait_for(lambda: len(h.bus.made("SetPointerBarriers")) == 2, what="the barriers removed")+ self.assertEqual(h.bus.made("SetPointerBarriers")[1][2], [])+ enables = len(h.bus.made("Enable"))+ h.models = models+ wait_for(lambda: len(h.bus.made("SetPointerBarriers")) == 3, what="the barriers back")+ wait_for(lambda: len(h.bus.made("Enable")) == enables + 1, what="enabled again")++ def test_a_stop_while_input_is_away_lets_go_and_ends_the_connection(self):+ h = self.make()+ h.start()+ h.cross()+ h.hooks.stop()+ self.assertEqual(len(h.releases()), 1)+ self.assertTrue(h.bus.closed and h.ei.closed)+ self.assertFalse(h.hooks.holding)++ def test_a_dead_input_connection_lets_go_ends_the_session_and_says_why(self):+ h = self.make()+ h.start()+ h.cross()+ h.ei.feed(("disconnect",))+ wait_for(lambda: h.failures, what="the failure")+ self.assertIn("stopped letting Beamer capture", h.failures[0].sentence)+ wait_for(lambda: h.bus.closed, what="the connection closed")+ self.assertEqual(len(h.releases()), 1)++ def test_a_stalled_thread_holding_input_has_its_connection_ended(self):+ saved = capture_portal.STALL_SECONDS+ capture_portal.STALL_SECONDS = 0.3+ try:+ h = self.make()+ h.start()+ h.activate()+ stalled = h.hooks._on_motion++ def stall(dx, dy):+ time.sleep(1.0)+ stalled(dx, dy)++ h.hooks._on_motion = stall+ h.ei.feed(("motion", h.pointer, 10.0, 0.0))+ wait_for(lambda: h.bus.aborted, timeout=2, what="the watchdog")+ finally:+ capture_portal.STALL_SECONDS = saved++ def test_a_refusal_is_said_in_the_apps_words_after_start_returns(self):+ h = self.make()+ h.bus.answers["CreateSession"] = (1, {})+ h.hooks.start()+ wait_for(lambda: h.failures, what="the refusal")+ self.assertEqual(h.failures[0].sentence, capture_portal.REFUSED)++ def test_no_input_capture_portal_fails_the_start_in_the_apps_words(self):+ h = self.make(version=0)+ with self.assertRaises(capture_portal.CaptureUnavailable) as raised:+ h.hooks.start()+ self.assertEqual(raised.exception.sentence, capture_portal.NO_PORTAL)++ # Review fixes (Codex Sol and a cold Opus pass, 01-10-2026)++ def test_a_release_that_fails_ends_the_session_rather_than_leaving_input_captured(self):+ h = self.make()+ h.start()+ h.activate()++ def broken(body):+ raise portal.PortalError("Release failed")++ h.bus.returns["Release"] = broken+ h.ei.feed(("motion", h.pointer, -5.0, 0.0))+ wait_for(lambda: h.failures, what="the failure")+ wait_for(lambda: h.bus.closed, what="the connection closed")++ def test_input_sent_away_with_nothing_captured_is_brought_home(self):+ h = self.make()+ h.start()+ h.away = True # the tray, or a driven machine's move that passed input_held() a moment too early+ wait_for(lambda: h.homes, what="input home")+ self.assertFalse(h.away)++ def test_input_sent_away_from_another_thread_during_a_press_keeps_the_key_that_follows(self):+ h = self.make(push_to_cross=99)+ h.start()+ h.activate()+ h.away = True+ h.ei.feed(("key", h.keyboard, 1, True), ("frame", h.keyboard, 0))+ wait_for(lambda: h.keys, what="the key away")+ self.assertEqual(h.keys, [("esc", True, 1)])+ self.assertEqual(h.releases(), [])++ def test_the_desktop_ending_a_press_the_sender_already_took_away_brings_it_home(self):+ h = self.make(push_to_cross=99)+ h.start()+ h.activate()+ h.away = True+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Deactivated", (SESSION, vardict({"activation_id": 3})))+ wait_for(lambda: h.homes, what="input home")++ def test_a_barrier_request_the_portal_never_answers_ends_the_capture(self):+ saved = capture_portal.REQUEST_SECONDS+ capture_portal.REQUEST_SECONDS = 0.3+ try:+ h = self.make()+ h.bus.answers["SetPointerBarriers"] = None+ h.hooks.start()+ wait_for(lambda: h.failures, what="the failure")+ finally:+ capture_portal.REQUEST_SECONDS = saved++ def test_an_activation_with_no_id_is_still_let_go(self):+ h = self.make(push_to_cross=99)+ h.start()+ h.ei.feed(("start", h.pointer, 1))+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"cursor_position": (1920.0, 500.0), "barrier_id": 1})))+ wait_for(lambda: h.hooks.holding, what="the capture")+ h.ei.feed(("motion", h.pointer, -5.0, 0.0))+ wait_for(lambda: h.bus.made("Release"), what="the let-go")+ self.assertNotIn("activation_id", h.bus.made("Release")[0][1])++ def test_a_push_that_meets_two_barriers_at_once_finds_its_wall_from_the_pointer(self):+ h = self.make(models=[return_edge.CornerPush("top_right", "right")], push_to_cross=99)+ h.start()+ h.activate(x=1920.0, y=3.0, barrier=0)+ h.ei.feed(("motion", h.pointer, 4.0, -4.0))+ wait_for(lambda: h.motions, what="the corner push")+ self.assertTrue(h.hooks.holding)++ def test_input_from_an_earlier_activation_never_feeds_a_later_one(self):+ h = self.make()+ h.start()+ h.ei.feed(("start", h.pointer, 3), ("motion", h.pointer, 10.0, 0.0), ("motion", h.pointer, 10.0, 0.0),+ ("stop", h.pointer), ("start", h.pointer, 4))+ time.sleep(0.15)+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"activation_id": 4, "cursor_position": (1920.0, 9.0), "barrier_id": 1})))+ wait_for(lambda: h.hooks.holding, what="the capture")+ time.sleep(0.15)+ self.assertEqual(h.motions, [])++ def test_a_landing_reported_while_the_release_is_in_flight_still_places_the_pointer(self):+ h = self.make()+ h.start()+ h.cross()+ moved = []+ desktop_portal.set_mover(lambda x, y: moved.append((x, y)))++ def late_landing(body):+ desktop_portal.note_position(0, 640)+ return ()++ h.bus.returns["Release"] = late_landing+ h.away = False+ wait_for(lambda: moved, timeout=2, what="the late landing")+ self.assertEqual(moved, [(0, 640)])+ desktop_portal.set_mover(None)++ # Second review (Opus, 01-10-2026)++ def test_a_corner_push_reported_off_the_barrier_line_finds_its_wall(self):+ for corner, point, push in (("bottom_right", (1919.0, 1079.0), (4.0, 4.0)), ("top_right", (1950.0, 3.0), (4.0, -4.0))):+ h = self.make(models=[return_edge.CornerPush(corner, "right")], push_to_cross=99)+ h.start()+ h.activate(x=point[0], y=point[1], barrier=0)+ h.ei.feed(("motion", h.pointer, *push))+ wait_for(lambda: h.motions, what=f"the {corner} push")+ self.assertTrue(h.hooks.holding, corner)+ h.hooks.stop()++ def test_input_away_with_nothing_captured_keeps_being_brought_home(self):+ h = self.make()+ h.hooks.on_home = lambda: h.homes.append(True) # a sender slow to come home+ h.start()+ h.away = True+ wait_for(lambda: len(h.homes) >= 2, timeout=3, what="a second try")++ def test_a_newer_captures_input_ahead_of_its_signal_is_kept_for_it(self):+ h = self.make()+ h.start()+ h.activate(activation=3)+ h.ei.feed(("motion", h.pointer, -5.0, 0.0))+ wait_for(lambda: h.releases(), what="the let-go")+ h.ei.feed(("stop", h.pointer), ("stop", h.keyboard))+ time.sleep(0.1)+ # The next capture's input arrives before its Activated signal.+ h.ei.feed(("start", h.pointer, 4), ("motion", h.pointer, 10.0, 0.0))+ time.sleep(0.1)+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Activated",+ (SESSION, vardict({"activation_id": 4, "cursor_position": (1920.0, 9.0), "barrier_id": 1})))+ wait_for(lambda: h.motions, what="the newer capture's push")++ def test_a_capture_the_desktop_never_announces_is_let_go(self):+ h = self.make()+ h.start()+ h.ei.feed(("start", h.pointer, 6), ("motion", h.pointer, 10.0, 0.0))+ wait_for(lambda: h.releases(), timeout=capture_portal.EARLY_SECONDS + 1.5, what="the let-go")+ self.assertEqual(h.releases()[0][0], 6)++ def test_repeated_disabled_signals_do_not_spin(self):+ h = self.make()+ h.start()+ for _ in range(5):+ h.bus.emit(portal.OBJECT_PATH, capture_portal.INTERFACE, "Disabled", (SESSION, {}))+ time.sleep(0.4)+ self.assertLessEqual(len(h.bus.made("SetPointerBarriers")), 2)++ def test_version_two_starts_with_the_kept_token_and_keeps_the_new_one(self):+ h = self.make(version=2, tokens=MemoryTokens("old"))+ h.bus.answers["Start"] = (0, {"capabilities": 3, "restore_token": "new"})+ h.start()+ self.assertEqual(h.bus.made("CreateSession"), [])+ options = h.bus.made("Start")[0][2]+ self.assertEqual((options["restore_token"], options["persist_mode"]), (("s", "old"), ("u", 2)))+ self.assertEqual(h.tokens.token, "new")++ def test_a_refusal_under_version_two_forgets_the_token(self):+ h = self.make(version=2, tokens=MemoryTokens("old"))+ h.bus.answers["Start"] = (1, {})+ h.hooks.start()+ wait_for(lambda: h.failures, what="the refusal")+ self.assertEqual(h.tokens.token, "")+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_capture_x11.py b/win_app/tests/test_capture_x11.pynew file mode 100644index 0000000..31e6a2b--- /dev/null+++ b/win_app/tests/test_capture_x11.py@@ -0,0 +1,657 @@+"""capture_x11 against a fake X connection: names, the raw-event parser, XTEST and absolute+filtering, buttons and the wheel as Windows messages, the grab taken and let go as the predicate+says, which side of a grab an event came from, events handed back played here, and the safety net+under a stuck thread. tools/x11_proof.sh runs the same module against a real X server."""++import struct+import sys+import threading+import time+import unittest+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+sys.path.append(str(Path(__file__).resolve().parent.parent.parent))++import capture_x11 # noqa: E402+from capture_x11 import Device # noqa: E402++POINTER = Device(2, capture_x11.XI_MASTER_POINTER, "Virtual core pointer")+KEYBOARD = Device(3, capture_x11.XI_MASTER_KEYBOARD, "Virtual core keyboard")+XTEST_POINTER = Device(4, capture_x11.XI_SLAVE_POINTER, "Virtual core XTEST pointer")+XTEST_KEYBOARD = Device(5, 4, "Virtual core XTEST keyboard")+MOUSE = Device(6, capture_x11.XI_SLAVE_POINTER, "Logitech USB Receiver Mouse", scrolls={2: (False, 15.0), 3: (True, 15.0)})+TABLET = Device(7, capture_x11.XI_SLAVE_POINTER, "Wacom Intuos Pen", absolute=True)+KEYS = Device(8, 4, "AT Translated Set 2 keyboard")++U = 0x01000000+# keycode to its groups, each [level 1, level 2]+KEYMAP = {+ 38: [[ord("a"), ord("A")], [U | 0x444, U | 0x424], [ord("a"), ord("A")], [U | 0x3B1, U | 0x391]], # a; ф; a; α+ 10: [[ord("1"), ord("!")]],+ 48: [[ord("'"), ord('"')]],+ 87: [[0xFF9C, 0xFFB1]], # KP_End, KP_1+ 65: [[ord(" "), ord(" ")]],+ 34: [[0xFE52, 0xFE52]], # dead circumflex+}+++class FakeKeymap:+ """XKB as far as these tests need it: Shift picks level 2, Caps Lock flips a letter, Num Lock+ flips a keypad key, and a group the key does not have wraps."""++ min_keycode, max_keycode = 8, 255++ def keysym(self, keycode, mods, group):+ groups = KEYMAP.get(keycode)+ if not groups:+ return 0+ levels = groups[group % len(groups)]+ level = 1 if mods & capture_x11.SHIFT_MASK else 0+ upper = capture_x11.keysym_text(levels[1]) or ""+ if mods & capture_x11.LOCK_MASK and upper.isalpha():+ level ^= 1+ if mods & capture_x11.NUM_LOCK_MASK and 0xFFAA <= levels[1] <= 0xFFB9:+ level ^= 1+ return levels[level]++ def text(self, keysym):+ return capture_x11.keysym_text(keysym)++ def empty(self, keycode):+ return keycode not in KEYMAP++ def reload(self):+ pass+++def raw_bytes(detail=0, sourceid=6, flags=0, raw=None, deviceid=2):+ """An XI2 raw event's bytes after its first ten, as python-xlib hands them over."""+ raw = raw or {}+ numbers = sorted(raw)+ mask_len = 1 if not numbers else max(numbers) // 32 + 1+ mask = bytearray(mask_len * 4)+ for number in numbers:+ mask[number // 8] |= 1 << (number % 8)+ data = struct.pack("=HIIHHI4x", deviceid, 1234, detail, sourceid, mask_len, flags) + bytes(mask)+ for number in numbers: # accelerated, then raw: the accelerated ones doubled so a mix-up shows+ value = raw[number] * 2+ data += struct.pack("=iI", int(value // 1), int((value % 1) * 2 ** 32))+ for number in numbers:+ value = raw[number]+ data += struct.pack("=iI", int(value // 1), int((value % 1) * 2 ** 32))+ return data+++class FakeConnection:+ def __init__(self, devices=None):+ self.device_list = devices or [POINTER, KEYBOARD, XTEST_POINTER, XTEST_KEYBOARD, MOUSE, TABLET, KEYS]+ self.queue = []+ self.grabs = []+ self.refuse = set()+ self.calls = []+ self.mods, self.group = 0, 0+ self.mapping = list(range(1, 11))+ self.closed = False+ self.aborted = False+ self.raise_in_events = None+ self.keymap = FakeKeymap()+ self.serial = 100+ self.lock = threading.Lock()++ def next_serial(self):+ self.serial += 1+ return self.serial++ def events(self, timeout):+ if self.aborted:+ raise ConnectionError("aborted")+ if self.raise_in_events is not None:+ raise self.raise_in_events+ with self.lock:+ found, self.queue = self.queue, []+ if not found:+ time.sleep(timeout / 10)+ return found++ def push(self, *events):+ with self.lock:+ self.queue.extend(events)++ def devices(self):+ return list(self.device_list)++ def grab(self, device):+ self.calls.append(("grab", device.deviceid))+ if device.deviceid in self.refuse:+ return None+ self.grabs.append(device.deviceid)+ return self.next_serial()++ def ungrab(self, device):+ self.calls.append(("ungrab", device.deviceid, self.held_while_ungrabbing()))+ self.grabs.remove(device.deviceid)+ return self.next_serial()++ def fake_key(self, keycode, down):+ self.calls.append(("fake_key", keycode, down, tuple(self.grabs)))++ def fake_button(self, button, down):+ self.calls.append(("fake_button", button, down, tuple(self.grabs)))++ def pointer_mapping(self):+ return list(self.mapping)++ def state(self):+ self.calls.append(("state",))+ return self.mods, self.group++ def abort(self):+ self.aborted = True++ held_while_ungrabbing = staticmethod(lambda: None)++ def close(self):+ self.closed = True+++def raw(evtype, detail=0, sourceid=6, values=None, flags=0, sequence=0, master=None):+ if master is None:+ master = 3 if evtype in (capture_x11.XI_RAW_KEY_PRESS, capture_x11.XI_RAW_KEY_RELEASE) else 2+ _deviceid, detail, sourceid, flags, parsed = capture_x11.parse_raw(raw_bytes(detail, sourceid, flags, values))+ return ("raw", evtype, detail, sourceid, flags, parsed, master, sequence)+++def key(down, keycode, mods=0, group=0, sourceid=8, flags=0, sequence=0):+ return ("key", down, keycode, sourceid, flags, mods, group, 3, sequence)+++class Recorder:+ def __init__(self):+ self.keys, self.mice, self.motions = [], [], []+ self.answer = True++ def on_key(self, name, down, vk, us):+ self.keys.append((name, down, vk, us))+ return self.answer++ def on_mouse(self, message, x, y, data):+ self.mice.append((message, data))+ return self.answer++ def on_motion(self, dx, dy):+ self.motions.append((dx, dy))+++class Harness(unittest.TestCase):+ """Drives Hooks' handlers directly on a fake connection, with no thread."""++ def setUp(self):+ self.connection = FakeConnection()+ self.seen = Recorder()+ self.hooks = capture_x11.Hooks(self.seen.on_key, self.seen.on_mouse, self.seen.on_motion, connect=lambda: self.connection)+ self.hooks._connection = self.connection+ self.hooks._read_devices()+ self.hooks._buttons = self.connection.pointer_mapping()++ def feed(self, *events):+ for event in events:+ self.hooks._handle(event)++ def messages(self):+ return [capture_x11.mouse_event(message, data) for message, data in self.seen.mice]+++class ParseRawTest(unittest.TestCase):+ def test_reads_the_raw_values_not_the_accelerated_ones(self):+ deviceid, detail, sourceid, flags, values = capture_x11.parse_raw(raw_bytes(0, 6, 0, {0: 3.5, 1: -2.25}))+ self.assertEqual((deviceid, detail, sourceid, flags), (2, 0, 6, 0))+ self.assertEqual(values, {0: 3.5, 1: -2.25})++ def test_reads_a_sparse_mask(self):+ self.assertEqual(capture_x11.parse_raw(raw_bytes(raw={1: 4.0, 3: -1.0}))[4], {1: 4.0, 3: -1.0})++ def test_a_key_event_has_no_valuators(self):+ self.assertEqual(capture_x11.parse_raw(raw_bytes(detail=38, sourceid=8))[1:], (38, 8, 0, {}))+++class NamesTest(unittest.TestCase):+ def test_modifiers_are_named_as_windows_names_them(self):+ names = capture_x11.VK_TO_NAME+ self.assertEqual((names[29], names[97]), ("cmd", "cmd_r")) # Ctrl is "cmd", as on Windows+ self.assertEqual((names[125], names[126]), ("ctrl", "ctrl_r")) # Super is "ctrl"+ self.assertEqual((names[56], names[100], names[42], names[54]), ("alt", "alt_r", "shift", "shift_r"))+ self.assertEqual((names[1], names[28], names[96], names[59], names[88], names[194]), ("esc", "enter", "enter", "f1", "f12", "f24"))++ def test_the_trigger_names_and_titles_cover_the_default(self):+ self.assertEqual(capture_x11.VK_TITLES[97], "Right Ctrl")+ self.assertEqual(capture_x11.VK_TITLES[125], "Left Super")+ self.assertNotIn(163, set(capture_x11.VK_TO_NAME) - capture_x11.NOT_TRIGGER_VKS) # media keys are not triggers+ self.assertIn(57, capture_x11.UNRECORDABLE_TRIGGER_VKS)++ def test_hook_vk_is_the_keycode_less_eight(self):+ self.assertEqual(capture_x11.hook_vk(0xFFE4, 105), 97)+ self.assertEqual(capture_x11.hook_vk(0, 0), 0)++ def test_input_titles(self):+ self.assertEqual(capture_x11.input_title("key:97"), "Right Ctrl")+ self.assertEqual(capture_x11.input_title("key:30"), "A")+ self.assertEqual(capture_x11.input_title("key:240"), "Key 240")+ self.assertEqual(capture_x11.input_title("button:back"), "Back button")++ def test_keysym_text(self):+ self.assertEqual(capture_x11.keysym_text(ord("a")), "a")+ self.assertEqual(capture_x11.keysym_text(0xE9), "é")+ self.assertEqual(capture_x11.keysym_text(0x010020AC), "€")+ self.assertIsNone(capture_x11.keysym_text(0))+++class CharacterTest(unittest.TestCase):+ def char(self, keycode, mods=0, group=0):+ return capture_x11.character(keycode, mods, group, FakeKeymap())++ def test_shift_and_caps_lock(self):+ self.assertEqual(self.char(38), "a")+ self.assertEqual(self.char(38, capture_x11.SHIFT_MASK), "A")+ self.assertEqual(self.char(38, capture_x11.LOCK_MASK), "A")+ self.assertEqual(self.char(38, capture_x11.LOCK_MASK | capture_x11.SHIFT_MASK), "a")+ self.assertEqual(self.char(10, capture_x11.SHIFT_MASK), "!")+ self.assertEqual(self.char(10, capture_x11.LOCK_MASK), "1")++ def test_a_chord_sends_the_plain_key(self):+ self.assertEqual(self.char(38, capture_x11.CONTROL_MASK | capture_x11.SHIFT_MASK), "a")+ self.assertEqual(self.char(38, capture_x11.MOD1_MASK | capture_x11.LOCK_MASK), "a")+ self.assertEqual(self.char(10, capture_x11.MOD4_MASK | capture_x11.SHIFT_MASK), "1")++ def test_every_group_the_layout_has(self):+ self.assertEqual(self.char(38, 0, 1), "ф")+ self.assertEqual(self.char(38, capture_x11.SHIFT_MASK, 1), "Ф")+ self.assertEqual(self.char(38, 0, 3), "α") # a fourth group is read, not folded onto the first+ self.assertEqual(self.char(10, 0, 1), "1") # a key without the group wraps++ def test_the_keypad(self):+ self.assertEqual(self.char(87), "end") # Num Lock off: it moves, as Windows' VK_END+ self.assertEqual(self.char(87, capture_x11.NUM_LOCK_MASK), "1")+ self.assertEqual(self.char(87, capture_x11.NUM_LOCK_MASK | capture_x11.CONTROL_MASK), "1")++ def test_a_dead_key_types_nothing(self):+ self.assertIsNone(self.char(34))+++class KeyTest(Harness):+ def test_a_named_key_outside_a_grab_from_a_raw_event(self):+ self.feed(raw(capture_x11.XI_RAW_KEY_PRESS, 105, sourceid=8), raw(capture_x11.XI_RAW_KEY_RELEASE, 105, sourceid=8))+ self.assertEqual(self.seen.keys, [("cmd_r", True, 97, None), ("cmd_r", False, 97, None)])+ self.assertNotIn(("state",), self.connection.calls)++ def test_a_character_outside_a_grab_reads_the_state_once(self):+ self.connection.mods = capture_x11.SHIFT_MASK+ self.feed(raw(capture_x11.XI_RAW_KEY_PRESS, 38, sourceid=8))+ self.assertEqual(self.seen.keys, [("A", True, 30, "a")])+ self.assertEqual(self.connection.calls.count(("state",)), 1)++ def test_a_release_goes_out_under_its_press_s_name(self):+ self.connection.mods = capture_x11.NUM_LOCK_MASK+ self.feed(raw(capture_x11.XI_RAW_KEY_PRESS, 87, sourceid=8))+ self.connection.mods = 0 # Num Lock turned off while 1 is held+ self.feed(raw(capture_x11.XI_RAW_KEY_RELEASE, 87, sourceid=8))+ self.assertEqual(self.seen.keys, [("1", True, 79, None), ("1", False, 79, None)])++ def test_keys_from_inside_a_grab_come_from_the_grab(self):+ self.hooks.grab_while(lambda: True)+ self.hooks._tick()+ inside = self.connection.serial+ self.feed(raw(capture_x11.XI_RAW_KEY_PRESS, 38, sourceid=8, sequence=inside), key(True, 38, capture_x11.SHIFT_MASK, sequence=inside),+ key(True, 38, capture_x11.SHIFT_MASK, flags=capture_x11.XI_KEY_REPEAT, sequence=inside),+ raw(capture_x11.XI_RAW_KEY_RELEASE, 38, sourceid=8, sequence=inside), key(False, 38, sequence=inside))+ self.assertEqual(self.seen.keys, [("A", True, 30, "a"), ("A", True, 30, "a"), ("A", False, 30, "a")])+ self.assertNotIn(("state",), self.connection.calls)++ def test_a_raw_key_from_before_the_grab_still_counts_after_it(self):+ # Hold style, a quick tap: the release is queued before the grab and read after it.+ before = self.connection.serial+ self.hooks.grab_while(lambda: True)+ self.hooks._tick()+ self.feed(raw(capture_x11.XI_RAW_KEY_RELEASE, 105, sourceid=8, sequence=before))+ self.assertEqual(self.seen.keys, [("cmd_r", False, 97, None)])++ def test_a_raw_key_from_inside_a_grab_read_after_it_is_not_read_twice(self):+ away = [True]+ self.hooks.grab_while(lambda: away[0])+ self.hooks._tick()+ inside = self.connection.serial+ away[0] = False+ self.hooks._tick()+ self.feed(raw(capture_x11.XI_RAW_KEY_PRESS, 105, sourceid=8, sequence=inside), key(True, 105, sequence=inside))+ self.assertEqual(self.seen.keys, [("cmd_r", True, 97, None)])+ after = self.connection.serial+ self.feed(raw(capture_x11.XI_RAW_KEY_RELEASE, 105, sourceid=8, sequence=after))+ self.assertEqual(self.seen.keys[-1], ("cmd_r", False, 97, None))++ def test_sequence_numbers_wrap(self):+ self.assertTrue(capture_x11._at_or_after(3, 0xFFFE))+ self.assertFalse(capture_x11._at_or_after(0xFFFE, 3))++ def test_injected_keys_are_dropped_unless_asked_for(self):+ self.feed(raw(capture_x11.XI_RAW_KEY_PRESS, 105, sourceid=5), key(True, 105, sourceid=5))+ self.assertEqual(self.seen.keys, [])+ self.hooks.drop_injected = False+ self.feed(raw(capture_x11.XI_RAW_KEY_PRESS, 105, sourceid=5))+ self.assertEqual(self.seen.keys, [("cmd_r", True, 97, None)])++ def test_a_dead_key_is_not_reported(self):+ self.feed(raw(capture_x11.XI_RAW_KEY_PRESS, 34, sourceid=8))+ self.assertEqual(self.seen.keys, [])+++class HandedBackTest(Harness):+ """An input the sender hands back from inside a grab reached no app; it is played here."""++ def setUp(self):+ super().setUp()+ self.hooks.grab_while(lambda: True)+ self.hooks._tick()+ self.inside = self.connection.serial+ self.seen.answer = False++ def test_a_key_is_played_with_the_keyboard_let_go_around_it(self):+ self.feed(key(True, 123, sequence=self.inside)) # volume up, on the stays-here list+ self.assertEqual([call for call in self.connection.calls if call[0] == "fake_key"], [("fake_key", 123, True, (2,))])+ self.assertEqual(sorted(self.connection.grabs), [2, 3])++ def test_a_button_and_the_wheel_are_played_with_the_pointer_let_go(self):+ self.feed(raw(capture_x11.XI_RAW_BUTTON_PRESS, 8, sequence=self.inside), raw(capture_x11.XI_RAW_BUTTON_PRESS, 4, sequence=self.inside))+ fakes = [call for call in self.connection.calls if call[0] == "fake_button"]+ self.assertEqual(fakes, [("fake_button", 8, True, (3,)), ("fake_button", 4, True, (3,)), ("fake_button", 4, False, (3,))])+ self.assertEqual(sorted(self.connection.grabs), [2, 3])++ def test_nothing_from_outside_a_grab_is_played(self):+ self.feed(raw(capture_x11.XI_RAW_KEY_PRESS, 123, sourceid=8, sequence=self.inside - 1),+ raw(capture_x11.XI_RAW_BUTTON_PRESS, 8, sequence=self.inside - 2))+ self.assertEqual([call for call in self.connection.calls if call[0].startswith("fake")], [])++ def test_a_grab_refused_after_playing_lets_go_of_everything(self):+ self.connection.refuse = {3}+ self.feed(key(True, 123, sequence=self.inside))+ self.assertEqual(self.connection.grabs, [])+ self.assertFalse(self.hooks.grabbed)+++class PlayedTest(Harness):+ """What was played here stays held only until its own release, whichever way that comes."""++ def setUp(self):+ super().setUp()+ self.away = True+ self.hooks.grab_while(lambda: self.away)+ self.hooks._tick()+ self.inside = self.connection.serial++ def fakes(self):+ return [call[:3] for call in self.connection.calls if call[0].startswith("fake")]++ def test_a_played_key_is_let_go_when_its_release_comes_from_outside_the_grab(self):+ self.seen.answer = False+ self.feed(key(True, 123, sequence=self.inside))+ self.away = False+ self.hooks._tick()+ self.seen.answer = True # at home the sender keeps nothing+ self.feed(raw(capture_x11.XI_RAW_KEY_RELEASE, 123, sourceid=8, sequence=self.connection.serial))+ self.assertEqual(self.fakes(), [("fake_key", 123, True), ("fake_key", 123, False)])++ def test_a_played_button_is_let_go_by_its_release(self):+ self.seen.answer = False+ self.feed(raw(capture_x11.XI_RAW_BUTTON_PRESS, 9, sequence=self.inside))+ self.seen.answer = True+ self.feed(raw(capture_x11.XI_RAW_BUTTON_RELEASE, 9, sequence=self.inside))+ self.assertEqual(self.fakes(), [("fake_button", 9, True), ("fake_button", 9, False)])++ def test_whatever_is_still_played_is_let_go_when_capture_ends(self):+ self.seen.answer = False+ self.feed(key(True, 123, sequence=self.inside), raw(capture_x11.XI_RAW_BUTTON_PRESS, 8, sequence=self.inside))+ self.hooks._release_played()+ self.assertEqual(self.fakes()[-2:], [("fake_key", 123, False), ("fake_button", 8, False)])+++class SpanTest(Harness):+ def test_a_let_go_span_is_forgotten_before_the_sequence_comes_round(self):+ away = [True]+ self.hooks.grab_while(lambda: away[0])+ self.hooks._tick()+ inside = self.connection.serial+ away[0] = False+ self.hooks._tick()+ self.assertTrue(self.hooks._inside(3, inside))+ with mock.patch.object(capture_x11, "SPAN_KEEP_SECONDS", -1):+ self.assertFalse(self.hooks._inside(3, inside)) # one lap on, the same number is outside++ def test_the_grab_counts_as_held_through_the_ungrab_s_round_trip(self):+ self.connection.held_while_ungrabbing = lambda: self.hooks.grabbed+ self.hooks.grab_while(lambda: True)+ self.hooks._tick()+ self.hooks._let_go()+ self.assertEqual([call[2] for call in self.connection.calls if call[0] == "ungrab"], [True, True])+++class MouseTest(Harness):+ def test_buttons_as_windows_messages(self):+ for number in (1, 2, 3, 8, 9):+ self.feed(raw(capture_x11.XI_RAW_BUTTON_PRESS, number), raw(capture_x11.XI_RAW_BUTTON_RELEASE, number))+ self.assertEqual(self.messages(), [("button", name, down) for name in ("left", "middle", "right", "back", "forward") for down in (True, False)])++ def test_buttons_follow_the_pointer_mapping(self):+ self.connection.mapping = [3, 2, 1] + list(range(4, 11)) # left-handed+ self.feed(("mapping", capture_x11.MAPPING_POINTER), raw(capture_x11.XI_RAW_BUTTON_PRESS, 1))+ self.assertEqual(self.messages(), [("button", "right", True)])++ def test_the_wheel_buttons_on_press_only(self):+ for number in (4, 5, 6, 7):+ self.feed(raw(capture_x11.XI_RAW_BUTTON_PRESS, number, sourceid=9), raw(capture_x11.XI_RAW_BUTTON_RELEASE, number, sourceid=9))+ self.assertEqual(self.messages(), [("wheel", 1.0, 0.0), ("wheel", -1.0, 0.0), ("wheel", 0.0, -1.0), ("wheel", 0.0, 1.0)])++ def test_a_smooth_scrolling_wheel_is_its_valuators_and_its_emulated_buttons_are_skipped(self):+ self.feed(raw(capture_x11.XI_RAW_BUTTON_PRESS, 5, flags=capture_x11.XI_POINTER_EMULATED),+ raw(capture_x11.XI_RAW_MOTION, values={3: 15.0}), raw(capture_x11.XI_RAW_MOTION, values={3: -7.5}),+ raw(capture_x11.XI_RAW_MOTION, values={3: -7.5}), raw(capture_x11.XI_RAW_MOTION, values={2: 15.0}))+ self.assertEqual(self.messages(), [("wheel", -1.0, 0.0), ("wheel", 0.5, 0.0), ("wheel", 0.5, 0.0), ("wheel", 0.0, 1.0)])+ self.assertEqual(self.seen.motions, [])++ def test_motion_carries_its_fraction_and_moves_the_pin(self):+ self.feed(raw(capture_x11.XI_RAW_MOTION, values={0: 0.6, 1: -1.5}), raw(capture_x11.XI_RAW_MOTION, values={0: 0.6, 1: -0.5}))+ self.assertEqual(self.seen.motions, [(0, -1), (1, -1)])+ self.assertEqual(self.seen.mice, [(capture_x11.WM_MOUSEMOVE, 0)] * 2)++ def test_injected_motion_is_dropped(self):+ self.feed(raw(capture_x11.XI_RAW_MOTION, sourceid=4, values={0: 5.0, 1: 0.0}), raw(capture_x11.XI_RAW_BUTTON_PRESS, 1, sourceid=4))+ self.assertEqual((self.seen.motions, self.seen.mice), ([], []))++ def test_an_absolute_pointer_moves_the_pin_but_gives_no_pressure(self):+ self.feed(raw(capture_x11.XI_RAW_MOTION, sourceid=7, values={0: 900.0, 1: 300.0}))+ self.assertEqual((self.seen.motions, self.seen.mice), ([], [(capture_x11.WM_MOUSEMOVE, 0)]))++ def test_a_new_device_is_read_on_a_hierarchy_change(self):+ self.connection.device_list.append(Device(9, capture_x11.XI_SLAVE_POINTER, "Virtual XTEST pointer 2"))+ self.feed(("hierarchy",), raw(capture_x11.XI_RAW_MOTION, sourceid=9, values={0: 5.0}))+ self.assertEqual(self.seen.motions, [])+++class GrabTest(Harness):+ def setUp(self):+ super().setUp()+ self.away = False+ self.hooks.grab_while(lambda: self.away)++ def test_grabs_every_master_while_away_and_lets_go_at_home(self):+ self.hooks._tick()+ self.assertEqual(self.connection.grabs, [])+ self.away = True+ self.hooks._tick()+ self.hooks._tick()+ self.assertEqual(self.connection.grabs, [2, 3])+ self.assertEqual(self.connection.calls.count(("grab", 2)), 1)+ self.away = False+ self.hooks._tick()+ self.assertEqual(self.connection.grabs, [])+ self.assertFalse(self.hooks.grabbed)++ def test_a_refused_grab_holds_nothing_and_is_tried_again(self):+ self.connection.refuse = {3}+ self.away = True+ with self.assertLogs(capture_x11.LOGGER, "WARNING") as logs:+ self.hooks._tick()+ self.hooks._tick()+ self.assertEqual(len(logs.records), 1)+ self.assertEqual(self.connection.grabs, [])+ self.connection.refuse = set()+ self.hooks._tick()+ self.assertEqual(self.connection.grabs, [2, 3])++ def test_a_predicate_that_raises_lets_go(self):+ self.away = True+ self.hooks._tick()++ def broken():+ raise RuntimeError("no")++ self.hooks.grab_while(broken)+ with self.assertLogs(capture_x11.LOGGER, "ERROR"):+ self.hooks._tick()+ self.assertEqual(self.connection.grabs, [])++ def test_a_new_master_while_away_is_grabbed_too(self):+ self.away = True+ self.hooks._tick()+ self.connection.device_list += [Device(10, capture_x11.XI_MASTER_POINTER, "Second pointer"),+ Device(11, capture_x11.XI_MASTER_KEYBOARD, "Second keyboard")]+ self.feed(("hierarchy",))+ self.assertEqual(self.connection.grabs, [])+ self.hooks._tick()+ self.assertEqual(sorted(self.connection.grabs), [2, 3, 10, 11])++ def test_raw_events_still_count_while_grabbed(self):+ self.away = True+ self.hooks._tick()+ inside = self.connection.serial+ self.feed(raw(capture_x11.XI_RAW_MOTION, values={0: 4.0, 1: 0.0}, sequence=inside), raw(capture_x11.XI_RAW_BUTTON_PRESS, 1, sequence=inside))+ self.assertEqual(self.seen.motions, [(4, 0)])+ self.assertEqual(self.messages()[-1], ("button", "left", True))+++class ThreadTest(unittest.TestCase):+ def make(self, connection, on_key=None):+ self.seen = Recorder()+ return capture_x11.Hooks(on_key or self.seen.on_key, self.seen.on_mouse, self.seen.on_motion, connect=lambda: connection)++ def wait_for(self, condition, timeout=2.0):+ end = time.monotonic() + timeout+ while time.monotonic() < end:+ if condition():+ return True+ time.sleep(0.01)+ return condition()++ def test_stop_lets_go_and_closes(self):+ connection = FakeConnection()+ hooks = self.make(connection)+ hooks.grab_while(lambda: True)+ hooks.start()+ self.assertTrue(self.wait_for(lambda: connection.grabs == [2, 3]))+ hooks.stop()+ self.assertEqual(connection.grabs, [])+ self.assertTrue(connection.closed)++ def test_the_loop_dying_lets_go(self):+ connection = FakeConnection()+ hooks = self.make(connection)+ hooks.grab_while(lambda: True)+ hooks.start()+ self.assertTrue(self.wait_for(lambda: connection.grabs == [2, 3]))+ with self.assertLogs(capture_x11.LOGGER, "ERROR"):+ connection.raise_in_events = ConnectionError("the X server went away")+ self.assertTrue(self.wait_for(lambda: connection.closed))+ self.assertEqual(connection.grabs, [])+ hooks.stop()++ def test_an_event_that_fails_does_not_stop_capture(self):+ connection = FakeConnection()+ hooks = self.make(connection)+ hooks.start()+ with self.assertLogs(capture_x11.LOGGER, "ERROR"):+ connection.push(("raw", capture_x11.XI_RAW_MOTION, 0, 6, 0, None, 2, 0)) # a malformed event+ connection.push(raw(capture_x11.XI_RAW_KEY_PRESS, 105, sourceid=8))+ self.assertTrue(self.wait_for(lambda: self.seen.keys))+ hooks.stop()+ self.assertEqual(self.seen.keys, [("cmd_r", True, 97, None)])++ def test_capture_ending_on_its_own_is_reported_and_a_stop_is_not(self):+ connection = FakeConnection()+ hooks = self.make(connection)+ failures = []+ hooks.on_failure = failures.append+ hooks.start()+ with self.assertLogs(capture_x11.LOGGER, "ERROR"):+ connection.raise_in_events = ConnectionError("the X server went away")+ self.assertTrue(self.wait_for(lambda: failures))+ hooks.stop()+ self.assertIsInstance(failures[0], ConnectionError)+ quiet = FakeConnection()+ hooks = self.make(quiet)+ hooks.on_failure = failures.append+ hooks.start()+ hooks.stop()+ self.assertEqual(len(failures), 1)++ def test_a_connection_that_cannot_open_is_the_caller_s_error(self):+ def refuse():+ raise RuntimeError("This X server has XInput 2.0; Beamer needs 2.1")++ hooks = capture_x11.Hooks(None, None, None, connect=refuse)+ with self.assertLogs(capture_x11.LOGGER, "ERROR"), self.assertRaisesRegex(RuntimeError, "needs 2.1"):+ hooks.start()++ def test_a_thread_stuck_while_grabbed_has_its_connection_ended(self):+ connection = FakeConnection()+ release = threading.Event()++ def stuck(*args):+ release.wait(5)+ return True++ hooks = self.make(connection, on_key=stuck)+ hooks.grab_while(lambda: True)+ with mock.patch.object(capture_x11, "STALL_SECONDS", 0.3):+ hooks.start()+ self.assertTrue(self.wait_for(lambda: connection.grabs == [2, 3]))+ with self.assertLogs(capture_x11.LOGGER, "ERROR") as logs:+ connection.push(key(True, 38, sequence=connection.serial))+ self.assertTrue(self.wait_for(lambda: connection.aborted))+ release.set()+ self.assertTrue(self.wait_for(lambda: connection.closed))+ self.assertIn("has not answered", logs.output[0])+ hooks.stop()++ def test_a_stop_that_times_out_ends_the_connection_and_a_start_waits_for_it(self):+ connection = FakeConnection()+ release = threading.Event()++ def stuck(*args):+ release.wait(10)+ return True++ hooks = self.make(connection, on_key=stuck)+ hooks.start()+ connection.push(raw(capture_x11.XI_RAW_KEY_PRESS, 105, sourceid=8))+ time.sleep(0.2)+ with mock.patch.object(threading.Thread, "join", lambda self, timeout=None: None), \+ self.assertLogs(capture_x11.LOGGER, "ERROR"):+ hooks.stop()+ self.assertTrue(connection.aborted)+ with self.assertRaisesRegex(RuntimeError, "has not stopped"):+ hooks.start()+ release.set()+ self.assertTrue(self.wait_for(lambda: connection.closed))+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_clipboard_win.py b/win_app/tests/test_clipboard_win.pyindex 55b8256..918d1c9 100644--- a/win_app/tests/test_clipboard_win.py+++ b/win_app/tests/test_clipboard_win.py@@ -15,6 +15,7 @@ sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(import clipboard_winfrom core import protocol+from core.tests import pngsfrom clipboard_win import BI_BITFIELDS, BI_RGB, CF_DIB, CF_UNICODETEXT, bgra_to_dib, dib_to_bgra@@ -25,7 +26,7 @@ def header(width, height, bpp, compression=BI_RGB, size=40):# 2x2 image, top-down, BGRA: blue, green / red, half-transparent white.BGRA = bytes([255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 128])-PNG = protocol.PNG_SIGNATURE + b"\x00" * 64+PNG = pngs.png()class DibCodecTests(unittest.TestCase):diff --git a/win_app/tests/test_clipboard_x11.py b/win_app/tests/test_clipboard_x11.pynew file mode 100644index 0000000..831ddfb--- /dev/null+++ b/win_app/tests/test_clipboard_x11.py@@ -0,0 +1,211 @@+import os+import subprocess+import sys+import threading+import time+import unittest+from pathlib import Path++try:+ from PySide6.QtCore import QBuffer, QIODevice+ from PySide6.QtGui import QColor, QImage+ from PySide6.QtWidgets import QApplication+except ImportError: # PySide6 is only in the Windows venv+ QApplication = None++WIN_APP = Path(__file__).resolve().parent.parent+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"+++def make_png(colour="red", size=2) -> bytes:+ image = QImage(size, size, QImage.Format.Format_ARGB32)+ image.fill(QColor(colour))+ buffer = QBuffer()+ buffer.open(QIODevice.OpenModeFlag.WriteOnly)+ assert image.save(buffer, "PNG")+ return bytes(buffer.data())++[email protected](QApplication is None, "needs PySide6")+class ClipboardX11Test(unittest.TestCase):+ def setUp(self):+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ self.app = QApplication.instance() or QApplication([])+ import clipboard_x11++ self.cb = clipboard_x11+ self.clipboard = self.app.clipboard()+ self.real_timeout = clipboard_x11.TIMEOUT_SECONDS+ self.real_owns = clipboard_x11._owns+ self.clipboard.clear()+ clipboard_x11.forget_sync()++ def tearDown(self):+ self.cb.TIMEOUT_SECONDS = self.real_timeout+ self.cb._owns = self.real_owns+ self.app.processEvents()++ def outside_text(self, text):+ self.clipboard.setText(text)++ def spin_until(self, done, limit=3.0):+ end = time.monotonic() + limit+ while not done() and time.monotonic() < end:+ self.app.processEvents()+ time.sleep(0.001)++ def on_worker(self, fn):+ """Run fn on a plain thread while this (the GUI) thread spins the event loop."""+ box = {}++ def run():+ box["value"] = fn()++ thread = threading.Thread(target=run)+ thread.start()+ self.spin_until(lambda: not thread.is_alive())+ thread.join(1)+ self.assertFalse(thread.is_alive(), "worker call never returned")+ return box["value"]++ def test_text_round_trip(self):+ self.assertTrue(self.cb.set_contents("héllo\nworld", None))+ self.assertEqual(self.cb.get_contents(), ("héllo\nworld", None))++ def test_crlf_text_is_written_as_lf(self):+ self.assertTrue(self.cb.set_contents("one\r\ntwo", None))+ self.assertEqual(self.cb.get_contents(), ("one\ntwo", None))++ def test_png_round_trip_is_the_same_bytes(self):+ png = make_png()+ self.assertTrue(self.cb.set_contents(None, png))+ self.assertEqual(self.cb.get_contents(), (None, png))++ def test_image_only_clipboard_is_encoded_as_png(self):+ image = QImage(3, 2, QImage.Format.Format_ARGB32)+ image.fill(QColor("blue"))+ self.clipboard.setImage(image)+ text, png = self.cb.get_contents()+ self.assertIsNone(text)+ self.assertTrue(png.startswith(PNG_SIGNATURE))+ decoded = QImage.fromData(png, "PNG")+ self.assertEqual((decoded.width(), decoded.height()), (3, 2))++ def test_text_and_png_together(self):+ png = make_png("green")+ self.assertTrue(self.cb.set_contents("caption", png))+ self.assertEqual(self.cb.get_contents(), ("caption", png))++ def test_nothing_to_set_is_false(self):+ self.assertFalse(self.cb.set_contents(None, None))++ def test_undecodable_png_leaves_the_text_only(self):+ self.assertTrue(self.cb.set_contents("kept", b"not a png"))+ self.assertEqual(self.cb.get_contents(), ("kept", None))+ self.assertFalse(self.cb.set_contents(None, b"not a png"))++ def test_empty_clipboard_reads_as_nothing(self):+ self.assertEqual(self.cb.get_contents(), (None, None))++ def test_changed_contents_after_an_outside_change(self):+ self.outside_text("from another app")+ self.assertEqual(self.cb.changed_contents(), ("from another app", None))+ self.assertEqual(self.cb.changed_contents(), (None, None))+ self.outside_text("again")+ self.assertEqual(self.cb.changed_contents(), ("again", None))++ def test_first_call_sends_what_is_there(self):+ self.outside_text("already copied")+ self.cb.forget_sync()+ self.assertEqual(self.cb.changed_contents(), ("already copied", None))++ def test_a_failed_read_does_not_count_as_sent(self):+ self.assertEqual(self.cb.changed_contents(), (None, None))+ self.assertIsNone(self.cb._synced_counter)+ self.outside_text("now there")+ self.assertEqual(self.cb.changed_contents(), ("now there", None))++ def test_own_write_is_not_a_change(self):+ self.outside_text("old")+ self.cb.changed_contents()+ self.assertTrue(self.cb.set_contents("from the other machine", None))+ self.assertEqual(self.cb.changed_contents(), (None, None))+ self.outside_text("copied here afterwards")+ self.assertEqual(self.cb.changed_contents(), ("copied here afterwards", None))++ def test_own_write_announced_late_is_not_a_change(self):+ # dataChanged may arrive from the event loop after setMimeData has returned. The offscreen+ # platform never reports ownership, which X11 does for data this process set.+ self.cb._owns = lambda clipboard: True+ self.assertTrue(self.cb.set_contents("late", None))+ self.cb._on_data_changed()+ self.assertEqual(self.cb.changed_contents(), (None, None))++ def test_outside_change_after_a_late_own_announcement_still_counts(self):+ self.cb._owns = lambda clipboard: True+ self.assertTrue(self.cb.set_contents("mine", None))+ self.outside_text("theirs")+ self.cb._on_data_changed()+ self.assertEqual(self.cb.changed_contents(), ("theirs", None))++ def test_forget_sync_sends_again(self):+ self.outside_text("once")+ self.assertEqual(self.cb.changed_contents(), ("once", None))+ self.assertEqual(self.cb.changed_contents(), (None, None))+ self.cb.forget_sync()+ self.assertEqual(self.cb.changed_contents(), ("once", None))++ def test_worker_thread_calls_are_marshalled_to_the_gui_thread(self):+ seen = []+ real = self.cb._read++ def spy():+ seen.append(threading.current_thread() is threading.main_thread())+ return real()++ self.cb._read = spy+ try:+ self.assertTrue(self.on_worker(lambda: self.cb.set_contents("via worker", None)))+ self.assertEqual(self.on_worker(self.cb.get_contents), ("via worker", None))+ self.assertEqual(self.on_worker(self.cb.changed_contents), (None, None))+ self.outside_text("outside")+ self.assertEqual(self.on_worker(self.cb.changed_contents), ("outside", None))+ finally:+ self.cb._read = real+ self.assertEqual(seen, [True, True])++ def test_a_wedged_gui_thread_times_out_instead_of_wedging_the_caller(self):+ self.cb.TIMEOUT_SECONDS = 0.05+ box = {}++ def run():+ box["get"] = self.cb.get_contents()+ box["changed"] = self.cb.changed_contents()+ box["set"] = self.cb.set_contents("never written", None)++ thread = threading.Thread(target=run)+ started = time.monotonic()+ thread.start()+ thread.join(3) # this thread does not process events, as a wedged GUI thread would not+ self.assertFalse(thread.is_alive())+ self.assertLess(time.monotonic() - started, 2)+ self.assertEqual(box, {"get": (None, None), "changed": (None, None), "set": False})+ self.app.processEvents()+ self.assertEqual(self.cb.get_contents(), (None, None), "a cancelled write must not land late")++ def test_no_application_reads_and_writes_nothing(self):+ code = (+ "import clipboard_x11 as c; "+ "print(c.get_contents(), c.changed_contents(), c.set_contents('a', None)); "+ "c.forget_sync()"+ )+ env = dict(os.environ, QT_QPA_PLATFORM="offscreen")+ result = subprocess.run(+ [sys.executable, "-c", code], cwd=WIN_APP, env=env, capture_output=True, text=True, timeout=30+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual(result.stdout.strip(), "(None, None) (None, None) False")+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_crossing_matrix.py b/win_app/tests/test_crossing_matrix.pyindex 15b0658..368ee09 100644--- a/win_app/tests/test_crossing_matrix.py+++ b/win_app/tests/test_crossing_matrix.py@@ -229,7 +229,7 @@ class WhatIsSharedTests(unittest.TestCase):line = pages_win.SCOPE["crossing"]self.assertNotIn("Two are shared", line)- self.assertIn("Only which side the other machine is on is shared", line)+ self.assertIn("Only which side a machine is on is shared, with that machine", line)try:@@ -238,6 +238,24 @@ except ImportError: # PySide6 is only in the Windows venvkvm_bridge_win = None+def real_window(path):+ """The window over the settings at `path`, built offscreen, which starts no receiver, hooks or announcer."""+ from PySide6.QtWidgets import QApplication++ import theme++ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ QApplication.instance() or QApplication([])+ theme.init_fonts()+ # A free port, as cfad061 has every window test take: 24820 is the installed Beamer's.+ settings = app_config.load_settings(path)+ settings["port"] = harness.free_port()+ app_config.write_settings(path, settings)+ window = kvm_bridge_win.WindowsApplication(path)+ window._send_to = lambda peer, message: True+ return window++@unittest.skipIf(kvm_bridge_win is None, "needs PySide6")class ArrangementHeldByBothTests(unittest.TestCase):"""`_on_arrangement` is how a peer's idea of where the machines are reaches this PC: a stamped@@ -264,6 +282,7 @@ class ArrangementHeldByBothTests(unittest.TestCase):_pull_peer_fields=lambda: self.refreshed.append("pulled"),sender=types.SimpleNamespace(refresh=lambda: self.refreshed.append("sender")),server=types.SimpleNamespace(peers_changed=lambda: self.refreshed.append("server")),+ _tell=lambda peer: self.refreshed.append("answered"),)def arrive(self, edge, stamp, by=None):@@ -275,7 +294,7 @@ class ArrangementHeldByBothTests(unittest.TestCase):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"])+ self.assertEqual(self.refreshed, ["pulled", "sender", "server", "answered"])def test_an_older_arrangement_is_ignored(self):self.arrive("top", 50)@@ -289,25 +308,18 @@ class ArrangementHeldByBothTests(unittest.TestCase):self.arrive("top", 200)self.assertEqual(self.refreshed, [])- 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-- config = default_config()- config.mac_return_edge, config.machine_id = "right", self.own+ def test_a_change_made_here_is_stamped_and_sent_to_that_machine(self):+ window = real_window(self.path)+ self.addCleanup(window.server.stop)told = []- page = 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(config.mac_return_edge, "top")- self.assertGreater(config.arrangement_set_at, 0)+ window._send_to = lambda peer, message: told.append((peer, message)) or False+ window._set_arrangement("top")+ entry = json.loads(self.path.read_text(encoding="utf-8"))["peers"][0]+ self.assertEqual((entry["side"], entry["side_by"]), ("top", self.own))+ self.assertGreater(entry["side_set_at"], 100)peer, message = told[0]self.assertEqual(peer, harness.B)- self.assertEqual(message["data"], {"edge": "top", "set_at": config.arrangement_set_at, "by": self.own})+ self.assertEqual(message["data"], {"edge": "top", "set_at": entry["side_set_at"], "by": self.own, "way_back": True})def test_a_fresh_config_holds_no_edge_though_the_crossing_page_offers_right(self):# Pinned known gap (G3 in the report).@@ -321,13 +333,20 @@ if __name__ == "__main__":@unittest.skipIf(kvm_bridge_win is None, "needs PySide6")class WaysReachTheDesignPageTests(unittest.TestCase):def test_changing_a_way_in_moves_the_design_preview(self):- config = default_config()+ import tempfile+ from pathlib import Path++ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ path = Path(directory.name) / "settings.json"+ settings = app_config.migrate(None, machine_id=protocol.id_text(harness.HERE))+ settings["peers"] = [harness.entry(harness.B, "Mac", side="right")]+ app_config.write_settings(path, settings)+ window = real_window(path)+ self.addCleanup(window.server.stop)looked = []- page = types.SimpleNamespace(- _config=config, _persist=lambda: True, sender=types.SimpleNamespace(update_config=lambda config: None),- _reflect_ways=lambda: None, _reflect_look=lambda: looked.append(tuple(config.crossing_methods)),- )- kvm_bridge_win.WindowsApplication._ways_changed(page, "corner", True)- kvm_bridge_win.WindowsApplication._set_part(page, "start", True)+ window._reflect_look = lambda: looked.append(sorted(window._ways_in()))+ window._ways_changed("corner", True)+ window._set_part("start", True)self.assertEqual(len(looked), 2)self.assertIn("corner", looked[0])diff --git a/win_app/tests/test_desktop_x11.py b/win_app/tests/test_desktop_x11.pynew file mode 100644index 0000000..fe37300--- /dev/null+++ b/win_app/tests/test_desktop_x11.py@@ -0,0 +1,271 @@+import os+import subprocess+import sys+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest import mock++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import desktop_x11+from core.return_edge import Rect++WIN_APP = Path(__file__).resolve().parent.parent+++class FakeXError(Exception):+ pass+++class FakeClosed(Exception):+ pass+++class FakeProperty:+ def __init__(self, value):+ self.value = value+++class FakeWindow:+ def __init__(self, wid, state=(), wm_class=("kate", "Kate"), error=None):+ self.wid, self.state, self.wm_class, self.error = wid, state, wm_class, error++ def get_full_property(self, atom, kind):+ if self.error:+ raise self.error+ return FakeProperty(list(self.state)) if self.state is not None else None++ def get_wm_class(self):+ if self.error:+ raise self.error+ return self.wm_class+++class FakeRoot:+ def __init__(self, display):+ self.display = display+ self.pointer = SimpleNamespace(root_x=0, root_y=0, mask=0)+ self.geometry = SimpleNamespace(width=1600, height=900)+ self.monitor_list = []+ self.monitor_error = None+ self.warps = []+ self.active = None+ self.calls = []++ def xrandr_get_monitors(self, is_active=True):+ self.calls.append(("xrandr_get_monitors", is_active))+ if self.monitor_error:+ raise self.monitor_error+ return SimpleNamespace(monitors=self.monitor_list)++ def get_geometry(self):+ return self.geometry++ def query_pointer(self):+ if self.display.dead:+ raise FakeClosed()+ return self.pointer++ def warp_pointer(self, x, y):+ self.warps.append((x, y))++ def get_full_property(self, atom, kind):+ assert atom == self.display.intern_atom("_NET_ACTIVE_WINDOW")+ return None if self.active is None else FakeProperty([self.active])+++class FakeDisplay:+ ATOMS = {"_NET_ACTIVE_WINDOW": 11, "_NET_WM_STATE": 12, "_NET_WM_STATE_FULLSCREEN": 13, "_NET_WM_STATE_ABOVE": 14}++ def __init__(self, randr=(1, 5)):+ self.randr = randr+ self.root = FakeRoot(self)+ self.windows = {}+ self.flushes = 0+ self.closed = False+ self.dead = False++ def has_extension(self, name):+ return name == "RANDR" and self.randr is not None++ def xrandr_query_version(self):+ return SimpleNamespace(major_version=self.randr[0], minor_version=self.randr[1])++ def intern_atom(self, name):+ return self.ATOMS[name]++ def create_resource_object(self, kind, wid):+ assert kind == "window"+ return self.windows[wid]++ def flush(self):+ self.flushes += 1++ def close(self):+ self.closed = True+++def connection(display):+ return SimpleNamespace(display=display, root=display.root, x_error=FakeXError, closed=(FakeClosed, OSError))+++class DesktopX11Test(unittest.TestCase):+ def setUp(self):+ self.display = FakeDisplay()+ self.root = self.display.root+ self.connects = mock.Mock(side_effect=lambda: connection(self.display))+ patch = mock.patch.object(desktop_x11, "_connect", self.connects)+ patch.start()+ self.addCleanup(patch.stop)+ desktop_x11._reset()+ self.addCleanup(desktop_x11._reset)++ def two_monitors(self):+ self.root.monitor_list = [+ SimpleNamespace(x=-1280, y=100, width_in_pixels=1280, height_in_pixels=1024),+ SimpleNamespace(x=0, y=0, width_in_pixels=1920, height_in_pixels=1080),+ ]++ def test_monitors_from_randr_one_five(self):+ self.two_monitors()+ self.assertEqual(desktop_x11.monitors(), [Rect(-1280, 100, 1280, 1024), Rect(0, 0, 1920, 1080)])+ self.assertEqual(self.root.calls, [("xrandr_get_monitors", True)])++ def test_monitors_falls_back_to_the_root_without_randr(self):+ self.display.randr = None+ self.two_monitors()+ self.assertEqual(desktop_x11.monitors(), [Rect(0, 0, 1600, 900)])+ self.assertEqual(self.root.calls, [])++ def test_monitors_falls_back_to_the_root_on_randr_one_four(self):+ self.display.randr = (1, 4)+ self.two_monitors()+ self.assertEqual(desktop_x11.monitors(), [Rect(0, 0, 1600, 900)])+ self.assertEqual(self.root.calls, [])++ def test_monitors_accepts_a_later_major_version(self):+ self.display.randr = (2, 0)+ self.two_monitors()+ self.assertEqual(len(desktop_x11.monitors()), 2)++ def test_monitors_falls_back_to_the_root_when_the_request_fails(self):+ self.root.monitor_error = FakeXError()+ self.assertEqual(desktop_x11.monitors(), [Rect(0, 0, 1600, 900)])++ def test_monitors_falls_back_to_the_root_when_randr_lists_none(self):+ self.assertEqual(desktop_x11.monitors(), [Rect(0, 0, 1600, 900)])++ def test_cursor_position(self):+ self.root.pointer = SimpleNamespace(root_x=-40, root_y=612, mask=0)+ self.assertEqual(desktop_x11.cursor_position(), (-40, 612))++ def test_set_cursor_position_warps_with_ints_and_flushes_once(self):+ desktop_x11.set_cursor_position(321.0, 123.9)+ self.assertEqual(self.root.warps, [(321, 123)])+ for value in self.root.warps[0]:+ self.assertIs(type(value), int)+ self.assertEqual(self.display.flushes, 1)++ def test_button_down_reads_the_pointer_mask(self):+ cases = {"left": 1 << 8, "middle": 1 << 9, "right": 1 << 10}+ for name, bit in cases.items():+ for other in cases:+ with self.subTest(name=name, mask=other):+ self.root.pointer = SimpleNamespace(root_x=0, root_y=0, mask=cases[other] | 1)+ self.assertEqual(desktop_x11.button_down(name), other == name)+ self.root.pointer = SimpleNamespace(root_x=0, root_y=0, mask=0)+ self.assertFalse(desktop_x11.button_down(name))++ def test_button_down_is_false_for_back_forward_and_unknown(self):+ self.root.pointer = SimpleNamespace(root_x=0, root_y=0, mask=0x1F00)+ for name in ("back", "forward", "wheel", ""):+ with self.subTest(name=name):+ self.assertFalse(desktop_x11.button_down(name))++ def fullscreen(self, **kwargs):+ window = FakeWindow(77, state=kwargs.pop("state", (13,)), **kwargs)+ self.display.windows[77] = window+ self.root.active = 77+ return window++ def test_full_screen_app_names_the_window_class(self):+ self.fullscreen()+ self.assertEqual(desktop_x11.full_screen_app(), "Kate")++ def test_full_screen_app_is_none_when_not_full_screen(self):+ self.fullscreen(state=(14,))+ self.assertIsNone(desktop_x11.full_screen_app())++ def test_full_screen_app_is_none_without_a_state_property(self):+ self.fullscreen(state=None)+ self.assertIsNone(desktop_x11.full_screen_app())++ def test_full_screen_app_is_none_without_an_active_window(self):+ self.assertIsNone(desktop_x11.full_screen_app())+ self.root.active = 0+ self.assertIsNone(desktop_x11.full_screen_app())++ def test_full_screen_app_without_a_wm_class_is_an_app(self):+ self.fullscreen(wm_class=None)+ self.assertEqual(desktop_x11.full_screen_app(), "An app")+ self.fullscreen(wm_class=("kate", ""))+ self.assertEqual(desktop_x11.full_screen_app(), "An app")++ def test_full_screen_app_is_none_when_the_window_vanishes(self):+ self.fullscreen(error=FakeXError())+ self.assertIsNone(desktop_x11.full_screen_app())++ def test_one_connection_is_shared_across_calls(self):+ desktop_x11.cursor_position()+ desktop_x11.button_down("left")+ desktop_x11.set_cursor_position(1, 2)+ self.assertEqual(self.connects.call_count, 1)++ def test_a_dropped_connection_reconnects_on_the_next_call(self):+ first = self.display+ desktop_x11.cursor_position()+ first.dead = True+ with self.assertRaises(FakeClosed):+ desktop_x11.cursor_position()+ self.assertTrue(first.closed)+ self.display = FakeDisplay()+ self.display.root.pointer = SimpleNamespace(root_x=5, root_y=6, mask=0)+ self.assertEqual(desktop_x11.cursor_position(), (5, 6))+ self.assertEqual(self.connects.call_count, 2)++ def test_an_oserror_also_drops_the_connection(self):+ desktop_x11.cursor_position()+ with mock.patch.object(self.root, "query_pointer", side_effect=BrokenPipeError()):+ with self.assertRaises(OSError):+ desktop_x11.cursor_position()+ desktop_x11.cursor_position()+ self.assertEqual(self.connects.call_count, 2)++ def test_an_x_error_keeps_the_connection(self):+ with mock.patch.object(self.root, "query_pointer", side_effect=FakeXError()):+ with self.assertRaises(FakeXError):+ desktop_x11.cursor_position()+ desktop_x11.cursor_position()+ self.assertEqual(self.connects.call_count, 1)++ def test_a_failed_connect_is_retried(self):+ self.connects.side_effect = [OSError("no display"), connection(self.display)]+ with self.assertRaises(OSError):+ desktop_x11.cursor_position()+ desktop_x11.cursor_position()+ self.assertEqual(self.connects.call_count, 2)+++class ImportTest(unittest.TestCase):+ def test_imports_without_loading_xlib(self):+ code = (+ "import sys; sys.path.append('..'); import desktop_x11; "+ "sys.exit(1 if any(m == 'Xlib' or m.startswith('Xlib.') for m in sys.modules) else 0)"+ )+ done = subprocess.run([sys.executable, "-c", code], cwd=WIN_APP, capture_output=True, text=True)+ self.assertEqual(done.returncode, 0, done.stderr)+++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 8d25a95..f0d8756 100644--- a/win_app/tests/test_hide_addresses_win.py+++ b/win_app/tests/test_hide_addresses_win.py@@ -11,6 +11,7 @@ try:from PySide6.QtWidgets import QApplicationimport kvm_bridge_win+ from core.tests import responder_harness as harnessimport themeexcept ImportError: # PySide6 is only in the Windows venvkvm_bridge_win = None@@ -24,12 +25,13 @@ class HideAddressesWindowTest(unittest.TestCase):theme.init_fonts()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",+ self.raw = {"host": "192.0.2.20", "port": harness.free_port(), "auth_token": "synthetic", "paired_with": "MacBook Pro","mac_host": "192.0.2.10", "mac_return_edge": "left"}(folder / "config.json").write_text(json.dumps(self.raw))self.window = kvm_bridge_win.WindowsApplication(self.config)def tearDown(self):+ self.window.server.stop()self.window.deleteLater()def edit_settings(self, **changes):diff --git a/win_app/tests/test_inject_portal.py b/win_app/tests/test_inject_portal.pynew file mode 100644index 0000000..0ab38bf--- /dev/null+++ b/win_app/tests/test_inject_portal.py@@ -0,0 +1,453 @@+"""Wayland injection and its clipboard on fakes: key steps for a desktop that repeats keys itself+and whose keymap cannot change, the wheel in libei's units, and the RemoteDesktop session against+a scripted portal and libei: the remembered permission, the devices, the pointer kept on the+displays, keys and buttons let go, a refusal said in the app's words, and the clipboard both ways."""++import os+import sys+import threading+import time+import unittest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++import clipboard_portal+import desktop_portal+import inject_portal+import portal+from inject_x11 import MAP, NO_REPEAT, PRESS, RELEASE, REPEAT+from portal_fakes import FakeBus, FakeDevice, FakeEi, vardict, wait_for++SESSION = "/org/freedesktop/portal/desktop/session/1_42/beamer2"+++class FakeKeymap:+ """A US keymap's letters and digits, as xkb_x11.Keymap answers: keycodes are evdev + 8, the+ Shift bit is 1 and Caps Lock 2."""++ KEYS = {38: ("a", "A"), 10: ("1", "!"), 39: ("s", "S")}+ min_keycode, max_keycode = 8, 255++ def keysym(self, keycode, mods, group):+ pair = self.KEYS.get(keycode)+ if pair is None:+ return 0+ return ord(pair[1] if mods & 1 else pair[0])++ def text(self, keysym):+ return chr(keysym) if keysym else None++ def empty(self, keycode):+ return keycode not in self.KEYS++ def core_mods(self, mask):+ return mask+++class StepsTest(unittest.TestCase):+ def test_a_key_with_shift_worked_around_it_is_let_go_at_once_and_repeat_and_map_mean_nothing(self):+ steps = [(NO_REPEAT, 38), (PRESS, 50), (PRESS, 38), (RELEASE, 50), (REPEAT, 38), (MAP, 200, 0x41, False)]+ self.assertEqual(inject_portal.wayland_steps(steps), [(42, True), (30, True), (30, False), (42, False)])++ def test_the_wheel_in_120ths_with_the_fraction_carried_and_pixels_as_they_are(self):+ carry = [0.0, 0.0]+ self.assertEqual(inject_portal.scroll_steps(1, 0, "line", carry), ("discrete", 0, -120))+ self.assertEqual(inject_portal.scroll_steps(0.004, 0, "line", carry), ("discrete", 0, 0))+ self.assertEqual(inject_portal.scroll_steps(0.005, -1, "line", carry), ("discrete", -120, -1))+ self.assertEqual(inject_portal.scroll_steps(-3.5, 2, "pixel", carry), ("pixels", 2.0, 3.5))++ def test_a_layout_with_no_key_for_a_character_has_no_spare_to_map(self):+ layout = inject_portal.WaylandLayout(FakeKeymap())+ self.assertEqual(layout.spare(), [])+ state = inject_portal.KeyState()+ self.assertEqual(inject_portal.plan_key("é", True, None, state, layout, 0, 0), [])+++class MemoryTokens:+ def __init__(self, token=""):+ self.token = token++ def read(self):+ return self.token++ def write(self, token):+ self.token = token++[email protected](sys.platform == "win32", "the Wayland back ends select on pipes, which Windows cannot; they run only on Linux")+class RemoteTest(unittest.TestCase):+ def setUp(self):+ desktop_portal._position = None+ desktop_portal._zones = []+ desktop_portal._regions = []+ desktop_portal._captured = False+ desktop_portal._mover = None+ self.problems = []+ inject_portal.on_problem = self.problems.append+ self.bus = FakeBus(versions={inject_portal.INTERFACE: 2, inject_portal.CLIPBOARD: 1})+ self.bus.answers["CreateSession"] = (0, {"session_handle": SESSION})+ self.bus.answers["Start"] = (0, {"devices": 3, "clipboard_enabled": True, "restore_token": "new"})+ self.bus.returns["ConnectToEIS"] = (99,)+ self.ei = FakeEi()+ self.tokens = MemoryTokens("old")+ self.remote = inject_portal.Remote(connect=lambda: self.bus, ei=lambda fd: self.ei, tokens=self.tokens,+ keymap=lambda text: FakeKeymap())+ inject_portal._remote = self.remote+ clipboard_portal.forget_sync()++ def tearDown(self):+ self.remote.stop()+ inject_portal._remote = None+ inject_portal.on_problem = None++ def up(self):+ self.remote.start()+ wait_for(self.remote.ready.is_set, what="the session")+ self.absolute = FakeDevice("absolute", {2, 16, 32}, regions=[(0, 0, 1920, 1080, 1.0)])+ self.pointer = FakeDevice("pointer", {1, 16, 32})+ self.keyboard = FakeDevice("keyboard", {4}, keymap="xkb_keymap {}")+ devices = (self.absolute, self.pointer, self.keyboard)+ self.ei.feed(("seat", 7), *[("device_added", d) for d in devices], *[("device_resumed", d) for d in devices])+ wait_for(lambda: len(self.ei.sends("start")) == 3, what="the devices to emulate")+ wait_for(lambda: self.remote.layout is not None, what="the layout")++ def test_the_session_asks_with_the_kept_permission_and_keeps_the_new_one(self):+ self.up()+ names = [method for _interface, method, _body in self.bus.calls if method not in ("Get",)]+ self.assertEqual(names[:5], ["CreateSession", "SelectDevices", "RequestClipboard", "Start", "ConnectToEIS"])+ options = self.bus.made("SelectDevices")[0][1]+ self.assertEqual((options["restore_token"], options["persist_mode"], options["types"]), (("s", "old"), ("u", 2), ("u", 3)))+ self.assertEqual(self.tokens.token, "new")+ self.assertEqual(desktop_portal.monitors()[0].width, 1920)++ def test_the_pointer_lands_moves_and_stays_on_the_displays(self):+ self.up()+ desktop_portal.set_cursor_position(100, 100)+ inject_portal.inject_mouse_move(10, -5)+ inject_portal.inject_mouse_move(5000, 0)+ wait_for(lambda: len(self.ei.sends("absolute")) == 3, what="three moves")+ self.assertEqual([item[2:] for item in self.ei.sends("absolute")], [(100.0, 100.0), (110.0, 95.0), (1919.0, 95.0)])+ self.assertEqual(desktop_portal.cursor_position(), (1919, 95))++ def test_nothing_is_moved_for_real_while_the_capture_holds_the_pointer(self):+ self.up()+ desktop_portal.set_captured(True)+ desktop_portal.set_cursor_position(300, 300)+ inject_portal.inject_mouse_button("left", True)+ wait_for(lambda: self.ei.sends("button"), what="the button")+ self.assertEqual(self.ei.sends("absolute"), [])+ self.assertEqual(desktop_portal.cursor_position(), (300, 300))++ def test_keys_play_by_evdev_code_with_shift_worked_around_and_all_are_let_go(self):+ self.up()+ inject_portal.inject_key("A", True)+ inject_portal.inject_key("A", False)+ inject_portal.inject_key("ctrl", True)+ inject_portal.inject_key("A", True) # under a chord the peer's own Shift is never touched+ inject_portal.inject_mouse_button("left", True)+ inject_portal.release_all()+ wait_for(lambda: len(self.ei.sends("button")) == 2, what="the release")+ keys = [item[2:] for item in self.ei.sends("key")]+ self.assertEqual(keys, [(42, True), (30, True), (30, False), (42, False), (29, True), (30, True),+ (29, False), (30, False)])+ self.assertEqual([item[2:] for item in self.ei.sends("button")], [(0x110, True), (0x110, False)])++ def test_text_is_typed_with_the_peers_modifiers_let_go_around_it(self):+ self.up()+ inject_portal.inject_key("ctrl", True)+ inject_portal.inject_text("a!")+ wait_for(lambda: len(self.ei.sends("key")) >= 9, what="the text")+ keys = [item[2:] for item in self.ei.sends("key")]+ self.assertEqual(keys, [(29, True), (29, False), (30, True), (30, False),+ (42, True), (2, True), (42, False), (2, False), (29, True)])++ def test_the_wheel_goes_out_as_clicks(self):+ self.up()+ inject_portal.inject_scroll(-2, 0, "line")+ wait_for(lambda: self.ei.sends("scroll_discrete"), what="the wheel")+ self.assertEqual(self.ei.sends("scroll_discrete")[0][2:], (0, 240))++ def test_a_refusal_forgets_the_permission_and_says_so_in_the_apps_words(self):+ self.bus.answers["Start"] = (1, {})+ self.remote.start()+ wait_for(lambda: self.problems, what="the refusal")+ self.assertEqual(self.problems, [inject_portal.REFUSED])+ self.assertEqual(self.tokens.token, "")+ self.assertIsNone(clipboard_portal.change_stamp())+ self.assertEqual(clipboard_portal.get_contents(), (None, None))++ def test_a_desktop_without_remote_control_over_libei_is_said_plainly(self):+ self.bus.versions[inject_portal.INTERFACE] = 1+ self.remote.start()+ wait_for(lambda: self.problems, what="the problem")+ self.assertEqual(self.problems, [inject_portal.NO_PORTAL])++ def test_beamers_clipboard_is_written_to_the_app_that_pastes_it(self):+ self.up()+ before = clipboard_portal.change_stamp()+ self.assertTrue(clipboard_portal.set_contents("hello\r\nthere", None))+ self.assertEqual(clipboard_portal.change_stamp(), before + 1)+ offered = self.bus.made("SetSelection")[0][1]["mime_types"][1]+ self.assertIn("text/plain;charset=utf-8", offered)+ read, write = os.pipe()+ self.bus.returns["SelectionWrite"] = (write,)+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionOwnerChanged",+ (SESSION, vardict({"mime_types": offered, "session_is_owner": True})))+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionTransfer", (SESSION, "text/plain;charset=utf-8", 4))+ with os.fdopen(read, "rb") as handle:+ self.assertEqual(handle.read(), b"hello\nthere")+ wait_for(lambda: self.bus.made("SelectionWriteDone"), what="the transfer to finish")+ self.assertEqual(self.bus.made("SelectionWriteDone")[0][1:], (4, True))+ self.assertEqual(clipboard_portal.change_stamp(), before + 1) # its own echo is no change+ self.assertEqual(clipboard_portal.changed_contents(), (None, None))++ def test_another_apps_copy_is_read_once_and_moves_the_stamp(self):+ self.up()+ before = clipboard_portal.change_stamp()+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionOwnerChanged",+ (SESSION, vardict({"mime_types": ["UTF8_STRING", "text/plain;charset=utf-8"], "session_is_owner": False})))+ wait_for(lambda: clipboard_portal.change_stamp() == before + 1, what="the copy")++ def selection(body):+ read, write = os.pipe()+ threading.Thread(target=lambda: (os.write(write, b"from another app"), os.close(write))).start()+ return (read,)++ self.bus.returns["SelectionRead"] = selection+ self.assertEqual(clipboard_portal.changed_contents(), ("from another app", None))+ self.assertEqual(self.bus.made("SelectionRead")[0][1], "text/plain;charset=utf-8")+ self.assertEqual(clipboard_portal.changed_contents(), (None, None))+ self.assertEqual(clipboard_portal.get_contents(), ("from another app", None))++ def test_an_app_that_never_hands_the_clipboard_over_costs_one_read(self):+ self.up()+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionOwnerChanged",+ (SESSION, vardict({"mime_types": ["text/plain"], "session_is_owner": False})))+ wait_for(lambda: self.remote.offered, what="the copy")+ read, write = os.pipe()+ self.bus.returns["SelectionRead"] = (read,)+ saved = clipboard_portal.TIMEOUT_SECONDS+ clipboard_portal.TIMEOUT_SECONDS = 0.2+ try:+ self.assertEqual(clipboard_portal._read_fd(read, clipboard_portal.TIMEOUT_SECONDS), None)+ finally:+ clipboard_portal.TIMEOUT_SECONDS = saved+ os.close(write)++ def test_the_session_closing_lets_go_and_says_so(self): # closed from the desktop+ self.up()+ inject_portal.inject_key("shift", True)+ wait_for(lambda: self.ei.sends("key"), what="the key")+ self.bus.emit(SESSION, portal.SESSION, "Closed", ())+ wait_for(lambda: self.problems, what="the problem")+ self.assertEqual(self.problems[0], inject_portal.CLOSED)+ self.assertEqual(self.ei.sends("key")[-1][2:], (42, False))+ self.assertTrue(self.ei.closed and self.bus.closed)+++ # Review fixes (Codex Sol and a cold Opus pass, 01-10-2026)++ def test_a_paste_the_portal_fails_costs_that_paste_and_not_the_session(self):+ self.up()+ clipboard_portal.set_contents("x", None)++ def broken(body):+ raise portal.PortalError("stale serial")++ self.bus.returns["SelectionWrite"] = broken+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionTransfer", (SESSION, "text/plain", 9))+ wait_for(lambda: self.bus.made("SelectionWriteDone"), what="the failed transfer answered")+ self.assertEqual(self.bus.made("SelectionWriteDone")[0][1:], (9, False))+ self.assertTrue(self.remote.ready.is_set())+ self.assertEqual(self.problems, [])++ def test_a_session_that_ended_opens_again_without_asking_but_a_refusal_stands(self):+ self.up()+ saved = inject_portal.RETRY_SECONDS+ inject_portal.RETRY_SECONDS = 0.0+ try:+ self.ei.feed(("disconnect",))+ wait_for(lambda: self.problems, what="the problem")+ wait_for(lambda: not self.remote.ready.is_set(), what="the session down")+ self.bus.closed = False+ self.ei = FakeEi()+ inject_portal.inject_key("ctrl", True)+ wait_for(self.remote.ready.is_set, what="the session again")+ finally:+ inject_portal.RETRY_SECONDS = saved++ def test_nothing_queues_once_the_desktop_has_refused(self):+ self.bus.answers["Start"] = (1, {})+ self.remote.start()+ wait_for(lambda: self.problems, what="the refusal")+ for _ in range(50):+ inject_portal.inject_mouse_move(1, 1)+ self.assertEqual(self.remote._commands.qsize(), 0)++ def test_input_sent_before_the_devices_resume_is_played_once_they_do(self):+ self.remote.start()+ wait_for(self.remote.ready.is_set, what="the session")+ inject_portal.inject_key("ctrl", True)+ time.sleep(0.2)+ self.keyboard = FakeDevice("keyboard", {4}, keymap="xkb_keymap {}")+ self.absolute = FakeDevice("absolute", {2, 16, 32}, regions=[(0, 0, 1920, 1080, 1.0)])+ self.ei.feed(("device_added", self.keyboard), ("device_added", self.absolute),+ ("device_resumed", self.keyboard), ("device_resumed", self.absolute))+ wait_for(lambda: self.ei.sends("key"), what="the held key")+ self.assertEqual(self.ei.sends("key")[0][1:], ("keyboard", 29, True))++ def test_buttons_and_the_wheel_go_to_the_devices_that_have_them(self):+ self.remote.start()+ wait_for(self.remote.ready.is_set, what="the session")+ motion = FakeDevice("motion", {1})+ buttons = FakeDevice("buttons", {32})+ wheel = FakeDevice("wheel", {16})+ keyboard = FakeDevice("keyboard", {4}, keymap="xkb_keymap {}")+ devices = (motion, buttons, wheel, keyboard)+ self.ei.feed(*[("device_added", d) for d in devices], *[("device_resumed", d) for d in devices])+ wait_for(lambda: len(self.ei.sends("start")) == 4, what="the devices")+ inject_portal.inject_mouse_button("left", True)+ inject_portal.inject_scroll(1, 0, "line")+ wait_for(lambda: self.ei.sends("scroll_discrete"), what="the wheel")+ self.assertEqual(self.ei.sends("button")[0][1], "buttons")+ self.assertEqual(self.ei.sends("scroll_discrete")[0][1], "wheel")++ def test_an_fd_answered_after_its_caller_gave_up_is_closed(self):+ self.up()+ read, write = os.pipe()+ gate = threading.Event()++ def slow(session):+ gate.wait(2)+ return read++ self.assertIsNone(self.remote.ask(slow, timeout=0.1, discard=os.close))+ gate.set()+ wait_for(lambda: _closed(read), what="the late fd closed")+ os.close(write)++ def test_a_paste_that_never_reads_is_given_up_on(self):+ self.up()+ saved = inject_portal.WRITE_SECONDS+ inject_portal.WRITE_SECONDS = 0.3+ try:+ clipboard_portal.set_contents("y" * 200000, None)+ read, write = os.pipe()+ self.bus.returns["SelectionWrite"] = (write,)+ self.bus.emit(portal.OBJECT_PATH, inject_portal.CLIPBOARD, "SelectionTransfer", (SESSION, "text/plain", 5))+ wait_for(lambda: self.bus.made("SelectionWriteDone"), what="the transfer given up")+ self.assertEqual(self.bus.made("SelectionWriteDone")[0][1:], (5, False))+ os.close(read)+ finally:+ inject_portal.WRITE_SECONDS = saved++ def test_input_after_a_stop_does_not_open_the_session_again(self):+ self.up()+ self.remote.stop()+ inject_portal.inject_key("ctrl", True)+ time.sleep(0.2)+ self.assertFalse(self.remote._thread is not None and self.remote._thread.is_alive())+++ # Second review (Opus, 01-10-2026)++ def test_a_button_held_on_a_device_the_desktop_removes_is_forgotten_not_played(self):+ self.up()+ inject_portal.inject_mouse_button("left", True)+ wait_for(lambda: self.ei.sends("button"), what="the press")+ holder = next(d for d in (self.pointer, self.absolute) if d.name == self.ei.sends("button")[0][1])+ self.ei.feed(("device_removed", holder))+ inject_portal.inject_mouse_button("left", False)+ inject_portal.inject_key("ctrl", True)+ wait_for(lambda: self.ei.sends("key"), what="the session carrying on")+ self.assertEqual(len(self.ei.sends("button")), 1)++ def test_a_release_is_admitted_however_full_the_queue(self):+ self.up()+ inject_portal.inject_key("ctrl", True)+ inject_portal.inject_mouse_button("left", True)+ wait_for(lambda: self.ei.sends("key") and self.ei.sends("button"), what="the presses")+ saved = inject_portal.MAX_PENDING+ inject_portal.MAX_PENDING = 0+ try:+ inject_portal.inject_mouse_move(5, 5) # dropped: the queue is full+ inject_portal.inject_key("ctrl", False)+ inject_portal.inject_mouse_button("left", False)+ wait_for(lambda: len(self.ei.sends("key")) == 2 and len(self.ei.sends("button")) == 2, what="the releases")+ finally:+ inject_portal.MAX_PENDING = saved+ self.assertEqual([item[2:] for item in self.ei.sends("key")], [(29, True), (29, False)])++ def test_a_missing_library_is_said_once_and_never_retried(self):+ def missing():+ raise RuntimeError("libei is not installed; Beamer needs it to capture and play input on Wayland")++ factory = lambda fd: self.ei # noqa: E731+ factory.preflight = missing+ self.remote._ei_factory = factory+ saved = inject_portal.RETRY_SECONDS+ inject_portal.RETRY_SECONDS = 0.0+ try:+ self.remote.start()+ wait_for(lambda: self.problems, what="the problem")+ for _ in range(5):+ inject_portal.inject_key("ctrl", True)+ time.sleep(0.05)+ self.assertEqual(len(self.problems), 1)+ self.assertIn("libei", self.problems[0])+ self.assertEqual(self.bus.made("CreateSession"), [])+ finally:+ inject_portal.RETRY_SECONDS = saved++ def test_a_session_the_user_stopped_from_the_desktop_stays_stopped(self):+ self.up()+ saved = inject_portal.RETRY_SECONDS+ inject_portal.RETRY_SECONDS = 0.0+ try:+ self.bus.emit(SESSION, portal.SESSION, "Closed", ())+ wait_for(lambda: self.problems, what="the problem")+ wait_for(lambda: not self.remote.ready.is_set(), what="the session down")+ self.bus.closed = False # a new connection could be made+ inject_portal.inject_key("ctrl", True)+ time.sleep(0.2)+ self.assertEqual(len(self.bus.made("CreateSession")), 1)+ finally:+ inject_portal.RETRY_SECONDS = saved++ def test_a_session_with_no_remembered_permission_is_not_reopened_to_ask_again(self):+ self.bus.answers["Start"] = (0, {"devices": 3, "clipboard_enabled": True}) # the box unticked: no token+ self.up()+ saved = inject_portal.RETRY_SECONDS+ inject_portal.RETRY_SECONDS = 0.0+ try:+ self.ei.feed(("disconnect",))+ wait_for(lambda: self.problems, what="the problem")+ wait_for(lambda: not self.remote.ready.is_set(), what="the session down")+ self.bus.closed = False # a new connection could be made+ inject_portal.inject_key("ctrl", True)+ time.sleep(0.2)+ self.assertEqual(len(self.bus.made("CreateSession")), 1)+ finally:+ inject_portal.RETRY_SECONDS = saved+++def _closed(fd):+ try:+ os.fstat(fd)+ except OSError:+ return True+ return False+++class DesktopTest(unittest.TestCase):+ def test_a_point_off_every_display_is_brought_to_the_nearest(self):+ displays = [desktop_portal.Rect(0, 0, 1920, 1080), desktop_portal.Rect(1920, 200, 1280, 1024)]+ self.assertEqual(desktop_portal.clamp_to(displays, 1920, 100), (1919, 100))+ self.assertEqual(desktop_portal.clamp_to(displays, 3300, 700.4), (3199, 700))+ self.assertEqual(desktop_portal.clamp_to(displays, 2500, 1500), (2500, 1223))+ self.assertEqual(desktop_portal.clamp_to([], 5, 6), (5, 6))+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_inject_x11.py b/win_app/tests/test_inject_x11.pynew file mode 100644index 0000000..fd74349--- /dev/null+++ b/win_app/tests/test_inject_x11.py@@ -0,0 +1,335 @@+"""inject_x11's planning on a fake layout, and its functions against a fake connection.+tools/x11_proof.sh types through the same module on a real X server and reads it back."""++import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+sys.path.append(str(Path(__file__).resolve().parent.parent.parent))++import capture_x11 # noqa: E402+import inject_x11 # noqa: E402+from inject_x11 import MAP, NO_REPEAT, PRESS, RELEASE, REPEAT, KeyState, Layout # noqa: E402++U = 0x01000000+SHIFT_L, SHIFT_R, CTRL_L = 50, 62, 37+A, ONE, C, E, SEVEN = 38, 10, 54, 26, 16+CAPS = capture_x11.LOCK_MASK+++class FakeKeymap:+ """A US layout in group one and Russian in group two, the 7 key typing / with Shift as on a+ German keyboard, and two empty keycodes. Shift picks level 2, Caps Lock flips a letter."""++ min_keycode, max_keycode = 8, 202++ def __init__(self):+ self.rows = {+ A: [[ord("a"), ord("A")], [U | 0x444, U | 0x424]], # ф Ф+ C: [[ord("c"), ord("C")], [U | 0x441, U | 0x421]], # с С+ E: [[ord("e"), ord("E")], [U | 0x443, U | 0x423]], # у У+ ONE: [[ord("1"), ord("!")]],+ SEVEN: [[ord("7"), ord("/")]],+ SHIFT_L: [[0xFFE1, 0xFFE1]],+ }+ for keycode in range(self.min_keycode, self.max_keycode + 1):+ if keycode not in self.rows and keycode not in (200, 201):+ self.rows[keycode] = [[0xFF00 + keycode, 0xFF00 + keycode]] # something with no text++ def keysym(self, keycode, mods, group):+ groups = self.rows.get(keycode)+ if not groups:+ return 0+ levels = groups[group % len(groups)]+ level = 1 if mods & capture_x11.SHIFT_MASK else 0+ if mods & CAPS and (capture_x11.keysym_text(levels[1]) or "").isalpha():+ level ^= 1+ return levels[level]++ def text(self, keysym):+ return capture_x11.keysym_text(keysym) if keysym < 0xFF00 or keysym > 0xFFFF else None++ def empty(self, keycode):+ return keycode not in self.rows+++def plan(name, down=True, us=None, state=None, layout=None, group=0, locks=0):+ state = state if state is not None else KeyState()+ return inject_x11.plan_key(name, down, us, state, layout or Layout(FakeKeymap()), group, locks)+++class NamedKeyTest(unittest.TestCase):+ def test_named_keys_by_evdev_code(self):+ self.assertEqual(plan("enter"), [(PRESS, 36)])+ self.assertEqual(plan("return", down=False), [(RELEASE, 36)])+ self.assertEqual(plan("cmd"), [(PRESS, 133)]) # Super+ self.assertEqual(plan("ctrl_r"), [(PRESS, 105)])+ self.assertEqual(plan("alt_r"), [(PRESS, 108)])+ self.assertEqual(plan("f24"), [(PRESS, 202)])+ self.assertEqual(plan("media_play_pause"), [(PRESS, 172)])++ def test_the_server_repeats_a_held_named_key(self):+ state = KeyState()+ self.assertEqual(plan("backspace", state=state), [(PRESS, 22)])+ self.assertEqual(plan("backspace", state=state), [])+ self.assertEqual(plan("backspace", down=False, state=state), [(RELEASE, 22)])+ self.assertEqual(plan("backspace", state=state), [(PRESS, 22)])++ def test_modifiers_are_tracked(self):+ state = KeyState()+ plan("ctrl", state=state)+ plan("shift_r", state=state)+ self.assertEqual(state.mods_down, {"ctrl", "shift_r"})+ plan("ctrl", down=False, state=state)+ self.assertEqual(state.mods_down, {"shift_r"})++ def test_an_unknown_name_is_dropped(self):+ with self.assertLogs(inject_x11.LOGGER, "WARNING"):+ self.assertEqual(plan("hyper_q"), [])+++class CharacterTest(unittest.TestCase):+ def test_a_plain_character_and_the_server_s_repeat(self):+ state = KeyState()+ self.assertEqual(plan("a", state=state), [(PRESS, A)])+ self.assertEqual(plan("a", state=state), []) # the peer's repeat: the server is repeating it+ self.assertEqual(plan("a", down=False, state=state), [(RELEASE, A)])+ self.assertEqual(state.chars_down, {})++ def test_shift_is_pressed_around_a_character_that_needs_it(self):+ state = KeyState()+ self.assertEqual(plan("!", state=state), [(NO_REPEAT, ONE), (PRESS, SHIFT_L), (PRESS, ONE), (RELEASE, SHIFT_L)])+ # Each of the peer's repeats is typed again with its Shift, the server's being off for it.+ self.assertEqual(plan("!", state=state), [(RELEASE, ONE), (PRESS, SHIFT_L), (PRESS, ONE), (RELEASE, SHIFT_L)])+ self.assertEqual(plan("!", down=False, state=state), [(RELEASE, ONE), (REPEAT, ONE)])++ def test_a_german_slash_repeats_as_a_slash(self):+ state = KeyState()+ plan("/", state=state)+ self.assertEqual(plan("/", state=state), [(RELEASE, SEVEN), (PRESS, SHIFT_L), (PRESS, SEVEN), (RELEASE, SHIFT_L)])++ def test_a_repeat_works_shift_out_again_when_the_peer_s_shift_changed(self):+ state = KeyState()+ plan("shift", state=state)+ self.assertEqual(plan("1", state=state), [(NO_REPEAT, ONE), (RELEASE, SHIFT_L), (PRESS, ONE), (PRESS, SHIFT_L)])+ plan("shift", down=False, state=state)+ self.assertEqual(plan("1", state=state), [(RELEASE, ONE), (PRESS, ONE)]) # no Shift pressed for nobody++ def test_a_held_shift_is_let_go_around_a_character_that_must_not_have_it(self):+ state = KeyState()+ plan("shift_r", state=state)+ self.assertEqual(plan("1", state=state), [(NO_REPEAT, ONE), (RELEASE, SHIFT_R), (PRESS, ONE), (PRESS, SHIFT_R)])+ self.assertEqual(plan("A", state=state), [(PRESS, A)])++ def test_caps_lock_as_the_layout_applies_it(self):+ self.assertEqual(plan("A", locks=CAPS), [(PRESS, A)])+ self.assertEqual(plan("a", locks=CAPS), [(NO_REPEAT, A), (PRESS, SHIFT_L), (PRESS, A), (RELEASE, SHIFT_L)])+ self.assertEqual(plan("!", locks=CAPS), [(NO_REPEAT, ONE), (PRESS, SHIFT_L), (PRESS, ONE), (RELEASE, SHIFT_L)])++ def test_under_a_chord_shift_is_the_peer_s(self):+ state = KeyState()+ plan("ctrl", state=state)+ plan("shift", state=state)+ self.assertEqual(plan("a", state=state), [(PRESS, A)])++ def test_the_current_group(self):+ self.assertEqual(plan("ф", group=1), [(PRESS, A)])+ self.assertEqual(plan("Ф", group=1), [(NO_REPEAT, A), (PRESS, SHIFT_L), (PRESS, A), (RELEASE, SHIFT_L)])+ self.assertEqual(plan("1", group=1), [(PRESS, ONE)]) # a key without the group wraps+ self.assertEqual(plan("ф", group=3), [(PRESS, A)]) # a fourth group, wrapped as XKB wraps it++ def test_a_repeat_and_its_release_stay_on_the_first_key(self):+ state = KeyState()+ layout = Layout(FakeKeymap())+ plan("a", state=state, layout=layout)+ self.assertEqual(plan("a", state=state, layout=layout, group=1), [])+ self.assertEqual(plan("a", down=False, state=state, layout=layout, group=1), [(RELEASE, A)])++ def test_by_place_under_a_chord(self):+ state = KeyState()+ plan("ctrl", state=state)+ # Ctrl-C from an English Mac to Russian: no key types "c", so the key in C's place.+ self.assertEqual(plan("c", us="c", state=state, group=1), [(PRESS, C)])++ def test_by_place_for_another_script_s_letter(self):+ # A Russian Mac types "у" on its E key; on this English layout that is the E key too.+ self.assertEqual(plan("у", us="e"), [(PRESS, E)])++ def test_a_character_on_no_key_gets_a_spare_that_stays_mapped(self):+ state = KeyState()+ layout = Layout(FakeKeymap())+ self.assertEqual(plan("é", state=state, layout=layout), [(MAP, 201, 0xE9, False), (PRESS, 201)])+ plan("é", down=False, state=state, layout=layout)+ self.assertEqual(plan("é", state=state, layout=layout), [(PRESS, 201)])+ self.assertEqual(plan("€", state=state, layout=layout), [(MAP, 200, U | 0x20AC, False), (PRESS, 200)])++ def test_a_spare_wiped_by_a_new_keymap_is_mapped_again(self):+ state = KeyState()+ plan("é", state=state, layout=Layout(FakeKeymap()))+ plan("é", down=False, state=state, layout=Layout(FakeKeymap()))+ self.assertEqual(plan("é", state=state, layout=Layout(FakeKeymap())), [(MAP, 201, 0xE9, False), (PRESS, 201)])++ def test_the_least_recent_free_spare_is_reused_after_a_pause(self):+ state = KeyState()+ layout = Layout(FakeKeymap())+ plan("é", state=state, layout=layout)+ plan("é", down=False, state=state, layout=layout)+ plan("€", state=state, layout=layout) # held+ self.assertEqual(plan("ß", state=state, layout=layout), [(MAP, 201, 0xDF, True), (PRESS, 201)])+ with self.assertLogs(inject_x11.LOGGER, "WARNING"):+ self.assertEqual(plan("ñ", state=state, layout=layout), []) # both spares held+++class TextTest(unittest.TestCase):+ def test_text_lets_held_modifiers_go_and_presses_them_again(self):+ state = KeyState()+ plan("ctrl", state=state)+ plan("shift", state=state)+ steps = inject_x11.plan_text("a!", state, Layout(FakeKeymap()), 0, 0)+ self.assertEqual(steps, [+ (RELEASE, CTRL_L), (RELEASE, SHIFT_L),+ (PRESS, A), (RELEASE, A),+ (PRESS, SHIFT_L), (PRESS, ONE), (RELEASE, SHIFT_L), (RELEASE, ONE),+ (PRESS, CTRL_L), (PRESS, SHIFT_L),+ ])+ self.assertEqual(state.mods_down, {"ctrl", "shift"})++ def test_text_off_the_layout_uses_a_spare(self):+ self.assertEqual(inject_x11.plan_text("é", KeyState(), Layout(FakeKeymap()), 0, 0),+ [(MAP, 201, 0xE9, False), (PRESS, 201), (RELEASE, 201)])+++class ScrollTest(unittest.TestCase):+ def test_line_clicks(self):+ carry = [0.0, 0.0]+ self.assertEqual(inject_x11.plan_scroll(2, -1, "line", carry), (2, -1))+ self.assertEqual(inject_x11.scroll_buttons(2, -1), [4, 4, 6])+ self.assertEqual(inject_x11.scroll_buttons(-1, 1), [5, 7])++ def test_pixels_carry_their_remainder(self):+ carry = [0.0, 0.0]+ self.assertEqual(inject_x11.plan_scroll(30, 0, "pixel", carry), (0, 0))+ self.assertEqual(inject_x11.plan_scroll(30, 0, "pixel", carry), (1, 0))+ self.assertAlmostEqual(carry[0], 0.5)++ def test_a_fractional_line_carries(self):+ carry = [0.0, 0.0]+ self.assertEqual(inject_x11.plan_scroll(0.5, 0, "line", carry), (0, 0))+ self.assertEqual(inject_x11.plan_scroll(0.5, 0, "line", carry), (1, 0))+++class FakeConnection:+ def __init__(self):+ self.sent = []+ self.changed = False+ self.group, self.locks = 0, 0+ self.closed = False+ self.fail = None+ self.repeat_restored = 0++ def layout(self):+ return Layout(FakeKeymap())++ def mapping_changed(self):+ changed, self.changed = self.changed, False+ return changed++ def state(self):+ return self.group, self.locks++ def run(self, steps):+ if self.fail is not None:+ raise self.fail+ self.sent.extend(steps)++ def restore_repeat(self):+ self.repeat_restored += 1++ def button(self, number, down):+ self.sent.append(("button", number, down))++ def move(self, dx, dy):+ self.sent.append(("move", dx, dy))++ def move_to(self, x, y):+ self.sent.append(("move_to", x, y))++ def close(self):+ self.closed = True+++class ModuleTest(unittest.TestCase):+ def setUp(self):+ self.connection = FakeConnection()+ self.made = 0++ def connect():+ self.made += 1+ return self.connection++ self.real = inject_x11._connect+ inject_x11._connect = connect+ inject_x11._drop()+ inject_x11._state.__init__()+ inject_x11._buttons_down.clear()+ inject_x11._scroll_carry[:] = [0.0, 0.0]++ def tearDown(self):+ inject_x11._drop()+ inject_x11._connect = self.real++ def test_keys_buttons_moves_and_scrolls_reach_the_connection(self):+ inject_x11.inject_key("ctrl", True)+ inject_x11.inject_key("c", True, us="c")+ inject_x11.inject_mouse_button("back", True)+ inject_x11.inject_mouse_move(3, -2)+ inject_x11.inject_scroll(-1, 0, "line")+ self.assertEqual(self.connection.sent, [+ (PRESS, CTRL_L), (PRESS, C), ("button", 8, True), ("move", 3, -2), ("button", 5, True), ("button", 5, False),+ ])+ self.assertEqual(self.made, 1)++ def test_the_layout_is_read_again_after_a_mapping_change(self):+ self.connection.group = 1+ inject_x11.inject_key("ф", True)+ layout = inject_x11._layout+ inject_x11.inject_key("ф", False)+ self.assertIs(inject_x11._layout, layout)+ self.connection.changed = True+ inject_x11.inject_key("a", True)+ self.assertIsNot(inject_x11._layout, layout)++ def test_release_all_lets_go_of_everything_held(self):+ inject_x11.inject_key("shift", True)+ inject_x11.inject_key("A", True)+ inject_x11.inject_key("backspace", True)+ inject_x11.inject_mouse_button("left", True)+ inject_x11.inject_scroll(0.5, 0, "line")+ self.connection.sent.clear()+ inject_x11.release_all()+ self.assertEqual(self.connection.sent, [(RELEASE, SHIFT_L), (RELEASE, 22), (RELEASE, A), ("button", 1, False)])+ self.assertEqual(self.connection.repeat_restored, 1)+ state = inject_x11._state+ self.assertEqual((state.mods_down, state.named_down, state.chars_down, inject_x11._buttons_down), (set(), set(), {}, set()))+ self.assertEqual(inject_x11._scroll_carry, [0.0, 0.0])++ def test_a_failed_request_reconnects_next_time(self):+ self.connection.fail = ConnectionError("gone")+ with self.assertRaises(ConnectionError):+ inject_x11.inject_key("a", True)+ self.assertTrue(self.connection.closed)+ self.connection.fail = None+ inject_x11.inject_key("enter", True)+ self.assertEqual(self.made, 2)++ def test_a_gesture_is_dropped_with_one_line(self):+ with self.assertLogs(inject_x11.LOGGER, "WARNING") as logs:+ inject_x11.inject_gesture("swipe_left_once_test")+ inject_x11.inject_gesture("swipe_left_once_test")+ self.assertEqual(len(logs.records), 1)+ self.assertEqual(self.connection.sent, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_links.py b/win_app/tests/test_links.pyindex 99fc65d..65be512 100644--- a/win_app/tests/test_links.py+++ b/win_app/tests/test_links.py@@ -1,6 +1,8 @@"""This PC's input going to its peers (WIRE.md sections 3 to 5): the zones, the owner's decisionscarried out, the key names, the clipboard and the way home, against links that only record."""+import queue+import threadingimport timeimport unittest@@ -8,8 +10,10 @@ from links_rig import B, C, CAPS, HERE, Rig, edge_zone, make_configimport capture_winimport sender+from core import owner as owner_modulefrom core import protocolfrom core.return_edge import Rect+from core.tests import pngsfrom core.tests import responder_harness as harness@@ -151,6 +155,16 @@ class TakingTests(unittest.TestCase):self.assertEqual(kinds, ["focus", "clipboard", "keydown"])self.assertEqual(self.rig.sent(B, "clipboard")[0]["data"]["text"], "here")+ def test_an_image_too_large_to_decode_is_not_sent_but_the_text_is(self):+ for image, sent in ((pngs.png(), True), (pngs.png(16384, 16384), False)):+ with self.subTest(sent=sent):+ rig = Rig()+ rig.clipboard.image = image+ rig.sender.set_redirecting(True)+ data = rig.sent(B, "clipboard")[0]["data"]+ self.assertEqual(data["text"], "here")+ self.assertEqual("image" in data, sent)+def test_a_peer_without_the_clipboard_capability_is_sent_none(self):self.rig.links.caps_of[B] = frozenset()self.sender.set_redirecting(True)@@ -324,6 +338,24 @@ class OnwardTests(unittest.TestCase):self.switch(HERE, edge="left", offset=0.5)self.assertTrue(self.rig.desktop.placed)+ def test_a_hand_over_given_up_before_its_answer_closes_that_peers_link(self):+ # Its accept may still be on the way: the close is what ends that ownership (WIRE.md+ # section 5). Abandoned by the shortcut home here; the owner's tests cover every way.+ self.switch(C)+ self.assertEqual(self.rig.links.closed, [])+ self.sender.set_redirecting(False)+ self.rig.flush()+ self.assertEqual(self.rig.links.closed, [C])+ self.assertFalse(self.sender.redirecting)++ def test_a_hand_over_given_up_when_the_outbound_queue_is_full_still_closes_that_peers_link(self):+ # The close cannot wait in a queue that has no room: C would stay owned by nobody driving.+ self.switch(C)+ self.sender._outbound = queue.Queue(maxsize=1)+ self.sender._outbound.put_nowait(owner_module.Send(B, protocol.ping_msg()))+ self.sender.set_redirecting(False)+ self.assertIn(C, self.rig.links.closed)+def test_a_peer_that_cannot_be_reached_leaves_the_input_where_it_is(self):self.switch(C)self.rig.inbound(C, protocol.refuse_msg(self.sender._owner.route, "owned"))@@ -453,6 +485,36 @@ class ReviewTests(unittest.TestCase):self.assertTrue(self.wait(lambda: [m for t, m in rig.links.sent if t == C and m["type"] == "focus"], 0.4),"the take of the next peer waited for the clipboard read")+ def test_a_read_asked_for_again_waits_its_turn_behind_a_write_decided_before_it(self):+ rig = self.two()+ rig.clipboard.block_get = True+ rig.clipboard.block_set = True+ rig.sender._deliver(owner_module.SendClipboard(B))+ self.assertTrue(rig.clipboard.get_started.wait(1), "the first clipboard read never started")++ write = threading.Thread(+ target=rig.sender._deliver,+ args=(owner_module.SetClipboard(protocol.clipboard_msg("from there")),),+ daemon=True,+ )+ write.start()+ time.sleep(0.1)++ key = {"type": protocol.MSG_KEYDOWN, "data": {"key": "v"}}+ rig.sender._deliver(owner_module.SendClipboard(B))+ rig.sender._deliver(owner_module.Send(B, key))+ rig.clipboard.release_get.set()+ self.assertTrue(rig.clipboard.set_started.wait(1), "the clipboard write never started")+ rig.clipboard.release_set.set()+ write.join(1)+ self.assertFalse(write.is_alive(), "the clipboard write did not finish")+ self.assertTrue(self.wait(lambda: not rig.sender._clip_wait), "the peer's queued messages did not finish")++ sent = [m for peer, m in rig.links.sent if peer == B]+ clipboards = [m["data"]["text"] for m in sent if m["type"] == protocol.MSG_CLIPBOARD]+ self.assertEqual(clipboards, ["here", "from there"])+ self.assertEqual([m["type"] for m in sent[-3:]], [protocol.MSG_CLIPBOARD, protocol.MSG_CLIPBOARD, protocol.MSG_KEYDOWN])+def test_what_follows_a_clipboard_read_for_that_peer_still_goes_after_it(self):rig = self.two()rig.clipboard.slow_get = 0.2diff --git a/win_app/tests/test_linux_start.py b/win_app/tests/test_linux_start.pyindex 842f621..cb1725f 100644--- a/win_app/tests/test_linux_start.py+++ b/win_app/tests/test_linux_start.py@@ -1,7 +1,11 @@"""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."""+stdlib are already loaded by then) and the window is built offscreen. On Wayland the portal parts+are chosen, the capture is wired to the sender's zones and its way home, and main() also runs to a+clean exit with no desktop portal to reach. On X11 the X11 parts are chosen, the capture starts on+a fake X connection holding the grab predicate, and the receiver listens. Either way, of Windows'+modules only the pure pieces capture_x11 borrows are loaded. Skipped on+Windows, where a faked platform would break the stdlib; the rig proves the other half, that+Windows is unchanged."""import jsonimport os@@ -16,6 +20,35 @@ WINDOWS_ONLY = ("input_injector", "touchpad_injector", "winreg", "msvcrt",)PORT = 24993+# capture_x11 borrows Windows' pure pieces (the trigger, the mouse messages, the US places).+X11_ALLOWED = {"capture_win", "input_injector"}+++class FakeX:+ """Just enough of capture_x11's connection for the hooks to start and idle."""++ def __init__(self):+ import capture_x11++ self.devices_read = 0+ self.masters = [capture_x11.Device(2, capture_x11.XI_MASTER_POINTER, "Virtual core pointer"),+ capture_x11.Device(3, capture_x11.XI_MASTER_KEYBOARD, "Virtual core keyboard")]++ def events(self, timeout):+ import time++ time.sleep(timeout)+ return []++ def devices(self):+ self.devices_read += 1+ return list(self.masters)++ def pointer_mapping(self):+ return list(range(1, 11))++ def close(self):+ passdef child(mode: str, config: Path) -> None:@@ -29,26 +62,51 @@ def child(mode: str, config: Path) -> None:sys.path[:0] = [str(here), str(here.parent)]sys.platform = "linux"+ if mode == "x11":+ x11_child()+ return+import kvm_bridge_winfrom core.receiver import ServerStateif mode == "window":+ import platform_parts++ assert [platform_parts.capture.__name__, platform_parts.injector.__name__, platform_parts.clipboard.__name__,+ platform_parts.desktop.__name__, platform_parts.autostart.__name__] == [+ "capture_portal", "inject_portal", "clipboard_portal", "desktop_portal", "autostart_x11"]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 "Wayland support is coming" not in window._status_detail, window._status_detail+ import time++ deadline = time.monotonic() + 5+ while time.monotonic() < deadline and "not yet on Linux" not in window.firewall_note.text():+ app.processEvents()+ time.sleep(0.05)assert "not yet on Linux" in window.firewall_note.text(), window.firewall_note.text()assert not window.logon_switch.isEnabled()+ assert window.hooks._predicate is not None and window.hooks._predicate() is False+ assert window.hooks._models == window.sender.zone_models+ assert window.hooks.on_home is not None+ assert platform_parts.injector.on_problem is not None+ # Nothing is captured, so the shortcut cannot send input away.+ assert window.sender.input_held() is False+ assert window._identity()["platform"] == "linux"+ # What Wayland takes away, said where it applies, and no window drawn at an edge.+ assert platform_parts.WAYLAND is True+ assert "only brings input back" in window.wayland_shortcut_note.text()+ assert not window.wayland_shortcut_note.isHidden()+ assert window.hold_switch.isHidden() and window.crossing_rows["dragging"].isHidden()+ assert "full-screen" in window.wayland_crossing_note.text() and not window.wayland_crossing_note.isHidden()+ window._on_pressure("right", 0.7, False)+ window._on_arrival("edge", "left", 10.0, 10.0)+ assert window.glow is None and window.effects is None+ window._reflect_look()+ assert "Wayland" in window.effect_note.text(), window.effect_note.text()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:@@ -64,7 +122,54 @@ def child(mode: str, config: Path) -> None: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]+ loaded = [name for name in WINDOWS_ONLY if name in sys.modules and name not in X11_ALLOWED]+ assert not loaded, f"Windows-only modules imported: {loaded}"+ print("ok")+++def x11_child() -> None:+ import socket+ import time++ from PySide6.QtWidgets import QApplication++ import capture_x11+ import desktop_x11++ fake = FakeX()+ capture_x11._Connection = lambda: fake++ def no_server():+ raise RuntimeError("no X server in this test")++ desktop_x11._connect = no_server++ import kvm_bridge_win+ import platform_parts++ assert platform_parts.capture is capture_x11+ assert platform_parts.injector.__name__ == "inject_x11"+ assert platform_parts.clipboard.__name__ == "clipboard_x11"+ assert platform_parts.autostart.__name__ == "autostart_x11"+ assert platform_parts.desktop is desktop_x11+ app = QApplication([])+ window = kvm_bridge_win.WindowsApplication(Path(sys.argv[2]))+ window.start()+ assert "Wayland" not in window._status_detail, window._status_detail+ assert window._identity()["platform"] == "linux"+ assert "gestures" not in window._identity()["caps"] and "text" in window._identity()["caps"]+ assert platform_parts.WAYLAND is False and window.wayland_shortcut_note.isHidden() and not window.hold_switch.isHidden()+ assert window.hooks._predicate is not None and window.hooks._predicate() is False+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline and not window.server.listening:+ app.processEvents()+ time.sleep(0.05)+ assert window.server.listening+ socket.create_connection(("127.0.0.1", PORT), timeout=2).close()+ assert fake.devices_read >= 1, "the capture never started"+ window.quit()+ window.deleteLater()+ loaded = [name for name in WINDOWS_ONLY if name in sys.modules and name not in X11_ALLOWED]assert not loaded, f"Windows-only modules imported: {loaded}"print("ok")@@ -83,7 +188,7 @@ class LinuxStartTest(unittest.TestCase):"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 = dict(os.environ, QT_QPA_PLATFORM="offscreen", XDG_CONFIG_HOME=directory, XDG_SESSION_TYPE="wayland")env.pop("LOCALAPPDATA", None)for mode in ("window", "main"):done = subprocess.run(@@ -93,6 +198,52 @@ class LinuxStartTest(unittest.TestCase):self.assertEqual(done.returncode, 0, mode + done.stdout + done.stderr)self.assertIn("ok", done.stdout)+ @unittest.skipIf(sys.platform == "win32", "a faked platform breaks the Windows stdlib")+ def test_on_x11_the_x11_parts_start_and_the_receiver_listens(self):+ try:+ import PySide6 # noqa: F401+ except ImportError:+ self.skipTest("needs PySide6")+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))+ from core import protocol++ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+ import app_config++ with tempfile.TemporaryDirectory() as directory:+ config = Path(directory) / "settings.json"+ # A machine paired by 1.5.0, so the hooks go in: neither a typed token nor one migrated+ # from 1.4.x links (protocol.linkable).+ settings = app_config.migrate({+ "host": "192.0.2.20", "port": PORT, "auth_token": protocol.id_text(bytes(range(32))), "paired_with": "MacBook Pro",+ "mac_host": "192.0.2.10", "mac_return_edge": "left",+ "allow_mac_to_drive": True, "send_to_mac": True,+ })+ settings["peers"][0]["from_1_4"] = False+ config.write_text(json.dumps(settings))+ env = dict(os.environ, QT_QPA_PLATFORM="offscreen", XDG_CONFIG_HOME=directory, XDG_SESSION_TYPE="x11", DISPLAY=":0")+ env.pop("LOCALAPPDATA", None)+ env.pop("WAYLAND_DISPLAY", None)+ done = subprocess.run(+ [sys.executable, str(Path(__file__).resolve()), "x11", str(config)],+ env=env, capture_output=True, text=True, timeout=120,+ )+ self.assertEqual(done.returncode, 0, done.stdout + done.stderr)+ self.assertIn("ok", done.stdout)+++class SessionTest(unittest.TestCase):+ def test_which_display_server(self):+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+ import platform_parts++ session = platform_parts.session+ self.assertEqual(session({"XDG_SESSION_TYPE": "x11", "DISPLAY": ":0"}), "x11")+ self.assertEqual(session({"XDG_SESSION_TYPE": "wayland", "DISPLAY": ":0", "WAYLAND_DISPLAY": "wayland-0"}), "wayland")+ self.assertEqual(session({"XDG_SESSION_TYPE": "tty", "DISPLAY": ":0"}), "x11") # startx+ self.assertEqual(session({"DISPLAY": ":1", "WAYLAND_DISPLAY": "wayland-0"}), "wayland")+ self.assertEqual(session({}), "wayland")+if __name__ == "__main__":child(sys.argv[1], Path(sys.argv[2]))diff --git a/win_app/tests/test_motion.py b/win_app/tests/test_motion.pyindex 41fc342..1d7d8c4 100644--- a/win_app/tests/test_motion.py+++ b/win_app/tests/test_motion.py@@ -81,12 +81,16 @@ class MotionTest(unittest.TestCase):def test_the_diagram_lands_on_its_side_at_once_before_the_window_opens(self):import diagram+ def mac(side):+ return [{"key": "b", "label": "Mac", "side": side, "methods": ["edge"], "parts": [], "corner": "top_left",+ "chosen": True}]+picture = diagram.ArrangementDiagram(self.window)- picture.set_state("left", ["edge"], [], "top_left", "Right Ctrl", "hold")- picture.set_state("top", ["edge", "shortcut"], [], "top_left", "Right Ctrl", "hold")- self.assertEqual(picture._angle, 90.0)- self.assertEqual(picture._marks[("edge", "top")], 1.0)- self.assertEqual(picture._marks[("edge", "left")], 0.0)+ picture.set_machines(mac("left"), "Right Ctrl", "hold", False)+ picture.set_machines(mac("top"), "Right Ctrl", "hold", True)+ self.assertEqual(picture._places["b"][0], 90.0)+ self.assertEqual(picture._marks[("edge", "b", "top")], 1.0)+ self.assertEqual(picture._marks[("edge", "b", "left")], 0.0)self.assertEqual(picture._marks[("cap",)], 1.0)self.assertIn("hold Right Ctrl", picture.accessibleDescription())diff --git a/win_app/tests/test_pages_win.py b/win_app/tests/test_pages_win.pyindex 320b463..e9e94d6 100644--- a/win_app/tests/test_pages_win.py+++ b/win_app/tests/test_pages_win.py@@ -1,6 +1,5 @@import osimport unittest-from types import SimpleNamespaceimport syssys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))@@ -169,32 +168,7 @@ class CrossingWaysTest(unittest.TestCase):class ArrangementGeometryTest(unittest.TestCase):- SCREEN = (120.0, 75.0)-- def test_the_mac_sits_on_the_chosen_side_of_this_pc(self):- for side, check in (- ("right", lambda pc, mac: mac[0] == pc[0] + 134 and mac[1] == pc[1]),- ("left", lambda pc, mac: mac[0] == pc[0] - 134 and mac[1] == pc[1]),- ("top", lambda pc, mac: mac[1] == pc[1] - 89 and mac[0] == pc[0]),- ("bottom", lambda pc, mac: mac[1] == pc[1] + 89 and mac[0] == pc[0]),- ):- pc, mac, _height = pages_win.arrangement_rects(400.0, 0.0, pages_win.SIDE_ANGLE[side], self.SCREEN, 14.0)- self.assertTrue(check(pc, mac), (side, pc, mac))-- def test_the_pair_is_centred_and_only_as_tall_as_it_needs(self):- pc, mac, height = pages_win.arrangement_rects(400.0, 10.0, 0.0, self.SCREEN, 14.0)- self.assertEqual(height, 75.0)- self.assertEqual((pc[0] + mac[0] + mac[2]) / 2.0, 200.0)- self.assertEqual(pc[1], 10.0)- _pc, _mac, stacked = pages_win.arrangement_rects(400.0, 0.0, 90.0, self.SCREEN, 14.0)- self.assertEqual(stacked, 164.0)-- def test_the_mac_goes_round_this_pc_never_through_it(self):- for angle in range(0, 360, 5):- pc, mac, _height = pages_win.arrangement_rects(400.0, 0.0, float(angle), self.SCREEN, 14.0)- apart_x = mac[0] >= pc[0] + pc[2] or mac[0] + mac[2] <= pc[0]- apart_y = mac[1] >= pc[1] + pc[3] or mac[1] + mac[3] <= pc[1]- self.assertTrue(apart_x or apart_y, angle)+ # Where each screen sits: test_pc_three_machines.DiagramGeometryTests, one machine and several.def test_a_turn_takes_the_short_way_and_half_turns_go_round_the_top(self):turn = pages_win.turn_to@@ -306,89 +280,81 @@ class DesignControlsTest(unittest.TestCase):@unittest.skipIf(widgets is None, "needs PySide6")class CrossingPageTest(unittest.TestCase):- """The Crossing page's rows and chips, set from the config without building the whole window."""+ """The Crossing page's rows and chips, set from one machine's ways in the settings, in the real+ window built offscreen, which starts no receiver, hooks or announcer."""def setUp(self):- from types import SimpleNamespace+ import tempfile+ from pathlib import Path- from PySide6.QtWidgets import QApplication, QCheckBox, QPushButton, QWidget+ from PySide6.QtWidgets import QApplicationos.environ.setdefault("QT_QPA_PLATFORM", "offscreen")self.app = QApplication.instance() or QApplication([])- import diagramimport kvm_bridge_win-- self.reflect = kvm_bridge_win.WindowsApplication._reflect_ways- self.host = QWidget()- self.page = SimpleNamespace(- _config=app_config.default_config(),- way_boxes={way: QCheckBox(way) for way in pages_win.WAYS},- part_buttons={part: QPushButton() for part in ("start", "middle", "end")},- parts_note=widgets.label("", "note"),- # Inside a window that is never shown, as on a page before the window opens.- crossing_rows={key: QWidget(self.host) for key in ("edge", "parts", "corner", "dragging")},- resistance_module=QWidget(self.host),- shortcut_module=QWidget(self.host),- pause_row=QWidget(self.host),- ways_summary=widgets.label("", "note"),- edge_unlearned=QWidget(self.host),- arrangement_diagram=diagram.ArrangementDiagram(),- resistance_strip=diagram.PushStrip(),- )- for button in self.page.part_buttons.values():- button.setCheckable(True)+ import theme+ from core import protocol+ from core.tests import responder_harness as harness++ theme.init_fonts()+ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ self.path = Path(directory.name) / "settings.json"+ settings = app_config.migrate(None, machine_id=protocol.id_text(harness.HERE))+ self.peer = protocol.id_text(harness.B)+ settings["peers"] = [harness.entry(harness.B, "Mac", side="right")]+ settings["port"] = harness.free_port()+ app_config.write_settings(self.path, settings)+ self.page = kvm_bridge_win.WindowsApplication(self.path)+ self.page._send_to = lambda peer, message: True+ self.addCleanup(self.page.deleteLater)+ self.addCleanup(self.page.server.stop)++ def ways(self, methods=(), parts=("middle",), side=None):+ app_config.set_ways(self.path, self.peer, side=side, methods=list(methods), parts=list(parts), corner="top_left")+ self.page._pull_peer_fields()def shown(self):+ import motion+page = self.page- rows = {key for key, row in page.crossing_rows.items() if not row.isHidden()}- rows |= {"resistance"} - ({"resistance"} if page.resistance_module.isHidden() else set())- rows |= {"shortcut"} - ({"shortcut"} if page.shortcut_module.isHidden() else set())+ rows = {key for key, row in page.crossing_rows.items() if motion.target_shown(row)}+ rows |= {"resistance"} if motion.target_shown(page.resistance_module) else set()+ rows |= {"shortcut"} if motion.target_shown(page.shortcut_module) else set()return rowsdef test_rows_hide_and_come_back_with_the_ways(self):- self.page._config.crossing_methods = ["shortcut"]- self.reflect(self.page)+ self.ways()self.assertEqual(self.shown(), {"edge", "shortcut"})- self.page._config.crossing_methods = ["part"]- self.reflect(self.page)+ self.page._ways_changed("shortcut", False)+ self.ways(["part"])self.assertEqual(self.shown(), {"edge", "parts", "dragging", "resistance"})self.assertTrue(self.page.way_boxes["part"].isChecked())self.assertFalse(self.page.way_boxes["shortcut"].isChecked())def test_the_chips_are_named_for_the_current_edge(self):- self.page._config.mac_return_edge = "right"- self.page._config.crossing_edge_parts = ["start", "end"]- self.reflect(self.page)+ self.ways(["part"], ["start", "end"])buttons = self.page.part_buttonsself.assertEqual([buttons[p].text() for p in ("start", "middle", "end")], ["Top", "Middle", "Bottom"])self.assertEqual([buttons[p].isChecked() for p in ("start", "middle", "end")], [True, False, True])- self.page._config.mac_return_edge = "top"- self.reflect(self.page)+ self.ways(["part"], ["start", "end"], side="top")self.assertEqual([buttons[p].text() for p in ("start", "middle", "end")], ["Left", "Middle", "Right"])def test_an_edge_learned_from_a_peer_renames_the_chips(self):page = self.page- page._config.crossing_methods = ["part"]- page._config.mac_return_edge = "right"- self.reflect(page)- page._config.mac_return_edge = "top"- self.reflect(page)+ self.ways(["part"])+ page._on_arrangement(self.peer, "bottom", 1790000999, self.peer)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())def test_unticking_the_last_part_leaves_it_on(self):- import kvm_bridge_win-page = self.page- page._config.crossing_edge_parts = ["middle"]- page._persist = lambda: True- page.sender = SimpleNamespace(update_config=lambda config: None)- page._reflect_ways = lambda: self.reflect(page)- page._reflect_look = lambda: None+ self.ways(["part"], ["middle"])page.part_buttons["middle"].setChecked(False)- kvm_bridge_win.WindowsApplication._set_part(page, "middle", False)- self.assertEqual(page._config.crossing_edge_parts, ["middle"])+ page._set_part("middle", False)+ parts = [zone for zone in app_config.load_settings(self.path)["zones"] if zone["kind"] == "part"][0]["parts"]+ self.assertEqual(parts, ["middle"])self.assertTrue(page.part_buttons["middle"].isChecked())def test_the_crossing_line_gives_the_first_reason_nothing_can_cross(self):diff --git a/win_app/tests/test_pairing_window.py b/win_app/tests/test_pairing_window.pyindex 9e436fd..cd5a3f4 100644--- a/win_app/tests/test_pairing_window.py+++ b/win_app/tests/test_pairing_window.py@@ -13,6 +13,7 @@ from types import SimpleNamespacesys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))from core import pairing, peerlist, protocol+from core.tests import responder_harness as harnesstry:from PySide6.QtWidgets import QApplication@@ -45,11 +46,13 @@ class MachinesWindowTest(unittest.TestCase):def tearDown(self):if self.window is not None:+ self.window.server.stop()self.window.deleteLater()def open(self, *entries, **top):settings = app_config.load_settings(self.path)settings["peers"] = list(entries)+ settings["port"] = harness.free_port()settings.update(top)app_config.write_settings(self.path, settings)self.window = kvm_bridge_win.WindowsApplication(self.path)@@ -81,13 +84,21 @@ class MachinesWindowTest(unittest.TestCase):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_any_token_from_1_4_x_asks_to_pair_again(self):+ # "A" * 43 has pairing's shape: 1.4.x kept no record of whether a token was paired or typed.+ for token in ("typed by hand", "A" * 43):+ with self.subTest(token=token):+ for name in ("config.json", "settings.json"):+ (self.folder / name).unlink(missing_ok=True)+ (self.folder / "config.json").write_text(json.dumps({+ "host": "192.0.2.20", "port": harness.free_port(), "auth_token": token, "paired_with": "MacBook Pro",+ "mac_host": "192.0.2.10", "mac_return_edge": "left"}))+ self.window = kvm_bridge_win.WindowsApplication(self.path)+ row = next(iter(self.window.machines.rows.values()))+ self.assertEqual(row.word.text(), "Pair again")+ self.window.server.stop()+ self.window.deleteLater()+ self.window = Nonedef test_with_nothing_paired_the_list_says_so(self):self.window = kvm_bridge_win.WindowsApplication(self.path)@@ -163,7 +174,7 @@ class MachinesWindowTest(unittest.TestCase):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",+ "host": "192.0.2.20", "port": harness.free_port(), "auth_token": "typed by hand", "paired_with": "MacBook Pro","mac_host": "192.0.2.10", "mac_return_edge": "left"}))self.window = kvm_bridge_win.WindowsApplication(self.path)self.stub(self.window)@@ -293,6 +304,31 @@ class MachinesWindowTest(unittest.TestCase):window._store_peer(fresh, replaced)self.assertEqual([entry["token"] for entry in self.settings()["peers"]], [TOKEN_B])+ def test_pairing_the_mac_at_the_1_4_entrys_address_again_keeps_its_side_and_zones(self):+ # Every 1.4.x upgrader pairs again (no token migrates since 1.5.0), on purpose and at the+ # screen: where that Mac sits is not theirs to set a second time.+ migrated = {**peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"), "id": "", "from_1_4": True, "linked": False,+ "paired_at": 0, "side": "top", "side_set_at": 1_790_000_000}+ window = self.open(migrated, zones=[{"peer": "", "kind": "edge"}, {"peer": "", "kind": "corner",+ "corner": "top_left", "edge": "top", "off": True}])+ fresh = peer(b"\x0c" * 16, "Studio Mac", protocol.id_text(bytes(range(2, 34))), "192.0.2.10")+ window._store_peer(fresh, window.book.peers()[0])+ after = self.settings()+ new_id = protocol.id_text(b"\x0c" * 16)+ self.assertEqual([zone["peer"] for zone in after["zones"]], [new_id, new_id])+ self.assertEqual((after["peers"][0]["side"], after["peers"][0]["side_set_at"]), ("top", 1_790_000_000))++ def test_pairing_another_platform_at_that_address_keeps_nothing_of_it(self):+ migrated = {**peer(ID_A, "Studio Mac", TOKEN_A, "192.0.2.10"), "id": "", "from_1_4": True, "linked": False,+ "paired_at": 0, "side": "top", "side_set_at": 1_790_000_000}+ window = self.open(migrated, zones=[{"peer": "", "kind": "edge"}])+ fresh = peer(b"\x0c" * 16, "Studio PC", protocol.id_text(bytes(range(2, 34))), "192.0.2.10", platform="windows")+ window._store_peer(fresh, window.book.peers()[0])+ after = self.settings()+ # Only its own whole edge, which every machine paired starts with.+ self.assertEqual(after["zones"], [{"peer": protocol.id_text(b"\x0c" * 16), "kind": "edge"}])+ self.assertEqual(after["peers"][0]["side"], "")+@unittest.skipIf(kvm_bridge_win is None, "needs PySide6")class PairingSheetWindowTest(unittest.TestCase):@@ -315,6 +351,7 @@ class PairingSheetWindowTest(unittest.TestCase):def tearDown(self):self.service.cancel_pairing()+ self.window.server.stop()self.window.deleteLater()def show_code(self):@@ -359,6 +396,30 @@ class PairingSheetWindowTest(unittest.TestCase):self.assertEqual(self.window.sheet.pair_note.text(),peerlist.pairing_error_text(pairing.PairingError(pairing.ERROR_VERSION), "Old Mac"))+ STUDIO = {"name": "Studio", "address": "192.168.50.22", "port": 24820, "reply_port": 24821,+ "pair_id": "first", "pairing": 3, "platform": "windows"}++ def test_one_machine_heard_on_two_interfaces_shows_each_row_s_address(self):+ twice = [self.STUDIO, dict(self.STUDIO, address="169.254.3.7", pair_id="second")]+ self.window.sheet.set_machines(twice, self.window._shown)+ self.assertEqual([button.text() for button in self.window.sheet.group.buttons()], [+ "Studio · Windows · 192.168.50.22 · showing a code",+ "Studio · Windows · 169.254.3.7 · showing a code",+ ])++ def test_a_lone_machine_s_row_is_as_it_was(self):+ self.window.sheet.set_machines([self.STUDIO], self.window._shown)+ self.assertEqual(self.window.sheet.group.buttons()[0].text(), "Studio · Windows · showing a code")++ def test_the_addresses_follow_hide_addresses(self):+ twice = [self.STUDIO, dict(self.STUDIO, address="169.254.3.7", pair_id="second")]+ self.window.sheet.set_machines(twice, self.window._shown)+ self.window._config.hide_addresses = True+ self.window.sheet.set_machines(twice, self.window._shown)+ texts = [button.text() for button in self.window.sheet.group.buttons()]+ self.assertEqual(len(texts), 2)+ self.assertFalse([text for text in texts if "192.168.50.22" in text or "169.254.3.7" in text], texts)+def test_only_a_machine_showing_a_code_is_listed(self):quiet = {"name": "Quiet", "address": "192.0.2.61", "port": 24820, "reply_port": 24821, "pair_id": None,"pairing": 3, "platform": "macos"}diff --git a/win_app/tests/test_pc_three_machines.py b/win_app/tests/test_pc_three_machines.pynew file mode 100644index 0000000..757b715--- /dev/null+++ b/win_app/tests/test_pc_three_machines.py@@ -0,0 +1,589 @@+"""Three machines on the Windows app (1.5.0 milestone 5): the shortcut's machine, a tray item per+machine, each machine's ways written on its own, the Crossing page's choice of machine, the diagram+of this PC and its neighbours, and Pause counting every machine's zones (WIRE.md sections 5 and 8)."""++import json+import os+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from links_rig import B, C, Rig, edge_zone++import app_config+import pages_win+from core import protocol+from core import ways+from core.tests import responder_harness as harness++try:+ from PySide6.QtWidgets import QApplication++ import diagram+ import kvm_bridge_win+ import theme+except ImportError: # PySide6 is only in the Windows venv+ kvm_bridge_win = None++D = harness.D+BT, CT, DT = protocol.id_text(B), protocol.id_text(C), protocol.id_text(D)+HIGH_ID = bytes([200]) * 16+HIGH = protocol.id_text(HIGH_ID)+++def target_of(message):+ return protocol.read_id(message["data"]["target"])+++class ShortcutMachineTests(unittest.TestCase):+ """The shortcut, the Send button and the tray send input where core.ways.shortcut_peer says."""++ def rig(self, up, **entries):+ peers = [harness.entry(B, "Bee", side="left", **entries.get("b", {})),+ harness.entry(C, "Sea", side="right", **entries.get("c", {}))]+ return Rig(entries=peers, zones=[edge_zone(B), edge_zone(C)], up=up)++ def test_with_the_first_machine_down_the_shortcut_takes_one_that_is_up(self):+ rig = self.rig(up=(C,))+ self.assertTrue(rig.sender.set_redirecting(True))+ self.assertEqual(rig.sender.owner, C)+ self.assertEqual(target_of(rig.sent(C, "focus")[0]), C)++ def test_the_shortcut_goes_back_to_the_machine_input_was_last_on(self):+ rig = self.rig(up=(B, C))+ rig.sender.go(C)+ rig.accept_take(C)+ rig.sender.set_redirecting(False)+ self.assertEqual(rig.sender.shortcut_target(), C)+ self.assertTrue(rig.sender.set_redirecting(True))+ self.assertEqual(rig.sender.owner, C)++ def test_a_machine_that_does_not_accept_input_is_passed_over(self):+ rig = self.rig(up=(C,))+ rig.bring_up(B, accepts=False)+ self.assertEqual(rig.sender.shortcut_target(), C)++ def test_a_machine_this_pc_does_not_send_to_is_never_picked(self):+ rig = self.rig(up=(B, C), b={"send": False})+ self.assertEqual(rig.sender.shortcut_target(), C)++ def test_with_every_machine_down_the_first_is_woken(self):+ rig = self.rig(up=(), b={"hw": "aa:bb:cc:dd:ee:ff"})+ woken = []+ rig.sender._wake_sender = lambda address, host: woken.append(address)+ self.addCleanup(rig.sender._stop_event.set)+ self.assertFalse(rig.sender.set_redirecting(True))+ self.assertTrue(rig.sender.is_waking(B))+ self.assertFalse(rig.sender.is_waking(C))++ def test_with_every_machine_down_and_none_to_wake_the_first_is_named(self):+ rig = self.rig(up=())+ rig.sender.on_status(rig.links.key_of(rig.settings.data["peers"][0]), False, "Bee is unreachable")+ self.assertFalse(rig.sender.set_redirecting(True))+ self.assertEqual(rig.alerts, ["Cannot switch — Bee is unreachable"])++ def test_the_status_is_the_shortcut_machines(self):+ rig = self.rig(up=(C,))+ rig.sender.on_status(rig.links.key_of(rig.settings.data["peers"][0]), False, "Bee is unreachable")+ rig.sender.on_status(rig.links.key_of(rig.settings.data["peers"][1]), True, "Connected to Sea")+ self.assertTrue(rig.sender.connected)+ self.assertEqual(rig.sender.status, "Connected to Sea")+++class SetWaysTests(unittest.TestCase):+ """Each machine's side and zones are written one machine at a time, under the settings lock, and+ never by a flat save."""++ def setUp(self):+ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ self.path = Path(directory.name) / "settings.json"+ settings = app_config.migrate(None, machine_id=protocol.id_text(harness.HERE))+ settings["peers"] = [+ harness.entry(B, "Bee", side="left", side_set_at=100, side_by=HIGH),+ harness.entry(C, "Sea", platform="windows"),+ ]+ settings["zones"] = [{"peer": BT, "kind": "edge"}]+ app_config.write_settings(self.path, settings)++ def saved(self):+ return json.loads(self.path.read_text(encoding="utf-8"))++ def peer(self, ident):+ return next(item for item in self.saved()["peers"] if item["id"] == ident)++ def zones(self, ident):+ return {zone["kind"]: zone for zone in self.saved()["zones"] if zone["peer"] == ident}++ def test_reading_the_settings_gives_a_machine_with_no_zone_its_edge_and_writes_it(self):+ # The rig's beta.3 file of 01-10-2026: the laptop paired second, its side set, no zone at all.+ settings = self.saved()+ settings["peers"][1]["side"] = "right"+ app_config.write_settings(self.path, settings)+ loaded = app_config.load_settings(self.path)+ self.assertIn({"peer": CT, "kind": "edge"}, loaded["zones"])+ self.assertIn({"peer": CT, "kind": "edge"}, self.saved()["zones"])++ def test_one_whose_side_is_taken_gets_its_edge_off_and_the_file_still_reads(self):+ settings = self.saved()+ settings["peers"][1]["side"] = "left"+ app_config.write_settings(self.path, settings)+ loaded = app_config.load_settings(self.path)+ self.assertIn({"peer": CT, "kind": "edge", "off": True}, loaded["zones"])+ self.assertIn("Sea has no way in", ways.blocked_sentence(loaded, CT, "this PC"))++ def test_one_machines_side_and_zones_are_written_and_the_others_left_alone(self):+ moved = app_config.set_ways(self.path, CT, side="right", methods=["part", "corner"], parts=["end"], corner="bottom_right")+ self.assertTrue(moved)+ entry = self.peer(CT)+ self.assertEqual((entry["side"], entry["side_by"]), ("right", self.saved()["machine_id"]))+ self.assertGreater(entry["side_set_at"], 0)+ zones = self.zones(CT)+ self.assertEqual(zones["part"]["parts"], ["end"])+ self.assertNotIn("off", zones["part"])+ self.assertTrue(zones["edge"]["off"])+ self.assertEqual((zones["corner"]["corner"], zones["corner"]["edge"]), ("bottom_right", "right"))+ self.assertEqual(self.peer(BT)["side"], "left")+ self.assertEqual(self.zones(BT), {"edge": {"peer": BT, "kind": "edge"}})++ def test_an_unchanged_side_is_not_a_move(self):+ self.assertFalse(app_config.set_ways(self.path, BT, side="left", methods=["edge"], parts=["middle"], corner="top_left"))+ self.assertEqual(self.peer(BT)["side_set_at"], 100)++ def test_no_side_given_keeps_the_side_held_whatever_the_window_last_read(self):+ settings = self.saved()+ settings["peers"][0]["side"] = "top"+ app_config.write_settings(self.path, settings)+ self.assertFalse(app_config.set_ways(self.path, BT, methods=["edge", "corner"], parts=["middle"], corner="top_left"))+ self.assertEqual(self.peer(BT)["side"], "top")+ self.assertEqual(self.zones(BT)["corner"]["edge"], "top")++ def test_a_clash_is_refused_with_a_sentence_naming_both_and_nothing_is_written(self):+ # On Bee's side with no way in yet: turning Sea's edge on would cover Bee's.+ app_config.set_ways(self.path, CT, side="left", methods=[], parts=["middle"], corner="top_left")+ before = self.path.read_bytes()+ with self.assertRaises(app_config.ConfigError) as raised:+ app_config.set_ways(self.path, CT, side="left", methods=["edge"], parts=["middle"], corner="top_left")+ self.assertIn("Bee", str(raised.exception))+ self.assertIn("Sea", str(raised.exception))+ self.assertIn("this PC", str(raised.exception))+ self.assertEqual(self.path.read_bytes(), before)++ def test_a_machine_that_is_not_paired_is_an_error(self):+ with self.assertRaises(app_config.ConfigError):+ app_config.set_ways(self.path, DT, side="left", methods=[], parts=["middle"], corner="top_left")++ def test_a_flat_save_never_writes_a_side_or_a_zone(self):+ stale = app_config.load_config(self.path)+ settings = self.saved()+ settings["peers"][0].update(side="top", side_set_at=300, side_by=HIGH)+ app_config.write_settings(self.path, settings)+ app_config.save_config(self.path, app_config.replace(+ stale, crossing_methods=["part"], crossing_edge_parts=["start"], mac_return_edge="bottom",+ arrangement_set_at=400, pointer_speed=2.0))+ saved = self.saved()+ self.assertEqual((saved["peers"][0]["side"], saved["peers"][0]["side_set_at"], saved["peers"][0]["side_by"]),+ ("top", 300, HIGH))+ # Sea's edge is the repair every read makes for a machine paired with no zone, not the save's.+ self.assertEqual(saved["zones"], [{"peer": BT, "kind": "edge"}, {"peer": CT, "kind": "edge"}])+ self.assertFalse(saved["shortcut"])+ self.assertEqual(saved["pointer_speed"], 2.0)++ def test_a_flat_save_keeps_a_name_and_hardware_address_learnt_since_the_window_read(self):+ stale = app_config.load_config(self.path)+ settings = self.saved()+ settings["peers"][0].update(name="Bee Studio", hw="aa:bb:cc:dd:ee:01")+ app_config.write_settings(self.path, settings)+ app_config.save_config(self.path, app_config.replace(stale, pointer_speed=2.0))+ self.assertEqual((self.peer(BT)["name"], self.peer(BT)["hw"]), ("Bee Studio", "aa:bb:cc:dd:ee:01"))+ app_config.save_config(self.path, app_config.replace(stale, mac_host="192.0.2.99", paired_with="",+ mac_hardware_address=""))+ self.assertEqual((self.peer(BT)["host"], self.peer(BT)["name"], self.peer(BT)["hw"]), ("192.0.2.99", "", ""))++ def test_an_arrangement_rewrites_the_edge_that_machines_corner_crosses(self):+ settings = self.saved()+ settings["zones"].append({"peer": BT, "kind": "corner", "corner": "top_right", "edge": "left"})+ app_config.write_settings(self.path, settings)+ self.assertEqual(app_config.apply_arrangement(self.path, BT, "left", 500, HIGH), (True, []))+ self.assertEqual((self.peer(BT)["side"], self.zones(BT)["corner"]["edge"]), ("right", "right"))++ def test_an_arrangement_is_core_ways_and_names_both_machines(self):+ settings = self.saved()+ settings["peers"][1]["side"] = "right"+ settings["zones"].append({"peer": CT, "kind": "edge"})+ app_config.write_settings(self.path, settings)+ changed, notices = app_config.apply_arrangement(self.path, CT, "right", 500, HIGH)+ self.assertTrue(changed)+ self.assertEqual(self.peer(CT)["side"], "left")+ self.assertEqual(notices, ["Bee and Sea now lead from the same part of this PC's screen, so Sea's edge is off."])+ self.assertTrue(self.zones(CT)["edge"]["off"])+++class DiagramGeometryTests(unittest.TestCase):+ SCREEN = (120.0, 75.0)++ def test_machines_sharing_a_side_are_ordered_by_their_thirds_then_the_list(self):+ slots = pages_win.side_slots([+ {"side": "right", "methods": ["part"], "parts": ["end"]},+ {"side": "right", "methods": ["part"], "parts": ["start"]},+ {"side": "top", "methods": [], "parts": ["middle"]},+ {"side": "", "methods": ["corner"], "parts": ["middle"]},+ ])+ self.assertEqual(slots, [("right", 0.5, 1.0), ("right", 0.0, 0.5), ("top", 0.0, 1.0), None])++ def test_one_machine_sits_where_the_pair_always_did(self):+ for side, offset in (("right", (134.0, 0.0)), ("left", (-134.0, 0.0)), ("top", (0.0, -89.0)), ("bottom", (0.0, 89.0))):+ pc, (other,), _height = pages_win.layout_rects(400.0, 0.0, [(pages_win.SIDE_ANGLE[side], 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertEqual((other[0] - pc[0], other[1] - pc[1]), offset, side)+ self.assertEqual(other[2:], self.SCREEN)+ pc, (other,), height = pages_win.layout_rects(400.0, 10.0, [(0.0, 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertEqual(height, 75.0)+ self.assertEqual((pc[0] + other[0] + other[2]) / 2.0, 200.0)+ self.assertEqual(pc[1], 10.0)+ _pc, _rects, stacked = pages_win.layout_rects(400.0, 0.0, [(90.0, 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertEqual(stacked, 164.0)++ def test_a_row_puts_this_pc_in_the_middle(self):+ pc, (left, right), height = pages_win.layout_rects(+ 500.0, 0.0, [(180.0, 0.0, 1.0), (0.0, 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertEqual(pc[0] + pc[2] / 2.0, 250.0)+ self.assertEqual(left[0] + left[2] + 14.0, pc[0])+ self.assertEqual(right[0], pc[0] + pc[2] + 14.0)+ self.assertEqual(height, 75.0)++ def test_two_on_one_side_are_each_half_as_long_and_split_it(self):+ pc, (top, bottom), _height = pages_win.layout_rects(+ 500.0, 0.0, [(0.0, 0.0, 0.5), (0.0, 0.5, 1.0)], self.SCREEN, 14.0)+ self.assertEqual(top[2:], (60.0, 37.5))+ self.assertEqual(bottom[2:], (60.0, 37.5))+ self.assertEqual(top[0], pc[0] + pc[2] + 14.0)+ self.assertEqual((top[1], bottom[1] + bottom[3]), (pc[1], pc[1] + pc[3]))++ def test_an_l_has_one_beside_and_one_above(self):+ pc, (right, above), height = pages_win.layout_rects(+ 500.0, 0.0, [(0.0, 0.0, 1.0), (90.0, 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertEqual((right[0], right[1]), (pc[0] + pc[2] + 14.0, pc[1]))+ self.assertEqual((above[0], above[1] + above[3] + 14.0), (pc[0], pc[1]))+ self.assertEqual(above[1], 0.0)+ self.assertEqual(height, 164.0)++ def test_with_several_machines_this_pc_stays_in_the_middle_whatever_the_sides(self):+ for placed in ([(0.0, 0.0, 1.0), (90.0, 0.0, 1.0)], [(0.0, 0.0, 0.5), (0.0, 0.5, 1.0)]):+ pc, _rects, _height = pages_win.layout_rects(500.0, 0.0, placed, self.SCREEN, 14.0, centre_pc=True)+ self.assertEqual(pc[0] + pc[2] / 2.0, 250.0, placed)+ pc, (_left, right), _height = pages_win.layout_rects(+ 300.0, 0.0, [(0.0, 0.0, 1.0), (90.0, 0.0, 1.0)], self.SCREEN, 14.0, centre_pc=True)+ self.assertEqual(pc[0] + pc[2] / 2.0, 150.0)+ self.assertLessEqual(right[0] + right[2], 300.001)++ def test_a_narrow_width_shrinks_the_drawing_to_fit(self):+ pc, (left, right), _height = pages_win.layout_rects(+ 300.0, 0.0, [(180.0, 0.0, 1.0), (0.0, 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertGreaterEqual(left[0], -0.001)+ self.assertLessEqual(right[0] + right[2], 300.001)+ self.assertLess(pc[2], 120.0)++ def test_nobody_goes_through_this_pc_on_the_way_round(self):+ for start, end in ((0.0, 1.0), (0.0, 0.5), (0.5, 1.0)):+ for angle in range(0, 360, 5):+ pc, (other,), _height = pages_win.layout_rects(500.0, 0.0, [(float(angle), start, end)], self.SCREEN, 14.0)+ apart_x = other[0] >= pc[0] + pc[2] or other[0] + other[2] <= pc[0]+ apart_y = other[1] >= pc[1] + pc[3] or other[1] + other[3] <= pc[1]+ self.assertTrue(apart_x or apart_y, (angle, start, end))++ def test_the_description_names_every_machine_and_its_side(self):+ machines = [+ {"label": "Bee", "side": "right", "methods": ["edge"], "parts": ["middle"], "corner": "top_left", "chosen": True},+ {"label": "Sea", "side": "top", "methods": [], "parts": ["middle"], "corner": "top_left", "chosen": False},+ {"label": "Dee", "side": "", "methods": [], "parts": ["middle"], "corner": "top_left", "chosen": False},+ ]+ text = pages_win.diagram_description(machines, "Right Ctrl", "hold", True)+ self.assertIn("Bee is to the right of this PC", text)+ self.assertIn("Sea is above this PC", text)+ self.assertIn("Not placed yet: Dee", text)+ self.assertIn("Input moves to Bee when you push through the whole right edge", text)++ def test_the_unplaced_line_names_them_all(self):+ self.assertEqual(pages_win.unplaced_line(["Sea"]), "Not placed yet: Sea")+ self.assertEqual(pages_win.unplaced_line(["Sea", "Dee", "Eff"]), "Not placed yet: Sea, Dee and Eff")+ self.assertEqual(pages_win.unplaced_line([]), "")+++class WordingTests(unittest.TestCase):+ def test_the_summary_and_the_unlearned_side_name_the_machine(self):+ self.assertEqual(pages_win.ways_summary(["edge"], "right", [], "top_left", "F13", "hold", "Sea"),+ "Input moves to Sea when you push through the whole right edge.")+ self.assertIn("on Sea", pages_win.not_learned_edge("Sea"))+ self.assertIn("the other machine", pages_win.not_learned_edge())++ def test_no_page_purpose_pictures_exactly_one_other_machine(self):+ for _key, _name, purpose in pages_win.PAGES:+ self.assertNotIn("the other machine", purpose)+ for line in pages_win.SCOPE.values():+ self.assertNotIn("the other machine", line)++[email protected](kvm_bridge_win is None, "needs PySide6")+class WindowTests(unittest.TestCase):+ """The real window, built offscreen from a settings file, which starts no receiver, hooks or announcer."""++ PEERS = None++ def setUp(self):+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ self.app = QApplication.instance() or QApplication([])+ theme.init_fonts()+ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ self.path = Path(directory.name) / "settings.json"+ settings = app_config.migrate(None, machine_id=protocol.id_text(harness.HERE))+ settings["peers"] = self.PEERS if self.PEERS is not None else [+ harness.entry(B, "Bee", side="left", side_set_at=100, side_by=HIGH, paired_with=[]),+ harness.entry(C, "Sea", platform="windows", allow_drive=False),+ ]+ settings["zones"] = [{"peer": BT, "kind": "edge"}]+ settings["port"] = harness.free_port()+ app_config.write_settings(self.path, settings)+ self.window = kvm_bridge_win.WindowsApplication(self.path)+ self.sent = []+ self.window._send_to = lambda peer, message: self.sent.append((peer, message)) or True+ self.window._refresh_window()++ def tearDown(self):+ self.window.server.stop()+ self.window.deleteLater()++ def saved(self):+ return json.loads(self.path.read_text(encoding="utf-8"))++ def peer(self, ident):+ return next(item for item in self.saved()["peers"] if item["id"] == ident)+++class CrossingPageTests(WindowTests):+ def test_with_two_machines_paired_the_page_offers_a_choice_of_machine(self):+ window = self.window+ self.assertFalse(window.machine_row.isHidden())+ self.assertEqual(set(window.machine_choice._buttons), {BT, CT})+ self.assertEqual([button.text() for button in window.machine_choice._buttons.values()], ["Bee", "Sea"])+ self.assertEqual(window.machine_choice.value, BT)+ self.assertEqual(window.edge_choice.value, "left")+ self.assertTrue(window.way_boxes["edge"].isChecked())+ self.assertEqual(window.edge_heading.text(), "Where Bee is")++ def test_choosing_a_machine_shows_its_ways(self):+ window = self.window+ window._choose_machine(CT)+ self.assertEqual(window.edge_choice.value, None)+ # Every machine paired starts with its whole edge, which waits for a side.+ self.assertTrue(window.way_boxes["edge"].isChecked())+ self.assertTrue(window.way_boxes["shortcut"].isChecked())+ self.assertEqual(window.edge_heading.text(), "Where Sea is")+ self.assertEqual(window.edge_unlearned.text(), pages_win.not_learned_edge("Sea"))+ self.assertIn("Sea", window.ways_summary.text())++ def test_a_side_set_here_is_that_machines_alone_and_is_sent_to_it(self):+ window = self.window+ window._choose_machine(CT)+ window._set_arrangement("right")+ self.assertEqual(self.peer(CT)["side"], "right")+ self.assertEqual(self.peer(BT)["side"], "left")+ (peer, message), = self.sent+ self.assertEqual(peer, C)+ self.assertEqual(message["data"]["edge"], "right")+ self.assertEqual(message["data"]["set_at"], self.peer(CT)["side_set_at"])++ def arrangements(self):+ return [(peer, message["data"]) for peer, message in self.sent if message["type"] == protocol.MSG_ARRANGEMENT]++ def test_turning_off_every_way_to_a_machine_tells_it_so_with_its_side_as_it_was(self):+ self.window.way_boxes["edge"].setChecked(False)+ (peer, data), = self.arrangements()+ self.assertEqual((peer, data["edge"], data["set_at"], data["by"], data["way_back"]), (B, "left", 100, HIGH, False))+ self.window.way_boxes["corner"].setChecked(True)+ self.assertIs(self.arrangements()[-1][1]["way_back"], True)++ def test_an_arrangement_that_changed_something_is_answered_with_this_pcs_own(self):+ window = self.window+ window.bridge.arrangement.emit(CT, "left", 500, HIGH, True)+ (peer, data), = self.arrangements()+ self.assertEqual((peer, data["edge"], data["set_at"], data["by"], data["way_back"]), (C, "right", 500, HIGH, True))+ self.assertIs(self.peer(CT)["way_back"], True)+ window.bridge.arrangement.emit(CT, "left", 500, HIGH, True)+ self.assertEqual(len(self.arrangements()), 1)+ window.bridge.arrangement.emit(CT, "left", 500, HIGH, False)+ self.assertEqual(len(self.arrangements()), 2)+ self.assertIs(self.peer(CT)["way_back"], False)++ def test_every_link_up_says_whether_a_way_leads_to_that_machine(self):+ told = lambda: next(m["data"] for m in self.window._announce(B) if m["type"] == protocol.MSG_ARRANGEMENT)+ self.assertIs(told()["way_back"], True)+ self.window.way_boxes["edge"].setChecked(False)+ self.assertIs(told()["way_back"], False)++ def test_either_link_hands_on_way_back(self):+ heard = []+ self.window.bridge.arrangement.connect(lambda *args: heard.append(args))+ read = {"edge": "left", "set_at": 500, "by": HIGH_ID, "way_back": False}+ self.window.server._callbacks["arrangement"](C, read)+ self.window.sender.arrangement_callback(C, {**read, "set_at": 501, "way_back": True})+ self.assertEqual([args[4] for args in heard], [False, True])++ def test_a_way_that_would_clash_is_refused_with_the_sentence_and_the_box_goes_back(self):+ window = self.window+ window._choose_machine(CT)+ window._set_arrangement("left")+ before = self.path.read_bytes()+ window.way_boxes["edge"].setChecked(True)+ self.assertFalse(window.way_boxes["edge"].isChecked())+ self.assertEqual(self.path.read_bytes(), before)+ self.assertFalse(window.clash_note.isHidden())+ self.assertIn("Bee and Sea would both lead from the left edge of this PC", window.clash_note.text())+ window._choose_machine(BT)+ self.assertTrue(window.clash_note.isHidden())++ def test_ways_written_here_reach_that_machines_zones_only(self):+ window = self.window+ window._choose_machine(CT)+ window._set_arrangement("right")+ window.way_boxes["corner"].setChecked(True)+ window._set_corner("bottom_right")+ zones = {zone["kind"]: zone for zone in self.saved()["zones"] if zone["peer"] == CT}+ self.assertNotIn("off", zones["corner"])+ self.assertEqual(zones["corner"]["corner"], "bottom_right")+ self.assertEqual([zone for zone in self.saved()["zones"] if zone["peer"] == BT], [{"peer": BT, "kind": "edge"}])++ def test_the_shortcut_stays_this_pcs_own(self):+ window = self.window+ window._choose_machine(CT)+ window.way_boxes["shortcut"].setChecked(False)+ self.assertFalse(self.saved()["shortcut"])+ window._choose_machine(BT)+ self.assertFalse(window.way_boxes["shortcut"].isChecked())++ def test_a_machine_that_may_drive_this_pc_and_cannot_follow_the_way_is_named(self):+ window = self.window+ window._choose_machine(CT)+ self.assertFalse(window.missing_note.isHidden())+ self.assertIn("While Bee drives this PC, this way to Sea does nothing", window.missing_note.text())+ window._choose_machine(BT)+ self.assertTrue(window.missing_note.isHidden())++ def test_a_machine_whose_side_another_holds_is_named_with_the_one_that_holds_it(self):+ window = self.window+ window._on_arrangement(CT, "right", 500, HIGH)+ window._choose_machine(CT)+ self.assertFalse(window.blocked_note.isHidden())+ self.assertIn("Sea has no way in: Bee already leads from the left edge of this PC", window.blocked_note.text())+ window._choose_machine(BT)+ self.assertTrue(window.blocked_note.isHidden())++ def test_a_machine_that_said_no_way_leads_back_is_named_until_it_says_one_does(self):+ window = self.window+ self.assertTrue(window.no_way_back_note.isHidden())+ window._on_arrangement(BT, "right", 50, HIGH, False)+ self.assertFalse(window.no_way_back_note.isHidden())+ self.assertIn("Bee has no way back to this machine", window.no_way_back_note.text())+ window._on_arrangement(BT, "right", 50, HIGH, True)+ self.assertTrue(window.no_way_back_note.isHidden())++ def test_an_arrangement_from_the_machine_not_shown_moves_only_its_side(self):+ window = self.window+ window._on_arrangement(CT, "left", 500, HIGH)+ self.assertEqual(window.edge_choice.value, "left")+ window._choose_machine(CT)+ self.assertEqual(window.edge_choice.value, "right")++ def test_the_diagram_draws_every_machine(self):+ window = self.window+ window._choose_machine(CT)+ window._set_arrangement("right")+ drawn = {machine["label"]: machine for machine in window.arrangement_diagram._machines}+ self.assertEqual((drawn["Bee"]["side"], drawn["Sea"]["side"]), ("left", "right"))+ self.assertTrue(drawn["Sea"]["chosen"])+ self.assertFalse(drawn["Bee"]["chosen"])+ self.assertIn("Bee is to the left of this PC", window.arrangement_diagram.accessibleDescription())++ def test_pause_counts_every_machines_zones(self):+ window = self.window+ window._choose_machine(BT)+ window.way_boxes["edge"].setChecked(False)+ self.assertFalse(window._crossing_state_args()[4])+ window._choose_machine(CT)+ window._set_arrangement("right")+ window.way_boxes["edge"].setChecked(True)+ self.assertTrue(window._crossing_state_args()[4])++ def test_the_same_switch_reaches_every_machine(self):+ self.assertEqual(self.window.same_switch.text(), "Same on all machines")+++class OneMachineTests(WindowTests):+ PEERS = [harness.entry(B, "Bee", side="left")]++ def test_one_machine_has_no_choice_and_the_page_reads_as_before(self):+ window = self.window+ self.assertTrue(window.machine_row.isHidden())+ self.assertEqual(window.edge_heading.text(), "Where the other machine is")+ self.assertEqual(window.edge_choice.value, "left")+ self.assertTrue(window.way_boxes["edge"].isChecked())++ def test_the_tray_has_no_item_per_machine_and_the_button_names_it(self):+ window = self.window+ self.assertEqual(window.machine_actions, {})+ self.assertEqual(window.redirect_action.text(), "Send input to Bee")+ self.assertTrue(window.redirect_action.isVisible())+++class TrayTests(WindowTests):+ def test_each_machine_this_pc_sends_to_has_its_own_tray_item(self):+ window = self.window+ self.assertEqual([action.text() for action in window.machine_actions.values()],+ ["Send input to Bee", "Send input to Sea"])+ went = []+ window.sender.go = lambda peer, *args: went.append(peer) or True+ window.machine_actions[CT].trigger()+ self.assertEqual(went, [C])+ self.assertFalse(window.redirect_action.isVisible())++ def test_the_send_button_names_the_machine_the_shortcut_would_pick(self):+ window = self.window+ window.sender.shortcut_target = lambda: C+ window._refresh_window()+ self.assertEqual(window.redirect_button.text(), "Send input to Sea")++[email protected](kvm_bridge_win is None, "needs PySide6")+class DiagramWidgetTests(unittest.TestCase):+ def setUp(self):+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ self.app = QApplication.instance() or QApplication([])++ def machine(self, key, label, side, methods=(), chosen=False, parts=("middle",)):+ return {"key": key, "label": label, "side": side, "methods": list(methods), "parts": list(parts),+ "corner": "top_left", "chosen": chosen}++ def test_each_machines_marks_are_its_own_and_the_unplaced_are_named_underneath(self):+ picture = diagram.ArrangementDiagram()+ picture.resize(500, picture.height())+ picture.set_machines([self.machine("b", "Bee", "left", ["edge"], chosen=True),+ self.machine("c", "Sea", "right", ["part"], parts=["end"]),+ self.machine("d", "Dee", "")], "Right Ctrl", "hold", True)+ self.assertEqual(picture._marks[("edge", "b", "left")], 1.0)+ self.assertEqual(picture._marks[("part", "c", "right", "end")], 1.0)+ self.assertEqual(picture._marks[("part", "c", "right", "start")], 0.0)+ self.assertEqual(picture._unplaced, "Not placed yet: Dee")+ self.assertFalse(picture.grab().isNull())++ def test_one_machine_with_no_side_is_drawn_on_the_right_as_before(self):+ picture = diagram.ArrangementDiagram()+ picture.set_machines([self.machine("b", "Bee", "", ["edge"], chosen=True)], "Right Ctrl", "hold", False)+ self.assertEqual(picture._unplaced, "")+ self.assertEqual(picture._marks[("edge", "b", "right")], 1.0)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_peers_view.py b/win_app/tests/test_peers_view.pyindex 0baedaf..249e630 100644--- a/win_app/tests/test_peers_view.py+++ b/win_app/tests/test_peers_view.py@@ -66,10 +66,14 @@ class DescribeTest(unittest.TestCase):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_any_1_4_pairing_is_asked_to_pair_again(self):+ # 1.4.x kept no record of whether its token was paired or typed, so a token of pairing's+ # shape is asked again too, and so is one an earlier beta linked.+ for peer in (entry(token="typed by hand"), entry(id="", linked=False, from_1_4=True), entry(from_1_4=True)):+ with self.subTest(peer=peer):+ found = state(peer, up=peer.get("from_1_4") is True)+ self.assertEqual((found.word, found.tone), ("Pair again", "amber"))+ self.assertEqual(found.detail, "Studio Mac was paired on Beamer 1.4. Pair the two again to link them on 1.5.0.")def test_sending_off_with_no_link_waits_for_the_other_end(self):found = state(entry(send=False))diff --git a/win_app/tests/test_portal.py b/win_app/tests/test_portal.pynew file mode 100644index 0000000..3dfd968--- /dev/null+++ b/win_app/tests/test_portal.py@@ -0,0 +1,96 @@+"""The portal client over a fake bus: a request waits for its own Response however the signals+interleave, a refusal and a failure are told apart, other signals are kept, a stop ends a wait+for the user, and a restore token is kept for this user only."""++import os+import stat+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.abspath(__file__))))++import portal+from portal_fakes import FakeBus, vardict+++class PlainTest(unittest.TestCase):+ def test_variants_in_a_vardict_become_their_values_and_structs_stay(self):+ body = ("/session/1", {"cursor_position": ("(dd)", (10.0, 20.0)), "zones": ("a(uuii)", [(1920, 1080, 0, 0)])})+ self.assertEqual(portal.plain(body), ("/session/1", {"cursor_position": (10.0, 20.0), "zones": [(1920, 1080, 0, 0)]}))++ def test_a_struct_whose_first_member_is_a_short_string_is_not_taken_for_a_variant(self):+ self.assertEqual(portal.plain(("/path", "u")), ("/path", "u"))+++class RequestTest(unittest.TestCase):+ def test_a_granted_request_returns_its_results(self):+ bus = FakeBus()+ bus.answers["CreateSession"] = (0, {"session_handle": "/session/1", "capabilities": 3})+ results = portal.Portal(bus).request("I", "CreateSession", "sa{sv}", lambda token: ("", {"handle_token": ("s", token)}))+ self.assertEqual(results, {"session_handle": "/session/1", "capabilities": 3})++ def test_a_refusal_and_another_ending_are_told_apart(self):+ bus = FakeBus()+ bus.answers["Start"] = (1, {})+ with self.assertRaises(portal.Refused):+ portal.Portal(bus).request("I", "Start", "osa{sv}", lambda token: ("/s", "", {"handle_token": ("s", token)}))+ bus.answers["Start"] = (2, {})+ with self.assertRaises(portal.PortalError):+ portal.Portal(bus).request("I", "Start", "osa{sv}", lambda token: ("/s", "", {"handle_token": ("s", token)}))++ def test_other_signals_and_another_requests_response_are_kept_for_later(self):+ bus = FakeBus()+ bus.answers["GetZones"] = None # answered by hand below+ client = portal.Portal(bus)+ bus.emit("/org/freedesktop/portal/desktop", "org.freedesktop.portal.InputCapture", "Activated", ("/s", vardict({"activation_id": 4})))+ result = []++ def answer():+ time.sleep(0.05)+ bus.emit("/org/freedesktop/portal/desktop/request/1_42/other", portal.REQUEST, "Response", (0, {}))+ bus.emit("/org/freedesktop/portal/desktop/request/1_42/beamer1", portal.REQUEST, "Response", (0, vardict({"zone_set": 9})))++ threading.Thread(target=answer).start()+ result = client.request("I", "GetZones", "oa{sv}", lambda token: ("/s", {"handle_token": ("s", token)}), timeout=2)+ self.assertEqual(result, {"zone_set": 9})+ kept = client.signals()+ self.assertEqual([(member, body) for _path, _i, member, body in kept],+ [("Activated", ("/s", {"activation_id": 4})), ("Response", (0, {}))])++ def test_a_stop_ends_a_wait_for_the_user(self):+ bus = FakeBus()+ bus.answers["Start"] = None # the user never answers+ stopping = threading.Event()+ threading.Timer(0.1, stopping.set).start()+ with self.assertRaises(portal.PortalError):+ portal.Portal(bus, stopping.is_set).request("I", "Start", "osa{sv}", lambda token: ("/s", "", {"handle_token": ("s", token)}))++ def test_a_missing_interface_is_version_zero(self):+ bus = FakeBus(versions={"org.freedesktop.portal.InputCapture": 2})+ client = portal.Portal(bus)+ self.assertEqual(client.version("org.freedesktop.portal.InputCapture"), 2)+ self.assertEqual(client.version("org.freedesktop.portal.RemoteDesktop"), 0)+++class TokenStoreTest(unittest.TestCase):+ def test_a_token_is_kept_for_this_user_only_and_an_empty_one_forgets_it(self):+ with tempfile.TemporaryDirectory() as directory:+ store = portal.TokenStore("remote-desktop", Path(directory) / "beamer")+ self.assertEqual(store.read(), "")+ store.write("abc")+ self.assertEqual(store.read(), "abc")+ if sys.platform != "win32": # POSIX modes; the store is only used on Linux+ self.assertEqual(stat.S_IMODE(store.path.stat().st_mode), 0o600)+ store.write("def")+ self.assertEqual(store.read(), "def")+ store.write("")+ self.assertFalse(store.path.exists())+ self.assertEqual(store.read(), "")+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_power_throttling.py b/win_app/tests/test_power_throttling.pynew file mode 100644index 0000000..ada461e--- /dev/null+++ b/win_app/tests/test_power_throttling.py@@ -0,0 +1,98 @@+"""The PC's Beamer is never slowed by Windows' power throttling (EcoQoS).++On 01-10-2026 at 11:30:58 and 11:33:00 the Mac's responder found the rig's link quiet while the Mac+was not napped. Beamer lives in the tray with no window in front, which is what Windows' heuristics+throttle, and the rig's Beamer.exe had never said either way (control and state masks both 0). A+throttled process sends its pings and acks late, as the napped Mac did, so Beamer opts out at start,+the counterpart of the Mac's App Nap fix."""++import ctypes+import sys+import unittest+from unittest import mock++PROCESS_POWER_THROTTLING = 4+EXECUTION_SPEED = 0x1+++class FakeKernel32:+ def __init__(self, events):+ self.events = events+ self.calls = []++ def GetCurrentProcess(self):+ return -1++ def SetPriorityClass(self, process, priority):+ self.events.append("priority")+ return 1++ def SetProcessInformation(self, process, kind, info, size):+ self.calls.append((process, kind, tuple(info._obj), size))+ self.events.append("unthrottled")+ return 1+++class Started(Exception):+ pass++[email protected](sys.platform == "win32", "the app module needs Windows")+class PowerThrottlingTests(unittest.TestCase):+ def test_execution_speed_throttling_is_turned_off(self):+ import kvm_bridge_win++ kernel32 = FakeKernel32([])+ kvm_bridge_win._stay_unthrottled(kernel32)+ (process, kind, (version, control, state), size), = kernel32.calls+ self.assertEqual(process, -1)+ self.assertEqual(kind, PROCESS_POWER_THROTTLING)+ self.assertEqual(version, 1)+ self.assertEqual(control & EXECUTION_SPEED, EXECUTION_SPEED)+ self.assertEqual(state, 0)+ self.assertEqual(size, 12)++ def test_it_is_done_at_start_before_any_window(self):+ import kvm_bridge_win++ events = []+ kernel32 = FakeKernel32(events)++ def window(*args):+ events.append("window")+ raise Started()++ with mock.patch.object(kvm_bridge_win, "_claim_instance", return_value=lambda: None), \+ mock.patch.object(kvm_bridge_win, "parse_args"), \+ mock.patch.object(kvm_bridge_win, "configure_logging", return_value=None), \+ mock.patch.object(kvm_bridge_win, "_windows_kernel32", return_value=kernel32), \+ mock.patch.object(kvm_bridge_win, "QApplication", side_effect=window):+ with self.assertRaises(Started):+ kvm_bridge_win.main()+ self.assertIn("unthrottled", events)+ self.assertEqual(events[-1], "window")++ def test_a_refusal_is_logged_and_start_goes_on(self):+ import kvm_bridge_win++ kernel32 = FakeKernel32([])+ kernel32.SetProcessInformation = lambda *args: 0+ with self.assertLogs(kvm_bridge_win.LOGGER, "WARNING"):+ kvm_bridge_win._stay_unthrottled(kernel32)++ def test_the_real_process_reads_back_unthrottled(self):+ import kvm_bridge_win++ kernel32 = kvm_bridge_win._windows_kernel32()+ kvm_bridge_win._stay_unthrottled(kernel32)+ state = (ctypes.c_uint32 * 3)(1, 0, 0)+ get = ctypes.WinDLL("kernel32", use_last_error=True).GetProcessInformation+ get.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_ulong]+ self.assertTrue(get(kernel32.GetCurrentProcess(), PROCESS_POWER_THROTTLING, ctypes.byref(state), 12),+ ctypes.WinError(ctypes.get_last_error()))+ self.assertEqual(state[1] & EXECUTION_SPEED, EXECUTION_SPEED)+ self.assertEqual(state[2] & EXECUTION_SPEED, 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_same_on_both.py b/win_app/tests/test_same_on_both.pyindex 2b16a51..f00105f 100644--- a/win_app/tests/test_same_on_both.py+++ b/win_app/tests/test_same_on_both.py@@ -1,4 +1,4 @@-"""Same on both machines in the real window: the Overview switch, a Mac's settings arriving, and a+"""Same on all machines in the real window: the Overview switch, a Mac's settings arriving, and achange here going out. Built offscreen from a synthetic config as test_style_for builds it, whichstarts no receiver, hooks or announcer; the two links' sends are recorded instead."""@@ -41,7 +41,7 @@ class SameOnBothTest(unittest.TestCase):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",+ "host": "192.168.1.20", "port": harness.free_port(), "auth_token": "synthetic", "paired_with": "MacBook Pro","mac_host": "192.168.1.10", "mac_return_edge": "left", "edge_glow": True,}))self.window = kvm_bridge_win.WindowsApplication(self.path)@@ -52,6 +52,7 @@ class SameOnBothTest(unittest.TestCase):self.window._refresh_window()def tearDown(self):+ self.window.server.stop()self.window.deleteLater()def test_off_by_default_with_each_page_its_own(self):diff --git a/win_app/tests/test_settings_migration.py b/win_app/tests/test_settings_migration.pyindex 2116769..898bd2c 100644--- a/win_app/tests/test_settings_migration.py+++ b/win_app/tests/test_settings_migration.py@@ -474,26 +474,30 @@ class SavingTests(Folder):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"}+ # The ways across are each peer's, written by set_ways, never by a save of the flat view.+ ways = {"crossing_methods", "crossing_edge_parts", "crossing_corner", "mac_return_edge", "arrangement_set_at"}+ skipped = {"host", "mac_resistance_px"} | waysself.assertEqual({k: v for k, v in asdict(again).items() if k not in skipped},{k: v for k, v in asdict(changed).items() if k not in skipped})+ self.assertEqual({k: getattr(again, k) for k in ways}, {k: getattr(self.config, k) for k in ways})- def test_a_save_writes_the_peer_and_the_zones_not_the_old_names(self):+ def test_a_save_writes_the_shortcut_and_no_zone_and_not_the_old_names(self):+ before = self.settings()["zones"]app_config.save_config(self.path, replace(self.config, crossing_methods=["edge"], crossing_corner="bottom_left"))settings = self.settings()for key in MOVED_OR_DROPPED:self.assertNotIn(key, settings)self.assertIs(settings["shortcut"], False)- self.assertEqual([(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")+ self.assertEqual(settings["zones"], before)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"]))+ app_config.set_ways(self.path, "", methods=["edge"], parts=["start", "end"], corner="top_right")+ app_config.set_ways(self.path, "", methods=["part"], parts=["start", "end"], corner="top_right")+ settings = self.settings()+ self.assertEqual([(zone["kind"], zone.get("off", False)) for zone in settings["zones"]],+ [("edge", True), ("part", False), ("corner", True)])again = app_config.load_config(self.path)- self.assertEqual((again.crossing_methods, again.crossing_edge_parts), (["part"], ["start", "end"]))+ self.assertEqual((again.crossing_methods, again.crossing_edge_parts), (["part", "shortcut"], ["start", "end"]))def test_the_machine_id_and_the_migrated_hash_never_change_in_a_save(self):before = self.settings()@@ -510,14 +514,16 @@ class SavingTests(Folder):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):+ def test_a_side_is_stamped_by_this_machine_only_when_set_here_never_by_a_save(self):settings = self.settings()settings["peers"][0]["side_by"] = OTHER_IDself.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"])+ app_config.save_config(self.path, replace(self.config, pointer_speed=2.0, mac_return_edge="top",+ arrangement_set_at=1790000005))+ self.assertEqual((self.settings()["peers"][0]["side"], self.settings()["peers"][0]["side_by"]), ("left", OTHER_ID))+ app_config.set_ways(self.path, "", side="top", methods=["edge"], parts=["middle"], corner="top_left")+ self.assertEqual((self.settings()["peers"][0]["side"], self.settings()["peers"][0]["side_by"]),+ ("top", settings["machine_id"]))def test_a_changed_port_moves_this_machines_and_the_one_peers_together(self):app_config.save_config(self.path, replace(self.config, port=25000))diff --git a/win_app/tests/test_style_for.py b/win_app/tests/test_style_for.pyindex 1114e73..0ab87f7 100644--- a/win_app/tests/test_style_for.py+++ b/win_app/tests/test_style_for.py@@ -12,6 +12,7 @@ try:from PySide6.QtWidgets import QApplicationimport kvm_bridge_win+ from core.tests import responder_harness as harnessimport themeexcept ImportError: # PySide6 is only in the Windows venvkvm_bridge_win = None@@ -25,7 +26,7 @@ class StyleForTest(unittest.TestCase):theme.init_fonts()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",+ "host": "192.168.1.20", "port": harness.free_port(), "auth_token": "synthetic", "paired_with": "MacBook Pro","mac_host": "192.168.1.10", "mac_return_edge": "left", "shortcut_arrival": True,}))self.window = kvm_bridge_win.WindowsApplication(folder / "settings.json")@@ -33,6 +34,7 @@ class StyleForTest(unittest.TestCase):self.window._refresh_window()def tearDown(self):+ self.window.server.stop()self.window.deleteLater()def shown(self):diff --git a/win_app/tests/test_wayland_sender.py b/win_app/tests/test_wayland_sender.pynew file mode 100644index 0000000..1f000fd--- /dev/null+++ b/win_app/tests/test_wayland_sender.py@@ -0,0 +1,49 @@+"""The sender on a desktop where input leaves only across an edge (Wayland's InputCapture): the+shortcut and the tray cannot send input away while the desktop has not captured it, an edge push+still can, and the capture reads the zone models it puts barriers on."""++import os+import sys+import unittest++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from core import protocol, return_edge+from links_rig import B, Rig+++class WaylandSenderTest(unittest.TestCase):+ def test_the_shortcut_cannot_send_input_away_while_the_desktop_holds_none(self):+ rig = Rig()+ rig.sender.input_held = lambda: False+ self.assertFalse(rig.sender.set_redirecting(True))+ self.assertFalse(rig.sender.redirecting)+ self.assertEqual(rig.sent(B, protocol.MSG_FOCUS), [])+ self.assertTrue(any("edge" in alert for alert in rig.alerts), rig.alerts)++ def test_an_edge_push_still_sends_it_while_the_desktop_holds_input(self):+ rig = Rig()+ held = [False]+ rig.sender.input_held = lambda: held[0]+ held[0] = True # the barrier captured the pointer+ rig.push(times=6)+ self.assertTrue(rig.sender.redirecting)+ self.assertEqual(len(rig.sent(B, protocol.MSG_FOCUS)), 1)++ def test_the_shortcut_works_as_before_where_input_can_always_be_held(self):+ rig = Rig()+ self.assertTrue(rig.sender.set_redirecting(True))+ self.assertTrue(rig.sender.redirecting)++ def test_the_zone_models_are_read_for_the_barriers_and_are_empty_while_crossing_is_paused(self):+ rig = Rig()+ models = rig.sender.zone_models()+ self.assertEqual(len(models), 1)+ self.assertIsInstance(models[0], return_edge.ReturnEdge)+ self.assertEqual(models[0].edge, "left")+ rig.sender.crossing_paused = True+ self.assertEqual(rig.sender.zone_models(), [])+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/xkb_x11.py b/win_app/xkb_x11.pynew file mode 100644index 0000000..61d6937--- /dev/null+++ b/win_app/xkb_x11.py@@ -0,0 +1,166 @@+"""The keyboard layout as XKB has it, through libxkbcommon-x11 over ctypes: which keysym a key+gives under given modifiers and layout group, for the X11 capture (naming a key) and injection+(finding the key that types a character). On Wayland the same Keymap is made from the text of the+keymap the compositor hands a libei keyboard (Keymap.from_text), and only libxkbcommon is used.++XKB, not the core keymap: the core keymap holds only two groups in a fixed place, so a third or+fourth layout cannot be read from it, and it knows nothing of key types, so Caps Lock, Num Lock and+the keypad would have to be guessed. libxkbcommon-x11 reads the server's own keymap and answers+exactly as the server would. It and libxcb are what Qt's xcb plugin runs on, so they are on every+machine Beamer runs on under X11.++Each Keymap holds its own xcb connection and is used from one thread (or under one lock); call+reload() after a MappingNotify."""++import ctypes+import ctypes.util+from typing import Optional++_libs = {}+++def _load(names=None):+ names = names or {"xcb": "xcb", "xkb": "xkbcommon", "xkb_x11": "xkbcommon-x11"}+ if any(key not in _libs for key in names):+ for key, name in names.items():+ if key in _libs:+ continue+ path = ctypes.util.find_library(name)+ if not path:+ raise RuntimeError(f"lib{name} is not installed; Beamer reads the keyboard layout through it")+ _libs[key] = ctypes.CDLL(path)+ u32, p = ctypes.c_uint32, ctypes.c_void_p+ if "xcb" in names:+ _bind_x11(_libs["xcb"], _libs["xkb_x11"])+ xkb = _libs["xkb"]+ xkb.xkb_keymap_new_from_string.restype = p+ xkb.xkb_keymap_new_from_string.argtypes = [p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int]+ xkb.xkb_context_new.restype = p+ xkb.xkb_context_new.argtypes = [ctypes.c_int]+ xkb.xkb_context_unref.argtypes = [p]+ xkb.xkb_keymap_unref.argtypes = [p]+ xkb.xkb_state_new.restype = p+ xkb.xkb_state_new.argtypes = [p]+ xkb.xkb_state_unref.argtypes = [p]+ xkb.xkb_state_update_mask.argtypes = [p, u32, u32, u32, u32, u32, u32]+ xkb.xkb_state_key_get_one_sym.restype = u32+ xkb.xkb_state_key_get_one_sym.argtypes = [p, u32]+ xkb.xkb_keymap_min_keycode.restype = u32+ xkb.xkb_keymap_min_keycode.argtypes = [p]+ xkb.xkb_keymap_max_keycode.restype = u32+ xkb.xkb_keymap_max_keycode.argtypes = [p]+ xkb.xkb_keymap_num_layouts_for_key.restype = u32+ xkb.xkb_keymap_num_layouts_for_key.argtypes = [p, u32]+ xkb.xkb_keymap_num_layouts.restype = u32+ xkb.xkb_keymap_num_layouts.argtypes = [p]+ xkb.xkb_keymap_mod_get_index.restype = u32+ xkb.xkb_keymap_mod_get_index.argtypes = [p, ctypes.c_char_p]+ xkb.xkb_keysym_to_utf32.restype = u32+ xkb.xkb_keysym_to_utf32.argtypes = [u32]+ return tuple(_libs[key] for key in names)+++def _bind_x11(xcb, x11) -> None:+ p = ctypes.c_void_p+ xcb.xcb_connect.restype = p+ xcb.xcb_connect.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_int)]+ xcb.xcb_connection_has_error.argtypes = [p]+ xcb.xcb_disconnect.argtypes = [p]+ x11.xkb_x11_setup_xkb_extension.argtypes = [p, ctypes.c_uint16, ctypes.c_uint16, ctypes.c_int, p, p, p, p]+ x11.xkb_x11_get_core_keyboard_device_id.restype = ctypes.c_int32+ x11.xkb_x11_get_core_keyboard_device_id.argtypes = [p]+ x11.xkb_x11_keymap_new_from_device.restype = p+ x11.xkb_x11_keymap_new_from_device.argtypes = [p, p, ctypes.c_int32, ctypes.c_int]+++# The core state's eight modifier bits, in XKB's names.+_REAL_MODS = ("Shift", "Lock", "Control", "Mod1", "Mod2", "Mod3", "Mod4", "Mod5")+++_FORMAT_TEXT_V1 = 1+++class Keymap:+ def __init__(self, display_name: Optional[str] = None) -> None:+ self._xcb, self._xkb, self._x11 = _load()+ self._conn = self._xcb.xcb_connect(display_name.encode() if display_name else None, None)+ self._context = self._keymap = self._state = None+ if not self._conn or self._xcb.xcb_connection_has_error(self._conn):+ self.close()+ raise RuntimeError("Could not open an xcb connection to read the keyboard layout")+ if self._x11.xkb_x11_setup_xkb_extension(self._conn, 1, 0, 0, None, None, None, None) != 1:+ self.close()+ raise RuntimeError("This X server has no XKB extension")+ self._context = self._xkb.xkb_context_new(0)+ self.reload()++ @classmethod+ def from_text(cls, text: str) -> "Keymap":+ """A keymap from its text, as a Wayland compositor hands one to a libei keyboard: no X+ connection, and reload() is not used."""+ self = cls.__new__(cls)+ (self._xkb,) = _load({"xkb": "xkbcommon"})+ self._xcb = self._x11 = self._conn = self._keymap = self._state = None+ self._context = self._xkb.xkb_context_new(0)+ keymap = self._xkb.xkb_keymap_new_from_string(self._context, text.encode(), _FORMAT_TEXT_V1, 0)+ if not keymap:+ self.close()+ raise RuntimeError("Could not read the keyboard layout the desktop gave")+ self._use(keymap)+ return self++ def reload(self) -> None:+ device = self._x11.xkb_x11_get_core_keyboard_device_id(self._conn)+ keymap = self._x11.xkb_x11_keymap_new_from_device(self._context, self._conn, device, 0)+ if not keymap:+ raise RuntimeError("Could not read the keyboard layout")+ self._use(keymap)++ def _use(self, keymap) -> None:+ state = self._xkb.xkb_state_new(keymap)+ if self._state:+ self._xkb.xkb_state_unref(self._state)+ if self._keymap:+ self._xkb.xkb_keymap_unref(self._keymap)+ self._keymap, self._state = keymap, state+ # The core state's bit n is the real modifier XKB names _REAL_MODS[n]; where XKB indexes it+ # is the keymap's business.+ self._mod_bits = []+ for bit, name in enumerate(_REAL_MODS):+ index = self._xkb.xkb_keymap_mod_get_index(keymap, name.encode())+ if index != 0xFFFFFFFF:+ self._mod_bits.append((1 << bit, 1 << index))+ self.min_keycode = self._xkb.xkb_keymap_min_keycode(keymap)+ self.max_keycode = self._xkb.xkb_keymap_max_keycode(keymap)++ def core_mods(self, xkb_mask: int) -> int:+ """XKB's modifier mask (as libei reports one) as the core state's bits."""+ return sum(core for core, index in self._mod_bits if xkb_mask & index)++ def keysym(self, keycode: int, mods: int, group: int) -> int:+ """What `keycode` gives with the core modifier bits `mods` held and layout `group` (0 based)+ active; XKB wraps a group the key does not have as the server does."""+ xkb_mods = 0+ for core, index in self._mod_bits:+ if mods & core:+ xkb_mods |= index+ self._xkb.xkb_state_update_mask(self._state, xkb_mods, 0, 0, 0, 0, group)+ return self._xkb.xkb_state_key_get_one_sym(self._state, keycode)++ def empty(self, keycode: int) -> bool:+ return self._xkb.xkb_keymap_num_layouts_for_key(self._keymap, keycode) == 0++ def text(self, keysym: int) -> Optional[str]:+ point = self._xkb.xkb_keysym_to_utf32(keysym) if keysym else 0+ return chr(point) if point else None++ def close(self) -> None:+ if self._state:+ self._xkb.xkb_state_unref(self._state)+ if self._keymap:+ self._xkb.xkb_keymap_unref(self._keymap)+ if self._context:+ self._xkb.xkb_context_unref(self._context)+ if self._conn and self._xcb:+ self._xcb.xcb_disconnect(self._conn)+ self._state = self._keymap = self._context = self._conn = None