One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.2.0
Toby Kalkman84e3c1cb7c36
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..2579dbd--- /dev/null+++ b/.gitattributes@@ -0,0 +1,9 @@+# The repo is LF throughout, and half of it is edited on Windows. Without this,+# every tool that rewrites a file there stores it with CRLF and the diff is the+# whole file for no change at all -- which happened to seventeen files on+# 17-09-2026 and had to be undone by hand. Git now normalises on commit, so it+# cannot happen again whichever machine the edit was made on.+* text=auto eol=lf++# Vendored as they came: a third party's licence file is not ours to reflow.+win_app/assets/** -textdiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..c9e23ff--- /dev/null+++ b/.gitignore@@ -0,0 +1,21 @@+config.json+*.log+__pycache__/+*.pyc+.venv/+venv/++.DS_Store+++# Build output. Never committed and never left behind either: a .app under dist/ is indexed by+# Spotlight and turns up in Launchpad beside the real /Applications install.+win_app/Output/+win_app/build/+win_app/dist/+mac_app/build/+mac_app/dist/+++# Rendered on demand from docs/*.html; reaches the other machine via Syncthing+docs/pdf/diff --git a/Beamer.icns b/Beamer.icnsnew file mode 100644index 0000000..dac26e7Binary files /dev/null and b/Beamer.icns differdiff --git a/Beamer.ico b/Beamer.iconew file mode 100644index 0000000..c1f49c0Binary files /dev/null and b/Beamer.ico differdiff --git a/Beamer.png b/Beamer.pngnew file mode 100644index 0000000..6907690Binary files /dev/null and b/Beamer.png differdiff --git a/Beamer.svg b/Beamer.svgnew file mode 100644index 0000000..d4a2481--- /dev/null+++ b/Beamer.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect x="1" y="1" width="62" height="62" rx="14" fill="#161714"/><rect x="1.5" y="1.5" width="61" height="61" rx="13.5" fill="none" stroke="#34352f"/><rect x="8" y="13" width="20" height="36" rx="2" fill="#3d3e37"/><rect x="36" y="13" width="20" height="36" rx="2" fill="#6e6f66"/><rect x="29.5" y="9" width="5" height="44" rx="1.2" fill="#5fd4f4"/><polygon points="42,17 42,40.8 36.4,35.2 32.2,45 28.7,43.6 32.9,33.8 25.2,33.8" fill="#0e0f0d" stroke="#0e0f0d" stroke-width="5" stroke-linejoin="round"/><polygon points="42,17 42,40.8 36.4,35.2 32.2,45 28.7,43.6 32.9,33.8 25.2,33.8" fill="#efeee6"/></svg>diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..091465a--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Toby Kalkman++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..35ab746--- /dev/null+++ b/README.md@@ -0,0 +1,189 @@+# Beamer++Beamer lets one keyboard and pointing device drive both machines over the local network, in either direction. Push the pointer off the edge of the screen and it crosses to the other machine, the way it would to another monitor; or double-tap the trigger key — Right Option on the Mac, Right Ctrl on the PC — and again to come back.++The Mac's keyboard on Windows is the direction Beamer started with and the one everything is configured from. The PC's own keyboard and mouse go the other way across the same border, with nothing to set up on the PC: it learns where the Mac is and which of its edges leads back there from the Mac's own link, and its only choice is a switch to turn the whole thing off.++Both sides are desktop apps with a dark control window and tray/menu-bar status. Traffic stays on the LAN, and the link is encrypted and authenticated end to end: both apps derive a key from the same shared token and every frame is sealed with it, so a peer that cannot decrypt a frame does not hold the token. The token itself is never transmitted.++## Download++Installers for each release are on the [releases page](https://github.com/kalkman-code/beamer/releases): `Beamer-<version>.dmg` for macOS and `Beamer-Setup-<version>.exe` for Windows. On Windows, `winget install KalkmanCode.Beamer` installs the same thing.++The Mac app is signed and notarised by Apple. The Windows installer is not code-signed — a certificate costs money and Beamer is free — so Windows shows "Windows protected your PC" the first time: choose More info, then Run anyway. Installing through winget does not show that warning. Everything the installer contains is built from this repository, and the sections below say how to build it yourself.++Beamer is MIT licensed; see `LICENSE`.++## Install on macOS++Open the DMG and drag Beamer to Applications. To build from source instead, double-click `mac_app/Install-Beamer-Mac.command` from the repository root: it builds a self-contained app, installs it at `/Applications/Beamer.app`, and leaves it closed so permission prompts do not appear unexpectedly.++Open `/Applications/Beamer.app`, then use its two separate Grant buttons for Accessibility and Input Monitoring. Beamer never requests both permissions at once. Relaunch once after both are enabled if the control window asks.++Then pair. The Pair section lists every PC on the network that is running Beamer. Press Pair a Mac in Beamer on the PC, choose that PC in the list, type the six-digit code the PC is showing, and the address, port and shared token are filled in and saved. The code lasts one minute and works once; a wrong code cancels it, and the PC hands out a fresh one on the next press.++Pairing is the easy path, not the only one. The Connection fields still take an address, port and shared token typed by hand, exactly as before, and an existing set-up carries on working untouched.++The app runs in the Dock and menu bar. Closing the control window leaves the sender running; use the menu-bar Quit command to stop it.++macOS 27 beta 4 can block a signed app's local-network access even when Terminal can reach the same host. Until Apple fixes that OS fault, open `/Applications/Beamer Tunnel.command`, leave its Terminal window running, then open `/Applications/Beamer.app`. Beamer will use the localhost tunnel only when its direct connection is blocked.++## Install on Windows++Run `Beamer-Setup-<version>.exe`, or `winget install KalkmanCode.Beamer`. The installer puts Beamer in `%LOCALAPPDATA%\Beamer` for the current user and adds a Start menu shortcut; Beamer adds its own firewall rules the first time it starts elevated. Quit Beamer from the tray before installing a newer version over it.++To build from source instead, from the repository root, run `win_app\Install-Beamer.ps1` **from an admin PowerShell**. The installer builds and installs `%LOCALAPPDATA%\Beamer\Beamer.exe`, creates a Start menu shortcut, and adds two inbound Private-network firewall rules: TCP 24820 for input and UDP 24821 for pairing (both below 49152, out of the range Windows and macOS hand out for themselves). Run from a non-admin PowerShell and the installer still builds and installs the app, but it warns and skips the firewall rules; the app adds them itself on its first elevated start. Starting at logon is the app's own switch on its Overview page, which writes and removes the elevated `Beamer` scheduled task; no installer touches it.++Open Beamer and press Pair a Mac. A six-digit code appears, large enough to read from the Mac, and this PC announces itself on the network so the Mac can list it by name. Type the code into Beamer on the Mac within a minute and the two agree a shared token between themselves, which each saves; the token itself is never sent, and the code is good for one attempt. Nothing needs typing on the PC. The Connection fields below it still accept a port and a token entered by hand for anyone already set up that way.++The app checks that rule itself. The Receiver panel says in one sentence whether Windows Firewall lets the Mac in, and offers one button for whichever of the three things usually stops it: the rule is missing because the installer ran non-elevated (the button adds it), Cancel was pressed on Windows' own "allow this app" prompt, which writes a block rule that beats any allow rule and survives a reinstall (the button removes the block and adds the rule), or Windows has classed the network as public, where the Private-only rule does not apply (the button marks the network private rather than opening the port on every public network). It reads the firewall when the receiver starts listening and after a fix, not on a timer.++The Windows receiver runs elevated (the exe carries a `requireAdministrator` manifest) so its `SendInput` calls can still reach a focused elevated window, such as an admin Command Prompt or PowerShell — Windows UIPI silently drops input from a non-elevated sender aimed at an elevated one, which is why those windows used to ignore remote input. Launching `Beamer.exe` outside of the logon task (double-clicking it, or the installer's own launch-at-the-end) shows one UAC prompt, same as any other admin app.++The Windows address shown in the app is the value the Mac connects to; pairing fills it in on both sides. The listen port and shared token must match both apps.++The **To the Mac** card is the other direction: this PC's keyboard and mouse on the Mac. It is on by default and needs nothing typed — the address and the edge come from the Mac. Push this PC's pointer through the same edge input comes home by and it carries on onto the Mac; double-tap Right Ctrl to send it across without the pointer, and again to bring it back. Turning the switch off puts the keyboard hooks away entirely.++Closing the Windows control window leaves the receiver in the system tray. Beamer enforces one running instance, so launching it again cannot create a second receiver or duplicate tray icon. If an older, non-elevated Beamer is still running when you reinstall, quit it from the tray first — the installer's own instance check can't stop an elevated process from a non-admin session.++The Windows secure desktop — UAC consent prompts themselves, and Ctrl+Alt+Del — cannot receive remote input by OS design, elevated or not; use the PC's own keyboard and mouse there.++## The lock screen++Beamer still cannot *type* on the lock screen, and no amount of elevation would let it: the lock screen is the Winlogon secure desktop, whose security descriptor admits only SYSTEM, and `SendInput` only reaches the desktop its calling thread is attached to. Instead of typing on it, Beamer takes the PC off it.++On a PC with the author's separate unlock credential provider installed (not part of this repository), switching input to a locked PC signals that provider, which submits a stored password as SYSTEM; the console returns to the desktop in about four seconds, and input sent meanwhile is dropped rather than queued. Beamer only signals the provider's trigger event and never holds a password. Without the provider, which is every other PC, the Mac reports `Windows is locked — unlock it at the PC`: unlock it with the PC's own keyboard.++## Connection states++The states below are written from the Mac, which is the side that connects. The PC's own link to the Mac reports the mirror of them in the **To the Mac** card, and its receiver's states name the Mac rather than Windows.++- `Connected to <address>:<port>`: the encrypted link is up — Windows decrypted the Mac's first frame, proving both sides hold the same token, and the protocol versions match. Shows as `Connected to Windows via secure macOS 27 fallback` when the SSH tunnel above is carrying the connection instead.+- `Windows is reachable, but Beamer is not listening on this port.`: the PC answered but nothing accepted the configured TCP port.+- `Windows could not be authenticated — check the shared token matches on both sides`: the two apps derived different keys, so neither can read the other's frames. The tokens differ.+- `Windows is unreachable from this Mac`: the failure occurred before Beamer or the firewall could receive a packet. Check Wi-Fi client isolation, the Windows network attachment, and whether the Mac can resolve the Windows address on the LAN.+- `Windows did not answer the handshake — it is probably running an older Beamer; update it`, or `Windows receiver speaks Beamer protocol vN, this Mac vM — update both apps`: the two apps disagree on wire version. The version travels in cleartext at the very start of the connection (and an older Beamer that predates the encrypted handshake is recognised by its silence), so a mismatch produces this message rather than a hang or garbage. Windows shows the mirror-image status, "Mac app is an older Beamer version — update both apps". Update whichever side is behind.+- `Windows stopped responding`: no ping or acknowledgement arrived for about two seconds, so Beamer gave up on the connection.++Both statuses are now truthful within a few seconds of a real link failure, not just of the next action you take. Windows moves to "Waiting for your Mac" within about three seconds of the link actually dying (it enforces a 2.5-second read timeout per session, and the Mac pings at least once a second while idle, so silence past that window means the peer is gone). The Mac notices a dead link within about two seconds the same way and reverts input to itself; trying to double-tap into Windows while the link is down beeps and posts a macOS notification instead of silently doing nothing.++The Mac always fails open. A dropped connection, missing acknowledgement, crashed capture worker or full event queue immediately returns input to macOS. A watchdog runs for as long as a socket exists — not only while input is redirected — so a half-open connection is caught and the Mac auto-reconnects even if you never actually switched into Windows.++## Keyboard mapping++Mac modifier keys map to Windows *semantically*, so the shortcuts your fingers already know keep working:++| Mac key | Sends on Windows |+| --- | --- |+| Cmd | Ctrl |+| Ctrl | Windows key |+| Option | Alt |++Cmd+C, Cmd+V, Cmd+Z and Cmd+T are copy, paste, undo and new tab on Windows, exactly as on the Mac. The Windows key moves to Ctrl, so Ctrl+E opens Explorer and Ctrl on its own opens the Start menu.++An existing install picks this up on first launch: a saved `config.json` still carrying the old positional map is treated as the old default and replaced. A `key_map` you have edited yourself is left alone, so the positional mapping is still available by setting `cmd` to `cmd` and `ctrl` to `ctrl` there.++Chorded characters (Ctrl/Alt/Win held with a letter) are injected as real virtual-key presses on Windows rather than layout-independent Unicode, so shortcuts like Ctrl+Z land on the right key for the active Windows keyboard layout.++Beamer cannot raise Ctrl+Alt+Del, and deliberately no longer tries. It is the Secure Attention Sequence, trapped by the kernel before any application sees it, so `SendInput` can never produce it; the one supported route, `SendSAS()`, requires the caller to be a Windows service, or to be manifested `uiAccess="true"` *and* Authenticode-signed *and* installed under `\Program Files\` or `\windows\system32\`. Beamer is none of those, so the call was always a silent no-op. Use the PC's own keyboard for that chord.++## Crossing++Crossing is the pointer route between the two machines. Push the pointer at the outer edge of the Mac desktop and it does not move — the push builds as pressure instead, the edge lights up, the trackpad ticks at each quarter, and once you have pushed far enough the boundary gives and input is on Windows. Pushing back through the far edge over there brings it home the same way — and pushing the PC's own pointer through that same far edge sends the PC's keyboard and mouse to the Mac, which is the same crossing walked from the other end.++The notch cannot light up: the display has no pixels there. So a push through the notch grows the notch itself instead. A black island springs out of it with a cyan rim, a four-segment meter and the percentage appear inside once it is deep enough, each trackpad tick nudges it, and it snaps back into the notch when you cross. With Reduce Motion on it stays one size and fades with the push.++The resistance is the point. An edge that switches machines the instant you touch it does so every time you overshoot a close button, which is why edge switching gets turned off in every tool that has it. The default is 120 points of push; set it to zero for switch-on-contact, or drag the slider and try the real edge before saving.++There are four ways in and any combination can be on at once:++| Method | Where it triggers |+| --- | --- |+| Shortcut | Double-tap the trigger key, or hold it, whichever you choose |+| Edge | The whole of one outer edge of the Mac desktop |+| Corner | An 8pt box in one named corner, needing a diagonal push |+| Notch | The top edge, only within the notch's own width |++Only the outer boundary of the whole Mac desktop counts, so an edge between two Mac displays still behaves as macOS intends. Crossing never fires while a mouse button is held, because a drag that reaches the edge is a drag. It suspends itself while a full-screen app has focus — a game whose edge teleports your pointer to another computer reads as broken — and there is a Pause crossing item in the menu bar for when you want it out of the way, which deliberately does not survive a restart.++The pointer arrives where it left. Leaving the Mac's right edge 42% of the way down means arriving at the Windows left edge 42% of the way down it, on whichever monitor owns that edge. Without that it feels like a teleport rather than a monitor.++Every setting lives on the Mac, in the control window: which ways in are on, which edge and corner, the trigger key and whether it double-taps or holds, the resistance, the haptics, the glow, and the modifier style. Windows is told the way home in the Mac's first frame and again on every switch, so it knows the border before either machine has crossed it. Its only local preferences are whether its own edge lights up and whether it sends its keyboard to the Mac at all.++Only one machine owns the keyboard at a time. While the Mac is driving, the PC's outward edge is disarmed and the Mac's own tap ignores everything Beamer posts; while the PC is driving, the Mac passes every event through to itself untouched. Neither can push input back across the border it just arrived over.++## Media keys++The F7–F12 media row and the volume keys forward to Windows: play/pause, next, previous, mute, volume up and volume down. These do not arrive as ordinary key events on macOS — they are `NSSystemDefined` events, captured separately (see `mac_app/media_keys.py`). Brightness and keyboard-backlight keys share that event type and are deliberately left to macOS, since Windows has no equivalent.++The `key_map` object in each app's config JSON can override individual key names if you want different behaviour (for example, swapping Cmd and Ctrl). Right Option always remains the double-tap switch trigger regardless of `key_map`, so it can never itself be forwarded as input — Windows' AltGr, which a physical PC keyboard reaches through its own right Alt key, isn't reachable from the Mac side.++## Clipboard++Text and images on the clipboard follow you across a switch: copying on the Mac and then double-tapping into Windows carries them over, and switching back the other way carries Windows' clipboard back to the Mac. A screenshot copied on the Mac pastes into Teams on Windows; a Snipping Tool grab pastes into Preview or Notes on the Mac. Where the source clipboard holds both an image and text (a file copied in Finder carries its name as text), both cross and the pasting app picks the one it wants, as it would from the source. Files themselves do not cross. Sync only happens at the moment of the switch, and the clipboard travels ahead of the switch itself, so it is capped to keep the switch prompt: 256KB for text and 8MB for an image as PNG (a full-screen grab of a 16" Retina display is about 3MB). Over the cap, that half is left alone rather than truncated and the other half still crosses. On the wire the image is PNG; the Windows app converts to and from the clipboard's own DIB format itself, using the Qt it already ships for the PNG codec, so there is no imaging library in the build.++## Gestures++Trackpad scrolling is smooth and supports horizontal motion on Windows, always.++The system gestures — the ones that drive Mission Control, App Exposé, Spaces, Show desktop and Launchpad on the Mac — do the equivalent thing on Windows while input is redirected, and do nothing on the Mac in the meantime:++| Mac gesture | On Windows |+| --- | --- |+| Three or four fingers up (Mission Control) | Task View |+| Three or four fingers down (App Exposé) | Show desktop |+| Three or four fingers left or right (Spaces) | Switch virtual desktop, the same way round |+| Thumb and three fingers spread (Show desktop) | Show desktop |+| Thumb and three fingers pinched (Launchpad) | Start |++Beamer classifies the gesture when it ends and sends one message; the Windows receiver replays it as a real swipe through a synthetic Precision Touchpad, so Windows' own Settings → Touchpad choices apply and Task View animates as it would under fingers. Where Windows refuses that device, the receiver presses the shortcut with the same default meaning instead (Win+Tab, Win+D, Win+Ctrl+Left/Right, Win). Direction is read from private macOS event fields measured on macOS 26; the table is keyed by macOS major version in `mac_app/gestures.py`, since macOS 27 is reported to flip the horizontal sign.++Two-finger pinch (Ctrl+scroll) and the two-finger swipe between pages (Alt+Left/Right) remain best-effort: the zoom event was never seen to reach the event tap, so they depend on the overlay panel under the pinned cursor receiving them, which no run has yet confirmed.++## Latency++Traffic stays on the LAN, but if both machines are on Wi-Fi, every event is relayed through the access point — transmitted over the air twice (Mac to AP, then AP to Windows) instead of once. Plugging either machine into Ethernet removes one of those hops (or both, if you wire both machines). Where Wi-Fi is unavoidable, a 5GHz/6GHz network and disabling Wi-Fi power saving on the Windows adapter both help. On the software side, Beamer sends every event immediately (TCP_NODELAY, no Nagle buffering). Acknowledgements are prompt but batched: input is acked as soon as it lands, coalesced over 15ms so a 100Hz stream of mouse moves cannot double the packet count, with an idle heartbeat every 400ms so a dead link is still noticed quickly. The control window shows the measured round trip while input is on Windows.++## Switching a direction off++Each machine's menu has one tick per direction. On the Mac's menu-bar item they are This Mac drives Windows and Windows drives this Mac; in the Windows tray menu, Mac drives this PC and This PC drives the Mac, the same two switches the Overview page shows. Turning one off stops that direction only; the other carries on. Whichever machine the other is driving, its own switch — the menu item, or the trigger key — sends that input home, so a way back never depends on the return edge alone.++## Development checks++From `mac_app`:++```sh+.venv/bin/python3 -m unittest discover -s tests -v+./build_dmg.sh+```++From `win_app`:++```powershell+python -m unittest discover -s tests -v+.\build_win_app.ps1+```++The macOS build is signed with the same Developer ID identity as a release where the login keychain can reach it, so the privacy grants carry between local builds and releases, and ad-hoc otherwise (a build driven over SSH), under the hardened runtime either way. It is not a notarised release build.++## Release builds++The version is set once, in `VERSION` at the repository root. Both apps read it for their menus, py2app writes it into the Mac bundle and Inno Setup into the Windows installer; the Mac build number is the commit count. To release: change `VERSION`, commit, then build each platform from that commit with one command. Both commands refuse uncommitted changes outside `docs/`, and neither uploads anything except the Mac's submissions to Apple's notary service. Both write to `docs/beamer-releases/<version>/` in the folder that contains the repository.++On the Mac, from `mac_app`, in a desktop login session (the keychain will not release a Developer ID identity over SSH):++```sh+./build_dmg.sh --release+```++It signs every nested binary with the Developer ID Application identity in the login keychain, under the hardened runtime with a secure timestamp, checks the bundle still runs under that runtime, notarises and staples the app, puts it in a DMG that is signed, notarised and stapled in turn, and checks both with `stapler validate` and `spctl`. Notarisation authenticates with the App Store Connect API key named in `~/.appstoreconnect/key_id`. A rejected submission prints Apple's log and stops the build.++On Windows, from `win_app`:++```powershell+.\build_win_app.ps1 -Release+```++It runs the Windows tests, builds `Beamer.exe`, and compiles `Beamer-Setup.iss` with Inno Setup 6 into `Beamer-Setup-<version>.exe`, then prints the commit it came from. The installer is not code-signed, so SmartScreen warns about it until it has a download history; it adds no firewall rules (the app's own firewall check offers the one-click repair) and leaves autostart unticked.++Both apps draw with the tokens in `tokens.py`; `win_app/tokens.py` is a byte-identical copy, because PyInstaller only bundles what sits under the app, and a test fails if the two drift. `Beamer.svg` is the editable master of the mark, and `Beamer.ico`, `Beamer.png` and `Beamer.icns` are rendered from it.diff --git a/VERSION b/VERSIONnew file mode 100644index 0000000..26aaba0--- /dev/null+++ b/VERSION@@ -0,0 +1 @@+1.2.0diff --git a/config.example.json b/config.example.jsonnew file mode 100644index 0000000..9ad9693--- /dev/null+++ b/config.example.json@@ -0,0 +1,16 @@+{+ "host": "192.168.1.20",+ "port": 24820,+ "auth_token": "CHANGE_ME",+ "trigger_key": "alt_r",+ "double_tap_ms": 300,+ "key_map": {+ "cmd": "ctrl",+ "cmd_r": "ctrl",+ "ctrl": "cmd",+ "ctrl_r": "cmd",+ "alt": "alt",+ "alt_r": "alt"+ },+ "reconnect_interval_s": 2.0+}diff --git a/mac_app/.gitignore b/mac_app/.gitignorenew file mode 100644index 0000000..8ab35e9--- /dev/null+++ b/mac_app/.gitignore@@ -0,0 +1,6 @@+build/+dist/+.venv/+venv/+__pycache__/+*.pycdiff --git a/mac_app/Beamer Tunnel.command b/mac_app/Beamer Tunnel.commandnew file mode 100755index 0000000..4e61fee--- /dev/null+++ b/mac_app/Beamer Tunnel.command@@ -0,0 +1,34 @@+#!/bin/zsh+# Forwards Beamer's port over SSH for a macOS 27 build that blocks the app's direct LAN access.+# The PC's address comes from Beamer's own settings; the account on the PC is asked for, because+# nothing on this Mac knows it. Requires an SSH server on the PC and a key or password for it.++set -u++CONFIG="$HOME/Library/Application Support/Beamer/config.json"+HOST=""+if [ -r "$CONFIG" ]; then+ HOST="$(sed -n 's/.*"host": *"\([^"]*\)".*/\1/p' "$CONFIG" | head -n 1)"+fi++echo "Beamer macOS 27 fallback."+if [ -n "$HOST" ]; then+ read -r "TARGET?Windows account and address for SSH [user@$HOST]: "+ case "$TARGET" in+ "") echo "An account name is needed."; read -r "?Press Return to close"; exit 1 ;;+ *@*) ;;+ *) TARGET="$TARGET@$HOST" ;;+ esac+else+ read -r "TARGET?Windows account and address for SSH (user@address): "+ case "$TARGET" in+ *@*) ;;+ *) echo "Give it as user@address."; read -r "?Press Return to close"; exit 1 ;;+ esac+fi++echo "Tunnel to $TARGET is running. Keep this window open."+/usr/bin/ssh -N -T -o ExitOnForwardFailure=yes -o ConnectTimeout=5 -o ServerAliveInterval=15 -o ServerAliveCountMax=2 -L 127.0.0.1:24822:127.0.0.1:24820 "$TARGET" || {+ echo "Beamer could not start the tunnel to Windows."+ read -r "?Press Return to close"+}diff --git a/mac_app/Beamer.command b/mac_app/Beamer.commandnew file mode 100755index 0000000..ebdfaaf--- /dev/null+++ b/mac_app/Beamer.command@@ -0,0 +1,6 @@+#!/bin/bash+# Double-click launcher for Beamer (see build_notes.md: "Known issue: py2app+# packaging blocks LAN access" for why this runs as a script instead of the+# packaged .app).+cd "$(dirname "$0")"+exec .venv/bin/python3 kvm_bridge_app.pydiff --git a/mac_app/Install-Beamer-Mac.command b/mac_app/Install-Beamer-Mac.commandnew file mode 100755index 0000000..9bc2c44--- /dev/null+++ b/mac_app/Install-Beamer-Mac.command@@ -0,0 +1,75 @@+#!/bin/bash++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+APP_SOURCE="$SCRIPT_DIR/dist/Beamer.app"+DEST_APP="/Applications/Beamer.app"+DEST_TUNNEL="/Applications/Beamer Tunnel.command"++trap 'status=$?; echo "Installation failed."; read -r -p "Press Return to close"; exit $status' ERR++"$SCRIPT_DIR/build_dmg.sh"+killall Beamer 2>/dev/null || true++# The app was called OpenKB until 19-08-2026. Two copies in /Applications is+# how Spotlight ends up offering both, so the old one goes. Its data directory+# is deliberately left alone -- it still holds the config and auth token.+killall OpenKB 2>/dev/null || true+rm -rf "/Applications/OpenKB.app" "/Applications/OpenKB Tunnel.command"++# The app was called Beamy until 10-09-2026. Same reasoning as the OpenKB+# cleanup above: two copies in /Applications is how Spotlight ends up+# offering both, so the old one goes.+killall Beamy 2>/dev/null || true+rm -rf "/Applications/Beamy.app" "/Applications/Beamy Tunnel.command"+# Beamy shared the OpenKB bundle id (never got its own); Beamer uses a new+# one, so uk.co.kalkman.openkb.desktop's grants now belong to an app that no+# longer exists.+tccutil reset Accessibility uk.co.kalkman.openkb.desktop >/dev/null 2>&1 || true+tccutil reset ListenEvent uk.co.kalkman.openkb.desktop >/dev/null 2>&1 || true++rm -rf "$DEST_APP"+ditto "$APP_SOURCE" "$DEST_APP"+ditto "$SCRIPT_DIR/Beamer Tunnel.command" "$DEST_TUNNEL"+chmod +x "$DEST_TUNNEL"+xattr -cr "$DEST_APP"++# An ad-hoc build is a different code identity on every build wearing the same bundle id. macOS+# keeps the old grant against the old identity, which is why such a reinstall can sit in the+# Privacy pane with a tick beside it and still receive no events -- the tick belongs to a build+# that no longer exists. Revoking turns that silent failure into a visible prompt.+# Only ad-hoc builds need it. Since 31-08-2026 build_dmg.sh signs with a real identity where one+# is reachable, and that identity is stable across rebuilds, so the grants carry over and+# revoking them would throw away the very thing the signing bought. The ad-hoc path still+# exists for builds driven over SSH, where the login keychain cannot be unlocked.+# Resetting resolves the id through LaunchServices, so it runs after the new bundle is in place,+# and never blocks the install: a first install on a clean machine has nothing to revoke.+BUNDLE_ID="uk.co.kalkman.beamer"+if codesign -dv "$DEST_APP" 2>&1 | grep -q "Signature=adhoc"; then+ for service in Accessibility ListenEvent LocalNetwork; do+ if tccutil reset "$service" "$BUNDLE_ID" >/dev/null 2>&1; then+ echo "Revoked $service"+ else+ echo "Nothing to revoke for $service"+ fi+ done+ REVOKED=1+else+ REVOKED=0+fi++# The app is installed, so the staged copy has done its job and must not survive. Spotlight+# indexes any .app left under build/ or dist/, which puts a second Beamer in Launchpad beside the+# real one with no way to tell them apart. build_dmg.sh stages inside the repo, so nothing else+# clears these.+rm -rf "$SCRIPT_DIR/build" "$SCRIPT_DIR/dist"++echo "Beamer is installed at $DEST_APP"+echo "The macOS 27 fallback is installed at $DEST_TUNNEL"+if [ "$REVOKED" -eq 1 ]; then+ echo "This build is ad-hoc signed, so its privacy permissions were revoked on install. Grant Accessibility and Input Monitoring again, one at a time, inside the app."+else+ echo "Signed with a stable identity, so Accessibility and Input Monitoring carry over. Grant them inside the app only if it asks."+fi+read -r -p "Press Return to close" || truediff --git a/mac_app/bridge.py b/mac_app/bridge.pynew file mode 100644index 0000000..b9d695a--- /dev/null+++ b/mac_app/bridge.py@@ -0,0 +1,1720 @@+import collections+import errno+import logging+import platform+import queue+import socket+import struct+import threading+import time+import types+from dataclasses import dataclass++import objc+import Quartz++import clipboard_mac+import crossing+from input_injector_mac import INJECTED_MARK+import gestures+import media_keys+import protocol+from key_codes import (+ KEY_NAME_TO_CODE,+ MODIFIER_KEY_CODES,+ PRINTABLE_KEY_FALLBACKS,+ SPECIAL_KEY_NAMES,+)++# AppKit is only needed to read gesture-event fields (see+# _default_gesture_event_converter below); guarded the same way+# clipboard_mac guards it, so this module stays importable -- and its+# gesture behaviour fakeable in tests -- on a machine without it.+try:+ import AppKit+except ImportError: # pragma: no cover - exercised only off macOS+ AppKit = None+++ACK_TIMEOUT_SECONDS = 2.0+CONNECT_TIMEOUT_SECONDS = 1.0+AUTH_TIMEOUT_SECONDS = 2.0+SOCKET_IO_TIMEOUT_SECONDS = 0.5+OUTBOUND_QUEUE_SIZE = 2048+SSH_FALLBACK_HOST = "127.0.0.1"+# Below 49152 for the same reason the listening ports are: macOS hands out+# 49152-65535 itself, and a forward whose local port is taken never comes up.+SSH_FALLBACK_PORT = 24822+PING_INTERVAL_SECONDS = 1.0+DESKTOP_BOUNDS_MAX_AGE_SECONDS = 1.0+ROUND_TRIP_SAMPLES = 8+ROUND_TRIP_MAX_AGE_SECONDS = 5.0+# A receiver that accepts the TCP connection but never sends a preamble is, in practice, one+# running the pre-v4 cleartext protocol: it sits waiting for a hello frame it will never get.+OLD_RECEIVER_STATUS = "Windows did not answer the handshake — it is probably running an older Beamer; update it"+AUTH_FAILED_STATUS = "Windows could not be authenticated — check the shared token matches on both sides"++# Messages that must bypass both the outbound gate (they still need to go+# out when redirecting has just turned off, e.g. the switch-back focus+# message) and sequence assignment (like ping, they carry no `seq` and are+# never recorded by the receiver's ProcessedSequence). The sentinel is a+# purely local marker -- never sent on the wire -- that the outbound worker+# expands into a real clipboard message (or drops) at send time.+CONTROL_MESSAGE_TYPES = frozenset({protocol.MSG_FOCUS, protocol.MSG_CLIPBOARD, protocol.MSG_ARRANGEMENT})+_LOCAL_CLIPBOARD_SENTINEL_TYPE = "_local_clipboard"+_GATE_EXEMPT_TYPES = CONTROL_MESSAGE_TYPES | {_LOCAL_CLIPBOARD_SENTINEL_TYPE}+++class _HandshakeError(protocol.ProtocolError):+ """Raised for a handshake that completed but was rejected; carries the+ exact user-facing status so the generic OSError/ProtocolError handler+ doesn't wrap it with a less specific message."""++ def __init__(self, status):+ super().__init__(status)+ self.status = status+++def connection_error_message(exc):+ error_number = getattr(exc, "errno", None)+ if error_number in {51, 64, 65}:+ if "Beamer Tunnel.command" in str(exc):+ return "macOS 27 blocked direct LAN access. Open /Applications/Beamer Tunnel.command."+ return "Windows is unreachable from this Mac. Check that both devices can communicate on the local network."+ if error_number == 61:+ return "Windows is reachable, but Beamer is not listening on this port."+ if isinstance(exc, (socket.timeout, TimeoutError)):+ return "Windows did not answer before the connection timed out."+ return f"Connection failed: {exc}"+++class FrameDecoder:+ """Reassembles and opens frames from the raw chunks the reader thread+ receives. One per connection, like the session it opens frames with."""++ def __init__(self, session):+ self.session = session+ self.buffer = bytearray()++ def feed(self, chunk):+ self.buffer.extend(chunk)+ messages = []+ while len(self.buffer) >= protocol.HEADER_SIZE:+ length = struct.unpack_from(">I", self.buffer)[0]+ if length < 1 or length > protocol.MAX_FRAME_BYTES:+ raise protocol.ProtocolError(f"invalid message length: {length}")+ frame_length = protocol.HEADER_SIZE + length+ if len(self.buffer) < frame_length:+ break+ body = bytes(self.buffer[protocol.HEADER_SIZE:frame_length])+ del self.buffer[:frame_length]+ messages.append(self.session.open(body))+ return messages+++# NX device-specific modifier bits (IOLLEvent.h), keyed by keycode. Unlike the+# generic kCGEventFlagMask* bits, these distinguish left/right and are set+# directly from the current flags — deriving is_down from them makes+# modifier tracking stateless (no dependency on a remembered down/up toggle+# that a missed event could desync).+NX_DEVICE_MODIFIER_BITS = {+ 0x36: 0x0010,+ 0x37: 0x0008,+ 0x38: 0x0002,+ 0x3A: 0x0020,+ 0x3B: 0x0001,+ 0x3C: 0x0004,+ 0x3D: 0x0040,+ 0x3E: 0x2000,+}+# Command, Option and Control, left and right. Shift and caps lock are+# excluded on purpose -- see _unicode_character.+CHORD_MODIFIER_KEY_CODES = frozenset({0x36, 0x37, 0x3A, 0x3B, 0x3D, 0x3E})++_ALL_NX_DEVICE_MODIFIER_BITS = 0+for _bit in NX_DEVICE_MODIFIER_BITS.values():+ _ALL_NX_DEVICE_MODIFIER_BITS |= _bit+++@dataclass+class KeyResult:+ is_trigger: bool+ is_down: bool+ is_repeat: bool+ messages: list+++class QuartzEventTranslator:+ def __init__(self, quartz=Quartz):+ self.quartz = quartz+ self.modifier_down = set()+ self.printable_down = {}+ # Sub-pixel remainder carried across mousemove events: slow, precise+ # trackpad motion reports fractional per-event deltas that truncate+ # to zero if read as integers and dropped outright. Accumulating as+ # floats and emitting only the whole-number part (toward zero) keeps+ # that motion instead of losing it.+ self._move_accum_x = 0.0+ self._move_accum_y = 0.0+ # Shared with KVMController: which raw event types are mouse+ # move/drag (as opposed to buttons or scroll) -- both mouse_messages+ # below and the cursor-pin warp in _event_tap_callback need exactly+ # this set.+ self.movement_event_types = {+ quartz.kCGEventMouseMoved,+ quartz.kCGEventLeftMouseDragged,+ quartz.kCGEventRightMouseDragged,+ quartz.kCGEventOtherMouseDragged,+ }+ self.modifier_flags = {+ 0x36: quartz.kCGEventFlagMaskCommand,+ 0x37: quartz.kCGEventFlagMaskCommand,+ 0x38: quartz.kCGEventFlagMaskShift,+ 0x39: quartz.kCGEventFlagMaskAlphaShift,+ 0x3A: quartz.kCGEventFlagMaskAlternate,+ 0x3B: quartz.kCGEventFlagMaskControl,+ 0x3C: quartz.kCGEventFlagMaskShift,+ 0x3D: quartz.kCGEventFlagMaskAlternate,+ 0x3E: quartz.kCGEventFlagMaskControl,+ }++ def key_result(self, event_type, event, trigger_code, key_map):+ quartz = self.quartz+ keycode = int(quartz.CGEventGetIntegerValueField(event, quartz.kCGKeyboardEventKeycode))+ is_trigger = keycode == trigger_code+ if event_type == quartz.kCGEventFlagsChanged:+ if keycode not in MODIFIER_KEY_CODES:+ return KeyResult(is_trigger, False, False, [])+ if keycode == 0x39:+ messages = [] if is_trigger else self._caps_lock_messages(key_map)+ return KeyResult(is_trigger, True, False, messages)+ is_down = self._modifier_transition(keycode, event)+ messages = [] if is_trigger else self._special_key_messages(keycode, is_down, key_map)+ return KeyResult(is_trigger, is_down, False, messages)+ if event_type not in (quartz.kCGEventKeyDown, quartz.kCGEventKeyUp):+ return KeyResult(is_trigger, False, False, [])+ is_down = event_type == quartz.kCGEventKeyDown+ is_repeat = bool(+ quartz.CGEventGetIntegerValueField(event, quartz.kCGKeyboardEventAutorepeat)+ )+ if is_trigger:+ return KeyResult(True, is_down, is_repeat, [])+ special_messages = self._special_key_messages(keycode, is_down, key_map)+ if special_messages:+ return KeyResult(False, is_down, is_repeat, special_messages)+ if is_down:+ character = self._unicode_character(event, keycode)+ if character is not None and not is_repeat:+ self.printable_down[keycode] = character+ else:+ character = self.printable_down.pop(keycode, None)+ if character is None:+ character = self._unicode_character(event, keycode)+ if character is None:+ return KeyResult(False, is_down, is_repeat, [])+ message_type = protocol.MSG_KEYDOWN if is_down else protocol.MSG_KEYUP+ return KeyResult(False, is_down, is_repeat, [+ {"type": message_type, "data": {"key": character}}+ ])++ def mouse_messages(self, event_type, event):+ quartz = self.quartz+ if event_type in self.movement_event_types:+ dx = quartz.CGEventGetDoubleValueField(event, quartz.kCGMouseEventDeltaX)+ dy = quartz.CGEventGetDoubleValueField(event, quartz.kCGMouseEventDeltaY)+ self._move_accum_x += dx+ self._move_accum_y += dy+ int_x = int(self._move_accum_x) # truncates toward zero+ int_y = int(self._move_accum_y)+ self._move_accum_x -= int_x+ self._move_accum_y -= int_y+ if int_x == 0 and int_y == 0:+ return []+ return [{"type": protocol.MSG_MOUSEMOVE, "data": {"dx": int_x, "dy": int_y}}]+ button_events = {+ quartz.kCGEventLeftMouseDown: (protocol.MSG_MOUSEDOWN, "left"),+ quartz.kCGEventLeftMouseUp: (protocol.MSG_MOUSEUP, "left"),+ quartz.kCGEventRightMouseDown: (protocol.MSG_MOUSEDOWN, "right"),+ quartz.kCGEventRightMouseUp: (protocol.MSG_MOUSEUP, "right"),+ }+ if event_type in button_events:+ message_type, button = button_events[event_type]+ return [{"type": message_type, "data": {"button": button}}]+ if event_type in (quartz.kCGEventOtherMouseDown, quartz.kCGEventOtherMouseUp):+ button_number = int(+ quartz.CGEventGetIntegerValueField(event, quartz.kCGMouseEventButtonNumber)+ )+ if button_number != 2:+ return []+ message_type = (+ protocol.MSG_MOUSEDOWN+ if event_type == quartz.kCGEventOtherMouseDown+ else protocol.MSG_MOUSEUP+ )+ return [{"type": message_type, "data": {"button": "middle"}}]+ if event_type == quartz.kCGEventScrollWheel:+ is_continuous = bool(+ quartz.CGEventGetIntegerValueField(event, quartz.kCGScrollWheelEventIsContinuous)+ )+ if is_continuous:+ # Trackpad (and momentum from a trackpad swipe): reported in+ # points, as floats, so smooth motion stays smooth end to+ # end instead of being quantized into wheel "clicks" early.+ dy = quartz.CGEventGetDoubleValueField(+ event, quartz.kCGScrollWheelEventPointDeltaAxis1+ )+ dx = quartz.CGEventGetDoubleValueField(+ event, quartz.kCGScrollWheelEventPointDeltaAxis2+ )+ if dx == 0 and dy == 0:+ return []+ return [{"type": protocol.MSG_SCROLL, "data": {"dy": dy, "dx": dx, "mode": "pixel"}}]+ # A real (discrete) wheel: whole line/click deltas.+ dy = int(+ quartz.CGEventGetIntegerValueField(event, quartz.kCGScrollWheelEventDeltaAxis1)+ )+ dx = int(+ quartz.CGEventGetIntegerValueField(event, quartz.kCGScrollWheelEventDeltaAxis2)+ )+ if dx == 0 and dy == 0:+ return []+ return [{"type": protocol.MSG_SCROLL, "data": {"dy": dy, "dx": dx, "mode": "line"}}]+ return []++ def reset_mouse_accumulators(self):+ """Drop any sub-pixel remainder carried across mousemove events.+ Called when redirecting turns off so a stale fractional carry from+ one redirect session doesn't nudge the pointer at the start of the+ next one."""+ self._move_accum_x = 0.0+ self._move_accum_y = 0.0++ def _modifier_transition(self, keycode, event):+ """Derive is_down from the event's own flags rather than toggling a+ remembered state. A missed key-up (tap timeout/restart) can no longer+ desync detection, since every event is judged independently.++ `modifier_down` is still maintained (add/discard) for bookkeeping and+ so update_config can clear stale state, but nothing here depends on+ its prior contents to decide is_down.+ """+ flags = self.quartz.CGEventGetFlags(event)+ device_bit = NX_DEVICE_MODIFIER_BITS.get(keycode, 0)+ if device_bit and (flags & _ALL_NX_DEVICE_MODIFIER_BITS):+ is_down = bool(flags & device_bit)+ else:+ # No device-specific bits present in these flags at all (seen from+ # non-standard event sources, e.g. tests) — fall back to the+ # generic mask for this modifier's family.+ generic_mask = self.modifier_flags.get(keycode, 0)+ is_down = bool(generic_mask and flags & generic_mask)+ if is_down:+ self.modifier_down.add(keycode)+ else:+ self.modifier_down.discard(keycode)+ return is_down++ def _special_key_messages(self, keycode, is_down, key_map):+ name = SPECIAL_KEY_NAMES.get(keycode)+ if name is None:+ return []+ wire_name = key_map.get(name, name)+ message_type = protocol.MSG_KEYDOWN if is_down else protocol.MSG_KEYUP+ return [{"type": message_type, "data": {"key": wire_name}}]++ def _caps_lock_messages(self, key_map):+ wire_name = key_map.get("caps_lock", "caps_lock")+ return [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": wire_name}},+ {"type": protocol.MSG_KEYUP, "data": {"key": wire_name}},+ ]++ def _unicode_character(self, event, keycode):+ # While a chord modifier is held, what macOS composes is not the key+ # the chord is made of: Option+V is "\u221a", not "v", so forwarding the+ # composed character sends Windows a square-root sign and the Alt+V+ # chord never exists on the other side. Ctrl behaves the same way with+ # control characters, and only survives today because those are not+ # printable and already fall through. So while one of those is down,+ # the key's own unshifted character is what Windows needs. Shift and+ # caps lock are deliberately not in that set -- they are meant to+ # change the character, and the receiver reconciles them.+ if self.modifier_down & CHORD_MODIFIER_KEY_CODES:+ base = PRINTABLE_KEY_FALLBACKS.get(keycode)+ if base is not None:+ return base+ length, characters = self.quartz.CGEventKeyboardGetUnicodeString(+ event, 16, None, None+ )+ if length and isinstance(characters, str) and len(characters) == 1 and characters.isprintable():+ return characters+ return PRINTABLE_KEY_FALLBACKS.get(keycode)+++class _GestureEventView:+ """Lazy, defensive adapter from a real AppKit NSEvent to the plain+ `.magnification`/`.deltaX`/`.deltaY`/`.phase` surface GestureTranslator+ expects. Each accessor is only invoked when actually read -- gesture.py+ reads just the one or two fields relevant to the event's own type, so+ this never calls an accessor (e.g. `.magnification()`) that a different+ gesture subtype (e.g. a swipe) may not support. Any exception raised by+ the underlying NSEvent method propagates to the caller, which is exactly+ what GestureTranslator.translate already treats as "no gesture"."""++ def __init__(self, ns_event):+ self._ns_event = ns_event++ @property+ def magnification(self):+ return float(self._ns_event.magnification())++ @property+ def deltaX(self):+ return float(self._ns_event.deltaX())++ @property+ def deltaY(self):+ return float(self._ns_event.deltaY())++ @property+ def phase(self):+ return int(self._ns_event.phase())+++def _macos_major():+ """The running macOS major version, which keys the DockControl sign+ table in gestures.py. Falls back to the newest measured version when+ the string cannot be read, which is what the table does anyway."""+ try:+ return int(platform.mac_ver()[0].split(".")[0])+ except (ValueError, IndexError):+ return 26+++def _default_gesture_event_converter(cg_event):+ """Convert a raw CGEvent carrying a gesture (magnify/swipe/etc.) into the+ `_GestureEventView` surface GestureTranslator consumes. Returns None if+ AppKit is unavailable or the conversion itself fails -- both treated by+ the caller as "gesture data unreadable; let this one event pass through+ locally" rather than an error. This is unsupported API surface (see+ gestures.py): NSEvent.eventWithCGEvent_ is not documented to accept a+ gesture-type CGEvent at all, only observed to work in practice."""+ if AppKit is None:+ return None+ ns_event = AppKit.NSEvent.eventWithCGEvent_(cg_event)+ if ns_event is None:+ return None+ return _GestureEventView(ns_event)+++def _default_system_event_converter(cg_event):+ """Read (subtype, data1) off a system-defined CGEvent. Returns None if+ AppKit is unavailable or the event does not carry those fields, which+ the caller treats as "not a media key; pass it through locally"."""+ if AppKit is None:+ return None+ ns_event = AppKit.NSEvent.eventWithCGEvent_(cg_event)+ if ns_event is None:+ return None+ return int(ns_event.subtype()), int(ns_event.data1())+++class KVMController:+ def __init__(+ self,+ cfg,+ logger=None,+ quartz=Quartz,+ clock=time.monotonic,+ socket_factory=socket.create_connection,+ clipboard=clipboard_mac,+ gesture_event_converter=_default_gesture_event_converter,+ system_event_converter=_default_system_event_converter,+ dock_event_reader=None,+ macos_major=None,+ desktop_bounds=None,+ ):+ self.cfg = cfg+ self.logger = logger or logging.getLogger("Beamer")+ self.quartz = quartz+ self.clock = clock+ self.socket_factory = socket_factory+ self.clipboard = clipboard+ self.gesture_event_converter = gesture_event_converter+ self.system_event_converter = system_event_converter+ self.dock_event_reader = dock_event_reader or self._default_dock_event_reader+ self.gesture_translator = gestures.GestureTranslator(logger=self.logger)+ self.dock_classifier = gestures.DockSwipeClassifier(+ macos_major=_macos_major() if macos_major is None else macos_major,+ logger=self.logger,+ )+ self._gesture_capture_logged = False+ self._overlay_gesture_capture_logged = False+ # Belt-and-braces cursor pinning (see _warp_cursor_to_pin): on some+ # macOS versions CGAssociateMouseAndMouseCursorPosition(False) is+ # silently ineffective, so the Mac cursor is additionally warped+ # back to this point on every captured mouse move/drag while+ # redirecting. None whenever not redirecting.+ self.cursor_pin_point = None+ self._cursor_assoc_status_logged = False+ self._cursor_warp_error_logged = False+ self.redirecting = False+ # True while the PC is driving this Mac over the other link. The tap+ # passes everything through while it is, except this Mac's own trigger+ # key, so the two directions can never both own the keyboard. Set by+ # the app that owns both halves, which also hands in `send_peer_home`:+ # the receiver's way of sending the PC's input back to it.+ self.receiving = False+ self.send_peer_home = None+ self.stop_event = threading.Event()+ self.outbound = queue.Queue(maxsize=OUTBOUND_QUEUE_SIZE)+ self.socket_lock = threading.RLock()+ self.sequence_lock = threading.Lock()+ self.sock = None+ # Replaced by every _connect_once, so each connection gets a fresh nonce prefix and+ # counters that start from zero. Sealing happens on the outbound, watchdog and reader+ # threads only -- the event tap enqueues and never touches it.+ self.session = protocol.SecureSession(cfg.auth_token)+ self.last_sent_seq = 0+ self.last_ack_seq = -1+ self.last_ack_at = 0.0+ self.connected_at = 0.0+ self.last_send_at = 0.0+ self.redirect_started_at = 0.0+ self.on_user_alert = None+ # Set by the app: called when Windows says the two machines have moved+ # in relation to each other.+ self.on_arrangement = None+ self.threads = []+ self.started = False+ self.capture_lock = threading.Lock()+ self.capture_thread = None+ self.input_error = None+ self.connection_status = "Waiting to connect"+ # Set while Windows reports it is clearing its lock screen. Beamer+ # cannot type on the secure desktop, so Windows unlocks first and+ # drops input meanwhile; without this the switch just looks dead for+ # the few seconds that takes.+ self.windows_locked = False+ self._status_before_unlock = None+ self.tap_ready = threading.Event()+ self.event_tap = None+ self.tap_source = None+ self.tap_run_loop = None+ self.tap_callback_ref = self._event_tap_callback+ self.translator = QuartzEventTranslator(quartz)+ self.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]+ self.last_trigger_down = 0.0+ self.trigger_suppressed = False+ # Crossing: the engine is pure and runs on the event-tap thread; the+ # desktop bounds come from CoreGraphics (already in the top-left+ # global space CGEventGetLocation uses, so nothing is flipped) and are+ # cached because they are read on every local mouse move. The notch+ # range needs NSScreen, so the app measures it on the main thread and+ # assigns it here. on_crossing is fed (kind, step) off the tap and+ # ack threads for haptics and the glow; the app marshals it.+ self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)+ self.desktop_bounds = desktop_bounds or self._default_desktop_bounds+ self.notch_range = None+ self.on_crossing = None+ self._crossing_failed = False+ self._bounds_cache = None+ self._bounds_at = 0.0+ # Both hold the pointer methods off while the shortcut keeps working. Paused is the+ # person's own choice from the menu and deliberately not a setting, so a pause nobody+ # remembers cannot survive a restart; full_screen_app is the name of the frontmost app+ # while it is full screen, measured by the app on the main thread like notch_range.+ self.crossing_paused = False+ self.full_screen_app = None+ # Round trip: (seq, sent at) for every input event still unacknowledged, oldest first,+ # and the last few measured trips. Both under sequence_lock.+ self._unacked_sent_at = collections.deque()+ self._round_trips = collections.deque(maxlen=ROUND_TRIP_SAMPLES)+ self._round_trip_at = 0.0++ @property+ def connected(self):+ with self.socket_lock:+ return self.sock is not None++ @property+ def input_ready(self):+ return self.event_tap is not None and self.input_error is None++ @property+ def round_trip_ms(self):+ """The smoothed input round trip, or None whenever a figure would not be honest: input+ is not on Windows, the link is down, or nothing fresh has been acknowledged for a few+ seconds. The upper median of the last few trips, so an even count rounds towards the+ slower one. The receiver acknowledges on a timer rather than per event, so each trip+ includes however long the last event waited for that timer -- pessimistic by design."""+ if not self.redirecting or not self.connected:+ return None+ with self.sequence_lock:+ trips = sorted(self._round_trips)+ measured_at = self._round_trip_at+ if not trips or self.clock() - measured_at > ROUND_TRIP_MAX_AGE_SECONDS:+ return None+ return int(round(trips[len(trips) // 2] * 1000))++ def start(self):+ if self.started:+ return+ self.started = True+ workers = (+ ("connection", self._connection_worker),+ ("outbound", self._outbound_worker),+ ("ack-receiver", self._ack_worker),+ ("ack-watchdog", self._watchdog_worker),+ )+ for name, target in workers:+ thread = threading.Thread(+ target=self._thread_entry,+ args=(name, target),+ name=f"Beamer-{name}",+ daemon=True,+ )+ self.threads.append(thread)+ thread.start()++ def start_input_capture(self):+ """Spawn the event-tap thread and return immediately. This must never+ block, since it is called from the AppKit main thread. A separate+ watcher thread waits for tap_ready and records failure so a slow or+ failed tap creation can't freeze the UI."""+ with self.capture_lock:+ if self.stop_event.is_set():+ return False+ if self.capture_thread is not None and self.capture_thread.is_alive():+ return self.input_ready+ self.tap_ready.clear()+ self.input_error = None+ thread = threading.Thread(+ target=self._input_thread_entry,+ name="Beamer-event-tap",+ daemon=True,+ )+ self.capture_thread = thread+ self.threads.append(thread)+ thread.start()+ watcher = threading.Thread(+ target=self._capture_ready_watcher,+ name="Beamer-event-tap-watcher",+ daemon=True,+ )+ self.threads.append(watcher)+ watcher.start()+ return True++ def _capture_ready_watcher(self):+ if not self.tap_ready.wait(timeout=2.0):+ self.input_error = "Input capture did not start within two seconds."+ self._force_local(self.input_error)++ def stop(self):+ self._return_local()+ self.stop_event.set()+ self._drop_connection()+ run_loop = self.tap_run_loop+ if run_loop is not None:+ try:+ self.quartz.CFRunLoopStop(run_loop)+ except Exception:+ self.logger.exception("failed to stop the event-tap run loop")+ for thread in self.threads:+ if thread is not threading.current_thread():+ thread.join(timeout=1.5)++ def update_config(self, cfg):+ self._return_local()+ self.cfg = cfg+ self.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]+ self.last_trigger_down = 0.0+ self.trigger_suppressed = False+ self.translator.modifier_down.clear()+ self.translator.printable_down.clear()+ self.translator.reset_mouse_accumulators()+ self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)+ self._crossing_failed = False+ self._drop_connection()+ self._drain_outbound()+ self.connection_status = "Settings saved; reconnecting"+ self.logger.info("settings updated; redirect mode returned to local")++ def apply_settings(self, cfg):+ """Everything that does not change which PC this is or how it is reached, applied without+ touching the link: the trigger, key map, crossing and how it looks and feels. The settings+ window calls this as each control changes; update_config is for a new address or token,+ which has to reconnect."""+ was = self.cfg.crossing.get("edge") if self.cfg is not None else None+ self.cfg = cfg+ edge = cfg.crossing.get("edge")+ if edge != was and edge in crossing.EDGES:+ # The arrangement is one value both machines hold. Changing it+ # here is a change for Windows too, so it travels the moment it+ # changes rather than waiting for the next reconnect.+ self.send_arrangement(edge, cfg.crossing.get("arrangement_set_at", 0))+ self.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]+ self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)+ self._crossing_failed = False++ def set_redirecting(self, value, edge=None, offset=None):+ """`edge` and `offset` are the Windows edge and fraction along it a+ crossing arrives at; absent for the shortcut, when Windows leaves its+ pointer where it is. The way home is sent on every switch."""+ value = bool(value)+ if value == self.redirecting:+ return False+ if value:+ if not self.connected:+ self.logger.warning("cannot redirect: the Windows receiver is not connected")+ self._alert("Beamer", f"Cannot switch — {self.connection_status}")+ return False+ if self.receiving:+ # The PC is driving this Mac over the other link, so switching+ # to Windows means sending the PC's input home: the one way+ # back that does not depend on the PC or on the return edge.+ send_home = self.send_peer_home+ if send_home is not None and send_home():+ return True+ self.logger.warning("cannot redirect: Windows is driving this Mac and cannot be reached")+ return False+ if not self.cfg.send_to_windows:+ self.logger.info("cannot redirect: sending this Mac's input to Windows is switched off")+ return False+ self.redirect_started_at = self.clock()+ self.redirecting = True+ self.cursor_pin_point = self._capture_cursor_pin_point()+ self._set_cursor_follows_mouse(False)+ if not self.redirecting:+ # A link failure on another thread went local in the gap+ # above; its reassociation must not be the one overwritten.+ self._set_cursor_follows_mouse(True)+ self.cursor_pin_point = None+ return False+ # The sentinel is expanded into a real clipboard message (or+ # dropped) by the outbound worker at send time, not here -- this+ # runs on the event-tap thread and must never block on reading+ # the pasteboard.+ self._enqueue_control({"type": _LOCAL_CLIPBOARD_SENTINEL_TYPE, "data": {}})+ self._enqueue_control(+ protocol.focus_msg(+ "windows",+ edge=edge,+ offset=offset,+ return_edge=edge or self.crossing.home_edge(),+ resistance_px=int(self.crossing.resistance_px),+ )+ )+ self.logger.info("redirecting input to Windows")+ return True+ self._return_local()+ self.logger.info("input returned to this Mac")+ return True++ def _return_local(self):+ """Every way input comes back to this Mac ends here: the switch home,+ a dropped link, a crashed worker, a disabled tap, a settings change.+ The cursor association is the part that must not be skipped -- a+ path that only cleared `redirecting` left the pointer decoupled from+ the hand, frozen on screen while the keyboard already worked. Windows+ is told too, while the link is up: it keeps treating this Mac as+ driving, with whatever keys it was holding still down, until it hears+ otherwise. On a dead link the receiver hands back by itself."""+ was_redirecting = self.redirecting+ self.redirecting = False+ self._set_cursor_follows_mouse(True)+ self.cursor_pin_point = None+ self.translator.reset_mouse_accumulators()+ self.crossing.reset()+ self._forget_round_trips()+ if was_redirecting:+ # Queued after redirecting has already flipped False: only reaches+ # the wire because the outbound gate exempts control messages.+ self._enqueue_control(protocol.focus_msg("mac"))++ def set_receiving(self, value):+ """The PC has taken input on this Mac, or given it back. Input is+ returned to this Mac's own hardware first: whatever the PC is about to+ do with the pointer, it must not read as a push against the edge."""+ value = bool(value)+ if value == self.receiving:+ return+ if value and self.redirecting:+ self.set_redirecting(False)+ self.receiving = value+ self.crossing.reset()++ def _enqueue_control(self, message):+ """Enqueue a control message (focus, or the local-clipboard sentinel)+ from set_redirecting, which runs on the event-tap thread rather than+ the outbound worker. Best-effort: a momentarily full queue drops the+ message (logged) instead of blocking the tap thread."""+ try:+ self.outbound.put_nowait(message)+ except queue.Full:+ self.logger.error("outbound queue full; dropped control message %r", message.get("type"))++ def _capture_cursor_pin_point(self):+ """Snapshot the cursor's current location as the point that will be+ warped back to for the rest of this redirect session (see+ _warp_cursor_to_pin). Returns None -- logged once -- if Quartz can't+ tell us where the cursor is; callers must treat that as "no pinning+ available" rather than raise, the same fail-open posture as the rest+ of this module's Quartz calls."""+ try:+ probe = self.quartz.CGEventCreate(None)+ return self.quartz.CGEventGetLocation(probe)+ except Exception:+ self.logger.exception("failed to capture the cursor pin point")+ return None++ def _set_cursor_follows_mouse(self, follows):+ try:+ status = self.quartz.CGAssociateMouseAndMouseCursorPosition(follows)+ except Exception:+ self.logger.exception("failed to toggle local cursor association")+ return+ # CGAssociateMouseAndMouseCursorPosition's return value was+ # previously ignored outright, which is how a macOS version where+ # this call is silently ineffective (see _warp_cursor_to_pin, the+ # belt-and-braces compensation for exactly that) went unnoticed.+ # Logged once -- not every redirect toggle -- purely as a+ # diagnostic breadcrumb.+ if not self._cursor_assoc_status_logged:+ self._cursor_assoc_status_logged = True+ self.logger.info(+ "CGAssociateMouseAndMouseCursorPosition(%s) returned status %r (0 == success)",+ follows,+ status,+ )++ def _warp_cursor_to_pin(self):+ """Belt-and-braces compensation for CGAssociateMouseAndMouseCursorPosition+ not holding on every macOS version: forcibly snap the (still+ Association-decoupled, in theory) local cursor back to the pinned+ point after every captured mouse move/drag while redirecting, so it+ cannot visibly wander even when the association call was a no-op."""+ point = self.cursor_pin_point+ if point is None:+ return+ try:+ status = self.quartz.CGWarpMouseCursorPosition(point)+ except Exception:+ self.logger.exception("failed to warp the cursor back to the pin point")+ return+ if status != 0 and not self._cursor_warp_error_logged:+ self._cursor_warp_error_logged = True+ self.logger.warning("CGWarpMouseCursorPosition returned error %r", status)++ def _alert(self, title, message):+ callback = self.on_user_alert+ if callback is None:+ return+ try:+ callback(title, message)+ except Exception:+ self.logger.exception("on_user_alert callback failed")++ def _thread_entry(self, name, target):+ try:+ target()+ except BaseException:+ self._return_local()+ self.logger.exception("background thread %s crashed; input forced local", name)++ def _event_tap_worker(self):+ with objc.autorelease_pool():+ self._run_event_tap()++ def _input_thread_entry(self):+ try:+ self._event_tap_worker()+ except BaseException as exc:+ self._return_local()+ self.input_error = str(exc)+ self.logger.exception("input capture stopped; input forced local")+ finally:+ with self.capture_lock:+ if self.capture_thread is threading.current_thread():+ self.capture_thread = None++ def _run_event_tap(self):+ quartz = self.quartz+ event_types = (+ quartz.kCGEventKeyDown,+ quartz.kCGEventKeyUp,+ quartz.kCGEventFlagsChanged,+ quartz.kCGEventMouseMoved,+ quartz.kCGEventLeftMouseDragged,+ quartz.kCGEventRightMouseDragged,+ quartz.kCGEventOtherMouseDragged,+ quartz.kCGEventLeftMouseDown,+ quartz.kCGEventLeftMouseUp,+ quartz.kCGEventRightMouseDown,+ quartz.kCGEventRightMouseUp,+ quartz.kCGEventOtherMouseDown,+ quartz.kCGEventOtherMouseUp,+ quartz.kCGEventScrollWheel,+ )+ event_mask = 0+ for event_type in event_types:+ event_mask |= quartz.CGEventMaskBit(event_type)+ # Gesture events (pinch/swipe/etc., see gestures.py) have no public+ # kCGEventType* constant, so there is nothing to pass to+ # CGEventMaskBit -- these are the private NSEventType raw values,+ # bit-shifted directly. Harmless to request even if this macOS+ # version never delivers them (best-effort only); SmartMagnify's+ # value (32) needs the shift done in Python's arbitrary-precision+ # ints rather than a 32-bit C bitwise-or, hence not routed through+ # CGEventMaskBit here.+ for gesture_type in gestures.GESTURE_EVENT_TYPES:+ event_mask |= 1 << gesture_type+ # Media/volume keys arrive as NSSystemDefined, which likewise has no+ # public kCGEventType constant (see media_keys.py).+ event_mask |= 1 << media_keys.NX_SYSDEFINED_EVENT_TYPE+ try:+ tap = quartz.CGEventTapCreate(+ quartz.kCGSessionEventTap,+ quartz.kCGHeadInsertEventTap,+ quartz.kCGEventTapOptionDefault,+ event_mask,+ self.tap_callback_ref,+ None,+ )+ if tap is None:+ raise RuntimeError(+ "CGEventTapCreate failed; grant Accessibility and Input Monitoring permission, then relaunch"+ )+ source = quartz.CFMachPortCreateRunLoopSource(None, tap, 0)+ if source is None:+ raise RuntimeError("CFMachPortCreateRunLoopSource failed")+ run_loop = quartz.CFRunLoopGetCurrent()+ self.event_tap = tap+ self.tap_source = source+ self.tap_run_loop = run_loop+ quartz.CFRunLoopAddSource(run_loop, source, quartz.kCFRunLoopCommonModes)+ quartz.CGEventTapEnable(tap, True)+ self.input_error = None+ self.tap_ready.set()+ quartz.CFRunLoopRun()+ if not self.stop_event.is_set():+ raise RuntimeError("event-tap run loop exited unexpectedly")+ except BaseException:+ self.tap_ready.set()+ raise++ def _event_tap_callback(self, proxy, event_type, event, refcon):+ try:+ if event_type in (+ self.quartz.kCGEventTapDisabledByTimeout,+ self.quartz.kCGEventTapDisabledByUserInput,+ ):+ # Input is local from here, so the cursor follows the hand+ # again; a re-enabled tap is never a reason to keep it pinned.+ self._return_local()+ self.logger.error("macOS disabled the event tap; input forced local")+ if self.event_tap is not None:+ self.quartz.CGEventTapEnable(self.event_tap, True)+ return event+ if self.receiving:+ # The PC is driving this Mac over the other link. Everything+ # passes through untouched: crossing must not read a pointer+ # the PC is moving as a push against this Mac's own edge,+ # which would send input straight back where it came from.+ # The one exception is this Mac's own trigger key, which+ # sends the PC's input home -- so a return edge that never+ # fires cannot strand the PC's mouse here.+ if (+ event_type in (self.quartz.kCGEventKeyDown, self.quartz.kCGEventKeyUp, self.quartz.kCGEventFlagsChanged)+ and not self._was_injected(event)+ and self.quartz.CGEventGetIntegerValueField(event, self.quartz.kCGKeyboardEventKeycode) == self.trigger_code+ ):+ result = self.translator.key_result(event_type, event, self.trigger_code, self.cfg.key_map)+ if result.is_trigger:+ return self._handle_trigger(result, event)+ return event+ if self.gesture_translator.wants(event_type):+ return self._handle_gesture_event(event_type, event)+ if event_type == media_keys.NX_SYSDEFINED_EVENT_TYPE:+ return self._handle_system_event(event)+ if self._was_injected(event):+ # One Beamer itself posted for the PC, on its way to an app+ # here. Only keys and pointer events are ever injected, which+ # is why this sits below the gesture and media branches.+ return event+ if event_type in (+ self.quartz.kCGEventKeyDown,+ self.quartz.kCGEventKeyUp,+ self.quartz.kCGEventFlagsChanged,+ ):+ result = self.translator.key_result(+ event_type,+ event,+ self.trigger_code,+ self.cfg.key_map,+ )+ if result.is_trigger:+ return self._handle_trigger(result, event)+ messages = result.messages+ else:+ if not self.redirecting:+ return self._handle_local_mouse(event_type, event)+ messages = self.translator.mouse_messages(event_type, event)+ if not self.redirecting:+ return event+ for message in messages:+ try:+ self.outbound.put_nowait(message)+ except queue.Full:+ self._connection_failed("outbound event queue filled")+ return event+ if self.redirecting and event_type in self.translator.movement_event_types:+ self._warp_cursor_to_pin()+ if not self.redirecting:+ return event+ return None+ except BaseException:+ self._return_local()+ self.logger.exception("event-tap callback failed; input forced local")+ return event++ def _was_injected(self, event):+ """Whether this event carries the mark input_injector_mac stamps into+ every event it posts. Never raises: an event whose source cannot be+ read is treated as the hand's, which is the safe way round -- the+ worst case is a crossing that should not have fired, not a keyboard+ that stops working."""+ try:+ return self.quartz.CGEventGetIntegerValueField(+ event, self.quartz.kCGEventSourceUserData+ ) == INJECTED_MARK+ except Exception:+ return False++ def _handle_local_mouse(self, event_type, event):+ """Crossing lives on the local side of the tap: while the pointer is+ pushing against an armed edge, the event is swallowed and the pointer+ warped back to where the push began, which is the resistance; at+ breakthrough input moves to Windows. Everything else passes through.+ Fails open twice over: the caller's handler already returns the event+ on any exception, and a failure here also switches crossing off until+ the next settings save, so one broken geometry call cannot log an+ exception per mouse move."""+ if self._crossing_failed or 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:+ return event+ if event_type not in self.translator.movement_event_types:+ self.crossing.reset()+ return event+ if not self.connected:+ return event+ try:+ quartz = self.quartz+ location = quartz.CGEventGetLocation(event)+ x, y = location[0], location[1]+ dx = quartz.CGEventGetDoubleValueField(event, quartz.kCGMouseEventDeltaX)+ dy = quartz.CGEventGetDoubleValueField(event, quartz.kCGMouseEventDeltaY)+ step = self.crossing.feed(+ x,+ y,+ dx,+ dy,+ self._current_desktop_bounds(),+ self.clock(),+ notch_range=self.notch_range,+ dragging=event_type != quartz.kCGEventMouseMoved,+ )+ except Exception:+ self._crossing_failed = True+ self.crossing.reset()+ self.logger.exception("crossing failed; edge switching is off until settings are saved again")+ return event+ if step.crossed:+ if self.set_redirecting(True, edge=step.edge, offset=step.offset):+ self._notify_crossing("cross", step)+ return None+ return event+ if step.hold:+ self._warp_cursor_to(step.pin)+ self._notify_crossing("tick" if step.tick else "pressure", step)+ return None+ if step.pressure > 0:+ self._notify_crossing("tick" if step.tick else "pressure", step)+ return event++ def _current_desktop_bounds(self):+ now = self.clock()+ if self._bounds_cache is None or now - self._bounds_at > DESKTOP_BOUNDS_MAX_AGE_SECONDS:+ self._bounds_cache = self.desktop_bounds()+ self._bounds_at = now+ return self._bounds_cache++ def _default_desktop_bounds(self):+ quartz = self.quartz+ error, displays, count = quartz.CGGetActiveDisplayList(16, None, None)+ if error != 0 or not count:+ raise RuntimeError(f"CGGetActiveDisplayList failed: {error}")+ left = top = float("inf")+ right = bottom = float("-inf")+ for display in list(displays)[:count]:+ rect = quartz.CGDisplayBounds(display)+ left = min(left, rect.origin.x)+ top = min(top, rect.origin.y)+ right = max(right, rect.origin.x + rect.size.width)+ bottom = max(bottom, rect.origin.y + rect.size.height)+ return (left, top, right, bottom)++ def _warp_cursor_to(self, point):+ try:+ status = self.quartz.CGWarpMouseCursorPosition(point)+ except Exception:+ self.logger.exception("failed to warp the cursor")+ return+ if status != 0 and not self._cursor_warp_error_logged:+ self._cursor_warp_error_logged = True+ self.logger.warning("CGWarpMouseCursorPosition returned error %r", status)++ def _notify_crossing(self, kind, step):+ callback = self.on_crossing+ if callback is None:+ return+ try:+ callback(kind, step)+ except Exception:+ self.logger.exception("on_crossing callback failed")++ def crossing_pressure_now(self):+ """Current pressure as a fraction, decayed to now, for the glow to fade+ against after the last mouse event."""+ return self.crossing.pressure_at(self.clock())++ def _handle_switch(self, data):+ """Windows asked for input back, having pushed through its return+ edge. Stop redirecting first, then land the pointer where it left+ Windows: `edge` is the Mac edge to arrive at and `offset` the fraction+ along it. A malformed or unknown request is ignored; a switch that+ arrives while already local still gets the haptic, since the pointer+ genuinely came home."""+ if not isinstance(data, dict) or data.get("target") != "mac":+ return+ self.set_redirecting(False)+ edge = data.get("edge")+ offset = data.get("offset")+ if edge in crossing.EDGES and isinstance(offset, (int, float)) and not isinstance(offset, bool):+ try:+ point = crossing.CrossingEngine.arrival_point(edge, offset, self._current_desktop_bounds())+ except Exception:+ self.logger.exception("failed to place the pointer on arrival")+ else:+ self._warp_cursor_to(point)+ self._notify_crossing("arrive", crossing.Step(mac_edge=edge if edge in crossing.EDGES else None))++ def _handle_system_event(self, event):+ """Forward a media/volume key press. Anything that is not one --+ brightness, keyboard backlight, and the undocumented subtypes that+ share NSSystemDefined -- passes through to macOS untouched, as does+ everything when not redirecting."""+ if not self.redirecting:+ return event+ try:+ decoded = self.system_event_converter(event)+ except Exception:+ self.logger.debug("failed to convert a system-defined event", exc_info=True)+ return event+ if decoded is None:+ return event+ media = media_keys.decode(*decoded)+ if media is None:+ return event+ name, is_down, _is_repeat = media+ message_type = protocol.MSG_KEYDOWN if is_down else protocol.MSG_KEYUP+ wire_name = self.cfg.key_map.get(name, name)+ try:+ self.outbound.put_nowait({"type": message_type, "data": {"key": wire_name}})+ except queue.Full:+ self._connection_failed("outbound event queue filled")+ return event+ if not self.redirecting:+ return event+ return None++ def _handle_gesture_event(self, event_type, event):+ """Handle one gesture-family event (magnify/swipe/etc., see+ gestures.py). When not redirecting, passed through untouched -- no+ conversion is even attempted, matching every other event type's+ local behaviour. While redirecting, converting to a readable form+ can fail (AppKit missing, or the conversion itself raising, since+ this is unsupported API surface): that failure fails open, passing+ this one event through locally rather than forcing a full+ disconnect, and capture continues for the next event either way."""+ if not self.redirecting:+ return event+ if event_type == gestures.DOCK_CONTROL_TYPE:+ # Swallowed whichever way classification goes: passing it on+ # would open Mission Control or switch Spaces on the Mac while+ # the user is looking at Windows.+ fields = self._read_dock_event(event)+ messages = self.dock_classifier.translate(fields) if fields is not None else []+ else:+ gesture_view = self._convert_gesture_event(event)+ if gesture_view is None:+ return event+ messages = self.gesture_translator.translate(event_type, gesture_view)+ if not self._gesture_capture_logged:+ self._gesture_capture_logged = True+ self.logger.info("gesture capture active")+ for message in messages:+ try:+ self.outbound.put_nowait(message)+ except queue.Full:+ self._connection_failed("outbound event queue filled")+ return event+ if not self.redirecting:+ return event+ return None++ def handle_overlay_gesture(self, event_type, gesture_view):+ """Counterpart to _handle_gesture_event for gestures captured by the+ overlay NSPanel's ordinary AppKit responder methods (magnifyWithEvent_+ / swipeWithEvent_, see kvm_bridge_app.py) rather than the CGEventTap+ -- macOS 27 beta was observed to never deliver gesture event types+ 29-32 to the tap at all, so this is the path that actually works.++ Called from the AppKit main thread while the tap thread runs+ concurrently; thread-safe for the same reason the tap path is: it+ only translates the event and put_nowait()s onto the outbound+ queue, never blocking and never touching anything the tap thread+ also mutates apart from that queue. Silently a no-op when not+ redirecting, and never raises -- a broken conversion or translation+ must not be able to crash the AppKit main thread."""+ if not self.redirecting:+ return+ if not self._overlay_gesture_capture_logged:+ self._overlay_gesture_capture_logged = True+ self.logger.info("gesture capture active (overlay)")+ try:+ messages = self.gesture_translator.translate(event_type, gesture_view)+ except Exception:+ self.logger.exception("overlay gesture translation failed")+ return+ for message in messages:+ try:+ self.outbound.put_nowait(message)+ except queue.Full:+ self._connection_failed("outbound event queue filled")+ return++ def _convert_gesture_event(self, event):+ try:+ return self.gesture_event_converter(event)+ except Exception:+ self.logger.debug("failed to convert a gesture event", exc_info=True)+ return None++ def _read_dock_event(self, event):+ try:+ return self.dock_event_reader(event)+ except Exception:+ self.logger.debug("failed to read a DockControl event", exc_info=True)+ return None++ def _default_dock_event_reader(self, event):+ quartz = self.quartz+ return types.SimpleNamespace(+ hid=quartz.CGEventGetIntegerValueField(event, gestures.DOCK_FIELD_HID_TYPE),+ motion=quartz.CGEventGetIntegerValueField(event, gestures.DOCK_FIELD_MOTION),+ phase=quartz.CGEventGetIntegerValueField(event, gestures.DOCK_FIELD_PHASE),+ progress=quartz.CGEventGetDoubleValueField(event, gestures.DOCK_FIELD_PROGRESS),+ # Both axes carry the same value on the ended event; either is the direction.+ velocity=quartz.CGEventGetDoubleValueField(event, gestures.DOCK_FIELD_VELOCITY_X),+ )++ def _handle_trigger(self, result, event):+ was_redirecting = self.redirecting+ suppress = was_redirecting or self.trigger_suppressed+ changed = False+ if self.cfg.trigger_style == "hold":+ # Input is on Windows for exactly as long as the key is down. The+ # key itself never reaches either machine: it would be a stray+ # modifier on Windows, and on the Mac a press with nothing else is+ # what people use to switch for a single keystroke.+ if result.is_repeat:+ return None+ if result.is_down:+ self.set_redirecting(True)+ else:+ self.set_redirecting(False)+ return None+ if result.is_down and not result.is_repeat:+ now = self.clock()+ threshold = self.cfg.double_tap_ms / 1000.0+ if self.last_trigger_down and now - self.last_trigger_down <= threshold:+ changed = self.set_redirecting(not was_redirecting)+ self.last_trigger_down = 0.0+ else:+ self.last_trigger_down = now+ suppress = was_redirecting or changed+ self.trigger_suppressed = suppress+ elif not result.is_down:+ suppress = was_redirecting or self.trigger_suppressed+ self.trigger_suppressed = False+ return None if suppress else event++ def _connection_worker(self):+ while not self.stop_event.is_set():+ if not self.connected and self._config_ready():+ self._connect_once()+ self.stop_event.wait(self.cfg.reconnect_interval_s)++ def _config_ready(self):+ return bool(self.cfg.host and self.cfg.auth_token and 1 <= self.cfg.port <= 65535)++ def _connect_once(self):+ sock = None+ fallback = False+ self.connection_status = f"Connecting to {self.cfg.host}:{self.cfg.port}"+ try:+ try:+ sock = self.socket_factory(+ (self.cfg.host, self.cfg.port),+ timeout=CONNECT_TIMEOUT_SECONDS,+ )+ except OSError as exc:+ if exc.errno != errno.EHOSTUNREACH:+ raise+ sock = self._connect_via_ssh_fallback()+ fallback = True+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)+ session = protocol.SecureSession(self.cfg.auth_token)+ sock.sendall(session.preamble())+ sock.settimeout(AUTH_TIMEOUT_SECONDS)+ try:+ protocol.recv_preamble(sock, session)+ except socket.timeout:+ raise _HandshakeError(OLD_RECEIVER_STATUS) from None+ except protocol.VersionMismatch as exc:+ raise _HandshakeError(+ f"Windows receiver speaks Beamer protocol v{exc.peer_version}, this Mac v{protocol.PROTOCOL_VERSION} — update both apps"+ ) from None+ # The way home travels in the hello as well as on every switch,+ # so Windows knows which of its edges leads back here before this+ # Mac has ever crossed -- which is what lets the PC push its own+ # pointer out across that same border first.+ protocol.send_msg(+ sock,+ session,+ protocol.hello_msg(+ return_edge=self.crossing.home_edge(),+ resistance_px=int(self.crossing.resistance_px),+ ),+ )+ try:+ reply = protocol.recv_msg(sock, session)+ except protocol.ConnectionClosed:+ # The receiver closes without a word when the first frame fails to authenticate.+ raise _HandshakeError(AUTH_FAILED_STATUS) from None+ except protocol.AuthenticationError:+ raise _HandshakeError(AUTH_FAILED_STATUS) from None+ reply_type = reply.get("type")+ if reply_type != protocol.MSG_WELCOME:+ raise protocol.ProtocolError("receiver did not confirm authentication")+ welcome_data = reply.get("data")+ if not isinstance(welcome_data, dict):+ raise protocol.ProtocolError("welcome message missing data")+ error = welcome_data.get("error")+ if error == "version_mismatch":+ raise _HandshakeError(OLD_RECEIVER_STATUS)+ if error:+ raise _HandshakeError(f"Windows rejected the connection: {error}")+ if welcome_data.get("version") != protocol.PROTOCOL_VERSION:+ raise _HandshakeError(OLD_RECEIVER_STATUS)+ sock.settimeout(SOCKET_IO_TIMEOUT_SECONDS)+ except _HandshakeError as exc:+ self.redirecting = False+ self.connection_status = exc.status+ if sock is not None:+ try:+ sock.close()+ except OSError:+ pass+ self.logger.warning("connection to Windows failed: %s", exc.status)+ return False+ except protocol.ConnectionClosed:+ self.redirecting = False+ self.connection_status = "Windows closed the connection during the handshake."+ if sock is not None:+ try:+ sock.close()+ except OSError:+ pass+ self.logger.warning(self.connection_status)+ return False+ except (OSError, protocol.ProtocolError) as exc:+ self.redirecting = False+ self.connection_status = connection_error_message(exc)+ if sock is not None:+ try:+ sock.close()+ except OSError:+ pass+ self.logger.warning("connection to Windows failed: %s", exc)+ return False+ with self.socket_lock:+ if self.stop_event.is_set() or self.sock is not None:+ try:+ sock.close()+ except OSError:+ pass+ return False+ self.sock = sock+ self.session = session+ now = self.clock()+ with self.sequence_lock:+ self.last_ack_seq = -1+ self.last_ack_at = now+ self.connected_at = now+ self.last_send_at = now+ if fallback:+ self.connection_status = "Connected to Windows via secure macOS 27 fallback"+ self.logger.info("connected to Windows through the SSH fallback")+ else:+ self.connection_status = f"Connected to {self.cfg.host}:{self.cfg.port}"+ self.logger.info("connected to Windows at %s:%s", self.cfg.host, self.cfg.port)+ return True++ def _connect_via_ssh_fallback(self):+ try:+ return self.socket_factory(+ (SSH_FALLBACK_HOST, SSH_FALLBACK_PORT),+ timeout=CONNECT_TIMEOUT_SECONDS,+ )+ except OSError as exc:+ raise OSError(+ errno.EHOSTUNREACH,+ "Open /Applications/Beamer Tunnel.command",+ ) from exc++ def _outbound_worker(self):+ while not self.stop_event.is_set():+ try:+ message = self.outbound.get(timeout=0.2)+ except queue.Empty:+ continue+ try:+ self._process_outbound(message)+ except Exception:+ # One bad message must not end the only thread that drains+ # this queue: nothing restarts it, and the tap would keep+ # swallowing input into a queue nobody reads.+ self._force_local(f"outbound message {message.get('type')!r} failed")+ self.logger.exception("outbound worker recovered")+ finally:+ self.outbound.task_done()++ def _process_outbound(self, message):+ """Handle one dequeued outbound item. Control messages (focus,+ clipboard, and the local-clipboard sentinel) are exempt from the+ `not redirecting` gate -- otherwise the switch-back focus message+ would be dropped, since set_redirecting(False) closes the gate+ before this worker gets to dequeue it -- and bypass sequence+ assignment entirely, the same way ping does via _send_raw."""+ message_type = message.get("type")+ if message_type not in _GATE_EXEMPT_TYPES and not self.redirecting:+ return+ if message_type == _LOCAL_CLIPBOARD_SENTINEL_TYPE:+ self._send_local_clipboard()+ return+ if message_type in CONTROL_MESSAGE_TYPES:+ self._send_raw(message)+ return+ prepared = self._prepare_outbound(message)+ self._send_prepared(prepared)++ def _send_local_clipboard(self):+ """Expand the local-clipboard sentinel: read this Mac's clipboard and+ send it as a clipboard message. Text over CLIPBOARD_MAX_BYTES and an+ image over CLIPBOARD_IMAGE_MAX_BYTES are each dropped on their own,+ so an oversized screenshot still lets its text through; with nothing+ left the message is skipped and the focus message still goes out."""+ text, image = self.clipboard.get_contents()+ if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:+ self.logger.warning("local clipboard text is too large; skipping the text")+ text = None+ 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,+ )+ image = None+ if not text and image is None:+ self.logger.debug("local clipboard is empty; skipping clipboard sync")+ return+ self._send_raw(protocol.clipboard_msg(text or None, image))++ def _prepare_outbound(self, message):+ with self.sequence_lock:+ self.last_sent_seq += 1+ seq = self.last_sent_seq+ data = dict(message.get("data", {}))+ data["seq"] = seq+ return {"type": message["type"], "data": data}++ def _send_prepared(self, message):+ with self.socket_lock:+ sock = self.sock+ if sock is None:+ self._connection_failed("connection disappeared before an input event could be sent")+ return False+ try:+ protocol.send_msg(sock, self.session, message)+ self.last_send_at = self.clock()+ except (OSError, protocol.ProtocolError) as exc:+ self._connection_failed(f"send failed: {exc}", expected_socket=sock)+ return False+ with self.sequence_lock:+ self._unacked_sent_at.append((message["data"]["seq"], self.last_send_at))+ return True++ def _send_raw(self, message):+ """Serialize and send `message` directly under socket_lock, bypassing+ the outbound queue and its redirecting gate. Used for the idle+ heartbeat ping, which must go out whether or not input is redirected."""+ with self.socket_lock:+ sock = self.sock+ if sock is None:+ return False+ try:+ protocol.send_msg(sock, self.session, message)+ self.last_send_at = self.clock()+ return True+ except (OSError, protocol.ProtocolError) as exc:+ self._connection_failed(f"send failed: {exc}", expected_socket=sock)+ return False++ def _ack_worker(self):+ active_socket = None+ decoder = None+ while not self.stop_event.is_set():+ with self.socket_lock:+ sock = self.sock+ session = self.session+ if sock is None:+ active_socket = None+ decoder = None+ self.stop_event.wait(0.1)+ continue+ if sock is not active_socket:+ active_socket = sock+ decoder = FrameDecoder(session)+ try:+ chunk = sock.recv(4096)+ except socket.timeout:+ continue+ except OSError as exc:+ self._connection_failed(f"ACK receive failed: {exc}", expected_socket=sock)+ active_socket = None+ continue+ if not chunk:+ self._connection_failed("Windows closed the connection", expected_socket=sock)+ active_socket = None+ continue+ try:+ messages = decoder.feed(chunk)+ for message in messages:+ self._handle_inbound(message)+ except protocol.AuthenticationError:+ self._connection_failed(AUTH_FAILED_STATUS, expected_socket=sock)+ active_socket = None+ except protocol.ProtocolError as exc:+ self._connection_failed(f"invalid ACK stream: {exc}", expected_socket=sock)+ active_socket = None+ except Exception as exc:+ # The same outcome as a malformed frame: this connection goes,+ # the thread stays, and the next connection gets a reader.+ self.logger.exception("inbound handling failed")+ self._connection_failed(f"inbound message failed: {exc}", expected_socket=sock)+ active_socket = None++ def _handle_inbound(self, message):+ """Dispatch one inbound message. `ack` updates the sequence bookkeeping+ the watchdog relies on; any other well-formed message (a dict with a+ known "type" string) still refreshes liveness — bytes arriving at all+ prove the connection is alive — and is otherwise ignored, except for+ `clipboard`, which is applied to the local pasteboard. Malformed+ frames still drop the connection, since they mean the stream can no+ longer be trusted."""+ if message.get("type") == protocol.MSG_ACK:+ self._record_ack(message)+ return+ message_type = message.get("type")+ if not isinstance(message_type, str) or not message_type:+ raise protocol.ProtocolError(f"malformed inbound message: {message!r}")+ with self.sequence_lock:+ self.last_ack_at = self.clock()+ if message_type == protocol.MSG_CLIPBOARD:+ self._apply_inbound_clipboard(message.get("data", {}))+ return+ if message_type == protocol.MSG_SWITCH:+ self._handle_switch(message.get("data", {}))+ return+ if message_type == protocol.MSG_ARRANGEMENT:+ self._handle_arrangement(message.get("data", {}))+ return+ self.logger.debug("ignoring inbound message of type %r", message_type)++ def _handle_arrangement(self, data):+ """Windows changed which edge of this Mac leads to it. Handed to the+ app, which owns the settings file; nothing is applied here."""+ read = protocol.read_arrangement(data)+ if read is None or self.on_arrangement is None:+ return+ try:+ self.on_arrangement(*read)+ except Exception:+ self.logger.exception("arrangement handler failed")++ def send_arrangement(self, mac_edge, set_at):+ """Tell Windows where the machines are, when the change was made here.+ Sent straight out rather than queued: it is not input, and it must go+ whether or not input is currently redirected."""+ return self._send_raw(protocol.arrangement_msg(mac_edge, int(set_at)))++ def _apply_inbound_clipboard(self, data):+ if not isinstance(data, dict):+ return+ text = data.get("text")+ if not isinstance(text, str) or not text:+ text = None+ elif len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:+ self.logger.warning("ignoring oversized inbound clipboard text")+ text = None+ image = protocol.clipboard_image(data)+ if text is None and image is None:+ return+ if not self.clipboard.set_contents(text, image):+ self.logger.warning("failed to set the local clipboard from an inbound message")++ def _record_ack(self, message):+ if message.get("type") != protocol.MSG_ACK:+ raise protocol.ProtocolError(f"unexpected inbound message type: {message.get('type')!r}")+ data = message.get("data")+ if not isinstance(data, dict):+ raise protocol.ProtocolError("ACK data must be a JSON object")+ seq = data.get("seq")+ if isinstance(seq, bool) or not isinstance(seq, int) or seq < 0:+ raise protocol.ProtocolError("ACK seq must be a non-negative integer")+ with self.sequence_lock:+ if seq < self.last_ack_seq:+ raise protocol.ProtocolError("ACK seq moved backwards")+ if seq > self.last_sent_seq:+ raise protocol.ProtocolError("ACK seq is ahead of the sender")+ advanced = seq > self.last_ack_seq+ self.last_ack_seq = seq+ self.last_ack_at = self.clock()+ if advanced:+ self._measure_round_trip(seq, self.last_ack_at)+ self._note_windows_lock(data.get("locked") is True)++ def _measure_round_trip(self, seq, now):+ """Under sequence_lock. Measured from the send of the event the ACK names, not the+ oldest one it covers: the receiver acknowledges the highest seq it has processed on a+ timer, so the oldest would only ever measure that timer. An ACK that repeats a seq --+ every idle heartbeat does -- finds nothing left to measure and adds no sample."""+ sent_at = None+ while self._unacked_sent_at and self._unacked_sent_at[0][0] <= seq:+ sent_seq, at = self._unacked_sent_at.popleft()+ if sent_seq == seq:+ sent_at = at+ if sent_at is not None:+ self._round_trips.append(now - sent_at)+ self._round_trip_at = now++ def _forget_round_trips(self):+ with self.sequence_lock:+ self._unacked_sent_at.clear()+ self._round_trips.clear()+ self._round_trip_at = 0.0++ def _note_windows_lock(self, locked):+ """Surface Windows clearing its lock screen, on the transitions only:+ an ACK arrives every 400ms and must not restate the status each time.+ The previous status is restored verbatim rather than rebuilt, so the+ macOS 27 SSH-fallback wording survives an unlock."""+ if locked == self.windows_locked:+ return+ self.windows_locked = locked+ if locked:+ self._status_before_unlock = self.connection_status+ self.connection_status = "Unlocking Windows…"+ self.logger.info("Windows is on the lock screen; it is unlocking itself")+ else:+ if self._status_before_unlock is not None:+ self.connection_status = self._status_before_unlock+ self._status_before_unlock = None++ def _watchdog_worker(self):+ while not self.stop_event.wait(0.1):+ self._watchdog_tick()++ def _watchdog_tick(self):+ """Runs at all times a socket exists, not just while redirecting, so a+ half-open connection can't hide behind an idle UI: it is detected and+ torn down the same way whether or not input is currently redirected.+ Also drives the idle heartbeat ping so a silent connection is proven+ alive well before the peer's own read timeout could fire."""+ with self.socket_lock:+ sock = self.sock+ if sock is None:+ return False+ now = self.clock()+ with self.sequence_lock:+ last_heartbeat = max(self.last_ack_at, self.connected_at)+ if now - last_heartbeat > ACK_TIMEOUT_SECONDS:+ self._connection_failed("Windows stopped responding")+ return True+ if now - self.last_send_at >= PING_INTERVAL_SECONDS:+ self._send_raw(protocol.ping_msg())+ return False++ def _force_local(self, reason):+ self._return_local()+ self.logger.error("%s; input forced local", reason)++ def _connection_failed(self, reason, expected_socket=None):+ was_redirecting = self.redirecting+ self._return_local()+ self.connection_status = reason+ self._drop_connection(expected_socket)+ self.logger.error("%s; connection dropped and input forced local", reason)+ if was_redirecting:+ self._alert("Beamer", "Input returned to this Mac")++ def _drop_connection(self, expected_socket=None):+ with self.socket_lock:+ if expected_socket is not None and self.sock is not expected_socket:+ return+ sock = self.sock+ self.sock = None+ self._forget_round_trips()+ if sock is not None:+ try:+ sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+ try:+ sock.close()+ except OSError:+ pass++ def _drain_outbound(self):+ while True:+ try:+ self.outbound.get_nowait()+ except queue.Empty:+ return+ else:+ self.outbound.task_done()diff --git a/mac_app/build_dmg.sh b/mac_app/build_dmg.shnew file mode 100755index 0000000..7c68bcc--- /dev/null+++ b/mac_app/build_dmg.sh@@ -0,0 +1,174 @@+#!/bin/bash+# Builds Beamer.app and Beamer.dmg.+#+# ./build_dmg.sh local build in mac_app/dist, signed with the same Developer ID identity+# ./build_dmg.sh --release Developer ID, notarised and stapled, written to+# docs/beamer-releases/<version>/ beside the repository, with nothing left in dist+#+# The version is the repo-root VERSION file and the build number is the commit count, so a release+# rebuilt from the same commit carries the same numbers. Nothing here uploads anywhere but Apple's+# notary service.++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"+APP="$SCRIPT_DIR/dist/Beamer.app"+DMG="$SCRIPT_DIR/dist/Beamer.dmg"+RELEASE=0+case "${1:-}" in+ "") ;;+ --release) RELEASE=1 ;;+ *) echo "usage: $0 [--release]" >&2; exit 2 ;;+esac++STAGING_DIR="$(mktemp -d /private/tmp/Beamer.build.XXXXXX)"+cleanup() {+ rm -rf "$STAGING_DIR"+ # A release is copied out, so the staged app goes: Spotlight would offer it beside the installed one.+ if [ "$RELEASE" -eq 1 ]; then rm -rf "$SCRIPT_DIR/build" "$SCRIPT_DIR/dist"; fi+}+trap cleanup EXIT++cd "$SCRIPT_DIR"+if [ -d "/Applications/Xcode.app/Contents/Developer" ]; then+ export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer"+else+ export DEVELOPER_DIR="/Library/Developer/CommandLineTools"+fi+VERSION="$(tr -d '[:space:]' < "$PROJECT_DIR/VERSION")"+export BEAMER_BUILD="$(git -C "$PROJECT_DIR" rev-list --count HEAD)"++xcrun clang --version++if [ "$RELEASE" -eq 1 ]; then+ # docs/ is not part of the build and other sessions write there; anything else uncommitted would+ # ship code that no commit records.+ if [ -n "$(git -C "$PROJECT_DIR" status --porcelain -- . ':(exclude)docs')" ]; then+ echo "uncommitted changes outside docs/ - commit them so the release matches a commit" >&2+ exit 1+ fi+ IDENTITY="Developer ID Application: Toby Kalkman (YNL35YT683)"+ KEY_DIR="$HOME/.appstoreconnect"+ KEY_ID="$(cat "$KEY_DIR/key_id")"+ [ -f "$KEY_DIR/private_keys/AuthKey_$KEY_ID.p8" ] && [ -s "$KEY_DIR/issuer_id" ] \+ || { echo "the pinned App Store Connect key is missing from $KEY_DIR" >&2; exit 1; }+ RELEASE_DIR="$(cd "$PROJECT_DIR/.." && pwd)/docs/beamer-releases/$VERSION"+ echo "Release build of Beamer $VERSION ($BEAMER_BUILD) from $(git -C "$PROJECT_DIR" rev-parse --short HEAD)"+else+ # The release identity too: macOS keys the privacy grants to it, so a local install over a+ # release keeps Accessibility and Input Monitoring instead of silently losing them.+ IDENTITY="${BEAMER_SIGN_IDENTITY:-Developer ID Application: Toby Kalkman (YNL35YT683)}"+ echo "Local build of Beamer $VERSION ($BEAMER_BUILD); not for release distribution"+fi++if [ ! -x ".venv/bin/python3" ]; then+ python3 -m venv .venv+fi+.venv/bin/python3 -m pip install -q -r requirements-mac.txt++rm -rf "$SCRIPT_DIR/build" "$SCRIPT_DIR/dist"+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python3 -B setup.py py2app++PY2APP_DIR="$(.venv/bin/python3 -c 'from pathlib import Path; import py2app; print(Path(py2app.__file__).parent)')"+clang -O2 -arch arm64 -mmacosx-version-min=13.0 "$PY2APP_DIR/apptemplate/src/main.c" -framework Cocoa -o "$APP/Contents/MacOS/Beamer"++xattr -cr "$APP"++# PyObjC's wheels carry dSYM debug symbols, which py2app copies into the zipped stdlib. They are+# Mach-O files nothing loads, and codesign cannot reach inside a zip to sign them.+find "$APP" -name '*.dSYM' -prune -exec rm -rf {} ++for archive in "$APP"/Contents/Resources/lib/python3*.zip; do+ zip -q -d "$archive" '*.dSYM/*' || [ $? -eq 12 ]+done++# Every build runs under the hardened runtime, so a local build breaks the way a notarised one would.+# Only a release takes a secure timestamp: notarisation requires it, and it needs Apple's server.+if [ "$RELEASE" -eq 1 ]; then TIMESTAMP="--timestamp"; else TIMESTAMP="--timestamp=none"; fi++# Inside-out rather than --deep: every nested Mach-O (the Python framework, the extension modules,+# cryptography's _rust, the helper python) is signed on its own, then the framework, then the bundle,+# whose signature seals the lot. --identifier pins the bundle id, which must never change - the+# privacy grants are keyed to it.+sign_app() {+ local identity="$1" binary+ find "$APP/Contents" -type f ! -path "$APP/Contents/MacOS/Beamer" -print0 \+ | xargs -0 file | grep 'Mach-O' | grep -v '(for architecture' | cut -d: -f1 > "$STAGING_DIR/nested.txt"+ while IFS= read -r binary; do+ codesign --force --sign "$identity" --options runtime $TIMESTAMP "$binary" || return 1+ done < "$STAGING_DIR/nested.txt"+ codesign --force --sign "$identity" --options runtime $TIMESTAMP \+ "$APP/Contents/Frameworks/Python.framework/Versions/"[0-9]* || return 1+ codesign --force --sign "$identity" --options runtime $TIMESTAMP \+ --identifier uk.co.kalkman.beamer "$APP" || return 1+}++# A real identity is stable across rebuilds, so macOS keeps the Accessibility and Input Monitoring+# grants; an ad-hoc signature is a new code identity every build and silently drops them.+# A local build falls back to ad-hoc because the login keychain cannot be unlocked from a session+# driven over SSH (errSecInternalComponent), and losing the whole build to that would be worse.+# A release never falls back.+# Not grep -q anywhere here: it exits at the first match, and pipefail then reads the writer's SIGPIPE+# as failure.+if ! security find-identity -v -p codesigning 2>/dev/null | grep -F "$IDENTITY" >/dev/null; then+ [ "$RELEASE" -eq 1 ] && { echo "$IDENTITY is not in the keychain" >&2; exit 1; }+ echo "$IDENTITY is not in the keychain - signing ad-hoc instead"+ TIMESTAMP="--timestamp=none"+ sign_app -+elif ! sign_app "$IDENTITY" 2>"$STAGING_DIR/sign.log"; then+ [ "$RELEASE" -eq 1 ] && { cat "$STAGING_DIR/sign.log" >&2; exit 1; }+ echo "the login keychain would not release $IDENTITY - signing ad-hoc instead"+ TIMESTAMP="--timestamp=none"+ sign_app -+fi+codesign --verify --deep --strict --verbose=2 "$APP"+codesign -dvv "$APP" 2>&1 | grep -E '^(Identifier|Signature|Authority|Timestamp|CodeDirectory)' || true++# The bundle's own python runs under the same hardened runtime as the app, so code that needs an+# entitlement fails here rather than at a user's first launch.+env -i HOME="$HOME" PATH=/usr/bin:/bin PYTHONHOME="$APP/Contents/Resources" \+ "$APP/Contents/MacOS/python" "$PROJECT_DIR/tools/runtime_probe.py"++notarise() {+ local result="$STAGING_DIR/notary.json" id status+ xcrun notarytool submit "$1" --key "$KEY_DIR/private_keys/AuthKey_$KEY_ID.p8" --key-id "$KEY_ID" \+ --issuer "$(cat "$KEY_DIR/issuer_id")" --wait --output-format json > "$result" || true+ id="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("id", ""))' "$result")"+ status="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("status", ""))' "$result")"+ echo "Notary service: $status for $(basename "$1") ($id)"+ if [ "$status" != "Accepted" ]; then+ [ -n "$id" ] && xcrun notarytool log "$id" --key "$KEY_DIR/private_keys/AuthKey_$KEY_ID.p8" \+ --key-id "$KEY_ID" --issuer "$(cat "$KEY_DIR/issuer_id")" >&2+ exit 1+ fi+}++# The app is notarised and stapled before it goes into the image, so the copy a user drags out+# carries its own ticket; the image then gets a submission of its own.+if [ "$RELEASE" -eq 1 ]; then+ ditto -c -k --keepParent "$APP" "$STAGING_DIR/Beamer.zip"+ notarise "$STAGING_DIR/Beamer.zip"+ xcrun stapler staple "$APP"+fi++mkdir "$STAGING_DIR/image"+cp -R "$APP" "$STAGING_DIR/image/"+cp "$SCRIPT_DIR/Beamer Tunnel.command" "$STAGING_DIR/image/"+ln -s /Applications "$STAGING_DIR/image/Applications"+rm -f "$DMG"+diskutil image create from --format UDZO --volumeName "Beamer" "$STAGING_DIR/image" "$DMG"++if [ "$RELEASE" -eq 1 ]; then+ codesign --force --sign "$IDENTITY" --timestamp "$DMG"+ notarise "$DMG"+ xcrun stapler staple "$DMG"+ xcrun stapler validate "$APP"+ xcrun stapler validate "$DMG"+ spctl -a -vv "$APP"+ spctl -a -vv -t install "$DMG"+ mkdir -p "$RELEASE_DIR"+ cp "$DMG" "$RELEASE_DIR/Beamer.dmg"+ echo "Released Beamer $VERSION ($BEAMER_BUILD) at $RELEASE_DIR/Beamer.dmg"+else+ echo "Built Beamer $VERSION ($BEAMER_BUILD) at $DMG"+fidiff --git a/mac_app/clipboard_mac.py b/mac_app/clipboard_mac.pynew file mode 100644index 0000000..e636049--- /dev/null+++ b/mac_app/clipboard_mac.py@@ -0,0 +1,87 @@+"""macOS clipboard access via AppKit's NSPasteboard.++`get_contents`/`set_contents` are called from background threads: the+outbound worker (when switching redirect to Windows, to grab the outgoing+clipboard) and the ack-receiver thread (when a clipboard message arrives from+Windows). Apple doesn't document NSPasteboard as thread-safe, but+reading/writing the general pasteboard from a background thread is widely+relied upon in practice and has not shown problems in manual testing. Flagging+here as the one part of this feature that still wants confirmation on a real+machine under load (see the runtime-verification notes in the task writeup).++AppKit is imported at module level (pyobjc is already a hard dependency of+this app -- bridge.py imports Quartz/objc the same way) but guarded so the+module stays importable, and its behaviour fakeable, on a machine without+it: tests replace the module-level `AppKit` attribute with a fake object+rather than mocking imports.+"""++import logging++try:+ import AppKit+except ImportError: # pragma: no cover - exercised only off macOS+ AppKit = None++LOGGER = logging.getLogger("Beamer")+++def _text_from_pasteboard(pasteboard):+ text = pasteboard.stringForType_(AppKit.NSPasteboardTypeString)+ return text if isinstance(text, str) and text else None+++def _png_from_pasteboard(pasteboard):+ """PNG bytes for the image on the pasteboard, or None. PNG is taken as+ is; TIFF (what most apps put up, and what a Retina grab carries+ uncompressed at 25MB+) is re-encoded through NSBitmapImageRep, which+ also handles the odd TIFF a Windows consumer would never open."""+ png = pasteboard.dataForType_(AppKit.NSPasteboardTypePNG)+ if png is not None and len(png):+ return bytes(png)+ tiff = pasteboard.dataForType_(AppKit.NSPasteboardTypeTIFF)+ if tiff is None or not len(tiff):+ return None+ rep = AppKit.NSBitmapImageRep.imageRepWithData_(tiff)+ if rep is None:+ return None+ png = rep.representationUsingType_properties_(AppKit.NSBitmapImageFileTypePNG, None)+ return bytes(png) if png is not None and len(png) else None+++def get_contents():+ """(text, png) from the general pasteboard, either None when absent.+ Both are read independently and both are sent: an image copied from+ Finder or a browser usually carries a filename or URL as its text, and+ the pasting app on the other side picks the representation it wants,+ exactly as it would from the source clipboard. Never raises."""+ if AppKit is None:+ return None, None+ try:+ pasteboard = AppKit.NSPasteboard.generalPasteboard()+ return _text_from_pasteboard(pasteboard), _png_from_pasteboard(pasteboard)+ except Exception:+ LOGGER.exception("failed to read the macOS clipboard")+ return None, None+++def set_contents(text, png):+ """Replace the general pasteboard with `text` and/or `png`. Returns True+ when at least one of them was set, False otherwise. Only the PNG+ representation is written for the image; every current app pastes it,+ and a TIFF alongside would double the memory for nothing. Never raises."""+ if AppKit is None or (text is None and png is None):+ return False+ try:+ pasteboard = AppKit.NSPasteboard.generalPasteboard()+ pasteboard.clearContents()+ wrote = False+ if text is not None:+ wrote |= bool(pasteboard.setString_forType_(text, AppKit.NSPasteboardTypeString))+ if png is not None:+ data = AppKit.NSData.dataWithBytes_length_(png, len(png))+ wrote |= bool(pasteboard.setData_forType_(data, AppKit.NSPasteboardTypePNG))+ return wrote+ except Exception:+ LOGGER.exception("failed to set the macOS clipboard")+ return Falsediff --git a/mac_app/config.py b/mac_app/config.pynew file mode 100644index 0000000..80c7a02--- /dev/null+++ b/mac_app/config.py@@ -0,0 +1,133 @@+"""Shared config.json loader for mac_sender.py and win_receiver.py."""++import json+import os+from dataclasses import dataclass, field++from crossing import DEFAULT_CROSSING++DEFAULT_CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")++DEFAULT_KEY_MAP = {+ "alt": "alt",+ "alt_r": "alt",+ "ctrl": "cmd",+ "ctrl_r": "cmd",+ "cmd": "ctrl",+ "cmd_r": "ctrl",+}++# The positional map Beamer shipped before 09-09-2026, written verbatim into+# every existing config.json. A saved key_map beats the default, so without+# this an upgraded install would silently keep sending Cmd as the Windows key.+# A saved map whose every entry matches this one is the old default rather+# than a deliberate choice, so it is discarded.+LEGACY_POSITIONAL_KEY_MAP = {+ "alt": "alt",+ "alt_r": "alt",+ "ctrl": "ctrl",+ "ctrl_r": "ctrl",+ "cmd": "cmd",+ "cmd_r": "cmd",+}+++# The two modifier styles the settings window offers. A saved key_map may be one of these+# names instead of a JSON object; Positional has to be saved by name, because its object form is+# the pre-09-09-2026 default and is discarded on load (see LEGACY_POSITIONAL_KEY_MAP).+KEY_MAP_STYLES = {+ "semantic": DEFAULT_KEY_MAP,+ "positional": LEGACY_POSITIONAL_KEY_MAP,+}+++class ConfigError(Exception):+ pass+++@dataclass+class Config:+ host: str+ port: int+ auth_token: str+ trigger_key: str = "alt_r"+ double_tap_ms: int = 300+ key_map: dict = field(default_factory=lambda: dict(DEFAULT_KEY_MAP))+ reconnect_interval_s: float = 2.0+ trigger_style: str = "double_tap"+ crossing: dict = field(default_factory=lambda: dict(DEFAULT_CROSSING))+ # Learned, never typed: the PC's name from its pairing beacon and its hardware address from+ # the ARP table, which is what wake-on-LAN needs.+ pc_name: str = ""+ mac_address: str = ""+ # One switch per direction, each in the menu bar: this Mac's input going to Windows, and+ # the PC's input arriving here. Off stops that direction only; the other keeps working.+ send_to_windows: bool = True+ allow_windows_to_drive: bool = True+++def key_map_style(key_map):+ """The name of a key_map when it is one of the two offered styles, else None."""+ for name, mapping in KEY_MAP_STYLES.items():+ if key_map == mapping:+ return name+ return None+++def load_config(path: str = None) -> Config:+ path = path or DEFAULT_CONFIG_PATH+ if not os.path.exists(path):+ raise ConfigError(+ f"config file not found: {path}\n"+ f"Copy config.example.json to config.json and fill in your own values."+ )++ with open(path, "r", encoding="utf-8") as f:+ raw = json.load(f)++ missing = [k for k in ("host", "port", "auth_token") if k not in raw]+ if missing:+ raise ConfigError(f"config.json is missing required field(s): {', '.join(missing)}")++ # Empty means not yet paired, which every setting must still be able to save+ # around; only the example file's placeholder is refused.+ if raw["auth_token"] == "CHANGE_ME":+ raise ConfigError("config.json auth_token is still the placeholder — pair with a PC or pick a real shared secret")++ key_map = dict(DEFAULT_KEY_MAP)+ saved_key_map = raw.get("key_map", {})+ if isinstance(saved_key_map, str):+ if saved_key_map not in KEY_MAP_STYLES:+ raise ConfigError(f"config.json key_map style must be one of: {', '.join(KEY_MAP_STYLES)}")+ key_map = dict(KEY_MAP_STYLES[saved_key_map])+ elif not isinstance(saved_key_map, dict):+ raise ConfigError("config.json key_map must be a JSON object or a style name")+ elif saved_key_map != LEGACY_POSITIONAL_KEY_MAP:+ # Only the whole old default is the accident. A partial map whose+ # entries happen to agree with it -- {"cmd": "cmd"} on its own -- is a+ # choice, and was being thrown away.+ key_map.update(saved_key_map)++ crossing = dict(DEFAULT_CROSSING)+ saved_crossing = raw.get("crossing", {})+ if not isinstance(saved_crossing, dict):+ raise ConfigError("config.json crossing must be a JSON object")+ crossing.update(saved_crossing)+ crossing["methods"] = list(crossing["methods"])+ crossing["resistance_px"] = int(crossing["resistance_px"])++ return Config(+ host=raw["host"],+ port=int(raw["port"]),+ auth_token=raw["auth_token"],+ trigger_key=raw.get("trigger_key", "alt_r"),+ double_tap_ms=int(raw.get("double_tap_ms", 300)),+ key_map=key_map,+ reconnect_interval_s=float(raw.get("reconnect_interval_s", 2.0)),+ trigger_style=str(raw.get("trigger_style", "double_tap")),+ crossing=crossing,+ pc_name=str(raw.get("pc_name", "") or ""),+ mac_address=str(raw.get("mac_address", "") or ""),+ send_to_windows=raw.get("send_to_windows", True) is not False,+ allow_windows_to_drive=raw.get("allow_windows_to_drive", True) is not False,+ )diff --git a/mac_app/crossing.py b/mac_app/crossing.pynew file mode 100644index 0000000..121704d--- /dev/null+++ b/mac_app/crossing.py@@ -0,0 +1,323 @@+"""The crossing engine: pointer pressure against the outer edge of the Mac desktop.++Pure arithmetic, no AppKit and no Quartz, so it runs under unittest on any machine. bridge.py+feeds it every local mouse movement while the crossing methods are armed and acts on what comes+back; kvm_bridge_app.py reads pressure for the glow. Coordinates are Quartz global points+(top-left origin, the space CGEventGetLocation and CGDisplayBounds share), and `bounds` is the+union of every display as (left, top, right, bottom) with right and bottom exclusive.++Pressure is measured in raw pointer delta units, the same "pixels of travel" the trackpad reports,+and decays at a rate that empties a full push in DECAY_S once the outward movement stops. That one+mechanism is what keeps a slow lean against the edge from ever building a switch.+"""++from dataclasses import dataclass++EDGES = ("left", "right", "top", "bottom")+CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")+METHODS = ("shortcut", "edge", "corner", "notch")+NOTCH_STYLES = ("beam", "island")+HAPTIC_FEELS = ("light", "medium", "firm")+HAPTIC_STEPS = ("quarters", "halves", "breakthrough")+GLOW_STYLES = ("glow", "beam")+# The names of tokens.PALETTES, spelled out because this module stays importable without the root.+GLOW_COLOURS = ("signal", "colourful", "ocean", "sunset", "mono")+OPPOSITE = {"left": "right", "right": "left", "top": "bottom", "bottom": "top"}++DEFAULT_CROSSING = {+ "methods": ["shortcut", "edge"],+ "edge": "right",+ "corner": "top_right",+ "resistance_px": 120,+ "haptics": True,+ "glow": True,+ "notch_style": "beam",+ "notch_after_ms": 1200,+ "haptic_feel": "medium",+ "haptic_steps": "quarters",+ "glow_style": "glow",+ "glow_colour": "signal",+ "block_while_dragging": True,+ # Unix seconds at the moment this Mac last changed the arrangement -- which+ # edge leads to the PC. Either machine may change it, so when two ends meet+ # holding different answers the newer stamp wins. Never read by the engine;+ # it lives here so it is saved and loaded with the rest of the crossing.+ "arrangement_set_at": 0,+}++DECAY_S = 0.4+CORNER_PX = 8.0+# How close to the last pixel of the desktop counts as touching it. The cursor's reported+# location at an edge is fractional on a Retina display, so an exact comparison misses.+EDGE_TOLERANCE = 1.5+# Pressure below this passes events through untouched: a lean of a pixel or two per event+# would otherwise alternate between pinning and releasing the pointer at the trackpad's rate.+HOLD_MIN_PX = 3.0+++def tick_fires(steps, pressure):+ """Whether a quarter tick is felt under `crossing.haptic_steps`, given the pressure it fired at:+ every quarter, only the one at halfway, or none, leaving just the thud at breakthrough."""+ if steps == "quarters":+ return True+ if steps == "halves":+ return min(3, int(4 * pressure + 1e-9)) == 2+ return False+++@dataclass+class 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."""++ pressure: float = 0.0+ hold: bool = False+ pin: tuple = None+ tick: bool = False+ crossed: bool = False+ edge: str = None+ offset: float = None+ mac_edge: str = None+ region: tuple = None+ via: str = None+++class CrossingEngine:+ def __init__(+ self,+ methods=("shortcut", "edge"),+ edge="right",+ corner="top_right",+ resistance_px=120,+ block_while_dragging=True,+ ):+ self.methods = frozenset(methods)+ self.edge = edge+ self.corner = corner+ self.resistance_px = float(resistance_px)+ self.block_while_dragging = block_while_dragging+ self.reset()++ @classmethod+ def from_config(cls, crossing):+ return cls(+ methods=crossing["methods"],+ edge=crossing["edge"],+ corner=crossing["corner"],+ resistance_px=crossing["resistance_px"],+ block_while_dragging=crossing["block_while_dragging"],+ )++ @property+ def armed(self):+ return bool(self.methods & {"edge", "corner", "notch"})++ def reset(self):+ self.touching = False+ self.pressure = 0.0+ self.pin = None+ self.mac_edge = None+ self.region = None+ self._quarter_reached = 0+ self._last_at = None+ self._last_x = None+ self._last_y = None++ def home_edge(self, mac_edge=None):+ """The Windows edge the pointer comes home through: opposite the Mac edge it left by or,+ for a shortcut switch, opposite whichever pointer method is on. None when only the+ shortcut is on. The configured `edge` keeps its value while the edge method is off, so+ reading it unconditionally armed a Windows edge nobody had enabled and left the notch's+ own way home dead after every shortcut switch."""+ if mac_edge is None:+ if "edge" in self.methods:+ mac_edge = self.edge+ elif "notch" in self.methods:+ mac_edge = "top"+ elif "corner" in self.methods:+ mac_edge = self.corner.split("_")[1]+ else:+ return None+ return OPPOSITE[mac_edge]++ def pressure_at(self, now):+ """Pressure as a fraction, decayed to `now` without recording anything — for the glow,+ which has to keep fading after the last event arrives."""+ if self.resistance_px <= 0 or self._last_at is None:+ return 0.0+ 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):+ if self._last_at is not None:+ self.pressure = max(0.0, self.pressure - self._decay(now - self._last_at))+ self._last_at = now+ previous_x, previous_y = self._last_x, self._last_y+ self._last_x, self._last_y = x, y+ if dragging and self.block_while_dragging:+ self.touching = False+ return self._release()++ target = self._target(x, y, bounds, notch_range)+ # 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 None+ if target is None:+ return self._release()+ mac_edge, region, diagonal, via = target+ outward, inward = self._push(mac_edge, diagonal, x, y, dx, dy, previous_x, previous_y, bounds)+ before = self.pressure+ self.pressure = max(0.0, self.pressure + outward - inward)+ if self.pressure <= 0.0:+ return self._release()+ if self.pin is None:+ self.pin = (x, y)+ self.mac_edge = mac_edge+ self.region = region++ if outward > 0.0 and self.pressure >= self.resistance_px:+ step = Step(+ pressure=1.0,+ crossed=True,+ edge=OPPOSITE[mac_edge],+ offset=self._offset(mac_edge, self.pin, bounds),+ mac_edge=mac_edge,+ region=region,+ via=via,+ )+ self.reset()+ return step+ # Ticks are counted against the highest quarter this push has reached, not the+ # previous reading: decay between two events can drop the reading back under a+ # boundary, and comparing readings would then fire the same tick twice.+ quarter = self._quarter(self.pressure)+ tick = quarter > self._quarter_reached+ self._quarter_reached = max(self._quarter_reached, quarter)+ return Step(+ pressure=self._fraction(self.pressure),+ hold=before >= HOLD_MIN_PX,+ pin=self.pin,+ tick=tick,+ mac_edge=mac_edge,+ region=region,+ via=via,+ )++ @staticmethod+ def arrival_point(edge, offset, bounds, inset=2.0):+ """Where the pointer lands when input comes home through a Mac `edge`, `offset` of the+ way along it, a couple of points inside so the arrival itself is not already a push."""+ left, top, right, bottom = bounds+ offset = max(0.0, min(1.0, float(offset)))+ if edge in ("left", "right"):+ y = top + offset * (bottom - 1 - top)+ x = left + inset if edge == "left" else right - 1 - inset+ else:+ x = left + offset * (right - 1 - left)+ y = top + inset if edge == "top" else bottom - 1 - inset+ return (x, y)++ def _decay(self, elapsed):+ if elapsed <= 0 or self.resistance_px <= 0:+ return 0.0+ return self.resistance_px * elapsed / DECAY_S++ def _release(self):+ self.pressure = 0.0+ self.pin = None+ self.mac_edge = None+ self.region = None+ self._quarter_reached = 0+ return Step()++ def _fraction(self, pressure):+ if self.resistance_px <= 0:+ return 0.0+ return max(0.0, min(1.0, pressure / self.resistance_px))++ def _quarter(self, pressure):+ if self.resistance_px <= 0:+ return 0+ return min(3, int(4 * pressure / self.resistance_px))++ def _target(self, x, y, bounds, notch_range):+ """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."""+ left, top, right, bottom = bounds+ x_max, y_max = right - 1, bottom - 1+ at = {+ "left": x <= left + EDGE_TOLERANCE,+ "right": x >= x_max - EDGE_TOLERANCE,+ "top": y <= top + EDGE_TOLERANCE,+ "bottom": y >= y_max - EDGE_TOLERANCE,+ }+ if "corner" in self.methods:+ vertical, horizontal = self.corner.split("_")+ near_x = x <= left + CORNER_PX if horizontal == "left" else x >= x_max - CORNER_PX+ near_y = y <= top + CORNER_PX if vertical == "top" else y >= y_max - CORNER_PX+ if near_x and near_y and (at[horizontal] or at[vertical]):+ box_x = left if horizontal == "left" else x_max - CORNER_PX + 1+ box_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]:+ return self.edge, self._strip(self.edge, bounds), 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 None++ @staticmethod+ def _strip(edge, bounds):+ left, top, right, bottom = bounds+ if edge == "left":+ return (left, top, 1, bottom - top)+ if edge == "right":+ return (right - 1, top, 1, bottom - top)+ if edge == "top":+ return (left, top, right - left, 1)+ return (left, bottom - 1, right - left, 1)++ def _push(self, mac_edge, diagonal, x, y, dx, dy, previous_x, previous_y, bounds):+ """Outward and inward travel for this event. Against a flat edge the OS has already+ clamped the location, so the delta itself is the push once the pointer is there; on the+ event that first reaches the edge only the overshoot past it counts, so a pointer that+ merely arrives at the edge does not start with a head of pressure it never earned."""+ left, top, right, bottom = bounds+ out_x = self._axis(mac_edge, x, dx, previous_x, left, right - 1)+ if diagonal is None:+ out = out_x if mac_edge in ("left", "right") else self._axis(mac_edge, y, dy, previous_y, top, bottom - 1)+ return max(0.0, out), max(0.0, -out)+ out_y = self._axis(diagonal, y, dy, previous_y, top, bottom - 1)+ if out_x > 0 and out_y > 0:+ return (out_x * out_x + out_y * out_y) ** 0.5, 0.0+ inward = (min(0.0, out_x) ** 2 + min(0.0, out_y) ** 2) ** 0.5+ return 0.0, inward++ @staticmethod+ def _axis(edge, position, delta, previous, low, high):+ """Signed outward travel along one axis, positive when moving off the desktop."""+ if edge in ("left", "top"):+ outward = -delta+ if previous is not None and previous > low + EDGE_TOLERANCE:+ outward = min(outward, low - (previous + delta))+ else:+ outward = delta+ if previous is not None and previous < high - EDGE_TOLERANCE:+ outward = min(outward, (previous + delta) - high)+ return outward++ @staticmethod+ def _offset(mac_edge, point, bounds):+ left, top, right, bottom = bounds+ x, y = point+ if mac_edge in ("left", "right"):+ span = bottom - 1 - top+ fraction = (y - top) / span if span > 0 else 0.0+ else:+ span = right - 1 - left+ fraction = (x - left) / span if span > 0 else 0.0+ return round(max(0.0, min(1.0, fraction)), 4)diff --git a/mac_app/desktop_mac.py b/mac_app/desktop_mac.pynew file mode 100644index 0000000..db51e11--- /dev/null+++ b/mac_app/desktop_mac.py@@ -0,0 +1,66 @@+"""Quartz pointer and display geometry, the Mac twin of win_app/desktop_win.py.++`receiver.py` is handed this module and calls the same three functions on+either machine. Coordinates are Quartz global points -- top-left origin, the+space CGDisplayBounds, CGEventGetLocation and CGWarpMouseCursorPosition all+share -- so values from one feed the others unconverted, exactly as the+Win32 twin's do.++Quartz is imported at module level and guarded the same way clipboard_mac+guards AppKit, so this module stays importable, and its behaviour fakeable,+on a machine without it.+"""++from typing import List, Tuple++from return_edge import Rect++try:+ import Quartz+except ImportError: # pragma: no cover - exercised only off macOS+ Quartz = None++MAX_DISPLAYS = 16+++def _require():+ if Quartz is None:+ raise RuntimeError("Quartz display geometry is only available on macOS")+ return Quartz+++def monitors() -> List[Rect]:+ quartz = _require()+ error, display_ids, _count = quartz.CGGetActiveDisplayList(MAX_DISPLAYS, None, None)+ if error:+ raise RuntimeError(f"CGGetActiveDisplayList failed with error {error}")+ found: List[Rect] = []+ for display_id in display_ids:+ bounds = quartz.CGDisplayBounds(display_id)+ found.append(+ Rect(+ int(round(bounds.origin.x)),+ int(round(bounds.origin.y)),+ int(round(bounds.size.width)),+ int(round(bounds.size.height)),+ )+ )+ return found+++def cursor_position() -> Tuple[int, int]:+ quartz = _require()+ location = quartz.CGEventGetLocation(quartz.CGEventCreate(None))+ return int(round(location.x)), int(round(location.y))+++def set_cursor_position(x: int, y: int) -> None:+ quartz = _require()+ status = quartz.CGWarpMouseCursorPosition(quartz.CGPointMake(float(x), float(y)))+ if status:+ raise RuntimeError(f"CGWarpMouseCursorPosition failed with error {status}")+ # A warp normally suppresses hardware mouse input for a quarter of a+ # second so the pointer does not fight the warp. Beamer warps on every+ # held move at the return edge, so leaving that in place would make the+ # Mac's own trackpad feel dead while the PC is driving it.+ quartz.CGAssociateMouseAndMouseCursorPosition(True)diff --git a/mac_app/gestures.py b/mac_app/gestures.pynew file mode 100644index 0000000..185b77e--- /dev/null+++ b/mac_app/gestures.py@@ -0,0 +1,207 @@+"""Translation of macOS trackpad gestures into wire messages.++Two numberings share the values 29-32 and must not be confused:++At the CGEvent tap (bridge.py), measured on macOS 26.6.2 and documented in+docs/gestures-scope-06-09-2026.md:++ 29 Gesture -- everything two-finger, discriminated by field 110+ 30 DockControl -- a three/four-finger system swipe or thumb-and-three+ pinch, the events Mission Control, Spaces, Show+ desktop and Launchpad are driven by++At the AppKit level (kvm_bridge_app.py's overlay panel), the NSEventType+raw values:++ 29 NSEventTypeGesture (reserved; not translated)+ 30 NSEventTypeMagnify (pinch-to-zoom)+ 31 NSEventTypeSwipe (two-finger swipe between pages)+ 32 NSEventTypeSmartMagnify (reserved; not translated)++`DockSwipeClassifier` handles the tap's DockControl events and emits one+`gesture` message per completed movement. `GestureTranslator` handles the+overlay's NSEvents, turning a pinch into Ctrl+wheel and a page swipe into+Alt+Arrow with no Windows-side change. A zoom gesture was never observed to+reach the tap, so the overlay is the only route for it, and it remains+best-effort.++Everything here is defensive: an unreadable field is logged once and treated+as "no gesture" rather than raised, so a bug or a changed private field on a+future macOS can never take down keyboard/mouse capture. Neither class needs+AppKit or Quartz -- `ns_event` only has to expose `.magnification`,+`.deltaX`, `.deltaY` and `.phase`, and dock `fields` only `.hid`, `.motion`,+`.phase`, `.progress` and `.velocity` -- which keeps the tests free of both.+"""++import logging++import protocol++GESTURE_TYPE = 29+MAGNIFY_TYPE = 30+DOCK_CONTROL_TYPE = 30+SWIPE_TYPE = 31+SMART_MAGNIFY_TYPE = 32++GESTURE_EVENT_TYPES = frozenset({GESTURE_TYPE, MAGNIFY_TYPE, SWIPE_TYPE, SMART_MAGNIFY_TYPE})++# Private CGEvent fields on a DockControl event (numbers from iss, verified by+# probe on macOS 26.6.2): 110 IOHID type, 123 motion axis, 132 phase,+# 124 cumulative signed progress, 129/130 velocity on the ended event.+DOCK_FIELD_HID_TYPE = 110+DOCK_FIELD_MOTION = 123+DOCK_FIELD_PHASE = 132+DOCK_FIELD_PROGRESS = 124+DOCK_FIELD_VELOCITY_X = 129+DOCK_FIELD_VELOCITY_Y = 130++DOCK_SWIPE_HID_TYPE = 23+MOTION_HORIZONTAL = 1+MOTION_VERTICAL = 2+MOTION_PINCH = 3+DOCK_PHASE_ENDED = 4++# A full swipe ends between |0.3| and |0.9|; below this it was a twitch. A+# discrete flick can end with progress still near zero, in which case the+# ended event's velocity carries the direction instead, as iss found.+SWIPE_PROGRESS_THRESHOLD = 0.15++# (name when the sign is negative, name when positive), per motion axis.+# Measured on macOS 26.6.2. iss records the horizontal sign flipping in+# macOS 26 and again in 27, so the table is keyed by major version and an+# unknown version takes the newest entry. The 27 row is iss's report, not a+# measurement here.+_SIGN_TABLES = {+ 26: {+ MOTION_VERTICAL: (protocol.GESTURE_SWIPE_UP, protocol.GESTURE_SWIPE_DOWN),+ MOTION_HORIZONTAL: (protocol.GESTURE_SWIPE_RIGHT, protocol.GESTURE_SWIPE_LEFT),+ MOTION_PINCH: (protocol.GESTURE_SPREAD, protocol.GESTURE_PINCH),+ },+ 27: {+ MOTION_VERTICAL: (protocol.GESTURE_SWIPE_UP, protocol.GESTURE_SWIPE_DOWN),+ MOTION_HORIZONTAL: (protocol.GESTURE_SWIPE_LEFT, protocol.GESTURE_SWIPE_RIGHT),+ MOTION_PINCH: (protocol.GESTURE_SPREAD, protocol.GESTURE_PINCH),+ },+}+++def sign_table_for(macos_major):+ known = sorted(_SIGN_TABLES)+ if macos_major in _SIGN_TABLES:+ return _SIGN_TABLES[macos_major]+ return _SIGN_TABLES[known[-1]]+++class DockSwipeClassifier:+ """Turns the ended event of a DockControl gesture into one gesture+ message. Stateless on purpose: began/changed events carry nothing the+ ended one does not, and a swipe that straddles the moment redirecting+ turns on is not worth tracking."""++ def __init__(self, macos_major=26, logger=None):+ self.logger = logger or logging.getLogger("Beamer")+ self.signs = sign_table_for(macos_major)+ self._warned = False++ def translate(self, fields):+ try:+ if int(fields.hid) != DOCK_SWIPE_HID_TYPE:+ return []+ if int(fields.phase) != DOCK_PHASE_ENDED:+ return []+ names = self.signs.get(int(fields.motion))+ if names is None:+ return []+ value = float(fields.progress)+ if abs(value) < SWIPE_PROGRESS_THRESHOLD:+ value = float(fields.velocity)+ if value == 0.0:+ return []+ return [protocol.gesture_msg(names[0] if value < 0 else names[1])]+ except Exception:+ if not self._warned:+ self._warned = True+ self.logger.debug("failed to read a DockControl event; ignoring", exc_info=True)+ return []++# NSEventPhase bits (AppKit.h). Read defensively via getattr(..., 0): a+# converted event is not guaranteed to expose `.phase` meaningfully (or at+# all) on every macOS version.+NS_EVENT_PHASE_ENDED = 8+NS_EVENT_PHASE_CANCELLED = 16+_PHASE_RESET_MASK = NS_EVENT_PHASE_ENDED | NS_EVENT_PHASE_CANCELLED++# Accumulated `.magnification` needed before one Ctrl+wheel zoom step fires.+# Positive magnification (fingers spreading -- zooming in) maps to a+# positive wheel delta, matching the usual "Ctrl+scroll up zooms in"+# convention in browsers and other zoomable apps.+MAGNIFY_STEP = 0.05+++class GestureTranslator:+ def __init__(self, logger=None):+ self.logger = logger or logging.getLogger("Beamer")+ self._magnify_accum = 0.0+ self._warned_types = set()++ def wants(self, event_type):+ return event_type in GESTURE_EVENT_TYPES++ def translate(self, event_type, ns_event):+ """Return a (possibly empty) list of wire-message dicts for one+ gesture event. Never raises: any failure reading `ns_event` is+ logged once per event type and treated as no gesture."""+ try:+ if event_type == MAGNIFY_TYPE:+ return self._translate_magnify(ns_event)+ if event_type == SWIPE_TYPE:+ return self._translate_swipe(ns_event)+ # Gesture (29) and SmartMagnify (32) are reserved -- no+ # translation defined for them yet.+ return []+ except Exception:+ self._warn_once(event_type)+ return []++ def _warn_once(self, event_type):+ if event_type in self._warned_types:+ return+ self._warned_types.add(event_type)+ self.logger.debug(+ "failed to read gesture event type %r; ignoring", event_type, exc_info=True+ )++ def _translate_magnify(self, ns_event):+ self._magnify_accum += float(ns_event.magnification)+ messages = []+ while abs(self._magnify_accum) >= MAGNIFY_STEP:+ direction = 1 if self._magnify_accum > 0 else -1+ messages.extend(self._zoom_step_messages(direction))+ self._magnify_accum -= direction * MAGNIFY_STEP+ phase = int(getattr(ns_event, "phase", 0) or 0)+ if phase & _PHASE_RESET_MASK:+ self._magnify_accum = 0.0+ return messages++ @staticmethod+ def _zoom_step_messages(direction):+ return [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},+ protocol.scroll_msg(dy=direction, dx=0, mode="line"),+ {"type": protocol.MSG_KEYUP, "data": {"key": "ctrl"}},+ ]++ def _translate_swipe(self, ns_event):+ delta_x = float(ns_event.deltaX)+ if delta_x > 0:+ arrow = "left" # back+ elif delta_x < 0:+ arrow = "right" # forward+ else:+ return []+ return [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},+ {"type": protocol.MSG_KEYDOWN, "data": {"key": arrow}},+ {"type": protocol.MSG_KEYUP, "data": {"key": arrow}},+ {"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},+ ]diff --git a/mac_app/input_injector_mac.py b/mac_app/input_injector_mac.pynew file mode 100644index 0000000..ddb9402--- /dev/null+++ b/mac_app/input_injector_mac.py@@ -0,0 +1,314 @@+"""Quartz CGEvent keyboard and mouse injection, the Mac twin of+win_app/input_injector.py.++`receiver.py` calls the same five functions on either machine. The wire's key+names are already Mac-shaped -- "cmd" is Command here and the Windows key+there -- so the Windows capture does the semantic mapping before sending and+nothing is translated on arrival.++Every event posted from here carries INJECTED_MARK in its source user data,+which is how bridge.py's event tap tells Beamer's own injection apart from+Toby's hands on the Mac: without that the tap would read a pointer the PC is+driving as a push against the Mac's crossing edge and switch input straight+back.++Quartz is imported at module level and guarded the same way clipboard_mac+guards AppKit, so this module stays importable, and its behaviour fakeable,+on a machine without it.+"""++import functools+import logging+import threading+import time+from typing import Dict, List, Optional, Set, Tuple++from key_codes import KEY_NAME_TO_CODE, PRINTABLE_KEY_FALLBACKS++try:+ import Quartz+except ImportError: # pragma: no cover - exercised only off macOS+ Quartz = None++LOGGER = logging.getLogger("Beamer")++# Stamped into every injected event's kCGEventSourceUserData. Any non-zero+# value would do; this one is recognisable in a log.+INJECTED_MARK = 0xBEA3++# A US-layout character to the key that produces it, so a chord like Cmd+C+# lands on the right key rather than arriving as text with no key code. The+# table is the inverse of the one bridge.py reads keys with, so the two+# directions cannot disagree about which key is which.+CHAR_TO_KEY_CODE: Dict[str, int] = {}+for _code, _char in PRINTABLE_KEY_FALLBACKS.items():+ CHAR_TO_KEY_CODE.setdefault(_char, _code)++MODIFIER_FLAG_NAMES = {+ "cmd": "kCGEventFlagMaskCommand",+ "cmd_r": "kCGEventFlagMaskCommand",+ "shift": "kCGEventFlagMaskShift",+ "shift_r": "kCGEventFlagMaskShift",+ "alt": "kCGEventFlagMaskAlternate",+ "alt_r": "kCGEventFlagMaskAlternate",+ "ctrl": "kCGEventFlagMaskControl",+ "ctrl_r": "kCGEventFlagMaskControl",+ "caps_lock": "kCGEventFlagMaskAlphaShift",+}+# The modifiers that make a keystroke a shortcut rather than text. Shift is+# not one of them: a shifted character arrives as the character it produced.+CHORD_MODIFIERS = {"cmd", "cmd_r", "alt", "alt_r", "ctrl", "ctrl_r"}++BUTTONS = ("left", "right", "middle")+# How close together, in seconds and pixels, two clicks must be for the+# second to count as a double click. Matches macOS's own default interval;+# a click whose clickState is never set past 1 can never open a file.+DOUBLE_CLICK_SECONDS = 0.5+DOUBLE_CLICK_SLOP_PX = 5++# Wheel units per line of "line"-mode scroll. Both platforms call one wheel+# notch a line, so this is 1; it is named rather than inlined because it is+# the knob to turn if a mouse wheel feels wrong on the Mac.+LINES_PER_NOTCH = 1.0++_mods_down: Set[str] = set()+_buttons_down: Set[str] = set()+_last_click: Dict[str, Tuple[float, int, int, int]] = {}+_warned_names: Set[str] = set()+# One lock over the held-key bookkeeping and the post it describes: a session+# thread injecting while a reconnect's release_all snapshots and clears would+# otherwise press a key that nothing then remembers to release.+_state_lock = threading.RLock()+++def _locked(function):+ @functools.wraps(function)+ def wrapper(*args, **kwargs):+ with _state_lock:+ return function(*args, **kwargs)++ return wrapper+++def _require():+ if Quartz is None:+ raise RuntimeError("Quartz event injection is only available on macOS")+ return Quartz+++def current_flags(mods_down: Set[str]) -> int:+ quartz = _require()+ flags = 0+ for name in mods_down:+ attribute = MODIFIER_FLAG_NAMES.get(name)+ if attribute is not None:+ flags |= getattr(quartz, attribute)+ return flags+++def plan_key_event(name: str, down: bool, mods_down: Set[str]) -> Optional[Tuple[int, Optional[str]]]:+ """Pure planning: (key code, unicode string or None) for one key, or None+ when there is nothing to send. Mutates `mods_down` exactly as inject_key+ does, so a test can inspect the bookkeeping."""+ lowered = name.lower()+ if lowered in MODIFIER_FLAG_NAMES:+ # Recorded before the event is built, so the modifier's own event+ # already carries the flag it sets -- which is what a flagsChanged+ # event does on real hardware.+ if down:+ mods_down.add(lowered)+ else:+ mods_down.discard(lowered)+ key_code = KEY_NAME_TO_CODE.get(lowered)+ if key_code is not None:+ return key_code, None+ if len(name) != 1:+ if name not in _warned_names:+ LOGGER.warning("Unknown key name ignored: %r", name)+ _warned_names.add(name)+ return None+ key_code = CHAR_TO_KEY_CODE.get(name.lower())+ if key_code is not None and (name.islower() or not name.isalpha() or mods_down):+ return key_code, None+ # A character this layout table cannot place -- an accent, an em dash, a+ # capital with no shift held. Typed as text: it lands correctly in a text+ # field, which is all a character with no chord on it has to do.+ return 0, name+++@_locked+def inject_key(name: str, down: bool) -> None:+ quartz = _require()+ plan = plan_key_event(name, down, _mods_down)+ if plan is None:+ return+ key_code, text = plan+ event = quartz.CGEventCreateKeyboardEvent(None, key_code, bool(down))+ if event is None:+ raise RuntimeError(f"CGEventCreateKeyboardEvent failed for {name!r}")+ if text is None:+ quartz.CGEventSetFlags(event, current_flags(_mods_down))+ else:+ quartz.CGEventKeyboardSetUnicodeString(event, len(text), text)+ # Flags are deliberately cleared: the string says what to type, and+ # leaving shift set would have some apps type it twice over.+ quartz.CGEventSetFlags(event, 0)+ _post(event)+++def clamp_to_displays(x: int, y: int, rects) -> Tuple[int, int]:+ """The nearest point inside a display to (x, y). A move is clamped to the+ display it is already on where it can be, so a pointer on a shorter+ monitor cannot be pushed into the empty space beside a taller one and+ stick there -- which is the same outer-edge rule the return edge uses."""+ if not rects:+ return x, y+ for rect in rects:+ if rect.x <= x <= rect.right and rect.y <= y <= rect.bottom:+ return x, y+ best = None+ for rect in rects:+ cx = min(max(x, rect.x), rect.right)+ cy = min(max(y, rect.y), rect.bottom)+ distance = (cx - x) ** 2 + (cy - y) ** 2+ if best is None or distance < best[0]:+ best = (distance, cx, cy)+ return best[1], best[2]+++def plan_click_state(button: str, x: int, y: int, now: float, last_click: Dict) -> int:+ """Pure planning: the clickState for this press -- 2 for a double click,+ 3 for a triple -- given where and when the last one landed. Mutates+ `last_click`, as inject_mouse_button does."""+ previous = last_click.get(button)+ state = 1+ if previous is not None:+ when, px, py, previous_state = previous+ if (+ now - when <= DOUBLE_CLICK_SECONDS+ and abs(px - x) <= DOUBLE_CLICK_SLOP_PX+ and abs(py - y) <= DOUBLE_CLICK_SLOP_PX+ ):+ state = min(previous_state + 1, 3)+ last_click[button] = (now, x, y, state)+ return state+++MOVE_EVENTS = {+ None: "kCGEventMouseMoved",+ "left": "kCGEventLeftMouseDragged",+ "right": "kCGEventRightMouseDragged",+ "middle": "kCGEventOtherMouseDragged",+}+BUTTON_EVENTS = {+ "left": ("kCGEventLeftMouseDown", "kCGEventLeftMouseUp", "kCGMouseButtonLeft"),+ "right": ("kCGEventRightMouseDown", "kCGEventRightMouseUp", "kCGMouseButtonRight"),+ "middle": ("kCGEventOtherMouseDown", "kCGEventOtherMouseUp", "kCGMouseButtonCenter"),+}+++def _held_button() -> Optional[str]:+ for button in BUTTONS:+ if button in _buttons_down:+ return button+ return None+++def _post(event) -> None:+ quartz = _require()+ quartz.CGEventSetIntegerValueField(event, quartz.kCGEventSourceUserData, INJECTED_MARK)+ quartz.CGEventPost(quartz.kCGHIDEventTap, event)+++def _mouse_event(event_name: str, x: int, y: int, button_name: Optional[str]):+ quartz = _require()+ button = 0 if button_name is None else getattr(quartz, button_name)+ event = quartz.CGEventCreateMouseEvent(+ None, getattr(quartz, event_name), quartz.CGPointMake(float(x), float(y)), button+ )+ if event is None:+ raise RuntimeError(f"CGEventCreateMouseEvent failed for {event_name}")+ quartz.CGEventSetFlags(event, current_flags(_mods_down))+ return event+++def inject_mouse_move(dx: int, dy: int) -> None:+ import desktop_mac++ quartz = _require()+ x, y = desktop_mac.cursor_position()+ x, y = clamp_to_displays(x + int(dx), y + int(dy), desktop_mac.monitors())+ held = _held_button()+ event = _mouse_event(MOVE_EVENTS[held], x, y, None if held is None else BUTTON_EVENTS[held][2])+ # The deltas as well as the point: anything reading raw mouse movement --+ # a game, a 3D viewport -- sees nothing without them.+ quartz.CGEventSetIntegerValueField(event, quartz.kCGMouseEventDeltaX, int(dx))+ quartz.CGEventSetIntegerValueField(event, quartz.kCGMouseEventDeltaY, int(dy))+ _post(event)+++@_locked+def inject_mouse_button(button: str, down: bool) -> None:+ import desktop_mac++ quartz = _require()+ names = BUTTON_EVENTS.get(button)+ if names is None:+ LOGGER.warning("Unknown mouse button ignored: %r", button)+ return+ down_name, up_name, button_name = names+ x, y = desktop_mac.cursor_position()+ event = _mouse_event(down_name if down else up_name, x, y, button_name)+ if down:+ _buttons_down.add(button)+ state = plan_click_state(button, x, y, time.monotonic(), _last_click)+ else:+ _buttons_down.discard(button)+ previous = _last_click.get(button)+ state = previous[3] if previous is not None else 1+ quartz.CGEventSetIntegerValueField(event, quartz.kCGMouseEventClickState, state)+ _post(event)+++def inject_scroll(dy, dx=0.0, mode: str = "line") -> None:+ quartz = _require()+ if mode == "pixel":+ unit = quartz.kCGScrollEventUnitPixel+ wheel_y, wheel_x = int(round(float(dy))), int(round(float(dx)))+ else:+ unit = quartz.kCGScrollEventUnitLine+ wheel_y = int(round(float(dy) * LINES_PER_NOTCH))+ wheel_x = int(round(float(dx) * LINES_PER_NOTCH))+ if not wheel_y and not wheel_x:+ return+ event = quartz.CGEventCreateScrollWheelEvent(None, unit, 2, wheel_y, wheel_x)+ if event is None:+ raise RuntimeError("CGEventCreateScrollWheelEvent failed")+ quartz.CGEventSetFlags(event, current_flags(_mods_down))+ _post(event)+++def inject_gesture(name: str) -> None:+ """Windows sends no gestures -- there is no trackpad event it could+ classify -- so this exists only to keep the injector interface the same+ on both machines."""+ LOGGER.warning("Gesture %r ignored: Beamer does not inject gestures on the Mac", name)+++@_locked+def release_all() -> None:+ """Let go of every key and button this module is holding. Called when the+ link drops mid-chord, so a Command key held at the moment the PC went+ away does not stay down on the Mac."""+ for name in sorted(_mods_down):+ try:+ inject_key(name, down=False)+ except Exception:+ LOGGER.exception("Could not release %r", name)+ 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)+ _mods_down.clear()+ _buttons_down.clear()diff --git a/mac_app/key_codes.py b/mac_app/key_codes.pynew file mode 100644index 0000000..7647a44--- /dev/null+++ b/mac_app/key_codes.py@@ -0,0 +1,113 @@+SPECIAL_KEY_NAMES = {+ 0x24: "enter",+ 0x30: "tab",+ 0x31: "space",+ 0x33: "backspace",+ 0x35: "esc",+ 0x36: "cmd_r",+ 0x37: "cmd",+ 0x38: "shift",+ 0x39: "caps_lock",+ 0x3A: "alt",+ 0x3B: "ctrl",+ 0x3C: "shift_r",+ 0x3D: "alt_r",+ 0x3E: "ctrl_r",+ 0x40: "f17",+ 0x4C: "enter",+ 0x4F: "f18",+ 0x50: "f19",+ 0x5A: "f20",+ 0x60: "f5",+ 0x61: "f6",+ 0x62: "f7",+ 0x63: "f3",+ 0x64: "f8",+ 0x65: "f9",+ 0x67: "f11",+ 0x69: "f13",+ 0x6A: "f16",+ 0x6B: "f14",+ 0x6D: "f10",+ 0x6F: "f12",+ 0x71: "f15",+ 0x72: "insert",+ 0x73: "home",+ 0x74: "page_up",+ 0x75: "delete",+ 0x76: "f4",+ 0x77: "end",+ 0x78: "f2",+ 0x79: "page_down",+ 0x7A: "f1",+ 0x7B: "left",+ 0x7C: "right",+ 0x7D: "down",+ 0x7E: "up",+}++KEY_NAME_TO_CODE = {}+for _code, _name in SPECIAL_KEY_NAMES.items():+ KEY_NAME_TO_CODE.setdefault(_name, _code)++MODIFIER_KEY_CODES = {+ 0x36,+ 0x37,+ 0x38,+ 0x39,+ 0x3A,+ 0x3B,+ 0x3C,+ 0x3D,+ 0x3E,+}++PRINTABLE_KEY_FALLBACKS = {+ 0x00: "a",+ 0x01: "s",+ 0x02: "d",+ 0x03: "f",+ 0x04: "h",+ 0x05: "g",+ 0x06: "z",+ 0x07: "x",+ 0x08: "c",+ 0x09: "v",+ 0x0B: "b",+ 0x0C: "q",+ 0x0D: "w",+ 0x0E: "e",+ 0x0F: "r",+ 0x10: "y",+ 0x11: "t",+ 0x12: "1",+ 0x13: "2",+ 0x14: "3",+ 0x15: "4",+ 0x16: "6",+ 0x17: "5",+ 0x18: "=",+ 0x19: "9",+ 0x1A: "7",+ 0x1B: "-",+ 0x1C: "8",+ 0x1D: "0",+ 0x1E: "]",+ 0x1F: "o",+ 0x20: "u",+ 0x21: "[",+ 0x22: "i",+ 0x23: "p",+ 0x25: "l",+ 0x26: "j",+ 0x27: "'",+ 0x28: "k",+ 0x29: ";",+ 0x2A: "\\",+ 0x2B: ",",+ 0x2C: "/",+ 0x2D: "n",+ 0x2E: "m",+ 0x2F: ".",+ 0x32: "`",+}diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.pynew file mode 100644index 0000000..22e7d95--- /dev/null+++ b/mac_app/kvm_bridge_app.py@@ -0,0 +1,2322 @@+import argparse+import collections+import fcntl+import logging+import logging.handlers+import os+import re+import sys+import threading+import time+from dataclasses import replace+from pathlib import Path++import AppKit+import ApplicationServices+import Quartz+import objc+import rumps+from PyObjCTools import AppHelper++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))++import config as config_module+import crossing+import gestures+import notch_beam+import previews+from notch_beam import NotchBeam+from notch_island import NotchIsland+from bridge import _GestureEventView+import link_state+import login_item+import pages+import protocol+import pairing+from settings_store import (+ SettingsError,+ SettingsStore,+ config_to_raw,+ editable_default_config,+ migrate_legacy_config,+)+import theme+from wake import WakingController, lookup_mac+import widgets+from windows_input import WindowsInput+++LOG_DIRECTORY = Path.home() / "Library" / "Logs" / "Beamer"+LOG_PATH = LOG_DIRECTORY / "Beamer.log"+CAPTURE_RETRY_INTERVAL_SECONDS = 5.0+# The repo-root VERSION file is the one place the version is set; py2app copies it into Resources.+try:+ VERSION = (Path(os.environ.get("RESOURCEPATH") or Path(__file__).resolve().parent.parent) / "VERSION").read_text().strip()+except OSError:+ VERSION = "dev"+FULL_SCREEN_CHECK_INTERVAL_SECONDS = 1.0+# The pages switch between their two layouts at this width of the content pane, beside the sidebar.+WIDE_WIDTH = 600.0+# Accessibility description per menu-bar state. "held" is input on this Mac with the pointer ways+# in off, by a pause or a full-screen app.+MENU_BAR_STATES = {+ "local": "Input on this Mac",+ "held": "Input held on this Mac; crossing is off",+ "windows": "Input on Windows",+}+++def menu_bar_glyph(state):+ """Vernier's template glyph, 22 by 16pt: two screens, the filled one where input is, a chevron+ pointing at it for the way input went, and for crossing held a solid bar closing the gap+ between two outlines. Drawn in black and marked as a template, so macOS tints it for the bar."""++ def draw(_rect):+ AppKit.NSColor.blackColor().set()+ for x, filled in ((1.0, state == "local"), (13.0, state == "windows")):+ if filled:+ AppKit.NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(((x, 2), (8, 12)), 1.5, 1.5).fill()+ else:+ outline = AppKit.NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(((x + 0.75, 2.75), (6.5, 10.5)), 1, 1)+ outline.setLineWidth_(1.5)+ outline.stroke()+ if state == "held":+ AppKit.NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(((10, 0), (2, 16)), 1, 1).fill()+ return True+ tip, tail = (10.0, 12.0) if state == "local" else (12.0, 10.0)+ chevron = AppKit.NSBezierPath.bezierPath()+ chevron.moveToPoint_((tail, 5.5))+ chevron.lineToPoint_((tip, 8.0))+ chevron.lineToPoint_((tail, 10.5))+ chevron.setLineWidth_(1.4)+ chevron.setLineCapStyle_(AppKit.NSLineCapStyleRound)+ chevron.setLineJoinStyle_(AppKit.NSLineJoinStyleRound)+ chevron.stroke()+ return True++ image = AppKit.NSImage.imageWithSize_flipped_drawingHandler_((22, 16), True, draw)+ image.setTemplate_(True)+ image.setAccessibilityDescription_(MENU_BAR_STATES[state])+ return image+++def configure_logging():+ LOG_DIRECTORY.mkdir(parents=True, exist_ok=True, mode=0o700)+ try:+ os.chmod(LOG_DIRECTORY, 0o700)+ except OSError:+ pass+ # The handlers go on the root logger, not "Beamer": the shared modules --+ # receiver, return_edge, pairing -- log under their own names, and with+ # the handlers on "Beamer" everything the PC's input did on this Mac went+ # nowhere, which left the 23-09-2026 stranded mouse with no record here.+ root = logging.getLogger()+ root.setLevel(logging.INFO)+ root.handlers.clear()+ logger = logging.getLogger("Beamer")+ logger.setLevel(logging.INFO)+ logger.handlers.clear()+ formatter = logging.Formatter("%(asctime)s %(levelname)s %(threadName)s %(message)s")+ file_handler = logging.handlers.RotatingFileHandler(+ LOG_PATH,+ maxBytes=1024 * 1024,+ backupCount=3,+ encoding="utf-8",+ )+ file_handler.setFormatter(formatter)+ root.addHandler(file_handler)+ stream_handler = logging.StreamHandler()+ stream_handler.setFormatter(formatter)+ root.addHandler(stream_handler)+ return logger+++def accessibility_granted():+ return bool(+ ApplicationServices.AXIsProcessTrustedWithOptions(+ {ApplicationServices.kAXTrustedCheckOptionPrompt: False}+ )+ )+++def input_monitoring_granted():+ return bool(Quartz.CGPreflightListenEventAccess())+++def acquire_instance_lock():+ lock_path = Path.home() / "Library" / "Application Support" / "Beamer" / "Beamer.lock"+ lock_path.parent.mkdir(parents=True, exist_ok=True)+ handle = lock_path.open("a", encoding="utf-8")+ try:+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError:+ handle.close()+ return None+ return handle+++class _GestureCaptureView(AppKit.NSView):+ """Content view for the invisible gesture-capture overlay panel (see+ GestureOverlay below).++ Bug 3: the CGEventTap-based gesture path (bridge.py's+ _handle_gesture_event, fed by private NSEventType 29-32) is best-effort+ and was observed to never fire at all on macOS 27 beta -- no "gesture+ capture active" log line ever appeared. macOS instead routes trackpad+ gestures to whichever window sits directly under the cursor through+ ordinary, fully-supported NSResponder methods. Since Bug 1's cursor pin+ keeps that location fixed while redirecting, placing this (otherwise+ invisible, input-transparent-looking but not actually+ ignoresMouseEvents) panel there lets it receive gestures the normal way+ -- and because this view consumes them, the local Mac gesture no longer+ fires either.++ NOTE: three/four-finger system gestures (Mission Control, Spaces,+ App Exposé) are consumed by the system compositor before any+ application-level responder -- including this one -- ever sees them.+ Nothing running as a normal app can capture those; they remain local to+ the Mac by OS design, regardless of this overlay.+ """++ def magnifyWithEvent_(self, event):+ self._forward(gestures.MAGNIFY_TYPE, event)++ def swipeWithEvent_(self, event):+ self._forward(gestures.SWIPE_TYPE, event)++ def smartMagnifyWithEvent_(self, event):+ # Reserved, like the tap path's SMART_MAGNIFY_TYPE -- overridden+ # only so this doesn't fall through to a default AppKit handler.+ pass++ @objc.python_method+ def _forward(self, event_type, event):+ controller = getattr(self, "controller", None)+ if controller is None:+ return+ try:+ controller.handle_overlay_gesture(event_type, _GestureEventView(event))+ except Exception:+ # handle_overlay_gesture already guards its own body; this is+ # one more layer of "never let a gesture crash the app".+ logging.getLogger("Beamer").exception("overlay gesture forwarding failed")+++class GestureOverlay:+ """Owns the invisible NSPanel used to capture trackpad gestures while+ redirecting (see _GestureCaptureView above). Every method here touches+ AppKit and must only ever run on the main thread -- it is driven+ exclusively from TrayApp's periodic status-refresh timer (see+ refresh_status), which already runs there, so no locking is needed.++ Creation is attempted lazily, on first use, and any failure disables the+ overlay permanently for this run: gesture capture then simply falls back+ to whatever the (best-effort, possibly nonfunctional) event tap manages+ -- no crash, no regression versus today's behaviour.+ """++ SIZE = 400.0++ def __init__(self, controller, logger):+ self.controller = controller+ self.logger = logger+ self.panel = None+ self.view = None+ self.visible = False+ self.disabled = False++ def sync(self):+ """Call on every status-refresh tick. Shows the panel, repositioned+ on the controller's current cursor pin point, while redirecting;+ hides it the rest of the time. A show can lag the redirect flip by+ up to one tick of that timer (currently 0.4s), which is acceptable."""+ if self.disabled:+ return+ try:+ if self.controller.redirecting:+ self._show()+ else:+ self._hide()+ except Exception:+ self.disabled = True+ self.logger.exception(+ "gesture-capture overlay failed; falling back to tap-only gesture capture"+ )++ def _ensure_panel(self):+ if self.panel is not None:+ return True+ style = (+ AppKit.NSWindowStyleMaskBorderless+ | AppKit.NSWindowStyleMaskNonactivatingPanel+ )+ panel = AppKit.NSPanel.alloc().initWithContentRect_styleMask_backing_defer_(+ AppKit.NSMakeRect(0, 0, self.SIZE, self.SIZE),+ style,+ AppKit.NSBackingStoreBuffered,+ False,+ )+ panel.setLevel_(AppKit.NSStatusWindowLevel)+ panel.setOpaque_(False)+ panel.setHasShadow_(False)+ panel.setBackgroundColor_(AppKit.NSColor.colorWithCalibratedWhite_alpha_(0.0, 0.02))+ panel.setIgnoresMouseEvents_(False)+ panel.setCollectionBehavior_(AppKit.NSWindowCollectionBehaviorCanJoinAllSpaces)+ view = _GestureCaptureView.alloc().initWithFrame_(+ AppKit.NSMakeRect(0, 0, self.SIZE, self.SIZE)+ )+ view.controller = self.controller+ panel.setContentView_(view)+ self.panel = panel+ self.view = view+ return True++ def _show(self):+ self._ensure_panel()+ pin = self.controller.cursor_pin_point+ if pin is not None:+ half = self.SIZE / 2.0+ screen = AppKit.NSScreen.mainScreen()+ # CGEventGetLocation reports a top-left-origin Quartz point;+ # AppKit screen coordinates are bottom-left-origin. Flipping+ # against the main screen's height is only exactly right for an+ # un-rotated single-display setup, which is an acceptable+ # approximation for this best-effort overlay -- worst case it's+ # centered a bit off on an unusual multi-display arrangement,+ # not that gestures stop working.+ screen_height = screen.frame().size.height if screen is not None else pin.y * 2+ frame = AppKit.NSMakeRect(pin.x - half, screen_height - pin.y - half, self.SIZE, self.SIZE)+ self.panel.setFrame_display_(frame, False)+ # Never makeKey/makeMain -- this must not steal focus from whatever+ # the user is actually looking at.+ self.panel.orderFrontRegardless()+ self.visible = True++ def _hide(self):+ if self.panel is None or not self.visible:+ return+ self.panel.orderOut_(None)+ self.visible = False+++def notch_x_range():+ """The notch's x-range in global points, or None on a Mac without one. Derived from the+ two auxiliary top areas rather than hard-coded, and only when the notched screen forms the+ top of the desktop, because the engine tests it against the top of the bounding box. Only x+ is read, and x is the one axis AppKit and Quartz agree on, so nothing is flipped."""+ screens = AppKit.NSScreen.screens()+ if not screens:+ return None+ desktop_top = max(screen.frame().origin.y + screen.frame().size.height for screen in screens)+ for screen in screens:+ frame = screen.frame()+ if frame.origin.y + frame.size.height != desktop_top:+ continue+ try:+ if screen.safeAreaInsets().top <= 0:+ continue+ left = screen.auxiliaryTopLeftArea()+ right = screen.auxiliaryTopRightArea()+ except AttributeError:+ continue+ if left is None or right is None or left.size.width <= 0 or right.size.width <= 0:+ continue+ return (left.origin.x + left.size.width, right.origin.x)+ return None+++def full_screen_app():+ """The frontmost app's name while it is full screen, else None.++ The signal that works is Accessibility's `AXFullScreen` on the frontmost app's focused+ window. Beamer already holds Accessibility for its event tap, so this costs no new+ permission. Measured 10-09-2026 against Chrome driven by the OS's own Enter Full Screen+ shortcut: False windowed, True full screen, False again on leaving.++ ⚠ Three plausible signals were measured and do NOT work, so nobody should try them again:+ `currentSystemPresentationOptions()` stays 0, because that bit is for apps that request+ full-screen presentation explicitly rather than the green button; `NSMenu.menuBarVisible()`+ stays True throughout; and the window server reports a full-screen app's windows as+ fragments (1728x33, 1728x41, 1728x962 ...) rather than one window the size of the display,+ so a bounds comparison never matches. The bounds test is kept only as a fallback for a+ borderless full-screen game, which really is one window sized to the display and may not+ expose AXFullScreen at all.++ ⚠ Also measured: Chrome's AppleScript `fullscreen` property does not enter full screen, and+ believing it does produces a confident wrong answer. Drive the OS shortcut when testing.++ Main thread, once a second."""+ app = AppKit.NSWorkspace.sharedWorkspace().frontmostApplication()+ if app is None:+ return None+ name = app.localizedName() or "An app"+ if _ax_full_screen(app.processIdentifier()):+ return name+ error, displays, count = Quartz.CGGetActiveDisplayList(16, None, None)+ if error != 0:+ raise RuntimeError(f"CGGetActiveDisplayList failed: {error}")+ display_frames = []+ for display in list(displays)[:count]:+ rect = Quartz.CGDisplayBounds(display)+ display_frames.append((rect.origin.x, rect.origin.y, rect.size.width, rect.size.height))+ windows = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListOptionOnScreenOnly, Quartz.kCGNullWindowID)+ if _covers_a_display(windows or (), app.processIdentifier(), display_frames):+ return name+ return None+++def _ax_full_screen(pid) -> bool:+ """AXFullScreen on that process's focused window. False on any Accessibility error --+ a process with no focused window, or one that exposes no such attribute, is not full+ screen as far as crossing is concerned, and this must never raise into the tap's path."""+ try:+ element = ApplicationServices.AXUIElementCreateApplication(pid)+ error, window = ApplicationServices.AXUIElementCopyAttributeValue(+ element, "AXFocusedWindow", None)+ if error != 0 or window is None:+ return False+ error, value = ApplicationServices.AXUIElementCopyAttributeValue(+ window, "AXFullScreen", None)+ return error == 0 and bool(value)+ except Exception:+ return False+++def _covers_a_display(windows, pid, display_frames):+ """Whether that process has an ordinary window sized to a whole display — the borderless+ full-screen game that exposes no AXFullScreen. Both halves of this are load-bearing.++ ⚠ Only layer 0. Finder's desktop window, WindowManager's wallpaper and the window server's+ backstop are all exactly display-sized, so without the layer test clicking the desktop put+ Finder frontmost and switched crossing off.++ ⚠ The window must start at the display's own top and match its full height. There used to be+ slack of the screen's safe-area inset here, for a game that sits under the menu bar; on a+ notched Mac that inset IS the menu bar height, so every ordinary zoomed window (0, 33,+ 1728x1084 on this MacBook) matched it and crossing died the moment any other app came+ forward. A game that respects the safe area is indistinguishable from a zoomed window, and+ losing crossing daily is the worse of the two errors."""+ for info in windows:+ if info.get("kCGWindowOwnerPID") != pid or info.get("kCGWindowLayer") != 0:+ continue+ bounds = info.get("kCGWindowBounds") or {}+ for x, y, width, height in display_frames:+ if (+ abs((bounds.get("X") or 0) - x) <= 1+ and abs((bounds.get("Y") or 0) - y) <= 1+ and abs((bounds.get("Width") or 0) - width) <= 1+ and abs((bounds.get("Height") or 0) - height) <= 1+ ):+ return True+ return False+++class Haptics:+ """Force Touch trackpad feedback for crossing. A Mac with a mouse or an older trackpad gets+ a performer that does nothing, and any failure switches haptics off for the run rather than+ ever reaching the crossing path."""++ def __init__(self, logger):+ self.logger = logger+ try:+ self.performer = AppKit.NSHapticFeedbackManager.defaultPerformer()+ except Exception:+ self.performer = None+ self.logger.exception("haptic feedback unavailable")++ def tick(self, feel="medium"):+ """`feel` is crossing.haptic_feel: light, medium or firm, macOS's three patterns."""+ self._perform({+ "light": AppKit.NSHapticFeedbackPatternGeneric,+ "firm": AppKit.NSHapticFeedbackPatternLevelChange,+ }.get(feel, AppKit.NSHapticFeedbackPatternAlignment))++ def thud(self):+ self._perform(AppKit.NSHapticFeedbackPatternLevelChange)++ def _perform(self, pattern):+ if self.performer is None:+ return+ try:+ self.performer.performFeedbackPattern_performanceTime_(+ pattern, AppKit.NSHapticFeedbackPerformanceTimeNow+ )+ except Exception:+ self.performer = None+ self.logger.exception("haptic feedback failed; haptics off for this run")+++class EdgeGlow:+ """A band along the edge being pushed, in `crossing.glow_colour`: the `glow` style's width and+ opacity track pressure, the `beam` style is a thin line with a comet travelling it that runs on+ off the end at breakthrough, and both flash when the push goes through. The same borderless non-activating panel+ as GestureOverlay, with two differences that matter: it ignores mouse events, or it would+ eat the very push it is drawing, and it joins full-screen spaces as an auxiliary window so+ it sits above a full-screen app.++ Main thread only, like GestureOverlay. Pressure changes arrive through `update`; a timer+ then redraws at 30Hz until both the pressure and the flash have faded, since nothing+ arrives from the tap once the push stops. Any failure disables the glow for the run."""++ BAND_MAX = 18.0+ FLASH_SECONDS = 0.18+ PREVIEW_SECONDS = 0.6++ def __init__(self, controller, logger):+ self.controller = controller+ self.logger = logger+ self.panel = None+ self.fill = None+ self.comet = None+ self.visible = False+ self.disabled = False+ self.mac_edge = None+ self.region = None+ self.flash_at = None+ self.finish = 0.0+ self.centre = -notch_beam.EDGE_COMET / 2.0+ self.drawn_at = None+ self.preview_level = 0.0+ self.preview_until = 0.0+ self.timer = rumps.Timer(self._tick, 1 / 30)++ def update(self, kind, step):+ if self.disabled:+ return+ try:+ if kind == "cross":+ self.flash_at = time.monotonic()+ self.finish = 1.0+ elif kind not in ("pressure", "tick"):+ return+ elif not self.visible:+ self.centre = -notch_beam.EDGE_COMET / 2.0+ self.mac_edge = step.mac_edge+ self.region = step.region+ self._draw()+ except Exception:+ self._fail()++ def preview(self, mac_edge, level):+ """Lights the configured edge at `level` for a moment, for the resistance slider."""+ if self.disabled:+ return+ try:+ bounds = self.controller._current_desktop_bounds()+ self.mac_edge = mac_edge+ self.region = crossing.CrossingEngine._strip(mac_edge, bounds)+ self.preview_level = level+ self.preview_until = time.monotonic() + self.PREVIEW_SECONDS+ self._draw()+ except Exception:+ self._fail()++ def _fail(self):+ self.disabled = True+ self.logger.exception("edge glow failed; glow off for this run")+ try:+ self._hide()+ except Exception:+ pass++ def _tick(self, _timer):+ if self.disabled:+ self.timer.stop()+ return+ try:+ self._draw()+ except Exception:+ self._fail()+ self.timer.stop()++ def _draw(self):+ now = time.monotonic()+ elapsed = 0.0 if self.drawn_at is None else min(0.1, now - self.drawn_at)+ self.drawn_at = now+ feel = self.controller.cfg.crossing+ beam = feel["glow_style"] == "beam"+ level = self.controller.crossing_pressure_now()+ if now < self.preview_until:+ level = max(level, self.preview_level)+ flash = 0.0+ if self.flash_at is not None:+ flash = max(0.0, 1.0 - (now - self.flash_at) / self.FLASH_SECONDS)+ if flash <= 0.0:+ self.flash_at = None+ comet = notch_beam.EDGE_COMET+ if self.finish > 0.0:+ # Run on off the end of the edge instead of stopping, and never wrap back to the start.+ self.centre = min(1.0 + comet, self.centre + elapsed / notch_beam.EDGE_FINISH_TRAVERSE_S)+ self.finish = max(0.0, self.finish - elapsed / notch_beam.EDGE_FINISH_S)+ elif level > 0.0:+ self.centre += elapsed / notch_beam.edge_traverse_seconds(level)+ if self.centre > 1.0 + comet / 2.0:+ self.centre = -comet / 2.0+ lingering = self.finish if beam else 0.0+ if (level <= 0.0 and flash <= 0.0 and lingering <= 0.0) or self.region is None or self.mac_edge is None:+ self._hide()+ self.timer.stop()+ self.drawn_at = None+ return+ self._ensure_panel()+ strength = max(level, flash, lingering)+ band = 3.0 + 3.0 * strength if beam else 2.0 + self.BAND_MAX * strength+ self.panel.setFrame_display_(self._band_frame(band), False)+ # Colour runs along the edge: top to bottom on a side, left to right along the top or bottom.+ start, end = ((0.5, 1.0), (0.5, 0.0)) if self.mac_edge in ("left", "right") else ((0.0, 0.5), (1.0, 0.5))+ Quartz.CATransaction.begin()+ Quartz.CATransaction.setDisableActions_(True)+ try:+ bounds = self.panel.contentView().bounds()+ for layer in (self.fill, self.comet):+ layer.setFrame_(bounds)+ layer.setStartPoint_(start)+ layer.setEndPoint_(end)+ self.fill.setColors_(notch_beam.palette_colours(feel["glow_colour"]))+ if beam:+ stops = [index / 24 for index in range(25)]+ self.comet.setLocations_(stops)+ self.comet.setColors_([+ AppKit.NSColor.colorWithWhite_alpha_(1.0, notch_beam.edge_comet_alpha(at, self.centre, flash)).CGColor()+ for at in stops+ ])+ self.fill.setMask_(self.comet)+ self.fill.setOpacity_(min(1.0, strength))+ else:+ self.fill.setMask_(None)+ self.fill.setOpacity_(min(1.0, 0.3 + 0.7 * level + 0.6 * flash))+ finally:+ Quartz.CATransaction.commit()+ if not self.visible:+ self.panel.orderFrontRegardless()+ self.visible = True+ if not getattr(self.timer, "is_alive", lambda: False)():+ self.timer.start()++ def _band_frame(self, band):+ """The band grows inward from the strip the engine reported. Quartz rects are top-left+ origin and AppKit frames bottom-left; the flip is about the primary screen's height,+ which is exact for every arrangement because every screen is placed relative to it."""+ x, y, width, height = self.region+ edge = self.mac_edge+ if width <= crossing.CORNER_PX and height <= crossing.CORNER_PX:+ # A corner box: grow it inward on both axes.+ size = crossing.CORNER_PX + band+ top = self.controller._current_desktop_bounds()[1]+ x = x if edge == "left" else x + width - size+ y = y if y <= top else y + height - size+ width = height = size+ elif edge == "right":+ x, width = x + width - band, band+ elif edge == "left":+ width = band+ elif edge == "top":+ height = band+ else:+ y, height = y + height - band, band+ primary_height = AppKit.NSScreen.screens()[0].frame().size.height+ return AppKit.NSMakeRect(x, primary_height - (y + height), width, height)++ def _ensure_panel(self):+ if self.panel is not None:+ return+ panel = AppKit.NSPanel.alloc().initWithContentRect_styleMask_backing_defer_(+ AppKit.NSMakeRect(0, 0, 1, 1),+ AppKit.NSWindowStyleMaskBorderless | AppKit.NSWindowStyleMaskNonactivatingPanel,+ AppKit.NSBackingStoreBuffered,+ False,+ )+ panel.setLevel_(AppKit.NSStatusWindowLevel)+ panel.setOpaque_(False)+ panel.setHasShadow_(False)+ panel.setBackgroundColor_(AppKit.NSColor.clearColor())+ panel.setIgnoresMouseEvents_(True)+ panel.setCollectionBehavior_(+ AppKit.NSWindowCollectionBehaviorCanJoinAllSpaces+ | AppKit.NSWindowCollectionBehaviorFullScreenAuxiliary+ )+ view = AppKit.NSView.alloc().initWithFrame_(AppKit.NSMakeRect(0, 0, 1, 1))+ view.setWantsLayer_(True)+ panel.setContentView_(view)+ self.fill = Quartz.CAGradientLayer.layer()+ view.layer().addSublayer_(self.fill)+ self.comet = Quartz.CAGradientLayer.layer()+ self.panel = panel++ def _hide(self):+ if self.panel is None or not self.visible:+ return+ self.panel.orderOut_(None)+ self.visible = False+++def install_main_menu(control_window):+ """rumps builds a status-bar menu and no main menu at all, and Beamer is not a status-bar-only+ app: it shows a real window with text fields in it. Cmd+Q is not built into AppKit — it is the+ key equivalent of the Quit item in the application menu — so with no main menu the app could+ not be quit from the keyboard, and Cmd+C/V/A in the token field did nothing either."""+ def item(menu, title, action, key, modifiers=None, target=None):+ entry = menu.addItemWithTitle_action_keyEquivalent_(title, action, key)+ if modifiers is not None:+ entry.setKeyEquivalentModifierMask_(modifiers)+ if target is not None:+ entry.setTarget_(target)+ return entry++ main_menu = AppKit.NSMenu.alloc().init()++ application_item = main_menu.addItemWithTitle_action_keyEquivalent_("Beamer", None, "")+ application_menu = AppKit.NSMenu.alloc().initWithTitle_("Beamer")+ item(application_menu, "Hide Beamer", "hide:", "h")+ item(+ application_menu,+ "Hide Others",+ "hideOtherApplications:",+ "h",+ AppKit.NSEventModifierFlagCommand | AppKit.NSEventModifierFlagOption,+ )+ application_menu.addItem_(AppKit.NSMenuItem.separatorItem())+ item(application_menu, "Quit Beamer", "quitApp:", "q", target=control_window)+ main_menu.setSubmenu_forItem_(application_menu, application_item)++ edit_item = main_menu.addItemWithTitle_action_keyEquivalent_("Edit", None, "")+ edit_menu = AppKit.NSMenu.alloc().initWithTitle_("Edit")+ item(edit_menu, "Undo", "undo:", "z")+ item(+ edit_menu,+ "Redo",+ "redo:",+ "z",+ AppKit.NSEventModifierFlagCommand | AppKit.NSEventModifierFlagShift,+ )+ edit_menu.addItem_(AppKit.NSMenuItem.separatorItem())+ item(edit_menu, "Cut", "cut:", "x")+ item(edit_menu, "Copy", "copy:", "c")+ item(edit_menu, "Paste", "paste:", "v")+ item(edit_menu, "Select All", "selectAll:", "a")+ main_menu.setSubmenu_forItem_(edit_menu, edit_item)++ view_item = main_menu.addItemWithTitle_action_keyEquivalent_("View", None, "")+ view_menu = AppKit.NSMenu.alloc().initWithTitle_("View")+ for index, page in enumerate(pages.PAGES):+ item(view_menu, page[1], "showPage:", str(index + 1), target=control_window).setTag_(index)+ main_menu.setSubmenu_forItem_(view_menu, view_item)++ window_item = main_menu.addItemWithTitle_action_keyEquivalent_("Window", None, "")+ window_menu = AppKit.NSMenu.alloc().initWithTitle_("Window")+ # No target, so these travel the responder chain to whichever window is key rather than+ # being bound to one. Closing is safe to offer because the control window is created with+ # setReleasedWhenClosed_(False) and the menu-bar item reopens it.+ item(window_menu, "Close", "performClose:", "w")+ item(window_menu, "Minimise", "performMiniaturize:", "m")+ main_menu.setSubmenu_forItem_(window_menu, window_item)+ AppKit.NSApp.setWindowsMenu_(window_menu)++ AppKit.NSApp.setMainMenu_(main_menu)+++class FlippedView(AppKit.NSView):+ """A plain view that lays out top-down, so the scrolling page starts at the top of the window+ rather than the bottom of the document."""++ def isFlipped(self):+ return True+++class ControlWindow(AppKit.NSObject):+ def initWithController_settingsStore_logger_(self, controller, settings_store, logger):+ self = objc.super(ControlWindow, self).init()+ if self is None:+ return None+ self.controller = controller+ self.settings_store = settings_store+ self.logger = logger+ # Set by TrayApp once it exists: the listener for the PC's input, and+ # the second way an arrangement changed here can reach the PC.+ self.windows_input = None+ self.last_capture_attempt = 0.0+ # Set by TrayApp: the beacon listener whose PCs the Pair module lists.+ self.discovery = None+ self._pcs = []+ self._pcs_key = None+ self.chosen_pc = None+ self._pairing = False+ self._preview_flashes = 0+ self.latency = collections.deque(maxlen=widgets.Spark.SAMPLES)+ self.wide = None+ # Set by TrayApp: lights the chosen edge while the resistance ruler moves.+ self.preview = None+ self.has_notch = False+ # Set by TrayApp, for the Design page's Try it; the page builds its own preview loop.+ self.haptics = None+ self.previews = None+ self._apply_serial = 0+ self.page = None+ self.opened = False+ self.window = AppKit.NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(+ ((0, 0), (900, 640)),+ AppKit.NSWindowStyleMaskTitled+ | AppKit.NSWindowStyleMaskClosable+ | AppKit.NSWindowStyleMaskMiniaturizable+ | AppKit.NSWindowStyleMaskResizable,+ AppKit.NSBackingStoreBuffered,+ False,+ )+ self.window.setTitle_("Beamer")+ self.window.setReleasedWhenClosed_(False)+ self.window.setDelegate_(self)+ self.window.setContentMinSize_(AppKit.NSMakeSize(*theme.MIN_WINDOW))+ # Vernier is dark only: the window pins to the palette rather than following the Mac's+ # appearance, and the transparent title bar takes the window's own ground.+ self.window.setAppearance_(AppKit.NSAppearance.appearanceNamed_(AppKit.NSAppearanceNameDarkAqua))+ self.window.setBackgroundColor_(theme.colour("ground"))+ self.window.setTitlebarAppearsTransparent_(True)+ self.window.center()+ content = self.window.contentView()+ content.setWantsLayer_(True)+ content.layer().setBackgroundColor_(theme.colour("ground").CGColor())++ top = widgets.hairline()+ self.sidebar = widgets.Sidebar(pages.PAGES, self._select_page)+ divider = widgets.box("rule")+ pane = widgets.stack(spacing=0)+ for view in (top, self.sidebar.view, divider, pane):+ content.addSubview_(view)+ self.sidebar_width = self.sidebar.view.widthAnchor().constraintEqualToConstant_(theme.SIDEBAR_WIDTH[1])+ AppKit.NSLayoutConstraint.activateConstraints_([+ top.topAnchor().constraintEqualToAnchor_(content.topAnchor()),+ top.leadingAnchor().constraintEqualToAnchor_(content.leadingAnchor()),+ top.trailingAnchor().constraintEqualToAnchor_(content.trailingAnchor()),+ self.sidebar_width,+ self.sidebar.view.topAnchor().constraintEqualToAnchor_(top.bottomAnchor()),+ self.sidebar.view.bottomAnchor().constraintEqualToAnchor_(content.bottomAnchor()),+ self.sidebar.view.leadingAnchor().constraintEqualToAnchor_(content.leadingAnchor()),+ divider.widthAnchor().constraintEqualToConstant_(1),+ divider.topAnchor().constraintEqualToAnchor_(top.bottomAnchor()),+ divider.bottomAnchor().constraintEqualToAnchor_(content.bottomAnchor()),+ divider.leadingAnchor().constraintEqualToAnchor_(self.sidebar.view.trailingAnchor()),+ pane.topAnchor().constraintEqualToAnchor_(top.bottomAnchor()),+ pane.bottomAnchor().constraintEqualToAnchor_(content.bottomAnchor()),+ pane.leadingAnchor().constraintEqualToAnchor_(divider.trailingAnchor()),+ pane.trailingAnchor().constraintEqualToAnchor_(content.trailingAnchor()),+ ])+ # The page host is the only part of the pane that gives way when the window is resized;+ # the commit bar keeps its height on every page.+ host = widgets.box()+ host.setContentHuggingPriority_forOrientation_(+ AppKit.NSLayoutPriorityDefaultLow, AppKit.NSLayoutConstraintOrientationVertical+ )+ host.setContentCompressionResistancePriority_forOrientation_(+ AppKit.NSLayoutPriorityDefaultLow, AppKit.NSLayoutConstraintOrientationVertical+ )+ widgets.add(pane, host)+ widgets.add(pane, widgets.hairline())+ widgets.add(pane, self._commit())++ self.page_titles = []+ self.page_paddings = []+ self.pages = {}+ builders = {+ "overview": self._overview_page,+ "crossing": self._crossing_page,+ "design": self._design_page,+ "keyboard": self._keyboard_page,+ "pairing": self._pairing_page,+ "connection": self._connection_page,+ "permissions": self._permissions_page,+ }+ for key, name, _symbol, purpose in pages.PAGES:+ scroll, body = self._page(name, purpose)+ host.addSubview_(scroll)+ widgets.pin(scroll, host)+ scroll.setHidden_(True)+ self.pages[key] = scroll+ builders[key](body)++ self._load(config_to_raw(controller.cfg))+ self._select_page(pages.opening_page(None, accessibility_granted(), input_monitoring_granted()))+ self.windowDidResize_(None)+ self.refresh()+ return self++ def windowDidResize_(self, _notification):+ width = self.window.contentView().frame().size.width+ low, high = theme.SIDEBAR_WIDTH+ sidebar = min(high, max(low, width * 0.25))+ self.sidebar_width.setConstant_(sidebar)+ self._apply_width(width - sidebar - 1)++ @objc.python_method+ def _apply_width(self, width):+ """Two layouts, not a continuous reflow. Wide, the Overview's two controls sit side by+ side and Pairing puts the PC list beside the code; narrow, both stack and the large+ figures step down a size."""+ wide = width >= WIDE_WIDTH+ if wide == self.wide:+ return+ self.wide = wide+ narrow = not wide+ self.daily.arrange([[(0, 1), (1, 1)]] if wide else [[(0, 1)], [(1, 1)]], 2 if wide else 1)+ top, leading, bottom, trailing = theme.PAGE_PADDING_NARROW if narrow else theme.PAGE_PADDING+ for constraints in self.page_paddings:+ for constraint, constant in zip(constraints, (top, leading, bottom, trailing)):+ constraint.setConstant_(constant)+ for title in self.page_titles:+ title.set(size=theme.PAGE_TITLE_NARROW if narrow else theme.PAGE_TITLE)+ self.state_word.set(size=theme.TYPE["status_word_narrow" if narrow else "status_word"])+ for readout in (self.round_trip, self.resistance_readout, self.peer):+ readout.set_narrow(narrow)+ numeral = theme.TYPE["numeral_narrow" if narrow else "numeral"]+ self.resistance_numeral.set(size=numeral)+ self.double_tap_numeral.set(size=numeral)+ # Stacked, each half takes the full width; side by side, FillEqually shares it. The+ # distribution runs along the orientation, so stacked it must go back to Fill.+ self._show_peer()+ AppKit.NSLayoutConstraint.deactivateConstraints_(self.pair_stacked)+ self.pair_grid.setOrientation_(+ AppKit.NSUserInterfaceLayoutOrientationHorizontal if wide else AppKit.NSUserInterfaceLayoutOrientationVertical+ )+ self.pair_grid.setDistribution_(+ AppKit.NSStackViewDistributionFillEqually if wide else AppKit.NSStackViewDistributionFill+ )+ if narrow:+ AppKit.NSLayoutConstraint.activateConstraints_(self.pair_stacked)++ @objc.python_method+ def _select_page(self, key):+ self.page = key+ for name, scroll in self.pages.items():+ scroll.setHidden_(name != key)+ self.sidebar.select(key)+ self._run_previews()++ @objc.python_method+ def _run_previews(self):+ """The previews play only while someone can see them: the Design page open in a visible+ window, with crossing animations switched on."""+ if self.previews is None:+ return+ if self.page == "design" and self.window.isVisible() and self.glow_box.value:+ self.previews.start()+ else:+ self.previews.stop()++ def showPage_(self, sender):+ self.opened = True+ self._select_page(pages.KEYS[sender.tag()])+ self.show()+ @objc.python_method+ def _load(self, raw):+ self.host_field.setStringValue_(str(raw["host"]))+ self.port_field.setStringValue_(str(raw["port"]))+ self.token_field.setStringValue_(str(raw["auth_token"]))+ self.token_plain.setStringValue_(str(raw["auth_token"]))+ self._say_pairing("Choose a PC, then type the code it shows.")+ self.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"]))+ self.modifier_select.value = raw["key_map"] if isinstance(raw["key_map"], str) else "custom"+ crossing_raw = raw["crossing"]+ for name, tile in self.method_boxes.items():+ tile.value = name in crossing_raw["methods"]+ self.edge_select.value = crossing_raw["edge"]+ self.corner_select.value = crossing_raw["corner"]+ self.resistance_ruler.value = crossing_raw["resistance_px"]+ self.haptics_box.value = crossing_raw["haptics"]+ self.glow_box.value = crossing_raw["glow"]+ self.dragging_box.value = crossing_raw["block_while_dragging"]+ self.notch_style_select.value = crossing_raw["notch_style"]+ self.notch_after_select.value = crossing_raw["notch_after_ms"]+ self.tick_feel_select.value = crossing_raw["haptic_feel"]+ self.tick_steps_select.value = crossing_raw["haptic_steps"]+ self.glow_style_select.value = crossing_raw["glow_style"]+ self.glow_colour_select.value = crossing_raw["glow_colour"]+ self._reflect()++ @objc.python_method+ def _reflect(self, *_ignored):+ """Enables each control only when the setting it edits is in play, and keeps the figures+ beside the rulers in step with them."""+ self.edge_select.set_enabled(self.method_boxes["edge"].value)+ self.corner_select.set_enabled(self.method_boxes["corner"].value)+ notch = self.method_boxes["notch"]+ notch.set_enabled(self.has_notch)+ haptics, glow = self.haptics_box.value, self.glow_box.value+ for control in (self.tick_feel_select, self.tick_steps_select, self.try_button):+ control.set_enabled(haptics)+ for control in (self.notch_style_select, self.notch_after_select, self.glow_style_select, self.glow_colour_select):+ control.set_enabled(glow)+ self.tick_note.set(+ {+ "quarters": "A tick at a quarter, half and three quarters of the push, then a firmer one as the pointer goes through.",+ "halves": "One tick halfway through the push, then a firmer one as the pointer goes through.",+ "breakthrough": "Nothing on the way in, then one firm tick as the pointer goes through.",+ }.get(self.tick_steps_select.value, "")+ if haptics+ else "Off: the trackpad stays still while you push."+ )+ after = (self.notch_after_select.value or 1200) / 1000+ self.notch_note.set(+ f"Once the pointer is through to Windows the notch keeps playing for {after:g} seconds, so the "+ "animation finishes instead of cutting off."+ + ("" if self.has_notch else " There is no notch at the top of the desktop right now, so nothing plays there.")+ )+ self._run_previews()+ notch_range = self.controller.notch_range+ 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))+ hold = self.style_select.value == "hold"+ self.double_tap_ruler.set_enabled(not hold)+ self.double_tap_head.setAlphaValue_(0.4 if hold else 1.0)+ self.style_hint.set(+ "Input is on Windows for as long as the key is held."+ if hold+ else "Tap twice to switch; tap twice again to come back."+ )+ resistance = self.resistance_ruler.value+ self.resistance_numeral.set(str(resistance))+ self.resistance_readout.value.set(str(resistance))+ self.resistance_scale.fraction = min(1.0, max(0.0, resistance / 500.0))+ self.resistance_scale.setNeedsDisplay_(True)+ self.resistance_hint.set(+ "Switches the moment the pointer touches the edge."+ if resistance == 0+ else f"How far to push past the edge before it gives. It applies as you drag, and lights the {self.edge_select.value} edge so you can see the size of it."+ )+ if self._preview_flashes == 0:+ self._place_preview(theme.PREVIEW_REST)+ self.modifier_note.set({+ "semantic": "Semantic: Command sends Control, Control sends the Windows key.",+ "positional": "Positional: Command sends the Windows key.",+ }.get(self.modifier_select.value, "Custom: the key map in config.json is kept as it is."))++ @objc.python_method+ def _preview_resistance(self, value):+ # Applied to the live engine at once, so the edge can be felt mid-drag; the saved setting+ # 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:+ self.preview(self.edge_select.value, min(1.0, value / 500.0))+ self._flash_preview(min(1.0, value / 500.0))++ @objc.python_method+ def _show_peer(self):+ cfg = self.controller.cfg+ self.peer.value.set(link_state.peer_name(cfg))+ if not cfg.host:+ self.peer_footer.set("Not paired")+ else:+ # The port does not fit a third of the status module at the narrow grid.+ self.peer_footer.set(f"{cfg.host}:{cfg.port}" if self.wide else cfg.host)++ @objc.python_method+ def _flash_preview(self, level):+ self._place_preview(0.3 + 0.7 * level)+ self._preview_flashes += 1+ flash = self._preview_flashes++ def fade():+ if flash != self._preview_flashes:+ return+ Quartz.CATransaction.begin()+ Quartz.CATransaction.setAnimationDuration_(0.6)+ self.preview_glow.setOpacity_(theme.PREVIEW_REST)+ Quartz.CATransaction.commit()++ AppHelper.callLater(0.5, fade)++ @objc.python_method+ def _place_preview(self, opacity):+ width, height = 44.0, 28.0+ frames = {+ "left": (((0, 0), (7, height)), (1, 0.5), (0, 0.5)),+ "right": (((width - 7, 0), (7, height)), (0, 0.5), (1, 0.5)),+ "top": (((0, height - 7), (width, 7)), (0.5, 0), (0.5, 1)),+ "bottom": (((0, 0), (width, 7)), (0.5, 1), (0.5, 0)),+ }+ frame, start, end = frames.get(self.edge_select.value, frames["right"])+ Quartz.CATransaction.begin()+ Quartz.CATransaction.setDisableActions_(True)+ self.preview_glow.setFrame_(frame)+ self.preview_glow.setStartPoint_(start)+ self.preview_glow.setEndPoint_(end)+ self.preview_glow.setOpacity_(opacity)+ Quartz.CATransaction.commit()++ @objc.python_method+ def _double_tap_moved(self, value):+ self.double_tap_numeral.set(str(value))+ self._changed()++ @objc.python_method+ def _changed(self, *_ignored):+ """Every control outside the Connection page calls this. The settings are written and+ applied once the control has been still for a moment, so a ruler being dragged writes once+ at the end rather than on every step."""+ self._reflect()+ self._apply_serial += 1+ serial = self._apply_serial+ AppHelper.callLater(0.3, lambda: serial == self._apply_serial and self._apply_settings())++ def windowWillClose_(self, _notification):+ self.key_recorder.cancel()+ if self.previews is not None:+ self.previews.stop()++ @objc.python_method+ def _head(self, title, figure):+ line = widgets.stack(vertical=False, spacing=12)+ line.setAlignment_(AppKit.NSLayoutAttributeTop)+ line.addArrangedSubview_(widgets.hug(widgets.eyebrow(title), AppKit.NSLayoutPriorityDefaultLow))+ line.addArrangedSubview_(figure)+ return line++ @objc.python_method+ def _numeral(self, unit):+ """A big mono figure and its unit. Returns (view, Figure)."""+ figure = widgets.Figure("0", theme.TYPE["numeral"], unit, tracking=theme.TIGHT["numeral"])+ return widgets.hug(figure.view), figure++ @objc.python_method+ def _page(self, title, purpose):+ """One page: a vertical scroller holding the title, the sentence saying what the page is+ for, then the modules the builder adds to the returned body. Returns (scroll, body)."""+ scroll = AppKit.NSScrollView.alloc().init()+ scroll.setTranslatesAutoresizingMaskIntoConstraints_(False)+ scroll.setDrawsBackground_(False)+ scroll.setHasVerticalScroller_(True)+ # Nothing scrolls sideways, at any width.+ scroll.setHasHorizontalScroller_(False)+ scroll.setAutohidesScrollers_(True)+ page = FlippedView.alloc().init()+ page.setTranslatesAutoresizingMaskIntoConstraints_(False)+ body = widgets.stack(spacing=theme.MODULE_GAP)+ page.addSubview_(body)+ top, leading, bottom, trailing = theme.PAGE_PADDING+ padding = [+ body.topAnchor().constraintEqualToAnchor_constant_(page.topAnchor(), top),+ body.leadingAnchor().constraintEqualToAnchor_constant_(page.leadingAnchor(), leading),+ page.bottomAnchor().constraintEqualToAnchor_constant_(body.bottomAnchor(), bottom),+ page.trailingAnchor().constraintEqualToAnchor_constant_(body.trailingAnchor(), trailing),+ ]+ AppKit.NSLayoutConstraint.activateConstraints_(padding)+ self.page_paddings.append(padding)+ scroll.setDocumentView_(page)+ clip = scroll.contentView()+ AppKit.NSLayoutConstraint.activateConstraints_([+ page.topAnchor().constraintEqualToAnchor_(clip.topAnchor()),+ page.leadingAnchor().constraintEqualToAnchor_(clip.leadingAnchor()),+ page.widthAnchor().constraintEqualToAnchor_(clip.widthAnchor()),+ ])+ header = widgets.stack(spacing=6)+ heading = widgets.Label(title, theme.PAGE_TITLE, 700, tracking=-0.01)+ self.page_titles.append(heading)+ widgets.add(header, heading.view)+ purpose_label = widgets.Label(purpose, theme.TYPE["body"], ink="ink_2", wrap=True)+ purpose_label.view.widthAnchor().constraintLessThanOrEqualToConstant_(theme.READING_WIDTH).setActive_(True)+ widgets.add(header, purpose_label.view)+ widgets.add(body, header)+ body.setCustomSpacing_afterView_(32, header)+ return scroll, body++ @objc.python_method+ def _overview_page(self, body):+ widgets.add(body, self._status_module().view)+ self.daily = widgets.Rack(+ [self._keyboard_module(), self._pause_module()], bottom_rule=False, gap=theme.MODULE_GAP, fill=None+ )+ widgets.add(body, self.daily.view)+ widgets.add(body, self._login_module().view)++ @objc.python_method+ def _login_module(self):+ module = widgets.Module(spacing=10)+ self.login_switch = widgets.Switch("Start Beamer when you log in", on_change=self._set_login)+ module.add(self.login_switch.view)+ self.login_note = widgets.note()+ module.add(self.login_note.view)+ self._show_login_state()+ return module++ @objc.python_method+ def _show_login_state(self, refused=None):+ try:+ state = login_item.status()+ except Exception:+ self.logger.exception("could not read the login item")+ state = login_item.NOT_FOUND+ self.login_switch.value = state in (login_item.ENABLED, login_item.REQUIRES_APPROVAL)+ if refused:+ self.login_note.set(f"macOS refused: {refused}")+ elif state == login_item.REQUIRES_APPROVAL:+ self.login_note.set("Waiting for you to allow it in System Settings, General, Login Items.")+ else:+ self.login_note.set("In the menu bar, with no window.")++ @objc.python_method+ def _set_login(self, enabled):+ try:+ login_item.set_enabled(enabled)+ except OSError as exc:+ self.logger.warning("could not change the login item: %s", exc)+ self._show_login_state(refused=exc)+ return+ self._show_login_state()++ @objc.python_method+ def _crossing_page(self, body):+ for module in (self._ways_module(), self._resistance_module()):+ widgets.add(body, module.view)++ @objc.python_method+ def _design_page(self, body):+ self.previews = previews.PreviewLoop(self.controller)+ for module in (self._on_screen_module(), self._notch_module(), self._edge_module(), self._trackpad_module()):+ widgets.add(body, module.view)++ @objc.python_method+ def _keyboard_page(self, body):+ widgets.add(body, self._shortcut_module().view)+ widgets.add(body, self._modifier_module().view)++ @objc.python_method+ def _pairing_page(self, body):+ widgets.add(body, self._paired_module().view)+ widgets.add(body, self._pair_module().view)++ @objc.python_method+ def _connection_page(self, body):+ widgets.add(body, self._connection_module().view)++ @objc.python_method+ def _permissions_page(self, body):+ widgets.add(body, self._access_module().view)++ @objc.python_method+ def _status_module(self):+ module = widgets.Module(spacing=10)+ head = widgets.stack(vertical=False, spacing=7)+ head.addArrangedSubview_(widgets.hug(widgets.eyebrow("Link"), AppKit.NSLayoutPriorityDefaultLow))+ self.link_led = widgets.LED()+ head.addArrangedSubview_(self.link_led.view)+ self.link_tag = widgets.Label("", theme.TYPE["eyebrow"], 700, "ink_3", tracking=theme.TRACKING["eyebrow"], upper=True)+ head.addArrangedSubview_(self.link_tag.view)+ module.add(head)+ self.state_word = widgets.Label("", theme.TYPE["status_word"], 700, tracking=theme.TIGHT["status_word"])+ widgets.squeeze(self.state_word.view)+ module.add(self.state_word.view)+ self.state_detail = widgets.Label("", theme.TYPE["body"], ink="ink_2", wrap=True)+ # Two lines reserved, so a one-line state does not pull the readouts up and down.+ self.state_detail.view.heightAnchor().constraintGreaterThanOrEqualToConstant_(36).setActive_(True)+ module.add(self.state_detail.view)+ self.spark = widgets.size(widgets.flipped(widgets.Spark), height=14)+ self.round_trip = widgets.Readout("Round trip", "ms", self.spark)+ self.resistance_scale = widgets.size(widgets.flipped(widgets.Scale), height=14)+ self.resistance_readout = widgets.Readout("Resistance", "px", self.resistance_scale)+ self.peer_footer = widgets.Label("", theme.TYPE["small"], mono=True, ink="ink_3")+ widgets.squeeze(self.peer_footer.view)+ self.peer = widgets.Readout("Peer", "", self.peer_footer.view, sizes=(theme.PEER_SIZE, theme.PEER_SIZE_NARROW))+ module.add(widgets.grid([self.round_trip.view, self.resistance_readout.view, self.peer.view], 3))+ return module++ @objc.python_method+ def _keyboard_module(self):+ module = widgets.Module(spacing=14)+ module.add(widgets.eyebrow("Keyboard and pointer"))+ self.selector = widgets.Selector()+ module.add(self.selector.view)+ self.toggle_button = widgets.Button(+ "Send input to Windows", self, "toggleRedirect:", style="primary", scale="big", full_width=True+ )+ module.add(self.toggle_button.view)+ return module++ @objc.python_method+ def _pause_module(self):+ module = widgets.Module(spacing=14)+ module.add(widgets.eyebrow("Pointer crossing"))+ self.pause_button = widgets.Button("Pause crossing", self, "togglePause:", full_width=True)+ module.add(self.pause_button.view)+ self.crossing_state = widgets.note()+ module.add(self.crossing_state.view)+ return module++ @objc.python_method+ def _resistance_module(self):+ module = widgets.Module()+ figure, self.resistance_numeral = self._numeral("px of push")+ module.add(self._head("Resistance", figure))+ self.resistance_ruler = widgets.Ruler(+ 0, 500, (0, 100, 200, 300, 400, 500), step=1, minor=25, on_change=self._preview_resistance+ )+ module.add(self.resistance_ruler.view)+ line = widgets.stack(vertical=False, spacing=10)+ line.setAlignment_(AppKit.NSLayoutAttributeTop)+ screen = widgets.size(widgets.box("ground", "edge", 3), 46, 30)+ screen.layer().setMasksToBounds_(True)+ self.preview_glow = Quartz.CAGradientLayer.layer()+ self.preview_glow.setColors_([+ theme.colour("signal").colorWithAlphaComponent_(0).CGColor(), theme.colour("signal").CGColor(),+ ])+ screen.layer().addSublayer_(self.preview_glow)+ line.addArrangedSubview_(screen)+ self.resistance_hint = widgets.note()+ line.addArrangedSubview_(self.resistance_hint.view)+ module.add(line)+ return module++ @objc.python_method+ def _ways_module(self):+ module = widgets.Module()+ module.add(widgets.eyebrow("Ways in"))+ self.ways_note = widgets.note()+ module.add(self.ways_note.view)+ self.method_boxes = {+ "shortcut": widgets.WayTile("Shortcut", on_change=self._changed),+ "edge": widgets.WayTile("Edge", "One whole outer edge", on_change=self._changed),+ "corner": widgets.WayTile("Corner", f"{crossing.CORNER_PX:g} pt box, diagonal push", on_change=self._changed),+ "notch": widgets.WayTile("Notch", on_change=self._changed),+ }+ module.add(widgets.grid([tile.view for tile in self.method_boxes.values()], 2))+ self.edge_select = widgets.Segmented(+ [("left", "Left"), ("right", "Right"), ("top", "Top"), ("bottom", "Bottom")], on_change=self._changed+ )+ module.add(widgets.field_row("Edge", self.edge_select.view)[0])+ self.corner_select = widgets.Segmented(+ [+ ("top_left", "Top left"),+ ("top_right", "Top right"),+ ("bottom_left", "Bottom left"),+ ("bottom_right", "Bottom right"),+ ],+ columns=2,+ on_change=self._changed,+ )+ module.add(widgets.field_row("Corner", self.corner_select.view)[0])+ self.dragging_box = widgets.Switch("Never while dragging", on_change=self._changed)+ module.add(self.dragging_box.view)+ return module++ @objc.python_method+ def _shortcut_module(self):+ module = widgets.Module()+ self.double_tap_head, self.double_tap_numeral = self._numeral("ms between taps")+ module.add(self._head("Shortcut", self.double_tap_head))+ self.key_recorder = widgets.KeyRecorder("alt_r", on_change=self._changed)+ module.add(self.key_recorder.view)+ self.style_select = widgets.Segmented([("double_tap", "Double-tap"), ("hold", "Hold")], on_change=self._changed)+ module.add(widgets.field_row("Trigger style", self.style_select.view)[0])+ # The stored window runs 50 to 2000 ms, but only about 150 to 600 is useful, so the ruler+ # shows 50 to 1000 on a square-root scale; a stored value past 1000 pins the thumb.+ self.double_tap_ruler = widgets.Ruler(+ 50, 1000, (50, 150, 300, 600, 1000), step=10, scale="sqrt", minor=20, on_change=self._double_tap_moved+ )+ module.add(self.double_tap_ruler.view)+ self.style_hint = widgets.note()+ module.add(self.style_hint.view)+ return module++ @objc.python_method+ def _on_screen_module(self):+ module = widgets.Module(spacing=8)+ module.add(widgets.eyebrow("On screen"))+ self.glow_box = widgets.Switch("Animate crossings on this Mac", on_change=self._changed)+ module.add(self.glow_box.view)+ module.add(widgets.note(+ "Lights the notch or the edge as you push toward Windows. Switched off, crossing still "+ "works; you feel it rather than see it. Windows sets how its own edge looks."+ ).view)+ return module++ @objc.python_method+ def _preview_tile(self, base, value, title, detail, notch, **overrides):+ """One tile's preview: its own screen, a feed pinned to the style the tile shows, and the+ real renderer hosted on it, registered with the page's loop."""+ screen = widgets.size(previews.PreviewScreen.alloc().init().setup(notch), height=84)+ feed = previews.PreviewFeed(self.controller, **overrides)+ if notch is None:+ renderer = previews.hosted_edge(base)(feed, self.logger, screen)+ update = previews.edge_update(renderer)+ else:+ renderer = previews.hosted_notch(base)(feed, self.logger, screen)+ update = previews.notch_update(renderer)+ self.previews.add(feed, renderer, update)+ return value, title, detail, screen++ @objc.python_method+ def _notch_module(self):+ module = widgets.Module()+ module.add(widgets.eyebrow("Notch"))+ notch = previews.notch_size()+ self.notch_style_select = widgets.ChoiceTiles(+ [+ self._preview_tile(NotchBeam, "beam", "Beam", "A line of colour runs round the notch, faster the harder you push.", notch),+ self._preview_tile(NotchIsland, "island", "Island", "The notch grows as you push, with a meter inside, and flashes as you go through.", notch),+ ],+ on_change=self._changed,+ )+ module.add(self.notch_style_select.view)+ self.notch_after_select = widgets.Segmented(+ [(600, "0.6 s"), (1200, "1.2 s"), (2000, "2 s"), (3000, "3 s")], on_change=self._changed+ )+ module.add(widgets.field_row("Keep animating", self.notch_after_select.view)[0])+ self.notch_note = widgets.note()+ module.add(self.notch_note.view)+ return module++ @objc.python_method+ def _edge_module(self):+ module = widgets.Module()+ module.add(widgets.eyebrow("Edge and corner"))+ self.glow_style_select = widgets.ChoiceTiles(+ [+ self._preview_tile(EdgeGlow, "glow", "Glow", "A band of light that deepens the harder you push.", None, glow_style="glow"),+ self._preview_tile(EdgeGlow, "beam", "Beam", "A thin line with a comet of light running along it.", None, glow_style="beam"),+ ],+ on_change=self._changed,+ )+ module.add(self.glow_style_select.view)+ self.glow_colour_select = widgets.Swatches(+ [(name, name.capitalize()) for name in crossing.GLOW_COLOURS], on_change=self._changed+ )+ module.add(widgets.field_row("Colour", self.glow_colour_select.view)[0])+ module.add(widgets.note("The notch's Beam style uses this colour too. Island keeps Beamer's own cyan.").view)+ return module++ @objc.python_method+ def _trackpad_module(self):+ module = widgets.Module()+ module.add(widgets.eyebrow("Trackpad"))+ self.haptics_box = widgets.Switch("Tick as the push builds", on_change=self._changed)+ module.add(self.haptics_box.view)+ strength = widgets.stack(vertical=False, spacing=10)+ self.tick_feel_select = widgets.Segmented(+ [("light", "Light"), ("medium", "Medium"), ("firm", "Firm")], on_change=self._changed+ )+ strength.addArrangedSubview_(widgets.hug(self.tick_feel_select.view, AppKit.NSLayoutPriorityDefaultLow))+ self.try_button = widgets.Button("Try it", self, "tryTick:", scale="small")+ strength.addArrangedSubview_(self.try_button.view)+ module.add(widgets.field_row("Strength", strength)[0])+ self.tick_steps_select = widgets.Segmented(+ [("quarters", "Every quarter"), ("halves", "Halfway"), ("breakthrough", "Only when through")],+ on_change=self._changed,+ )+ module.add(widgets.field_row("Ticks at", self.tick_steps_select.view)[0])+ self.tick_note = widgets.note()+ module.add(self.tick_note.view)+ return module++ def tryTick_(self, _sender):+ if self.haptics is not None:+ self.haptics.tick(self.tick_feel_select.value)++ @objc.python_method+ def _modifier_module(self):+ module = widgets.Module()+ module.add(widgets.eyebrow("Modifier keys"))+ self.modifier_select = widgets.Segmented(+ [("semantic", "Semantic"), ("positional", "Positional")], on_change=self._changed+ )+ module.add(self.modifier_select.view)+ self.modifier_note = widgets.note()+ module.add(self.modifier_note.view)+ return module++ @objc.python_method+ def _paired_module(self):+ """What the page leads with once a PC is paired: which one, where, and the one way to change+ it. The PC list and code boxes stay hidden until they are wanted, or they read as an+ invitation to pair a Mac that already is."""+ module = widgets.Module()+ module.add(widgets.eyebrow("Paired with"))+ self.paired_name = widgets.Label("", theme.TYPE["readout"], 400, mono=True)+ module.add(self.paired_name.view)+ self.paired_address = widgets.Label("", theme.TYPE["small"], mono=True, ink="ink_3")+ module.add(self.paired_address.view)+ line = widgets.stack(vertical=False, spacing=10)+ line.setAlignment_(AppKit.NSLayoutAttributeCenterY)+ self.paired_note = widgets.note()+ line.addArrangedSubview_(self.paired_note.view)+ self.repair_button = widgets.Button("Pair a different PC", self, "togglePairing:", scale="small")+ line.addArrangedSubview_(self.repair_button.view)+ module.add(line)+ self.paired_module = module+ return module++ @objc.python_method+ def _pair_module(self):+ module = widgets.Module()+ self.pair_grid = widgets.stack(spacing=20)+ self.pair_grid.setAlignment_(AppKit.NSLayoutAttributeTop)+ found = widgets.stack(spacing=8)+ widgets.add(found, widgets.eyebrow("On this network"))+ self.pc_list = widgets.stack(spacing=1)+ self.pc_frame = widgets.box("rule")+ self.pc_frame.addSubview_(self.pc_list)+ widgets.pin(self.pc_list, self.pc_frame, (1, 1, 1, 1))+ widgets.add(found, self.pc_frame)+ self.pc_empty = widgets.note()+ widgets.add(found, self.pc_empty.view)+ code = widgets.stack(spacing=8)+ widgets.add(code, widgets.eyebrow("Code shown on the PC"))+ self.code_boxes = widgets.CodeBoxes(pairing.CODE_DIGITS, self.confirmPair_)+ widgets.add(code, self.code_boxes.view)+ line = widgets.stack(vertical=False, spacing=10)+ line.setAlignment_(AppKit.NSLayoutAttributeTop)+ self.pair_status = widgets.note()+ line.addArrangedSubview_(self.pair_status.view)+ self.confirm_button = widgets.Button("Pair", self, "confirmPair:", scale="small")+ line.addArrangedSubview_(self.confirm_button.view)+ widgets.add(code, line)+ self.pair_grid.addArrangedSubview_(found)+ self.pair_grid.addArrangedSubview_(code)+ module.add(self.pair_grid)+ self.pair_stacked = [+ view.widthAnchor().constraintEqualToAnchor_(self.pair_grid.widthAnchor()) for view in (found, code)+ ]+ self.pair_module = module+ return module++ @objc.python_method+ def _connection_module(self):+ module = widgets.Module(spacing=10)+ host_box, self.host_field = widgets.field()+ module.add(widgets.field_row("Windows address", host_box)[0])+ port_box, self.port_field = widgets.field()+ module.add(widgets.field_row("Port", port_box)[0])+ token_box, self.token_field = widgets.field(secure=True)+ plain_box, self.token_plain = widgets.field()+ plain_box.setHidden_(True)+ self.token_boxes = (token_box, plain_box)+ self.show_button = widgets.Button("Show", self, "showToken:", scale="small")+ token_line = widgets.stack(vertical=False, spacing=6)+ token_line.addArrangedSubview_(token_box)+ token_line.addArrangedSubview_(plain_box)+ token_line.addArrangedSubview_(self.show_button.view)+ for box in self.token_boxes:+ widgets.hug(box, AppKit.NSLayoutPriorityDefaultLow)+ module.add(widgets.field_row("Shared token", token_line)[0])+ self.wake_state = widgets.Label("", theme.TYPE["small"], mono=True)+ module.add(widgets.field_row("Wake-on-LAN", self.wake_state.view)[0])+ self.wake_hint = widgets.note()+ module.add(self.wake_hint.view)+ module.add(widgets.hairline())+ line = widgets.stack(vertical=False, spacing=12)+ line.addArrangedSubview_(widgets.note("A new address, port or token takes effect when you connect.").view)+ line.addArrangedSubview_(widgets.Button("Connect", self, "connect:", style="primary", scale="small").view)+ module.add(line)+ return module++ @objc.python_method+ def _access_module(self):+ module = widgets.Module(spacing=10)+ self.access_status, self.access_button = self._permission_row(module, "Accessibility", "requestAccessibility:")+ module.add(widgets.hairline())+ self.input_status, self.input_button = self._permission_row(module, "Input Monitoring", "requestInputMonitoring:")+ self.capture_status = widgets.note()+ module.add(self.capture_status.view)+ return module++ @objc.python_method+ def _permission_row(self, module, name, action):+ line = widgets.stack(vertical=False, spacing=10)+ words = widgets.stack(spacing=4)+ widgets.add(words, widgets.Label(name, theme.TYPE["body"], 600).view)+ status = widgets.Label("Required", theme.TYPE["small"], mono=True, ink="amber", tracking=theme.STATE_TRACKING, upper=True)+ widgets.add(words, status.view)+ line.addArrangedSubview_(widgets.hug(words, AppKit.NSLayoutPriorityDefaultLow))+ button = widgets.Button("Grant", self, action, scale="small")+ line.addArrangedSubview_(button.view)+ module.add(line)+ return status, button++ @objc.python_method+ def _ways_in_sentence(self):+ cfg = self.controller.cfg+ key = widgets.key_title(cfg.trigger_key)+ methods = set(cfg.crossing["methods"])+ parts = []+ if "shortcut" in methods:+ parts.append(f"{'Hold' if cfg.trigger_style == 'hold' else 'Double-tap'} {key}")+ ways = []+ if "edge" in methods:+ ways.append(f"the {cfg.crossing['edge']} edge")+ if "corner" in methods:+ ways.append(f"the {cfg.crossing['corner'].replace('_', ' ')} corner")+ if "notch" in methods:+ 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}")+ if not parts:+ return ""+ sentence = ", or ".join(parts)+ return sentence[0].upper() + sentence[1:]++ @objc.python_method+ def _commit(self):+ bar = widgets.box("ground")+ self.message_label = widgets.note(+ "Changes apply as you make them. Closing this window keeps Beamer running in the menu bar."+ )+ line = widgets.stack(vertical=False, spacing=16)+ line.addArrangedSubview_(self.message_label.view)+ bar.addSubview_(line)+ widgets.pin(line, bar, (12, 16, 12, 16))+ return bar++ @objc.python_method+ def _say(self, message, ink="ink_2"):+ self.message_label.set(message, ink=ink)++ @objc.python_method+ def show(self):+ self._select_page(pages.opening_page(+ self.page if self.opened else None, accessibility_granted(), input_monitoring_granted()+ ))+ self.opened = True+ self.window.makeKeyAndOrderFront_(None)+ AppKit.NSApp.activateIgnoringOtherApps_(True)+ self._run_previews()++ @objc.python_method+ def _token(self):+ return (self.token_plain if self.token_boxes[0].isHidden() else self.token_field).stringValue()++ def showToken_(self, _sender):+ secure_box, plain_box = self.token_boxes+ showing = plain_box.isHidden()+ if showing:+ self.token_plain.setStringValue_(self.token_field.stringValue())+ else:+ self.token_field.setStringValue_(self.token_plain.stringValue())+ secure_box.setHidden_(showing)+ plain_box.setHidden_(not showing)+ self.show_button.set_title("Hide" if showing else "Show")++ def connect_(self, _sender):+ """The Connection page's own commit: a new address, port or token has to reconnect, so it+ waits for the button rather than applying as it is typed."""+ raw = config_to_raw(self.controller.cfg)+ try:+ raw["host"] = self.host_field.stringValue().strip()+ raw["port"] = int(self.port_field.stringValue().strip())+ raw["auth_token"] = self._token()+ if raw["host"] != self.controller.cfg.host:+ # What was learned belonged to the old address.+ raw["pc_name"] = ""+ raw["mac_address"] = ""+ cfg = self.settings_store.save(raw)+ except (SettingsError, TypeError, ValueError) as exc:+ self._say(str(exc), "fault")+ return+ self._say("Saved. Connecting…", "signal")+ self.controller.update_config(cfg)++ @objc.python_method+ def _apply_settings(self):+ """Writes every setting outside the Connection page and applies it without dropping the link."""+ raw = config_to_raw(self.controller.cfg)+ try:+ raw["trigger_key"] = self.key_recorder.value+ raw["trigger_style"] = self.style_select.value+ raw["double_tap_ms"] = self.double_tap_ruler.value+ if self.modifier_select.value in config_module.KEY_MAP_STYLES:+ raw["key_map"] = self.modifier_select.value+ raw["crossing"] = {+ "methods": [name for name, tile in self.method_boxes.items() if tile.value],+ "edge": self.edge_select.value,+ "corner": self.corner_select.value,+ "resistance_px": self.resistance_ruler.value,+ "haptics": self.haptics_box.value,+ "glow": self.glow_box.value,+ "notch_style": self.notch_style_select.value,+ "notch_after_ms": self.notch_after_select.value,+ "haptic_feel": self.tick_feel_select.value,+ "haptic_steps": self.tick_steps_select.value,+ "glow_style": self.glow_style_select.value,+ "glow_colour": self.glow_colour_select.value,+ "block_while_dragging": self.dragging_box.value,+ "arrangement_set_at": self.controller.cfg.crossing.get("arrangement_set_at", 0),+ }+ moved = raw["crossing"]["edge"] != self.controller.cfg.crossing.get("edge")+ if moved:+ # The edge is half of a value Windows holds too, so a change+ # here is stamped with the moment it was made. When the two+ # ends meet holding different answers -- one changed while the+ # other was asleep -- the newer stamp is the one that stands.+ raw["crossing"]["arrangement_set_at"] = int(time.time())+ 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 moved and self.windows_input is not None:+ self.windows_input.send_arrangement(+ cfg.crossing["edge"], cfg.crossing.get("arrangement_set_at", 0)+ )+ self._say("Saved. Changes apply as you make them.", "ink_2")++ @objc.python_method+ def apply_arrangement(self, mac_edge, set_at):+ """Windows changed which edge of this Mac leads to it. Applied here+ rather than at either link, because this is the side that owns the+ settings file. An arrangement older than this Mac's own is ignored:+ both ends stamp their changes, and the newer one stands."""+ if mac_edge == self.controller.cfg.crossing.get("edge"):+ return+ mine = self.controller.cfg.crossing.get("arrangement_set_at", 0)+ if mine and not protocol.arrangement_wins(set_at, mine):+ self.logger.info("ignoring an older arrangement from the PC (%s vs %s)", set_at, mine)+ return+ raw = config_to_raw(self.controller.cfg)+ raw["crossing"] = {**raw["crossing"], "edge": mac_edge, "arrangement_set_at": int(set_at)}+ try:+ cfg = self.settings_store.save(raw)+ except (SettingsError, TypeError, ValueError):+ self.logger.exception("could not save the arrangement the PC sent")+ return+ self.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.refresh()++ def quitApp_(self, _sender):+ self.quit_handler()++ def requestAccessibility_(self, _sender):+ ApplicationServices.AXIsProcessTrustedWithOptions(+ {ApplicationServices.kAXTrustedCheckOptionPrompt: True}+ )+ self.refresh()++ def requestInputMonitoring_(self, _sender):+ Quartz.CGRequestListenEventAccess()+ self.refresh()++ def toggleRedirect_(self, _sender):+ if not self.controller.input_ready:+ self._say("Grant both Mac permissions first.", "fault")+ return+ if not self.controller.redirecting and self.controller.can_wake:+ self.controller.wake()+ self._say("Waking Windows. It connects on its own once it is up.", "ink_2")+ elif not self.controller.set_redirecting(not self.controller.redirecting):+ self._say(self.controller.connection_status, "fault")+ self.refresh()++ def togglePause_(self, _sender):+ self.controller.crossing_paused = not self.controller.crossing_paused+ self.refresh()++ def togglePairing_(self, _sender):+ self._repairing = not getattr(self, "_repairing", False)+ if not self._repairing:+ self.code_boxes.clear()+ self.chosen_pc = None+ self._pcs_key = None+ self._say_pairing("Choose a PC, then type the code it shows.")+ self.refresh()++ @objc.python_method+ def _refresh_paired(self, state):+ cfg = self.controller.cfg+ paired = bool(cfg.auth_token)+ refused = state.key == "token"+ repairing = getattr(self, "_repairing", False)+ peer = link_state.peer_name(cfg)+ self.paired_module.view.setHidden_(not paired)+ self.pair_module.view.setHidden_(paired and not refused and not repairing)+ self.paired_name.set(peer)+ self.paired_address.set(f"{cfg.host} · port {cfg.port}")+ if refused:+ self.paired_note.set(f"{peer} refused this Mac's token. Pair again below with the code it shows.", ink="fault")+ elif state.key in ("mac", "windows", "paused", "full_screen", "unlocking"):+ self.paired_note.set("Connected now.", ink="signal")+ else:+ self.paired_note.set("Beamer connects to it on its own whenever both are running.", ink="ink_2")+ self.repair_button.set_title("Cancel" if repairing else "Pair a different PC")+ self.repair_button.view.setHidden_(refused)++ @objc.python_method+ def _say_pairing(self, message, ink="ink_2"):+ self.pair_status.set(message, ink=ink)++ @objc.python_method+ def _refresh_pcs(self):+ """Rebuilds the PC rows only when what they would show has changed; the timer that+ drives this ticks several times a second."""+ discovery = self.discovery+ pcs = discovery.pcs() if discovery is not None else []+ chosen = self.chosen_pc["address"] if self.chosen_pc is not None else None+ key = (chosen, tuple((pc["name"], pc["address"], pc["port"], pc["pair_id"] is not None) for pc in pcs))+ if key == self._pcs_key:+ return+ self._pcs_key = key+ self._pcs = pcs+ for view in list(self.pc_list.arrangedSubviews()):+ self.pc_list.removeArrangedSubview_(view)+ view.removeFromSuperview()+ for index, pc in enumerate(pcs):+ picked = pc["address"] == chosen+ row = widgets.pressable(lambda index=index: self._choose_pc(index), "well" if picked else "ground",+ role=AppKit.NSAccessibilityRadioButtonRole)+ row.ring_inset = 1.0+ showing = pc["pair_id"] is not None+ row.setAccessibilityLabel_(f"{pc['name']}, {pc['address']}" + (", showing a code" if showing else ""))+ row.setToolTip_(f"Port {pc['port']}" + (", showing a code" if showing else ""))+ line = widgets.stack(vertical=False, spacing=9)+ led = widgets.LED()+ led.set("signal" if showing else "off")+ line.addArrangedSubview_(led.view)+ name = widgets.Label(pc["name"], theme.TYPE["note"], 600 if picked else 400)+ line.addArrangedSubview_(widgets.hug(widgets.squeeze(name.view), AppKit.NSLayoutPriorityDefaultLow))+ line.addArrangedSubview_(widgets.Label(pc["address"], theme.TYPE["small"], mono=True, ink="ink_3").view)+ row.addSubview_(line)+ widgets.pin(line, row, (7, 10, 7, 10))+ widgets.add(self.pc_list, row)+ if discovery is not None and discovery.error:+ self.pc_empty.set(f"Beamer cannot look for PCs: {discovery.error}", ink="fault")+ else:+ self.pc_empty.set(+ "Looking for PCs running Beamer on this network. Open Beamer on the PC and it appears here.", ink="ink_2"+ )+ self.pc_frame.setHidden_(not pcs)+ self.pc_empty.view.setHidden_(bool(pcs))+ if chosen is not None and chosen not in {pc["address"] for pc in pcs}:+ self.chosen_pc = None+ self._pcs_key = None+ self.confirm_button.set_enabled(self.chosen_pc is not None and not self._pairing)++ @objc.python_method+ def _choose_pc(self, index):+ if not 0 <= index < len(self._pcs):+ return+ self.chosen_pc = self._pcs[index]+ self.code_boxes.clear()+ self.code_boxes.view.setAccessibilityLabel_(f"Code shown on {self.chosen_pc['name']}")+ if self.chosen_pc["pair_id"] is None:+ self._say_pairing(f"{self.chosen_pc['name']} is not showing a code yet. Press Pair a Mac on it first.")+ else:+ self._say_pairing("Six digits, as shown on the PC.")+ self._refresh_pcs()+ self.code_boxes.focus(self.window)++ def confirmPair_(self, _sender):+ pc = self.chosen_pc+ if pc is None or self._pairing or self.discovery is None:+ return+ code = re.sub(r"\D", "", self.code_boxes.value)+ if len(code) != pairing.CODE_DIGITS:+ self._say_pairing(f"The code is {pairing.CODE_DIGITS} digits.", "fault")+ return+ # The list may have refreshed since the row was chosen; pair with the PC's latest beacon.+ current = next((entry for entry in self._pcs if entry["address"] == pc["address"]), pc)+ if current["pair_id"] is None:+ self._say_pairing(f"{current['name']} is not showing a code. Press Pair a Mac on it, then try again.", "fault")+ return+ self._pairing = True+ self.confirm_button.set_enabled(False)+ self._say_pairing(f"Pairing with {current['name']}…")+ discovery = self.discovery++ def work():+ try:+ result = discovery.pair(current, code)+ except pairing.PairingError as exc:+ result = exc+ except Exception as exc:+ self.logger.exception("pairing failed")+ result = pairing.PairingError(str(exc))+ AppHelper.callAfter(self._pairing_finished, current, result)++ threading.Thread(target=work, name="pair", daemon=True).start()++ @objc.python_method+ def _pairing_finished(self, pc, result):+ self._pairing = False+ self.confirm_button.set_enabled(self.chosen_pc is not None)+ name = pc["name"]+ if isinstance(result, pairing.PairingError):+ reason = str(result)+ if reason == pairing.ERROR_NOT_PAIRING:+ self._say_pairing(f"{name} is not showing a code. Press Pair a Mac on it, then try again.", "fault")+ elif reason == pairing.ERROR_REFUSED:+ self._say_pairing("That code was not accepted, and the PC has cancelled it. Press Pair a Mac there for a fresh one.", "fault")+ elif reason == "no_answer":+ self._say_pairing(f"{name} did not answer. Check both machines are on the same network, then try again.", "fault")+ else:+ self._say_pairing(f"Pairing failed: {reason}", "fault")+ return+ raw = config_to_raw(self.controller.cfg)+ raw["host"] = pc["address"]+ raw["port"] = pc["port"]+ raw["auth_token"] = result+ raw["pc_name"] = name+ # The Mac has just exchanged packets with the PC, so its ARP entry is fresh.+ raw["mac_address"] = lookup_mac(pc["address"]) or ""+ try:+ cfg = self.settings_store.save(raw)+ except SettingsError as exc:+ self._say_pairing(f"Paired, but the settings could not be saved: {exc}", "fault")+ return+ self.code_boxes.clear()+ self.chosen_pc = None+ self._pcs_key = None+ self._repairing = False+ self._load(config_to_raw(cfg))+ self.controller.update_config(cfg)+ self._say("Paired with " + name + ". Connecting…", "signal")+ self.logger.info("paired with %s at %s", name, pc["address"])++ @objc.python_method+ def _persist_mac(self, _mac):+ """The controller has already put the learned address on cfg; this writes it down."""+ try:+ self.settings_store.save(config_to_raw(self.controller.cfg))+ except SettingsError as exc:+ self.logger.warning("hardware address not saved: %s", exc)++ @objc.python_method+ def _crossing_state_sentence(self):+ controller = self.controller+ if not controller.crossing.armed:+ return "Only the shortcut is switched on; there is nothing to pause."+ if controller.crossing_paused:+ return "Paused. Edges, corners and the notch do nothing until you resume; the shortcut still works."+ if controller.full_screen_app is not None:+ return (+ f"Off while {controller.full_screen_app} is full screen, so the pointer stays put at "+ "the edges; the shortcut still works."+ )+ return "On. Pause it to lean on an edge without switching."++ @objc.python_method+ def _permission(self, status, button, granted):+ status.set("Granted" if granted else "Required", ink="signal" if granted else "amber")+ button.set_title("Granted" if granted else "Grant")+ button.set_enabled(not granted)++ @objc.python_method+ def refresh(self):+ controller = self.controller+ access = accessibility_granted()+ listening = input_monitoring_granted()+ self._permission(self.access_status, self.access_button, access)+ self._permission(self.input_status, self.input_button, listening)+ if access and listening and not controller.input_ready:+ now = time.monotonic()+ if now - self.last_capture_attempt >= CAPTURE_RETRY_INTERVAL_SECONDS:+ self.last_capture_attempt = now+ controller.start_input_capture()+ if controller.input_ready:+ self.capture_status.set("Input capture ready.", ink="signal")+ elif access and listening:+ detail = controller.input_error+ self.capture_status.set(f"Retrying input capture… {detail}" if detail else "Retrying input capture…", ink="fault")+ else:+ self.capture_status.set(+ "Beamer needs both, granted separately. macOS only delivers keyboard events to a process "+ "started after the grant, so relaunch Beamer once you have given them.",+ 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.")+ state = link_state.describe(controller)+ self._refresh_paired(state)+ self.sidebar.set_link(state, link_state.peer_name(controller.cfg))+ self.sidebar.set_dots(pages.dots(access, listening, state.key))+ self.link_led.set(state.led, state.blink)+ self.link_tag.set(state.tag)+ self.state_word.set(state.word, ink=state.tone)+ self.state_detail.set(state.detail)++ round_trip = controller.round_trip_ms+ if controller.redirecting:+ if round_trip is not None:+ self.latency.append(round_trip)+ else:+ self.latency.clear()+ live = controller.redirecting and round_trip is not None+ self.round_trip.value.set(str(round_trip) if live else "—", ink="signal" if live else "ink")+ self.spark.samples = list(self.latency)+ self.spark.live = controller.redirecting+ self.spark.setNeedsDisplay_(True)+ cfg = controller.cfg+ self._show_peer()++ self.pause_button.set_title("Resume crossing" if controller.crossing_paused else "Pause crossing")+ self.pause_button.set_style("primary" if controller.crossing_paused else "plain")+ self.pause_button.set_enabled(controller.crossing.armed)+ self.crossing_state.set(self._crossing_state_sentence())+ has_notch = controller.notch_range is not None+ if has_notch != self.has_notch:+ self.has_notch = has_notch+ self._reflect()+ self.selector.set("windows" if controller.redirecting else "mac")+ if controller.redirecting:+ self.toggle_button.set_title("Return input to Mac")+ elif controller.waking:+ self.toggle_button.set_title("Waking Windows…")+ elif controller.can_wake:+ self.toggle_button.set_title("Wake Windows")+ else:+ self.toggle_button.set_title("Send input to Windows")+ self.toggle_button.set_style("live" if controller.redirecting or controller.windows_locked else "primary")+ self.toggle_button.set_enabled(+ controller.input_ready+ and not controller.waking+ and (controller.connected or controller.can_wake)+ )+ mac = cfg.mac_address+ self.wake_state.set(mac if mac else "Not yet learned", ink="ink" if mac else "ink_3")+ self.wake_hint.set(+ "Crossing to the PC while it sleeps sends a wake-up packet and waits for it."+ if mac+ else "Read from the network the first time this Mac connects; nothing to type."+ )+ self._refresh_pcs()+++class StatusItemClick(AppKit.NSObject):+ """Splits the menu bar item's clicks: left opens the window, right opens the menu.++ An NSStatusItem with a menu attached hands it every click, and rumps attaches one, so the+ menu is detached at startup and put back for the moment a right click needs it."""++ def initWithTray_(self, tray):+ self = objc.super(StatusItemClick, self).init()+ if self is None:+ return None+ self.tray = tray+ return self++ def clicked_(self, _sender):+ item = self.tray.status_item_view+ event = AppKit.NSApp.currentEvent()+ right = event is not None and (+ event.type() == AppKit.NSEventTypeRightMouseUp+ or event.modifierFlags() & AppKit.NSEventModifierFlagControl+ )+ if not right:+ self.tray.control_window.show()+ return+ item.setMenu_(self.tray.detached_menu)+ item.button().performClick_(None)+ item.setMenu_(None)+++class _LaunchWatch(AppKit.NSObject):+ """A login item takes no arguments, so a login launch is recognised instead: macOS marks it+ as not the default launch, and that is the cue to stay in the menu bar."""++ def initWithTray_(self, tray):+ self = objc.super(_LaunchWatch, self).init()+ self.tray = tray+ AppKit.NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(+ self, "launched:", AppKit.NSApplicationDidFinishLaunchingNotification, None+ )+ return self++ def launched_(self, note):+ info = note.userInfo() or {}+ default = info.get("NSApplicationLaunchIsDefaultLaunchKey")+ if default is not None and not bool(default):+ self.tray.hidden = True+++class TrayApp(rumps.App):+ def __init__(self, controller, settings_store, logger, hidden=False):+ self.hidden = hidden+ self.launch_watch = _LaunchWatch.alloc().initWithTray_(self)+ self.controller = controller+ self.settings_store = settings_store+ self.logger = logger+ self.control_window = ControlWindow.alloc().initWithController_settingsStore_logger_(+ controller, settings_store, logger+ )+ self.control_window.quit_handler = self.quit_app+ install_main_menu(self.control_window)+ self.gesture_overlay = GestureOverlay(controller, logger)+ self.edge_glow = EdgeGlow(controller, logger)+ self.notch_island = NotchIsland(controller, logger)+ self.notch_beam = NotchBeam(controller, logger)+ self.haptics = Haptics(logger)+ self.control_window.preview = self.edge_glow.preview+ self.control_window.haptics = self.haptics+ self.controller.on_user_alert = self.notify_user+ self.controller.on_crossing = self.crossing_feedback+ self.controller.on_arrangement = self._arrangement+ self.controller.on_mac_learned = lambda mac: AppHelper.callAfter(self.control_window._persist_mac, 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.+ self.windows_input = WindowsInput(controller, logger, arrangement_callback=self._arrangement)+ self.control_window.windows_input = self.windows_input+ self.windows_input.sync(controller.cfg)+ self.discovery = pairing.Discovery(logger=logger)+ self.control_window.discovery = self.discovery+ self.discovery.start()+ self._notch_failed = False+ header = rumps.MenuItem(f"Beamer {VERSION}", callback=None)+ self.status_item = rumps.MenuItem("Starting", callback=None)+ self.toggle_item = rumps.MenuItem("Send input to Windows", callback=self.toggle_redirect)+ self.pause_item = rumps.MenuItem("Pause crossing", callback=self.toggle_pause)+ # One tick per direction, so either can be switched off while the other keeps working.+ self.send_item = rumps.MenuItem("This Mac drives Windows", callback=self.toggle_send_to_windows)+ self.receive_item = rumps.MenuItem("Windows drives this Mac", callback=self.toggle_windows_drives)+ self._symbol = None+ super().__init__(+ "Beamer",+ title="Beamer • Local",+ menu=[+ header,+ rumps.separator,+ self.status_item,+ self.toggle_item,+ self.pause_item,+ rumps.separator,+ self.send_item,+ self.receive_item,+ rumps.separator,+ rumps.MenuItem("Settings…", callback=self.open_window),+ rumps.MenuItem("Reload configuration", callback=self.reload_config),+ rumps.separator,+ rumps.MenuItem("Quit Beamer", callback=self.quit_app),+ ],+ quit_button=None,+ )+ self.status_timer = rumps.Timer(self.refresh_status, 0.4)+ self.startup_timer = rumps.Timer(self.show_on_startup, 0.2)+ # Its own timer, slower than the status tick: the window list is a window-server call,+ # and once a second is the cache the tap thread reads from.+ self.full_screen_timer = rumps.Timer(self.check_full_screen, FULL_SCREEN_CHECK_INTERVAL_SECONDS)+ self.status_timer.start()+ self.startup_timer.start()+ self.full_screen_timer.start()++ def _arrangement(self, mac_edge, set_at):+ """An arrangement from the PC, over either link, applied on the main+ thread -- it writes the settings file and redraws the window."""+ AppHelper.callAfter(self.control_window.apply_arrangement, mac_edge, set_at)++ def show_on_startup(self, _timer):+ self.startup_timer.stop()+ self.split_clicks()+ if not self.hidden:+ self.control_window.show()++ def split_clicks(self):+ """Runs once the status item exists, which is after rumps has started the app."""+ self.status_item_view = self._nsapp.nsstatusitem+ self.detached_menu = self.status_item_view.menu()+ self.status_item_view.setMenu_(None)+ self.click_handler = StatusItemClick.alloc().initWithTray_(self)+ button = self.status_item_view.button()+ button.setTarget_(self.click_handler)+ button.setAction_("clicked:")+ button.sendActionOn_(AppKit.NSEventMaskLeftMouseUp | AppKit.NSEventMaskRightMouseUp)++ def refresh_status(self, _timer):+ self.windows_input.sync(self.controller.cfg)+ self.measure_notch()+ self.control_window.refresh()+ self.gesture_overlay.sync()+ controller = self.controller+ held = controller.crossing.armed and (controller.crossing_paused or controller.full_screen_app is not None)+ self.set_menu_bar_symbol(+ "windows" if controller.redirecting or controller.receiving else "held" if held else "local"+ )+ if controller.redirecting:+ self.toggle_item.title = "Return input to Mac"+ else:+ self.toggle_item.title = "Send input to Windows"+ self.pause_item.title = "Resume crossing" if controller.crossing_paused else "Pause crossing"+ self.send_item.state = int(controller.cfg.send_to_windows)+ self.receive_item.state = int(controller.cfg.allow_windows_to_drive)+ self.status_item.title = link_state.describe(controller).word++ def set_menu_bar_symbol(self, state):+ """One template glyph per state instead of words. rumps only takes an icon as a file+ path, so the NSImage goes in by hand; _icon_nsimage is what it reads when the status+ item is first built, before nsstatusitem exists."""+ if state != self._symbol:+ self._symbol = state+ self._icon_nsimage = menu_bar_glyph(state)+ self._title = ""+ try:+ self._nsapp.setStatusBarIcon()+ except AttributeError:+ pass+ # rumps decides the status item is empty by reading the deprecated+ # NSStatusItem.image(), which is nil even while the image is on screen,+ # so it keeps putting the app name back as the title. Clear it instead+ # of fighting it.+ try:+ item = self._nsapp.nsstatusitem+ except AttributeError:+ return+ if item.title():+ item.setTitle_("")++ def open_window(self, _sender):+ self.control_window.show()++ def toggle_send_to_windows(self, _sender):+ self._set_direction(send_to_windows=not self.controller.cfg.send_to_windows)++ def toggle_windows_drives(self, _sender):+ self._set_direction(allow_windows_to_drive=not self.controller.cfg.allow_windows_to_drive)++ def _set_direction(self, **change):+ try:+ cfg = self.settings_store.save(config_to_raw(replace(self.controller.cfg, **change)))+ except SettingsError as exc:+ self.logger.warning("direction not saved: %s", exc)+ self.notify_user("Beamer", f"Could not save the change: {exc}")+ return+ self.controller.update_config(cfg)+ self.windows_input.sync(cfg)+ self.logger.info("directions: this Mac drives Windows %s, Windows drives this Mac %s",+ "on" if cfg.send_to_windows else "off", "on" if cfg.allow_windows_to_drive else "off")+ self.refresh_status(None)++ def reload_config(self, _sender):+ """Re-reads config.json, for the times it was edited outside the window."""+ try:+ self.controller.update_config(self.settings_store.load())+ except SettingsError as exc:+ self.logger.warning("configuration not reloaded: %s", exc)+ self.notify_user("Configuration not reloaded", str(exc))+ return+ self.notify_user("Configuration reloaded", "Beamer is using the config on disk.")++ def measure_notch(self):+ """Re-read on every tick so plugging a display in above the MacBook, which moves the+ notch off the top of the desktop, is noticed without a restart."""+ if self._notch_failed:+ return+ try:+ self.controller.notch_range = notch_x_range()+ except Exception:+ self._notch_failed = True+ self.controller.notch_range = None+ self.logger.exception("could not measure the notch; the notch method is off")++ def check_full_screen(self, _timer):+ """Feeds the controller the name of a full-screen frontmost app, or None. A failure+ stops the check for the run rather than logging once a second; crossing then simply+ stays on, as it was before this existed."""+ try:+ self.controller.full_screen_app = full_screen_app()+ except Exception:+ self.controller.full_screen_app = None+ self.full_screen_timer.stop()+ self.logger.exception("could not tell whether an app is full screen; crossing stays on")++ def toggle_pause(self, _sender):+ self.controller.crossing_paused = not self.controller.crossing_paused+ self.refresh_status(None)++ def crossing_feedback(self, kind, step):+ """Wired to controller.on_crossing, called off the event-tap and ack threads. Only the+ hop to the main thread happens here; haptics and the glow both touch AppKit."""+ AppHelper.callAfter(self._crossing_feedback_main, kind, step)++ def _crossing_feedback_main(self, kind, step):+ try:+ feel = self.controller.cfg.crossing+ if feel["haptics"]:+ if kind == "tick":+ if crossing.tick_fires(feel["haptic_steps"], step.pressure):+ self.haptics.tick(feel["haptic_feel"])+ elif kind in ("cross", "arrive"):+ self.haptics.thud()+ if feel["glow"]:+ if step.via == "notch":+ notch = self.notch_beam if feel["notch_style"] == "beam" else self.notch_island+ notch.update(kind)+ else:+ self.edge_glow.update(kind, step)+ except Exception:+ self.logger.exception("crossing feedback failed")++ def notify_user(self, title, message):+ """Wired to controller.on_user_alert, which fires on the event-tap and+ connection threads. AppKit is main-thread only, so the work hops+ there like every other controller callback in this class."""+ AppHelper.callAfter(self._notify_user_main, title, message)++ def _notify_user_main(self, title, message):+ try:+ AppKit.NSBeep()+ except Exception:+ self.logger.exception("failed to beep for a user alert")+ try:+ rumps.notification("Beamer", title, message)+ except Exception:+ self.logger.exception("failed to show a user notification")++ def toggle_redirect(self, _sender):+ self.control_window.toggleRedirect_(None)++ def quit_app(self, _sender=None):+ self.status_timer.stop()+ self.discovery.stop()+ self.windows_input.stop()+ self.controller.stop()+ rumps.quit_application()+++def parse_args(argv=None):+ parser = argparse.ArgumentParser(description="Beamer macOS sender")+ parser.add_argument(+ "--config",+ default=None,+ help="config path; defaults to ~/Library/Application Support/Beamer/config.json",+ )+ parser.add_argument("--hidden", action="store_true", help="start in the menu bar without opening the window")+ return parser.parse_args(argv)+++def main(argv=None):+ args = parse_args(argv)+ if sys.platform != "darwin":+ raise SystemExit("Beamer must run on macOS")+ instance_lock = acquire_instance_lock()+ if instance_lock is None:+ return+ AppKit.NSApplication.sharedApplication()+ theme.init_fonts()+ logger = configure_logging()+ # Which faces actually carried the window: the only way to tell the bundled copies failed to+ # register is to say what was used instead.+ logger.info("type: %s / %s", theme.sans(), theme.mono())+ if args.config is None:+ migrate_legacy_config()+ settings_store = SettingsStore(args.config)+ try:+ cfg = settings_store.load()+ except SettingsError as exc:+ logger.warning("settings not loaded: %s", exc)+ cfg = editable_default_config()+ controller = WakingController(cfg, logger=logger)+ app = TrayApp(controller, settings_store, logger, hidden=args.hidden)+ controller.start()+ try:+ app.run()+ finally:+ controller.stop()+ instance_lock.close()+++if __name__ == "__main__":+ main()diff --git a/mac_app/link_state.py b/mac_app/link_state.pynew file mode 100644index 0000000..0387c6a--- /dev/null+++ b/mac_app/link_state.py@@ -0,0 +1,99 @@+"""What the status module says about the link: a tone, a state word, the LED tag and one sentence.++Pure, so every status the controller can report is tested against a word. The controller's+booleans decide the broad state; its status string only picks the flavour of a fault, and a string+nobody has seen before still lands on a word with the controller's own sentence as the detail.+"""++from __future__ import annotations++from dataclasses import dataclass++from bridge import AUTH_FAILED_STATUS, OLD_RECEIVER_STATUS+from wake import NOT_WOKEN_STATUS++SIGNAL = "signal"+AMBER = "amber"+FAULT = "fault"+INK = "ink"++TUNNEL_STATUS = "Connected to Windows via secure macOS 27 fallback"+++@dataclass(frozen=True)+class LinkState:+ key: str+ tone: str+ word: str+ tag: str+ detail: str+ led: str+ blink: bool = False+++def peer_name(cfg) -> str:+ return cfg.pc_name or cfg.host or "Windows"+++def describe(controller) -> LinkState:+ cfg = controller.cfg+ peer = peer_name(cfg)+ status = controller.connection_status or ""+ tunnel = status.startswith(TUNNEL_STATUS) or getattr(controller, "_status_before_unlock", None) == TUNNEL_STATUS+ if getattr(controller, "receiving", False):+ return LinkState(+ "receiving", SIGNAL, "From Windows", "Live",+ f"{peer}'s keyboard and pointer are on this Mac. Push its pointer back through the edge "+ "it arrived by to send them home.",+ SIGNAL,+ )+ if controller.waking:+ return LinkState("waking", AMBER, "Waking", "Waking", "Waking Windows. It connects on its own once it is up.", AMBER, True)+ if controller.connected:+ linked = "Tunnel" if tunnel else "Linked"+ if controller.windows_locked:+ return LinkState(+ "unlocking", AMBER, "Unlocking", "Unlocking",+ f"{peer} is at its lock screen and is unlocking itself; input follows once the desktop is back.",+ AMBER, True,+ )+ if controller.redirecting:+ return LinkState(+ "windows", SIGNAL, "On Windows", "Live",+ f"Keyboard and pointer are on {peer}. Do the same again to bring them home.", SIGNAL,+ )+ armed = controller.crossing.armed+ if armed and controller.crossing_paused:+ return LinkState(+ "paused", INK, "Paused", "Held",+ f"Connected to {peer}. Crossing is held, so you can lean on an edge.", SIGNAL,+ )+ if armed and controller.full_screen_app is not None:+ return LinkState(+ "full_screen", INK, "Held", "Held",+ f"{controller.full_screen_app} is full screen, so edges are off while it has focus.", SIGNAL,+ )+ via = " through the macOS 27 tunnel" if tunnel else ""+ return LinkState("mac", INK, "On Mac", linked, f"Connected to {peer}{via}.", SIGNAL)+ if not (cfg.host and cfg.auth_token):+ return LinkState("unpaired", AMBER, "Not paired", "Setup", "Pair with a PC on the Pairing page and Beamer connects on its own.", AMBER)+ address = f"{cfg.host} port {cfg.port}"+ if status == AUTH_FAILED_STATUS:+ return LinkState("token", FAULT, "Token mismatch", "Refused", f"{peer} refused this Mac's shared token. Pair again to write a fresh one.", FAULT)+ if status == OLD_RECEIVER_STATUS or status.startswith("Windows receiver speaks Beamer protocol"):+ return LinkState("version", FAULT, "Version mismatch", "Refused", f"{peer} runs a different Beamer from this Mac. Update both to the same version.", FAULT)+ if status.startswith("Windows rejected the connection"):+ return LinkState("rejected", FAULT, "Refused", "Refused", status + ".", FAULT)+ if status == NOT_WOKEN_STATUS:+ return LinkState("not_woken", FAULT, "Did not wake", "No reply", f"{peer} did not answer within a minute of the wake-up packet.", FAULT)+ if status.startswith("macOS 27 blocked direct LAN access"):+ return LinkState("blocked", FAULT, "Blocked", "Tunnel", "macOS 27 blocked direct LAN access. Open Beamer Tunnel from Applications.", FAULT)+ if status.startswith("Windows is unreachable") or status.startswith("Windows did not answer before"):+ return LinkState("unreachable", FAULT, "Unreachable", "No reply", f"{address} is not answering. The PC may be asleep or off this network.", FAULT)+ if status.startswith("Windows is reachable, but Beamer is not listening"):+ return LinkState("not_listening", FAULT, "Not listening", "No receiver", f"{peer} answers, but Beamer is not listening on port {cfg.port}. Open Beamer on the PC.", FAULT)+ if status == "Windows stopped responding":+ return LinkState("stopped", FAULT, "No reply", "Dropped", f"{peer} stopped responding. Beamer keeps trying to reconnect.", FAULT)+ if status.startswith("Connecting to") or status in ("Waiting to connect", "Settings saved; reconnecting"):+ return LinkState("waiting", AMBER, "Waiting", "Looking", f"Looking for {peer}. It connects on its own once Beamer is open there.", AMBER, True)+ return LinkState("dropped", FAULT, "Disconnected", "Dropped", (status.rstrip(".") + ". Beamer keeps trying to reconnect.") if status else "Beamer keeps trying to reconnect.", FAULT)diff --git a/mac_app/login_item.py b/mac_app/login_item.pynew file mode 100644index 0000000..6a402c3--- /dev/null+++ b/mac_app/login_item.py@@ -0,0 +1,41 @@+"""Start at login, owned by the app through SMAppService: macOS keeps the record, so there is no+config field to disagree with it.++ServiceManagement is loaded from the system framework rather than through+pyobjc-framework-ServiceManagement, which would be a new dependency for four calls.+"""++import objc++objc.loadBundle(+ "ServiceManagement", {}, bundle_path="/System/Library/Frameworks/ServiceManagement.framework"+)+for _selector in (b"registerAndReturnError:", b"unregisterAndReturnError:"):+ objc.registerMetaDataForSelector(+ b"SMAppService", _selector, {"arguments": {2: {"type_modifier": objc._C_OUT}}}+ )+SMAppService = objc.lookUpClass("SMAppService")++NOT_REGISTERED, ENABLED, REQUIRES_APPROVAL, NOT_FOUND = 0, 1, 2, 3+++def status():+ return SMAppService.mainAppService().status()+++def is_enabled():+ """Waiting for approval in Login Items counts as on: the choice was made here."""+ return status() in (ENABLED, REQUIRES_APPROVAL)+++def set_enabled(enabled):+ """Raises OSError with macOS's own words when it refuses."""+ service = SMAppService.mainAppService()+ if enabled:+ ok, error = service.registerAndReturnError_(None)+ else:+ if service.status() not in (ENABLED, REQUIRES_APPROVAL):+ return+ ok, error = service.unregisterAndReturnError_(None)+ if not ok:+ raise OSError(error.localizedDescription() if error is not None else "macOS refused")diff --git a/mac_app/media_keys.py b/mac_app/media_keys.pynew file mode 100644index 0000000..8b5068b--- /dev/null+++ b/mac_app/media_keys.py@@ -0,0 +1,44 @@+"""macOS media/volume key capture.++The F7-F12 row does not produce ordinary key events. macOS delivers those+presses as NSSystemDefined events (raw NSEventType 14) carrying subtype 8,+NX_SUBTYPE_AUX_CONTROL_BUTTONS, with the actual button and its up/down state+packed into `data1`. There is no public kCGEventType constant for this, so+the tap mask is built from the raw value, exactly as gestures.py does.++Bit layout of data1 (IOKit's hidsystem/ev_keymap.h):+ bits 31..16 NX key code (which button)+ bits 15..8 key state: 0x0A down, 0x0B up+ bit 0 autorepeat+"""++NX_SYSDEFINED_EVENT_TYPE = 14+NX_SUBTYPE_AUX_CONTROL_BUTTONS = 8++NX_KEY_NAMES = {+ 0: "volume_up",+ 1: "volume_down",+ 7: "volume_mute",+ 16: "media_play_pause",+ 17: "media_next",+ 18: "media_prev",+ 19: "media_next",+ 20: "media_prev",+}++_KEY_STATE_DOWN = 0x0A+++def decode(subtype, data1):+ """Return (key_name, is_down, is_repeat) for a media-key press, or None+ if this system-defined event is not one (brightness, keyboard backlight,+ Mission Control and several undocumented subtypes share this event+ type)."""+ if int(subtype) != NX_SUBTYPE_AUX_CONTROL_BUTTONS:+ return None+ data1 = int(data1)+ name = NX_KEY_NAMES.get((data1 & 0xFFFF0000) >> 16)+ if name is None:+ return None+ state = (data1 & 0xFF00) >> 8+ return name, state == _KEY_STATE_DOWN, bool(data1 & 0x1)diff --git a/mac_app/no_unlock.py b/mac_app/no_unlock.pynew file mode 100644index 0000000..79869be--- /dev/null+++ b/mac_app/no_unlock.py@@ -0,0 +1,16 @@+"""The Mac has no lock-screen unlock, and the receiver is written to expect+one. `is_locked` answering None is how it says "no idea, carry on" -- the same+answer the Windows module gives when Room Deck's provider is absent.++A Mac at its own lock screen simply does not receive the PC's input; macOS+gives no application a way to type on it, exactly as Windows gives none for+Winlogon.+"""+++def is_locked():+ return None+++def ensure_unlocked():+ return Falsediff --git a/mac_app/notch_beam.py b/mac_app/notch_beam.pynew file mode 100644index 0000000..e309a50--- /dev/null+++ b/mac_app/notch_beam.py@@ -0,0 +1,321 @@+"""The notch beam: crossing feedback for a push through the notch, after Border Beam+(libraries.dev/beam, the `border-beam` package's `colorful` palette on a dark ground).++The other notch style, the island, is notch_island.py; which one plays is `crossing.notch_style`,+chosen on the Crossing page. This shares the island's panel, geometry, breakthrough timing and+lifecycle by subclassing it, and replaces what is drawn.++A small black tab extends the notch while pressure builds, so there is a border below the camera+housing for light to ride. A comet travels that border: the palette is seen through strokes of the+border's own path, a faint one all the way along and a few short stacked segments at the comet's+head, and a blurred copy through wider strokes is the bloom. Pressure sets how bright it is and how+fast it travels, a trackpad tick flares the bloom, and breakthrough lights the whole border in a halo+while the comet runs on off the end.++The comet moves by distance along the path (strokeStart and strokeEnd), in at the left shoulder and+out at the right, with the notch itself hiding the way back. The package turns a conic mask instead,+and on a card that is fine; on this tab, far wider than it is deep, it was not: half of every turn+pointed up into the camera cutout, which has no pixels, the short sides lit all at once as the sweep+crossed them, and the long bottom shrank the comet to a spot. Recorded 15-09-2026 as flashing.++Movement is integrated on the frame timer rather than left to a CABasicAnimation, because its speed+follows pressure and retiming a running animation jumps. Reduce Motion parks the comet mid-border.++Main thread only. Any failure disables it for the run; crossing never depends on it.+"""++import time++import AppKit+import Quartz++import tokens+from notch_island import (+ NOTCH_FALLBACK_HEIGHT,+ PAD,+ SHOULDER,+ NotchIsland,+ _colour,+ _no_actions,+ after_seconds,+ breakthrough_phase,+ ease_out,+)+# The comet as stacked stroke segments, (half length as a fraction of the border, opacity): stacked,+# they give the package's soft falloff, near 0.95 at the head and 0.2 at the tips.+SEGMENTS = ((0.16, 0.22), (0.10, 0.30), (0.05, 0.45), (0.02, 0.70))+COMET_HALF = SEGMENTS[0][0]+# One lap in head positions: from fully off the start of the border to fully off its end.+LAP = 1.0 + 2 * COMET_HALF+BASE = 0.16++GROW_W = 10.0+GROW_D = 9.0+STROKE = 1.5+BLOOM_STROKE = 6.0+BLUR = 7.0+SLOW_TURN_S = 2.8+FAST_TURN_S = 0.9+FADE_IN_S = 0.12+FADE_OUT_S = 0.35+TICK_S = 0.18+HALO_S = 0.6++# The edge glow's beam style, kvm_bridge_app.EdgeGlow: a comet running along a straight edge.+EDGE_COMET = 0.3+EDGE_BASE = 0.2+EDGE_SLOW_S = 2.4+EDGE_FAST_S = 0.8+EDGE_FINISH_S = 0.6+EDGE_FINISH_TRAVERSE_S = 0.35+++def palette_colours(name, closed=False):+ """CGColors for one of tokens.PALETTES, a lone colour repeated so a gradient has two stops, and+ with `closed` ending on the first colour so a conic ring has no seam."""+ values = list(tokens.PALETTES.get(name, tokens.PALETTES["signal"]))+ if len(values) == 1:+ values *= 2+ if closed:+ values.append(values[0])+ return [_colour(value) for value in values]+++def edge_traverse_seconds(strength):+ """One run of the edge comet from end to end: unhurried at a light lean, quick near breakthrough."""+ strength = max(0.0, min(1.0, strength))+ return EDGE_SLOW_S + (EDGE_FAST_S - EDGE_SLOW_S) * strength+++def edge_comet_alpha(position, centre, flash):+ """How lit a straight edge is at `position` (0 to 1 along it) with the comet's head at `centre`:+ a dim base, raised to `flash` at breakthrough, and a peak falling away over half the comet."""+ base = max(EDGE_BASE, min(1.0, flash))+ reach = max(0.0, 1.0 - abs(position - centre) / (EDGE_COMET / 2.0))+ return base + (1.0 - base) * reach * reach+++def lap_finish(position, after):+ """How far the comet travels once the push has gone through: off the end of the lap it is on,+ plus as many whole laps as fit at its fastest pace in `after` seconds, so it leaves by the far+ shoulder instead of stopping wherever the crossing caught it."""+ remaining = LAP - position % LAP+ extra = max(0, round(after / FAST_TURN_S - remaining / LAP))+ return remaining + LAP * extra+++def comet_segments(position):+ """(strokeStart, strokeEnd) for each of SEGMENTS with the lap at `position`, clamped to the+ border; a segment wholly off either end comes back empty, start equal to end."""+ head = position - COMET_HALF+ spans = []+ for half, _opacity in SEGMENTS:+ start = min(1.0, max(0.0, head - half))+ end = min(1.0, max(0.0, head + half))+ spans.append((start, max(start, end)))+ return spans+++def turn_seconds(strength):+ """One lap of the border: an unhurried drift at a light lean, quick near breakthrough."""+ strength = max(0.0, min(1.0, strength))+ return SLOW_TURN_S + (FAST_TURN_S - SLOW_TURN_S) * strength+++def approach(current, target, elapsed):+ """Strength moves toward pressure at a fixed rate, quicker in than out, so a push that stops+ fades the beam like the package's fade-out instead of cutting it."""+ if target > current:+ return min(target, current + elapsed / FADE_IN_S)+ return max(target, current - elapsed / FADE_OUT_S)+++def _rgb(red, green, blue, alpha=1.0):+ return AppKit.NSColor.colorWithSRGBRed_green_blue_alpha_(red / 255, green / 255, blue / 255, alpha).CGColor()+++class NotchBeam(NotchIsland):+ def __init__(self, controller, logger):+ super().__init__(controller, logger)+ self.strength = 0.0+ self.position = 0.0+ self.flare = 0.0+ self.drawn_at = None+ self.comets = []+ self.gradients = []+ self.painted = None+ self.cross_position = 0.0+ self.cross_travel = 0.0+ self.halo_at = None++ def update(self, kind):+ if self.disabled or kind not in ("pressure", "tick", "cross"):+ return+ try:+ if kind == "tick":+ self.flare = 1.0+ elif kind == "cross":+ self.cross_at = self.halo_at = time.monotonic()+ self.held = 0.0+ self.cross_position = self.position+ self.cross_travel = lap_finish(self.position, after_seconds(self.controller))+ self._draw()+ except Exception:+ self._fail()++ def _draw(self):+ now = time.monotonic()+ elapsed = 0.0 if self.drawn_at is None else min(0.1, now - self.drawn_at)+ self.drawn_at = now+ level = self._held(self.controller.crossing_pressure_now(), now)+ flash = 0.0+ after = after_seconds(self.controller)+ if self.cross_at is not None:+ phase = breakthrough_phase(now - self.cross_at, after)+ if phase is None:+ self.cross_at = None+ self.position = (self.cross_position + self.cross_travel) % LAP+ else:+ level, flash = max(level, phase[0]), phase[1]+ halo = 0.0 if self.halo_at is None else max(0.0, 1.0 - (now - self.halo_at) / HALO_S)+ if not self.visible:+ if level <= 0.0:+ self.drawn_at = None+ return+ if not self._show():+ return+ self.strength = approach(self.strength, level, elapsed)+ self.flare = max(0.0, self.flare - elapsed / TICK_S)+ if AppKit.NSWorkspace.sharedWorkspace().accessibilityDisplayShouldReduceMotion():+ self.position = LAP / 2.0+ elif self.cross_at is not None:+ travelled = self.cross_travel * ease_out((now - self.cross_at) / after)+ self.position = (self.cross_position + travelled) % LAP+ elif level > 0.0:+ # Only while pushing: fading out after a crossing it would otherwise start a fresh lap+ # in from the near shoulder, a new flash on the way out.+ self.position = (self.position + LAP * elapsed / turn_seconds(self.strength)) % LAP+ spans = comet_segments(self.position)+ colour = self.controller.cfg.crossing["glow_colour"]+ with _no_actions():+ if colour != self.painted:+ for gradient in self.gradients:+ gradient.setColors_(palette_colours(colour, closed=True))+ self.painted = colour+ for segments in self.comets:+ for layer, (start, end) in zip(segments, spans):+ # A round cap draws a dot even for an empty stroke, so a segment all but gone+ # off an end is hidden rather than left blinking at the shoulder.+ layer.setHidden_(end - start < 0.002)+ layer.setStrokeStart_(start)+ layer.setStrokeEnd_(end)+ # The tab is only somewhere for light to ride, so it is there at once rather than+ # greying in with pressure, which read as a dim flash under a slow lean.+ self.island.setOpacity_(min(1.0, self.strength * 20.0))+ self.beam.setOpacity_(min(1.0, self.strength + flash))+ self.bloom.setOpacity_(min(1.0, self.strength * 0.8 + self.flare * 0.35 + flash * 0.6))+ self.halo.setOpacity_(halo * 0.9)+ if level <= 0.0 and self.cross_at is None and self.strength <= 0.0:+ self.drawn_at = None+ self._hide()+ return+ if not getattr(self.timer, "is_alive", lambda: False)():+ self.timer.start()++ def _build(self, geometry):+ left, right, top, height = geometry+ self.notch_width = right - left+ self.notch_height = height or NOTCH_FALLBACK_HEIGHT+ spare = GROW_W + SHOULDER + PAD+ width = self.notch_width + 2 * spare+ panel_height = self.notch_height + GROW_D + PAD+ self.centre = width / 2.0+ panel, stage = self._panel(AppKit.NSMakeRect(left - spare, top - panel_height, width, panel_height))+ panel.contentView().setLayerUsesCoreImageFilters_(True)+ bounds = stage.bounds()++ island = Quartz.CAShapeLayer.layer()+ island.setFrame_(bounds)+ island.setFillColor_(AppKit.NSColor.blackColor().CGColor())+ island.setPath_(self._island_path(GROW_W, GROW_D))+ island.setOpacity_(0.0)+ stage.addSublayer_(island)++ border = self._outline(GROW_W, GROW_D, closed=False, shoulders=True)+ middle = (self.centre, (self.notch_height + GROW_D) / 2.0)+ side = 2.0 * max(width, panel_height)+ self.comets = []+ self.gradients = []+ self.painted = None++ bloom = self._blurred(bounds, BLUR)+ bloom.addSublayer_(self._ring(border, BLOOM_STROKE, bounds, middle, side))+ stage.addSublayer_(bloom)++ beam = self._ring(border, STROKE, bounds, middle, side)+ beam.setOpacity_(0.0)+ stage.addSublayer_(beam)++ # The breakthrough: the whole border lights at once and blooms out, like the package's+ # pulse-outside, while the comet runs on off the end.+ halo = self._blurred(bounds, BLUR * 1.6)+ halo.addSublayer_(self._ring(border, BLOOM_STROKE * 1.5, bounds, middle, side, comet=False))+ stage.addSublayer_(halo)++ self.panel = panel+ self.island = island+ self.bloom = bloom+ self.beam = beam+ self.halo = halo++ @staticmethod+ def _blurred(bounds, radius):+ layer = Quartz.CALayer.layer()+ layer.setFrame_(bounds)+ blur = Quartz.CIFilter.filterWithName_("CIGaussianBlur")+ blur.setDefaults()+ blur.setValue_forKey_(radius, "inputRadius")+ layer.setFilters_([blur])+ layer.setOpacity_(0.0)+ return layer++ def _ring(self, path, line_width, bounds, middle, side, comet=True):+ """The palette seen through strokes of `path`: a faint line the whole way with the comet's+ segments over it, or the whole path at full strength with `comet` off."""+ ring = Quartz.CALayer.layer()+ ring.setFrame_(bounds)+ mask = Quartz.CALayer.layer()+ mask.setFrame_(bounds)+ mask.addSublayer_(self._stroke(path, line_width, bounds, BASE if comet else 1.0))+ if comet:+ segments = []+ for _half, opacity in SEGMENTS:+ segment = self._stroke(path, line_width, bounds, opacity)+ segment.setHidden_(True)+ mask.addSublayer_(segment)+ segments.append(segment)+ self.comets.append(segments)+ ring.setMask_(mask)++ colours = Quartz.CAGradientLayer.layer()+ colours.setType_(Quartz.kCAGradientLayerConic)+ colours.setFrame_(((middle[0] - side / 2.0, middle[1] - side / 2.0), (side, side)))+ colours.setStartPoint_((0.5, 0.5))+ colours.setEndPoint_((0.5, 0.0))+ colours.setColors_(palette_colours("signal", closed=True))+ self.gradients.append(colours)+ ring.addSublayer_(colours)+ return ring++ @staticmethod+ def _stroke(path, line_width, bounds, opacity):+ stroke = Quartz.CAShapeLayer.layer()+ stroke.setFrame_(bounds)+ stroke.setPath_(path)+ stroke.setFillColor_(None)+ stroke.setStrokeColor_(_rgb(255, 255, 255))+ stroke.setLineWidth_(line_width)+ stroke.setLineCap_(Quartz.kCALineCapRound)+ stroke.setLineJoin_(Quartz.kCALineJoinRound)+ stroke.setOpacity_(opacity)+ return strokediff --git a/mac_app/notch_island.py b/mac_app/notch_island.pynew file mode 100644index 0000000..c9db26e--- /dev/null+++ b/mac_app/notch_island.py@@ -0,0 +1,469 @@+"""The notch island: crossing feedback for a push through the notch.++The edge glow cannot do this job. It draws a band inward from the strip being pushed, and the notch+strip sits in the top 32pt of a notched screen, where the display has no pixels at all: the band+topped out at 20pt, so every frame of it was drawn behind the camera housing and nobody ever saw it.++So the notch grows instead, drawn to the Vernier design (docs/designs/claude-2-vernier.html). A black+shape with the notch's own concave shoulders sits over the cutout, invisible at rest. Pressure+springs it wider and down past the cutout; a signal-coloured rim and glow trace its lower outline,+and once it is deep enough a four-segment meter and the percentage appear inside it. Each trackpad+tick gives the width a small velocity kick, so the tick is seen as well as felt. Breakthrough plays+as its own fixed sequence, see `breakthrough_phase`. Everything that glows or reads is masked to+below the cutout.++Core Animation does the motion: every pressure change retargets a CASpringAnimation on the shape's+path from its presentation value, so a push that wavers never jumps. Reduce Motion replaces growth+with a fixed island whose fill, rim and meter fade with pressure.++Main thread only, like EdgeGlow. Any failure disables it for the run; crossing never depends on it.+"""++import time++import AppKit+import Quartz+import rumps++import tokens++NOTCH_FALLBACK_HEIGHT = 32.0+SHOULDER = 8.0+PAD = 24.0+OVERSHOOT = 1.25+FLASH_RIM = "#d8f5fd"+BREAKTHROUGH_GROW_S = 0.28+BREAKTHROUGH_HOLD_S = 0.32+TRACE_PASS_S = 0.7+TRACE_LENGTH = 0.22+GRACE_S = 0.9+++def breakthrough_phase(elapsed, total=BREAKTHROUGH_GROW_S + BREAKTHROUGH_HOLD_S):+ """(level, flash) while a breakthrough plays, or None once it has. The island goes to full size+ with the rim flashing pale, holds, then the ordinary spring takes it home. It cannot simply+ follow pressure: replaying trackpad deltas through the crossing engine, a steady push breaks+ through 0.17s after pressure starts and a flick in 0.02 to 0.05s, while the island's spring+ needs about half a second to grow, so a push-driven island read as a flicker or not at all."""+ if elapsed < 0 or elapsed >= max(total, BREAKTHROUGH_GROW_S):+ return None+ return 1.0, max(0.0, 1.0 - elapsed / BREAKTHROUGH_GROW_S)+++def ease_out(t):+ t = max(0.0, min(1.0, t))+ return 1.0 - (1.0 - t) ** 3+++def after_seconds(controller):+ """How long a crossing keeps playing once it has gone through: crossing.notch_after_ms. Before+ it was a setting both styles stopped after a fixed 0.6s, mid-animation, which read as a pause."""+ return controller.cfg.crossing["notch_after_ms"] / 1000.0+++def trace_head(progress, after):+ """Where the light that runs along the rim after a crossing is: its head as a fraction of the+ rim, running up to TRACE_LENGTH past the end so the tail leaves too. It makes whole passes only,+ as many as fit at about TRACE_PASS_S each, and is off the end by 80% of the way through, so it+ never stops part way along."""+ passes = max(1, round(0.8 * after / TRACE_PASS_S))+ scaled = min(1.0, max(0.0, progress) / 0.8) * passes+ fraction = 1.0 if scaled >= passes else scaled % 1.0+ return ease_out(fraction) * (1.0 + TRACE_LENGTH)+++def notch_geometry():+ """(left, right, top, height) of the notch in AppKit global coordinates, or None. Same+ derivation as notch_x_range: the two auxiliary top areas of the screen that forms the top of+ the desktop, with the height taken from that screen's top safe-area inset."""+ screens = AppKit.NSScreen.screens()+ if not screens:+ return None+ desktop_top = max(s.frame().origin.y + s.frame().size.height for s in screens)+ for screen in screens:+ frame = screen.frame()+ top = frame.origin.y + frame.size.height+ if top != desktop_top:+ continue+ try:+ height = screen.safeAreaInsets().top+ left_area = screen.auxiliaryTopLeftArea()+ right_area = screen.auxiliaryTopRightArea()+ except AttributeError:+ continue+ if height <= 0 or left_area is None or right_area is None:+ continue+ if left_area.size.width <= 0 or right_area.size.width <= 0:+ continue+ return (left_area.origin.x + left_area.size.width, right_area.origin.x, top, height)+ return None+++def _colour(name_or_hex, alpha=1.0):+ value = tokens.PALETTE.get(name_or_hex, name_or_hex).lstrip("#")+ red, green, blue = (int(value[index:index + 2], 16) / 255 for index in (0, 2, 4))+ return AppKit.NSColor.colorWithSRGBRed_green_blue_alpha_(red, green, blue, alpha).CGColor()+++def _spring(key, stiffness, damping, start, end, velocity=0.0):+ spring = Quartz.CASpringAnimation.animationWithKeyPath_(key)+ spring.setMass_(1.0)+ spring.setStiffness_(stiffness)+ spring.setDamping_(damping)+ spring.setInitialVelocity_(velocity)+ spring.setFromValue_(start)+ spring.setToValue_(end)+ spring.setDuration_(spring.settlingDuration())+ return spring+++class NotchIsland:+ def __init__(self, controller, logger):+ self.controller = controller+ self.logger = logger+ self.panel = None+ self.geometry = None+ self.visible = False+ self.disabled = False+ self.cross_at = None+ self.rest_at = None+ self.target = None+ self.kick = 0.0+ self.held = 0.0+ self.held_at = None+ self.timer = rumps.Timer(self._tick, 1 / 60)++ def _held(self, level, now):+ """Pressure as the animation shows it. Lifting a finger to reposition lets real pressure+ drain to nothing in 0.4s, which dropped the animation and started it again from scratch;+ while the pointer is still pinned at the notch, the highest recent pressure is held for+ GRACE_S instead. That includes a slow push, whose pressure drains to nothing between every+ pair of events: reading the engine's pin, which it drops each time, showed and hid the+ notch several times a second, a strobe recorded 15-09-2026. Moving off the notch still lets+ go at once, since the engine stops touching."""+ if not getattr(getattr(self.controller, "crossing", None), "touching", False):+ self.held, self.held_at = level, now+ elif level >= self.held or self.held_at is None or now - self.held_at > GRACE_S:+ self.held, self.held_at = level, now+ return self.held++ def update(self, kind):+ if self.disabled or kind not in ("pressure", "tick", "cross"):+ return+ try:+ if kind == "tick":+ self.kick += tokens.SPRING["tick_velocity"]+ elif kind == "cross":+ self.cross_at = time.monotonic()+ self.held = 0.0+ self._draw()+ except Exception:+ self._fail()++ def _tick(self, _timer):+ if self.disabled:+ self.timer.stop()+ return+ try:+ self._draw()+ except Exception:+ self._fail()++ def _draw(self):+ now = time.monotonic()+ level = self._held(self.controller.crossing_pressure_now(), now)+ flash = 0.0+ trace = None+ if self.cross_at is not None:+ after = after_seconds(self.controller)+ phase = breakthrough_phase(now - self.cross_at, after)+ if phase is None:+ self.cross_at = None+ else:+ level, flash = max(level, phase[0]), phase[1]+ trace = trace_head((now - self.cross_at) / after, after)+ if not self.visible:+ if level <= 0.0:+ return+ if not self._show():+ return+ reduce_motion = AppKit.NSWorkspace.sharedWorkspace().accessibilityDisplayShouldReduceMotion()+ if reduce_motion:+ self._draw_reduced(level)+ else:+ self._draw_moving(level, flash, trace)+ if level > 0.0 or self.cross_at is not None:+ self.rest_at = None+ elif self.rest_at is None:+ self.rest_at = now+ elif now - self.rest_at > 0.6:+ self._hide()+ return+ if not getattr(self.timer, "is_alive", lambda: False)():+ self.timer.start()++ def _draw_moving(self, level, flash, trace=None):+ grow_w = level * tokens.ISLAND["grow_width"]+ grow_d = level * tokens.ISLAND["grow_depth"]+ kick, self.kick = self.kick, 0.0+ if self.target is None or kick or abs(self.target[0] - grow_w) >= 0.5 or abs(self.target[1] - grow_d) >= 0.5:+ self.target = (grow_w, grow_d)+ params = tokens.SPRING["island"]+ span = max(1.0, abs(grow_w - self._presented_width()))+ self._retarget(grow_w, grow_d, params["stiffness"], params["damping"], kick / span)+ with _no_actions():+ self.island.setOpacity_(1.0)+ self.rim.setStrokeColor_(_colour(FLASH_RIM) if flash > 0 else _colour("signal"))+ self.rim.setOpacity_(min(1.0, 0.25 + level * 0.9 + flash) if level > 0 or flash > 0 else 0.0)+ self.rim.setShadowOpacity_(min(1.0, level * 0.75 + flash))+ self.rim.setShadowRadius_(7.0 + flash * 7.0)+ if trace is None:+ self.trace.setOpacity_(0.0)+ else:+ self.trace.setStrokeStart_(max(0.0, trace - TRACE_LENGTH))+ self.trace.setStrokeEnd_(min(1.0, trace))+ self.trace.setOpacity_(1.0)+ meter = max(0.0, min(1.0, (grow_d - tokens.ISLAND["meter_after_depth"]) / 8.0))+ self._set_meter(level, meter)++ def _draw_reduced(self, level):+ full_w, full_d = tokens.ISLAND["grow_width"], tokens.ISLAND["grow_depth"]+ if self.target != (full_w, full_d):+ self.target = (full_w, full_d)+ with _no_actions():+ self.island.removeAllAnimations()+ self.rim.removeAllAnimations()+ self.island.setPath_(self._island_path(full_w, full_d))+ self.rim.setPath_(self._rim_path(full_w, full_d))+ with _no_actions():+ self.island.setOpacity_(min(1.0, level * 4.0))+ self.rim.setStrokeColor_(_colour("signal"))+ self.rim.setOpacity_(level)+ self.rim.setShadowOpacity_(level * 0.75)+ self._set_meter(level, level)++ def _retarget(self, grow_w, grow_d, stiffness, damping, velocity):+ layers = (+ (self.island, self._island_path(grow_w, grow_d)),+ (self.rim, self._rim_path(grow_w, grow_d)),+ (self.trace, self._rim_path(grow_w, grow_d)),+ )+ for layer, path in layers:+ presented = layer.presentationLayer()+ start = (presented or layer).path()+ with _no_actions():+ layer.setPath_(path)+ layer.addAnimation_forKey_(_spring("path", stiffness, damping, start, path, velocity), "path")++ def _presented_width(self):+ presented = self.island.presentationLayer()+ box = Quartz.CGPathGetBoundingBox((presented or self.island).path())+ return max(0.0, (box.size.width - 2 * SHOULDER - self.notch_width) / 2.0)++ def _set_meter(self, level, opacity):+ self.meter.setOpacity_(opacity)+ for index, bar in enumerate(self.segments):+ share = max(0.0, min(1.0, level * len(self.segments) - index))+ frame = bar.frame()+ bar.setFrame_(((frame.origin.x, frame.origin.y), (self.segment_width * share, frame.size.height)))+ self.percent.setString_(str(round(level * 100)))++ def _show(self):+ geometry = notch_geometry()+ if geometry is None:+ return False+ if geometry != self.geometry or self.panel is None:+ self.geometry = geometry+ self._build(geometry)+ self.panel.orderFrontRegardless()+ self.visible = True+ return True++ def _build(self, geometry):+ left, right, top, height = geometry+ self.notch_width = right - left+ self.notch_height = height or NOTCH_FALLBACK_HEIGHT+ spare = tokens.ISLAND["grow_width"] * OVERSHOOT + SHOULDER + PAD+ width = self.notch_width + 2 * spare+ panel_height = self.notch_height + tokens.ISLAND["grow_depth"] * OVERSHOOT + PAD+ self.centre = width / 2.0+ panel, stage = self._panel(AppKit.NSMakeRect(left - spare, top - panel_height, width, panel_height))+ scale = panel.backingScaleFactor()++ island = Quartz.CAShapeLayer.layer()+ island.setFrame_(stage.bounds())+ island.setFillColor_(AppKit.NSColor.blackColor().CGColor())+ island.setPath_(self._island_path(0.0, 0.0))+ stage.addSublayer_(island)++ below = Quartz.CALayer.layer()+ below.setFrame_(((0, self.notch_height), (width, panel_height - self.notch_height)))+ below.setBackgroundColor_(AppKit.NSColor.blackColor().CGColor())++ rim = Quartz.CAShapeLayer.layer()+ rim.setFrame_(stage.bounds())+ rim.setFillColor_(None)+ rim.setStrokeColor_(_colour("signal"))+ rim.setLineWidth_(2.0)+ rim.setPath_(self._rim_path(0.0, 0.0))+ rim.setShadowColor_(_colour("signal"))+ rim.setShadowOffset_((0.0, 0.0))+ rim.setShadowRadius_(7.0)+ rim.setOpacity_(0.0)+ rim.setMask_(below)+ stage.addSublayer_(rim)++ # A layer can mask only one other, so the trace gets its own copy of `below`.+ trace_below = Quartz.CALayer.layer()+ trace_below.setFrame_(below.frame())+ trace_below.setBackgroundColor_(AppKit.NSColor.blackColor().CGColor())+ trace = Quartz.CAShapeLayer.layer()+ trace.setFrame_(stage.bounds())+ trace.setFillColor_(None)+ trace.setStrokeColor_(_colour(FLASH_RIM))+ trace.setLineWidth_(2.5)+ trace.setLineCap_(Quartz.kCALineCapRound)+ trace.setPath_(self._rim_path(0.0, 0.0))+ trace.setShadowColor_(_colour(FLASH_RIM))+ trace.setShadowOffset_((0.0, 0.0))+ trace.setShadowRadius_(6.0)+ trace.setShadowOpacity_(1.0)+ trace.setOpacity_(0.0)+ trace.setMask_(trace_below)+ stage.addSublayer_(trace)++ meter = Quartz.CALayer.layer()+ meter.setFrame_(stage.bounds())+ meter.setOpacity_(0.0)+ stage.addSublayer_(meter)+ count = tokens.ISLAND["meter_segments"]+ self.segment_width = 30.0+ pitch = 34.0+ first = self.centre - 98.0+ bar_top = self.notch_height + 7.0+ self.segments = []+ for index in range(count):+ track = Quartz.CALayer.layer()+ track.setFrame_(((first + index * pitch, bar_top), (self.segment_width, 4.0)))+ track.setCornerRadius_(1.0)+ track.setBackgroundColor_(_colour("rule"))+ meter.addSublayer_(track)+ bar = Quartz.CALayer.layer()+ bar.setFrame_(((first + index * pitch, bar_top), (0.0, 4.0)))+ bar.setCornerRadius_(1.0)+ bar.setBackgroundColor_(_colour("signal"))+ meter.addSublayer_(bar)+ self.segments.append(bar)+ percent = Quartz.CATextLayer.layer()+ percent.setFrame_(((self.centre + 98.0 - 40.0, bar_top - 5.0), (40.0, 14.0)))+ percent.setFont_(tokens.MONO_FAMILY)+ percent.setFontSize_(10.0)+ percent.setForegroundColor_(_colour("ink"))+ percent.setAlignmentMode_(Quartz.kCAAlignmentRight)+ percent.setContentsScale_(scale)+ meter.addSublayer_(percent)++ self.panel = panel+ self.island = island+ self.rim = rim+ self.trace = trace+ self.meter = meter+ self.percent = percent+ self.target = None++ def _panel(self, frame):+ """A borderless, click-through panel over the notch holding one top-left-origin stage+ layer, shared with the beam style so both sit exactly where the notch is."""+ width, panel_height = frame.size.width, frame.size.height+ if self.panel is not None:+ self.panel.orderOut_(None)+ panel = AppKit.NSPanel.alloc().initWithContentRect_styleMask_backing_defer_(+ frame,+ AppKit.NSWindowStyleMaskBorderless | AppKit.NSWindowStyleMaskNonactivatingPanel,+ AppKit.NSBackingStoreBuffered,+ False,+ )+ # Above the menu bar, which is where most of the island's width lives.+ panel.setLevel_(AppKit.NSPopUpMenuWindowLevel)+ panel.setOpaque_(False)+ panel.setHasShadow_(False)+ panel.setBackgroundColor_(AppKit.NSColor.clearColor())+ panel.setIgnoresMouseEvents_(True)+ panel.setCollectionBehavior_(+ AppKit.NSWindowCollectionBehaviorCanJoinAllSpaces+ | AppKit.NSWindowCollectionBehaviorFullScreenAuxiliary+ | AppKit.NSWindowCollectionBehaviorStationary+ )+ view = AppKit.NSView.alloc().initWithFrame_(AppKit.NSMakeRect(0, 0, width, panel_height))+ view.setWantsLayer_(True)+ panel.setContentView_(view)++ # Top-left origin inside the island, so every path below reads like the mock's SVG. The+ # window server puts a window on whole points, so the stage is offset by whatever that+ # rounding moved: the island asked for 88.5pt from x 689.5 and got 89 from x 689, which+ # anchored at the bottom left a one-pixel row of wallpaper above the black.+ actual = panel.frame()+ stage = Quartz.CALayer.layer()+ stage.setFrame_(((frame.origin.x - actual.origin.x, frame.origin.y - actual.origin.y), (width, panel_height)))+ stage.setGeometryFlipped_(True)+ view.layer().addSublayer_(stage)+ return panel, stage++ def _outline(self, grow_w, grow_d, closed, shoulders=None):+ """The notch's outline grown by `grow_w` each side and `grow_d` down. `shoulders` adds the+ concave curves out along the top edge, which a closed fill always has and the beam's open+ border wants too; a closed outline also closes along the top."""+ shoulders = closed if shoulders is None else shoulders+ width = self.notch_width + 2 * grow_w+ depth = self.notch_height + grow_d+ x0 = self.centre - width / 2.0+ x1 = self.centre + width / 2.0+ radius = 10.0 + grow_d * 0.35+ path = Quartz.CGPathCreateMutable()+ if shoulders:+ Quartz.CGPathMoveToPoint(path, None, x0 - SHOULDER, 0.0)+ Quartz.CGPathAddQuadCurveToPoint(path, None, x0, 0.0, x0, SHOULDER)+ else:+ Quartz.CGPathMoveToPoint(path, None, x0, SHOULDER)+ Quartz.CGPathAddLineToPoint(path, None, x0, depth - radius)+ Quartz.CGPathAddQuadCurveToPoint(path, None, x0, depth, x0 + radius, depth)+ Quartz.CGPathAddLineToPoint(path, None, x1 - radius, depth)+ Quartz.CGPathAddQuadCurveToPoint(path, None, x1, depth, x1, depth - radius)+ Quartz.CGPathAddLineToPoint(path, None, x1, SHOULDER)+ if shoulders:+ Quartz.CGPathAddQuadCurveToPoint(path, None, x1, 0.0, x1 + SHOULDER, 0.0)+ if closed:+ Quartz.CGPathCloseSubpath(path)+ return path++ def _island_path(self, grow_w, grow_d):+ return self._outline(grow_w, grow_d, closed=True)++ def _rim_path(self, grow_w, grow_d):+ return self._outline(grow_w, grow_d, closed=False)++ def _hide(self):+ self.timer.stop()+ self.rest_at = None+ self.target = None+ if self.panel is not None and self.visible:+ self.panel.orderOut_(None)+ self.visible = False++ def _fail(self):+ self.disabled = True+ self.logger.exception("notch island failed; notch feedback off for this run")+ try:+ self._hide()+ except Exception:+ pass+++class _no_actions:+ def __enter__(self):+ Quartz.CATransaction.begin()+ Quartz.CATransaction.setDisableActions_(True)++ def __exit__(self, *_exc):+ Quartz.CATransaction.commit()+ return Falsediff --git a/mac_app/pages.py b/mac_app/pages.pynew file mode 100644index 0000000..87085d2--- /dev/null+++ b/mac_app/pages.py@@ -0,0 +1,49 @@+"""The control window's pages, which one opens first, and which carry a dot in the sidebar.++Pure, so the rules are tested without AppKit.+"""++from __future__ import annotations++# (key, name, SF Symbol, what the page is for), in sidebar order; Cmd+1 is the first.+PAGES = (+ ("overview", "Overview", "gauge.with.needle",+ "Where input is, whether the link is up, and the two controls you reach for every day."),+ ("crossing", "Crossing", "cursorarrow.motionlines",+ "How the pointer passes from this Mac to Windows, and how hard the edge pushes back first."),+ ("design", "Design", "paintpalette",+ "How crossing looks and feels on this Mac: the notch, the edge and the trackpad. Every change applies as you make it."),+ ("keyboard", "Keyboard", "keyboard",+ "The key that switches input, and how the Mac's modifier keys arrive on Windows."),+ ("pairing", "Pairing", "link",+ "Connect this Mac to a PC by typing the code the PC shows. Once per Mac."),+ ("connection", "Connection", "network",+ "Where the PC is and the token this Mac proves itself with. Pairing fills these in."),+ ("permissions", "Permissions", "lock.shield",+ "macOS must allow Beamer to read this keyboard and trackpad before it can send them anywhere."),+)+KEYS = tuple(page[0] for page in PAGES)+++def opening_page(last, accessibility, input_monitoring):+ """The last page viewed in this run; on the first open, Permissions while either is still+ required, otherwise Overview."""+ if last in KEYS:+ return last+ return "overview" if accessibility and input_monitoring else "permissions"+++def dots(accessibility, input_monitoring, link_key):+ """Page key to the tone of its sidebar dot, for the pages that need one."""+ marks = {}+ if not (accessibility and input_monitoring):+ marks["permissions"] = "amber"+ if link_key == "token":+ marks["pairing"] = "fault"+ return marks+++def step(current, direction):+ """The page an arrow key moves to, stopping at either end of the list."""+ index = KEYS.index(current) if current in KEYS else 0+ return KEYS[min(max(index + direction, 0), len(KEYS) - 1)]diff --git a/mac_app/pairing.py b/mac_app/pairing.pynew file mode 100644index 0000000..dfd7925--- /dev/null+++ b/mac_app/pairing.py@@ -0,0 +1,590 @@+"""LAN discovery and pairing, shared by mac_app and win_app (two identical copies; the Mac+test suite checks they match byte for byte).++The Windows receiver broadcasts a small UDP beacon -- hostname, Beamer TCP port, and a random+pairing id while a code is on screen -- and the Mac lists what it hears. Pairing then runs as+one datagram each way:++ Mac -> PC pair_request {pair, pub: X25519 public key, proof, name}+ PC -> Mac pair_reply {pair, ok, pub: X25519 public key, proof}++Both proofs are HMACs keyed from the six-digit code (scrypt, salted with the pairing id) over+the transcript, so each side shows the other that it knows the code. The shared token is+HKDF over the X25519 secret: an eavesdropper who records every datagram cannot derive it.++What this protects against, and what it does not:++- The token never crosses the wire, and neither does the code. The beacon carries nothing a+ token or key could be derived from.+- A wrong code fails closed. The PC consumes its code on the first confirmation it receives,+ right or wrong, so one code gives one guess; a fresh code needs a person at the PC to press+ Pair a Mac again, and that is the rate limit. Codes expire after CODE_LIFETIME_SECONDS.+- A passive listener can, offline, brute-force the code out of a recorded proof. That is why+ the code is single-use and why the key stretching is memory-hard: the code is worthless the+ moment it is consumed, and the token does not depend on it anyway.+- An ACTIVE attacker on the LAN during the pairing window is not stopped. One that answers the+ Mac's request in the PC's place receives the Mac's proof, can crack the six digits in the+ time the code is still valid given enough hardware, and pair with either side as the other.+ One that merely sends a junk confirmation burns the code and stops that pairing (a denial,+ not a compromise). A six-digit code without a PAKE cannot do better; the scheme trusts the+ LAN for the minute the code is on screen, and no longer.+"""++from __future__ import annotations++import base64+import hashlib+import hmac+import json+import logging+import queue+import secrets+import socket+import threading+import time++from cryptography.hazmat.primitives import hashes, serialization+from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey+from cryptography.hazmat.primitives.kdf.hkdf import HKDF++import protocol++# One home for the port, in the module both apps share byte-for-byte.+PAIRING_PORT = protocol.PAIRING_PORT+BEACON_VERSION = 1+BEACON_INTERVAL_SECONDS = 2.0+# Three missed beacons: long enough to ride out Wi-Fi hiccups, short enough that a PC that+# went to sleep leaves the list before anyone tries it.+BEACON_STALE_SECONDS = 7.0+CODE_LIFETIME_SECONDS = 60.0+CODE_DIGITS = 6+MAX_DATAGRAM_BYTES = 1024+PAIR_REPLY_TIMEOUT_SECONDS = 1.5+PAIR_ATTEMPTS = 3++MSG_BEACON = "beacon"+MSG_PAIR_REQUEST = "pair_request"+MSG_PAIR_REPLY = "pair_reply"++ERROR_NOT_PAIRING = "not_pairing"+ERROR_REFUSED = "refused"++# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing+# pairing and a mixed-version pair for no gain.+TOKEN_INFO = b"beamy-pair-token"+# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing+# pairing and a mixed-version pair for no gain.+CODE_INFO = b"beamy-pair-code"+++class PairingError(Exception):+ pass+++def new_code() -> str:+ return "".join(secrets.choice("0123456789") for _ in range(CODE_DIGITS))+++def _code_key(code: str, pair_id: str) -> bytes:+ # scrypt rather than HKDF on purpose: a recorded proof lets anyone try all million codes+ # offline, and 32MB per guess is what keeps that from finishing inside the code's minute.+ # maxmem is explicit because OpenSSL's default is exactly the 32MiB this needs, and it+ # refuses at the boundary.+ return hashlib.scrypt(+ code.encode("utf-8"), salt=pair_id.encode("utf-8") + CODE_INFO, n=2**15, r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024+ )+++def _proof(key: bytes, role: bytes, pair_id: str, mac_pub: bytes, pc_pub: bytes = b"") -> bytes:+ return hmac.new(key, role + pair_id.encode("utf-8") + mac_pub + pc_pub, hashlib.sha256).digest()+++def _b64(data: bytes) -> str:+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")+++def _unb64(text: str) -> bytes:+ if not isinstance(text, str):+ raise PairingError("expected base64 text")+ try:+ return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))+ except ValueError as exc:+ raise PairingError("bad base64") from exc+++def _public_bytes(key) -> bytes:+ return key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)+++def derive_token(private_key, peer_public: bytes, pair_id: str) -> str:+ shared = private_key.exchange(X25519PublicKey.from_public_bytes(peer_public))+ return _b64(HKDF(algorithm=hashes.SHA256(), length=32, salt=pair_id.encode("utf-8"), info=TOKEN_INFO).derive(shared))+++def encode(message: dict) -> bytes:+ # The "beamy" key is a wire constant, deliberately kept as the pre-rename name: changing it+ # would break an existing pairing and a mixed-version pair for no gain.+ return json.dumps({"beamy": BEACON_VERSION, **message}, separators=(",", ":")).encode("utf-8")+++def decode(data: bytes):+ """The dict a Beamer datagram carries, or None for anything else on the port."""+ if len(data) > MAX_DATAGRAM_BYTES:+ return None+ try:+ message = json.loads(data.decode("utf-8"))+ except (UnicodeDecodeError, ValueError):+ return None+ if not isinstance(message, dict) or message.get("beamy") != BEACON_VERSION:+ return None+ return message+++def beacon_msg(name: str, port: int, pair_id: str = None) -> dict:+ message = {"type": MSG_BEACON, "name": name, "port": int(port)}+ if pair_id:+ message["pair"] = pair_id+ return message+++class PairingHost:+ """The PC's half: holds at most one live code and answers pair requests. Pure -- the+ Announcer owns the socket and the clock is injected for the tests."""++ def __init__(self, clock=time.monotonic):+ self.clock = clock+ self.code = None+ self.pair_id = None+ self.expires_at = 0.0+ self._last = None+ self.paired = None+ # How the last code ended -- "paired", "refused" or "expired" -- for the window to say+ # so; None while a code is live or after a deliberate cancel.+ self.outcome = None++ @property+ def active(self) -> bool:+ if self.code is None:+ return False+ if self.clock() >= self.expires_at:+ self.cancel()+ self.outcome = "expired"+ return False+ return True++ @property+ def seconds_left(self) -> int:+ return max(0, int(self.expires_at - self.clock())) if self.active else 0++ def begin(self) -> str:+ self.code = new_code()+ self.pair_id = secrets.token_hex(4)+ self.expires_at = self.clock() + CODE_LIFETIME_SECONDS+ self._last = None+ self.outcome = None+ return self.code++ def cancel(self) -> None:+ self.code = None+ self.pair_id = None+ self.expires_at = 0.0+ self.outcome = None++ def handle(self, message: dict):+ """The reply to one datagram, or None when it deserves no answer. A successful pairing+ leaves the token in `self.paired` as (token, mac_name); the caller stores it."""+ if message.get("type") != MSG_PAIR_REQUEST:+ return None+ pair_id = message.get("pair")+ if not isinstance(pair_id, str):+ return None+ if self._last is not None and self._last[0] == (pair_id, message.get("pub"), message.get("proof")):+ # A lost reply makes the Mac send the same request again; answer it the same way,+ # so a retransmit is not read as a second attempt.+ return self._last[1]+ if not self.active or pair_id != self.pair_id:+ return {"type": MSG_PAIR_REPLY, "pair": pair_id, "ok": False, "error": ERROR_NOT_PAIRING}+ code, self.code = self.code, None+ try:+ mac_pub = _unb64(message.get("pub"))+ proof = _unb64(message.get("proof"))+ X25519PublicKey.from_public_bytes(mac_pub)+ except (PairingError, ValueError):+ return self._refuse(message, pair_id)+ key = _code_key(code, pair_id)+ if not hmac.compare_digest(proof, _proof(key, b"mac", pair_id, mac_pub)):+ return self._refuse(message, pair_id)+ private_key = X25519PrivateKey.generate()+ pc_pub = _public_bytes(private_key)+ name = message.get("name")+ self.paired = (derive_token(private_key, mac_pub, pair_id), name if isinstance(name, str) else "")+ reply = {+ "type": MSG_PAIR_REPLY,+ "pair": pair_id,+ "ok": True,+ "pub": _b64(pc_pub),+ "proof": _b64(_proof(key, b"pc", pair_id, mac_pub, pc_pub)),+ }+ self._last = ((pair_id, message.get("pub"), message.get("proof")), reply)+ self.cancel()+ self.outcome = "paired"+ return reply++ def _refuse(self, message: dict, pair_id: str) -> dict:+ reply = {"type": MSG_PAIR_REPLY, "pair": pair_id, "ok": False, "error": ERROR_REFUSED}+ self._last = ((pair_id, message.get("pub"), message.get("proof")), reply)+ self.cancel()+ self.outcome = "refused"+ return reply+++class PairingClient:+ """The Mac's half of one attempt: builds the request, checks the reply, yields the token."""++ def __init__(self, pair_id: str, code: str, name: str):+ self.pair_id = pair_id+ self.name = name+ self._private_key = X25519PrivateKey.generate()+ self._pub = _public_bytes(self._private_key)+ self._key = _code_key(code, pair_id)++ def request(self) -> dict:+ return {+ "type": MSG_PAIR_REQUEST,+ "pair": self.pair_id,+ "pub": _b64(self._pub),+ "proof": _b64(_proof(self._key, b"mac", self.pair_id, self._pub)),+ "name": self.name,+ }++ def accept(self, reply: dict) -> str:+ """The agreed token, or PairingError naming why not."""+ if reply.get("type") != MSG_PAIR_REPLY or reply.get("pair") != self.pair_id:+ raise PairingError("not a reply to this attempt")+ if reply.get("ok") is not True:+ raise PairingError(reply.get("error") if reply.get("error") in (ERROR_NOT_PAIRING, ERROR_REFUSED) else ERROR_REFUSED)+ pc_pub = _unb64(reply.get("pub"))+ proof = _unb64(reply.get("proof"))+ if not hmac.compare_digest(proof, _proof(self._key, b"pc", self.pair_id, self._pub, pc_pub)):+ raise PairingError(ERROR_REFUSED)+ return derive_token(self._private_key, pc_pub, self.pair_id)+++def _udp_socket(bind_port: int) -> socket.socket:+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ if hasattr(socket, "SO_REUSEPORT"):+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)+ sock.bind(("", bind_port))+ sock.settimeout(0.5)+ return sock+++def local_address_towards(host: str) -> str:+ """This machine's address on the interface that reaches `host`; nothing is sent."""+ probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ probe.connect((host, 9))+ return probe.getsockname()[0]+ finally:+ probe.close()+++def broadcast_targets(port: int) -> list:+ """Every address worth sending a beacon to, one per local IPv4 interface plus the limited+ broadcast as a backstop.++ ⚠ 255.255.255.255 alone is not enough and this is not theoretical: it leaves by the default+ route only, so a PC with a second interface — a Hyper-V vEthernet switch is the common case,+ and the owner's rig has one — announces on whichever the routing table prefers and may never+ reach the LAN the Mac is on. Measured 10-09-2026: the PC beaconed steadily while no beacon+ reached the Mac at all, and the Mac then paired against a stale id from an older beacon that+ had got through, which is what produced `not_pairing`.++ 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."""+ 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))+ return targets+++def _local_ipv4_addresses() -> list:+ found = []+ try:+ for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):+ address = info[4][0]+ if not address.startswith("127.") and address not in found:+ found.append(address)+ except OSError:+ pass+ return found+++def machine_name() -> str:+ return socket.gethostname().split(".", 1)[0] or "This machine"+++class Announcer:+ """The PC's socket loop: broadcasts the beacon and answers pairing requests on one socket.+ `port_getter` returns the current TCP port, so a changed listen port is announced without a+ restart. `on_paired(token, mac_name, mac_address)` is called on this thread."""++ def __init__(self, port_getter, on_paired, logger=None, bind_port=PAIRING_PORT, announce_to=("255.255.255.255", PAIRING_PORT), name=None):+ self.port_getter = port_getter+ self.on_paired = on_paired+ self.logger = logger or logging.getLogger("Beamer")+ self.bind_port = bind_port+ self.announce_to = announce_to+ self.name = name or machine_name()+ self.host = PairingHost()+ self._lock = threading.Lock()+ self._stop = threading.Event()+ self._thread = None+ self.error = None++ def start(self) -> None:+ if self._thread is not None:+ return+ self._stop.clear()+ self._thread = threading.Thread(target=self._run, name="Beamer-announcer", daemon=True)+ self._thread.start()++ def stop(self) -> None:+ self._stop.set()+ thread = self._thread+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout=2.0)+ self._thread = None++ def begin_pairing(self) -> str:+ with self._lock:+ return self.host.begin()++ def cancel_pairing(self) -> None:+ with self._lock:+ self.host.cancel()++ @property+ def code(self):+ with self._lock:+ return self.host.code if self.host.active else None++ @property+ def seconds_left(self) -> int:+ with self._lock:+ return self.host.seconds_left++ @property+ def outcome(self):+ with self._lock:+ self.host.active+ return self.host.outcome++ def _run(self) -> None:+ try:+ sock = _udp_socket(self.bind_port)+ except OSError as exc:+ self.error = str(exc)+ self.logger.error("pairing beacon could not bind UDP %s: %s", self.bind_port, exc)+ return+ self.error = None+ next_beacon = 0.0+ try:+ while not self._stop.is_set():+ now = time.monotonic()+ if now >= next_beacon:+ next_beacon = now + BEACON_INTERVAL_SECONDS+ with self._lock:+ pair_id = self.host.pair_id if self.host.active else None+ beacon = encode(beacon_msg(self.name, self.port_getter(), pair_id))+ delivered = 0+ # Only a caller asking for the limited broadcast wants the per-interface+ # fan-out; a named address is honoured exactly, which keeps the tests off+ # the real network.+ if self.announce_to[0] == "255.255.255.255":+ targets = broadcast_targets(self.announce_to[1])+ else:+ targets = [self.announce_to]+ for target in targets:+ try:+ sock.sendto(beacon, target)+ delivered += 1+ except OSError:+ continue+ if not delivered:+ self.logger.warning("beacon reached no interface")+ try:+ data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)+ except socket.timeout:+ continue+ except ConnectionResetError:+ # Windows reports an ICMP port-unreachable for a datagram this+ # socket sent as a reset on the next receive. The socket is+ # fine; the peer that was not listening is the Mac's problem.+ continue+ except OSError as exc:+ if self._stop.is_set():+ break+ self.error = str(exc)+ self.logger.error("pairing beacon stopped: %s", exc)+ break+ message = decode(data)+ if message is None:+ continue+ with self._lock:+ reply = self.host.handle(message)+ paired, self.host.paired = self.host.paired, None+ if reply is not None:+ try:+ sock.sendto(encode(reply), address)+ except OSError as exc:+ self.logger.warning("pairing reply not sent: %s", exc)+ if paired is not None:+ self.logger.info("paired with %s at %s", paired[1] or "a Mac", address[0])+ try:+ self.on_paired(paired[0], paired[1], address[0])+ except Exception:+ self.logger.exception("on_paired failed")+ except Exception as exc:+ self.error = str(exc)+ self.logger.exception("pairing beacon stopped")+ finally:+ sock.close()+++class Discovery:+ """The Mac's socket loop: listens for beacons and carries pairing attempts on the same+ socket, so a reply comes back to the port the PC heard from."""++ def __init__(self, logger=None, bind_port=PAIRING_PORT, clock=time.monotonic):+ self.logger = logger or logging.getLogger("Beamer")+ self.bind_port = bind_port+ self.clock = clock+ self._lock = threading.Lock()+ self._seen = {}+ self._replies = queue.Queue()+ self._stop = threading.Event()+ self._thread = None+ self._sock = None+ self.error = None++ def start(self) -> None:+ if self._thread is not None:+ return+ self._stop.clear()+ self._thread = threading.Thread(target=self._run, name="Beamer-discovery", daemon=True)+ self._thread.start()++ def stop(self) -> None:+ self._stop.set()+ thread = self._thread+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout=2.0)+ self._thread = None++ def pcs(self) -> list:+ """Every PC heard from recently: dicts of name, address, port, reply_port, pairing."""+ cutoff = self.clock() - BEACON_STALE_SECONDS+ with self._lock:+ stale = [key for key, entry in self._seen.items() if entry["seen_at"] < cutoff]+ for key in stale:+ del self._seen[key]+ return sorted(+ ({k: v for k, v in entry.items() if k != "seen_at"} for entry in self._seen.values()),+ key=lambda entry: (entry["name"].lower(), entry["address"]),+ )++ def pair(self, pc: dict, code: str, name: str = None) -> str:+ """Runs the exchange with `pc` (an entry from pcs()) and returns the token. Blocks for+ up to PAIR_ATTEMPTS replies' worth; call it off the main thread."""+ sock = self._sock+ if sock is None:+ raise PairingError("discovery is not running")+ client = PairingClient(pc["pair_id"], code, name or machine_name())+ target = (pc["address"], pc["reply_port"])+ while True:+ try:+ self._replies.get_nowait()+ except queue.Empty:+ break+ request = encode(client.request())+ for _attempt in range(PAIR_ATTEMPTS):+ sock.sendto(request, target)+ deadline = self.clock() + PAIR_REPLY_TIMEOUT_SECONDS+ while True:+ remaining = deadline - self.clock()+ if remaining <= 0:+ break+ try:+ reply, address = self._replies.get(timeout=remaining)+ except queue.Empty:+ break+ if address[0] != target[0] or reply.get("pair") != client.pair_id:+ continue+ return client.accept(reply)+ raise PairingError("no_answer")++ def _run(self) -> None:+ try:+ sock = _udp_socket(self.bind_port)+ except OSError as exc:+ self.error = str(exc)+ self.logger.error("discovery could not bind UDP %s: %s", self.bind_port, exc)+ return+ self.error = None+ self._sock = sock+ try:+ while not self._stop.is_set():+ try:+ data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)+ except socket.timeout:+ continue+ except ConnectionResetError:+ continue+ except OSError as exc:+ if self._stop.is_set():+ break+ self.error = str(exc)+ self.logger.error("discovery stopped: %s", exc)+ break+ message = decode(data)+ if message is None:+ continue+ kind = message.get("type")+ if kind == MSG_BEACON:+ self._note_beacon(message, address)+ elif kind == MSG_PAIR_REPLY:+ self._replies.put((message, address))+ except Exception as exc:+ self.error = str(exc)+ self.logger.exception("discovery stopped")+ finally:+ self._sock = None+ sock.close()++ def _note_beacon(self, message: dict, address) -> None:+ name = message.get("name")+ port = message.get("port")+ pair_id = message.get("pair")+ if not isinstance(name, str) or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:+ return+ entry = {+ "name": name[:64] or address[0],+ "address": address[0],+ "port": port,+ "reply_port": address[1],+ "pair_id": pair_id if isinstance(pair_id, str) and pair_id else None,+ "seen_at": self.clock(),+ }+ with self._lock:+ self._seen[address[0]] = entrydiff --git a/mac_app/previews.py b/mac_app/previews.pynew file mode 100644index 0000000..1cc3c64--- /dev/null+++ b/mac_app/previews.py@@ -0,0 +1,281 @@+"""Live previews for the Design page: the notch and edge animations, played in the settings window by+the very classes that draw them on screen, so a preview cannot drift from the real thing.++Each renderer is hosted in a view rather than a screen-level panel. Only where it draws, and how it+is shown and hidden, is redirected; everything else runs as it does on screen. PreviewFeed stands in+for the controller: the live settings, so a change shows at once, with a scripted push instead of a+trackpad. The script builds pressure, goes through, keeps animating for the chosen time and rests,+on a loop, and PreviewLoop only runs it while the Design page is showing.++Main thread only. A failing preview disables itself as the real renderer does; nothing depends on it.+"""++import time+import types++import AppKit+import Quartz+import objc+import rumps++import crossing+import notch_island+import theme++PUSH_S = 1.8+REST_S = 1.0+FALLBACK_NOTCH = (185.0, 32.0)+++def preview_frame(elapsed, after):+ """(pressure, phase) `elapsed` seconds into the loop: pressure builds for PUSH_S and goes+ through, the crossing plays for `after` seconds, then everything rests for REST_S and it starts+ again. Phases are push, after and rest."""+ t = elapsed % (PUSH_S + after + REST_S)+ if t < PUSH_S:+ return (t / PUSH_S) ** 1.6, "push"+ return 0.0, "after" if t < PUSH_S + after else "rest"+++def notch_size():+ """This Mac's notch as (width, height), or a typical MacBook's when it has none at the top of+ the desktop, so the Notch previews still show what the styles look like."""+ try:+ geometry = notch_island.notch_geometry()+ except Exception:+ geometry = None+ if geometry is None:+ return FALLBACK_NOTCH+ left, right, _top, height = geometry+ return (right - left, height)+++class PreviewFeed:+ """What a hosted renderer reads from its controller. `overrides` pins crossing settings for one+ preview, such as the style a tile shows, while the rest follow the live settings."""++ def __init__(self, controller, **overrides):+ self.controller = controller+ self.overrides = overrides+ self.level = 0.0+ self.crossing = types.SimpleNamespace(touching=False)++ @property+ def cfg(self):+ cfg = self.controller.cfg+ if not self.overrides:+ return cfg+ return types.SimpleNamespace(crossing=dict(cfg.crossing, **self.overrides))++ def crossing_pressure_now(self):+ return self.level+++class _Panel:+ """The panel calls the renderers make, answered by a view in the settings window."""++ def __init__(self, view, set_hidden):+ self.view = view+ self.set_hidden = set_hidden++ def contentView(self):+ return self.view++ def backingScaleFactor(self):+ window = self.view.window()+ return window.backingScaleFactor() if window is not None else 2.0++ def setFrame_display_(self, frame, _display):+ self.view.setFrame_(frame)++ def orderFrontRegardless(self):+ self.set_hidden(False)++ def orderOut_(self, _sender):+ self.set_hidden(True)+++def hosted_notch(base):+ """NotchBeam or NotchIsland, drawing into a PreviewScreen instead of over the notch."""++ class HostedNotch(base):+ def __init__(self, feed, logger, screen):+ super().__init__(feed, logger)+ self.screen = screen++ def _show(self):+ if self.panel is None:+ width, height = self.screen.notch+ self._build((0.0, width, 0.0, height))+ self.panel.orderFrontRegardless()+ self.visible = True+ return True++ def _panel(self, frame):+ stage = Quartz.CALayer.layer()+ stage.setBounds_(((0.0, 0.0), (frame.size.width, frame.size.height)))+ stage.setGeometryFlipped_(True)+ stage.setAnchorPoint_((0.5, 1.0))+ self.screen.hold(stage)+ return _Panel(self.screen, stage.setHidden_), stage++ return HostedNotch+++def hosted_edge(base):+ """The app's EdgeGlow, drawing its band along the right side of a PreviewScreen."""++ class HostedEdge(base):+ def __init__(self, feed, logger, screen):+ super().__init__(feed, logger)+ self.screen = screen++ def _ensure_panel(self):+ if self.panel is not None:+ return+ band = AppKit.NSView.alloc().initWithFrame_(AppKit.NSMakeRect(0, 0, 1, 1))+ band.setWantsLayer_(True)+ self.screen.addSubview_(band)+ self.fill = Quartz.CAGradientLayer.layer()+ band.layer().addSublayer_(self.fill)+ self.comet = Quartz.CAGradientLayer.layer()+ self.panel = _Panel(band, band.setHidden_)++ def _band_frame(self, band):+ bounds = self.screen.bounds()+ return AppKit.NSMakeRect(bounds.size.width - band, 0, band, bounds.size.height)++ return HostedEdge+++class PreviewScreen(AppKit.NSView):+ """The little desktop a preview plays on: a wallpaper-toned ground so a black notch tab reads+ against it and, for a notch preview, the notch itself drawn over whatever the renderer puts+ there, as the hardware covers it. The renderer's stage is scaled so the notch takes about 60% of+ the width, and never larger than life."""++ def layout(self):+ objc.super(PreviewScreen, self).layout()+ self.arrange()++ @objc.python_method+ def setup(self, notch=None):+ self.setTranslatesAutoresizingMaskIntoConstraints_(False)+ self.setWantsLayer_(True)+ layer = self.layer()+ layer.setCornerRadius_(theme.RADIUS["field"])+ layer.setMasksToBounds_(True)+ layer.setBorderWidth_(1)+ layer.setBorderColor_(theme.colour("rule").CGColor())+ self.ground = Quartz.CAGradientLayer.layer()+ self.ground.setColors_([theme.colour("edge").CGColor(), theme.colour("well").CGColor()])+ self.ground.setStartPoint_((0.5, 1.0))+ self.ground.setEndPoint_((0.5, 0.0))+ layer.addSublayer_(self.ground)+ self.notch = notch+ self.stage = None+ self.cutout = None+ if notch is not None:+ self.cutout = Quartz.CAShapeLayer.layer()+ self.cutout.setFillColor_(AppKit.NSColor.blackColor().CGColor())+ layer.addSublayer_(self.cutout)+ return self++ @objc.python_method+ def hold(self, stage):+ if self.stage is not None:+ self.stage.removeFromSuperlayer()+ self.stage = stage+ if self.cutout is not None:+ self.layer().insertSublayer_below_(stage, self.cutout)+ else:+ self.layer().addSublayer_(stage)+ self.arrange()++ @objc.python_method+ def arrange(self):+ if getattr(self, "ground", None) is None:+ return+ bounds = self.bounds()+ width, height = bounds.size.width, bounds.size.height+ scale = min(1.0, width * 0.6 / self.notch[0]) if self.notch is not None else 1.0+ Quartz.CATransaction.begin()+ Quartz.CATransaction.setDisableActions_(True)+ try:+ self.ground.setFrame_(bounds)+ if self.stage is not None:+ self.stage.setPosition_((width / 2.0, height))+ self.stage.setAffineTransform_(Quartz.CGAffineTransformMakeScale(scale, scale))+ if self.cutout is not None:+ notch_width, notch_height = self.notch[0] * scale, self.notch[1] * scale+ radius = 7.0 * scale+ # Taller than the notch by its radius, so only the bottom corners show rounded.+ rect = ((width / 2.0 - notch_width / 2.0, height - notch_height), (notch_width, notch_height + radius))+ self.cutout.setPath_(Quartz.CGPathCreateWithRoundedRect(rect, radius, radius, None))+ finally:+ Quartz.CATransaction.commit()+++class PreviewLoop:+ """Plays every preview on the page from one clock, and only while it is wanted."""++ def __init__(self, controller):+ self.controller = controller+ self.players = []+ self.started_at = None+ self.phase = None+ self.quarter = 0+ self.timer = rumps.Timer(self._tick, 1 / 30)++ def add(self, feed, renderer, update):+ """`update(kind, pressure)` passes an event to `renderer` the way the app's crossing+ feedback would."""+ self.players.append((feed, renderer, update))++ def start(self):+ if self.started_at is not None:+ return+ self.started_at = time.monotonic()+ self.phase = None+ self.quarter = 0+ self.timer.start()++ def stop(self):+ if self.started_at is None:+ return+ self.started_at = None+ self.timer.stop()+ for feed, renderer, _update in self.players:+ feed.level = 0.0+ feed.crossing.touching = False+ try:+ renderer._hide()+ renderer.timer.stop()+ except Exception:+ pass++ def _tick(self, _timer):+ if self.started_at is None:+ return+ after = self.controller.cfg.crossing["notch_after_ms"] / 1000.0+ level, phase = preview_frame(time.monotonic() - self.started_at, after)+ quarter = min(3, int(4 * level)) if phase == "push" else 0+ crossed = phase == "after" and self.phase == "push"+ ticked = quarter > self.quarter+ self.phase, self.quarter = phase, quarter+ for feed, _renderer, update in self.players:+ feed.level = level+ feed.crossing.touching = phase == "push"+ if crossed:+ update("cross", 1.0)+ elif phase == "push" and level > 0.0:+ update("tick" if ticked else "pressure", level)+++def edge_update(renderer):+ step = crossing.Step+ return lambda kind, level: renderer.update(kind, step(pressure=level, mac_edge="right", region=(0, 0, 1, 1)))+++def notch_update(renderer):+ return lambda kind, _level: renderer.update(kind)diff --git a/mac_app/protocol.py b/mac_app/protocol.pynew file mode 100644index 0000000..afe05b2--- /dev/null+++ b/mac_app/protocol.py@@ -0,0 +1,443 @@+"""Wire protocol shared by mac_app/bridge.py and win_app/receiver.py.++The link is encrypted and authenticated with ChaCha20-Poly1305 under a key both+sides derive from the shared token (HKDF-SHA256); the token itself never crosses+the wire, and a peer that cannot produce a valid tag does not hold it.++A connection opens with one cleartext preamble each way -- WIRE_MAGIC, one+version byte, and that side's 8-byte nonce prefix -- so a version mismatch+produces a readable status instead of undecryptable garbage. Every frame after+that is a 4-byte big-endian length, then a 4-byte big-endian counter, then the+ciphertext with its tag; the length covers the counter and ciphertext. The nonce+is prefix + counter, each side counting its own frames from 1, and the receiver+rejects any counter that is not the next one, so a captured frame cannot be+replayed. A reconnect draws a new prefix, so a counter never repeats under one+key and prefix.+"""++import base64+import binascii+import json+import os+import socket+import struct+import threading+import time++from cryptography.exceptions import InvalidTag+from cryptography.hazmat.primitives import hashes+from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305+from cryptography.hazmat.primitives.kdf.hkdf import HKDF++HEADER_SIZE = 4+COUNTER_SIZE = 4+NONCE_PREFIX_SIZE = 8+MAX_COUNTER = 0xFFFFFFFF+# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing+# pairing and a mixed-version pair for no gain.+WIRE_MAGIC = b"BEAMY"+PREAMBLE_SIZE = len(WIRE_MAGIC) + 1 + NONCE_PREFIX_SIZE+PROTOCOL_VERSION = 4++# Both ports sit below 49152 on purpose. Windows and macOS both hand out 49152-65535 as+# ephemeral ports, and Windows lets WinNAT reserve whole 100-port blocks from that range that+# move on every reboot: one landed on the old 51820 and the receiver could not bind at all,+# while the PC's outward link carried on working, so input went one way only. Nothing is+# handed out below 49152, so the port a user pairs on stays theirs.+DEFAULT_PORT = 24820+PAIRING_PORT = 24821+# What DEFAULT_PORT was until 20-09-2026. A config still carrying it was never chosen by+# anyone, so it is migrated rather than honoured; a port a user picked is left alone.+LEGACY_DEFAULT_PORT = 51820+# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing+# pairing and a mixed-version pair for no gain.+KEY_SALT = b"beamy-key-v1"+# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing+# pairing and a mixed-version pair for no gain.+KEY_INFO = b"beamy-input-channel"+CLIPBOARD_MAX_BYTES = 256 * 1024+# The clipboard goes out ahead of the focus message on every switch, sealed as one frame and+# buffered whole on both sides, so the image cap is a bound on how late the switch lands, not on+# bandwidth. A full-screen grab of a 3456x2234 Retina display measured 2.9MB as PNG (09-09-2026);+# 8MB covers that with room for a busier desktop, and as a base64 frame (~10.7MB) it is about+# 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 * 1024+CLIPBOARD_IMAGE_PNG = "png"+# 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 (18-09-2026).+MAX_FRAME_BYTES = 16 * 1024 * 1024+# The first frame each way is a hello or a welcome of a few dozen bytes. Anything larger before+# authentication is not a Beamer, so it is refused before it is read.+HELLO_MAX_BYTES = 4096+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"++MSG_HELLO = "hello"+MSG_WELCOME = "welcome"+MSG_PING = "ping"+MSG_KEYDOWN = "keydown"+MSG_KEYUP = "keyup"+MSG_MOUSEMOVE = "mousemove"+MSG_MOUSEDOWN = "mousedown"+MSG_MOUSEUP = "mouseup"+MSG_SCROLL = "scroll"+MSG_ACK = "ack"+MSG_CLIPBOARD = "clipboard"+MSG_FOCUS = "focus"+MSG_GESTURE = "gesture"+MSG_SWITCH = "switch"+MSG_ARRANGEMENT = "arrangement"++# System trackpad gestures. The Mac classifies one at the end of the movement and sends a+# single message; the name is the finger motion, not its meaning, so the receiver decides+# what a swipe does and Windows' own touchpad settings apply when it can inject a real one.+GESTURE_SWIPE_UP = "swipe_up"+GESTURE_SWIPE_DOWN = "swipe_down"+GESTURE_SWIPE_LEFT = "swipe_left"+GESTURE_SWIPE_RIGHT = "swipe_right"+GESTURE_SPREAD = "spread"+GESTURE_PINCH = "pinch"+GESTURE_NAMES = frozenset(+ {+ GESTURE_SWIPE_UP,+ GESTURE_SWIPE_DOWN,+ GESTURE_SWIPE_LEFT,+ GESTURE_SWIPE_RIGHT,+ GESTURE_SPREAD,+ GESTURE_PINCH,+ }+)++class ProtocolError(Exception):+ pass+++class ConnectionClosed(Exception):+ pass+++class AuthenticationError(ProtocolError):+ """A frame failed authentication: the peer does not hold the shared token,+ or the stream was tampered with. Deliberately carries nothing else."""++ def __init__(self):+ super().__init__("frame failed authentication")+++class VersionMismatch(ProtocolError):+ """The peer's preamble named another wire version. `peer_version` is None+ when the peer sent no preamble at all -- an older Beamer that opened with a+ length-prefixed cleartext frame instead."""++ def __init__(self, peer_version):+ super().__init__(f"peer speaks wire version {peer_version!r}, expected {PROTOCOL_VERSION}")+ self.peer_version = peer_version+++def derive_key(token: str) -> bytes:+ return HKDF(algorithm=hashes.SHA256(), length=32, salt=KEY_SALT, info=KEY_INFO).derive(+ token.encode("utf-8")+ )+++class SecureSession:+ """One connection's cipher state for both directions. Build a new one per+ connection: it draws a fresh nonce prefix and starts both counters at zero.+ `send_lock` serialises sealing, and send_msg holds it across the write too,+ so counters are never reused and frames reach the wire in counter order;+ `open` is expected to run on a single reader thread per connection."""++ def __init__(self, token: str, prefix: bytes = None):+ self._cipher = ChaCha20Poly1305(derive_key(token))+ self.prefix = os.urandom(NONCE_PREFIX_SIZE) if prefix is None else bytes(prefix)+ if len(self.prefix) != NONCE_PREFIX_SIZE:+ raise ValueError("nonce prefix must be 8 bytes")+ self.send_lock = threading.RLock()+ self._send_counter = 0+ self.peer_prefix = None+ self._recv_counter = 0++ def preamble(self) -> bytes:+ return WIRE_MAGIC + bytes([PROTOCOL_VERSION]) + self.prefix++ def accept_preamble(self, data: bytes) -> None:+ if len(data) != PREAMBLE_SIZE or not data.startswith(WIRE_MAGIC):+ raise VersionMismatch(None)+ version = data[len(WIRE_MAGIC)]+ if version != PROTOCOL_VERSION:+ raise VersionMismatch(version)+ peer_prefix = data[len(WIRE_MAGIC) + 1:]+ # A reflected preamble would let our own frames be played back to us.+ if peer_prefix == self.prefix:+ raise ProtocolError("peer echoed this side's nonce prefix")+ self.peer_prefix = peer_prefix++ def seal(self, msg: dict) -> bytes:+ body = json.dumps(msg).encode("utf-8")+ with self.send_lock:+ if self._send_counter >= MAX_COUNTER:+ raise ProtocolError("frame counter exhausted; reconnect")+ self._send_counter += 1+ counter = struct.pack(">I", self._send_counter)+ ciphertext = self._cipher.encrypt(self.prefix + counter, body, None)+ return struct.pack(">I", COUNTER_SIZE + len(ciphertext)) + counter + ciphertext++ def open(self, body: bytes) -> dict:+ if self.peer_prefix is None:+ raise ProtocolError("frame received before the peer's preamble")+ if len(body) <= COUNTER_SIZE:+ raise ProtocolError("frame too short")+ (counter,) = struct.unpack(">I", body[:COUNTER_SIZE])+ if counter != self._recv_counter + 1:+ raise ProtocolError("frame counter did not advance; replay rejected")+ try:+ plain = self._cipher.decrypt(self.peer_prefix + body[:COUNTER_SIZE], body[COUNTER_SIZE:], None)+ except InvalidTag:+ raise AuthenticationError() from None+ self._recv_counter = counter+ try:+ message = json.loads(plain.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise ProtocolError(f"malformed message body: {exc}") from exc+ if not isinstance(message, dict):+ raise ProtocolError("message body must be a JSON object")+ return message+++def send_msg(sock: socket.socket, session, msg: dict) -> None:+ with session.send_lock:+ sock.sendall(session.seal(msg))+++def legacy_frame(msg: dict) -> bytes:+ """The pre-v4 cleartext framing, kept only so an older peer can be told to+ update in words it understands rather than left waiting on silence."""+ body = json.dumps(msg).encode("utf-8")+ return struct.pack(">I", len(body)) + body+++def _recv_exact(sock: socket.socket, n: int, deadline: 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 one+ byte 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."""+ chunks = []+ remaining = n+ while remaining > 0:+ if deadline is not None:+ left = deadline - time.monotonic()+ if left <= 0:+ raise socket.timeout("deadline passed while reading")+ sock.settimeout(left)+ chunk = sock.recv(remaining)+ if not chunk:+ raise ConnectionClosed("socket closed while reading")+ chunks.append(chunk)+ remaining -= len(chunk)+ return b"".join(chunks)+++def recv_preamble(sock: socket.socket, session, deadline: float = None) -> None:+ session.accept_preamble(_recv_exact(sock, PREAMBLE_SIZE, deadline))+++def recv_msg(sock: socket.socket, session, limit: int = MAX_FRAME_BYTES, deadline: float = None) -> dict:+ """`limit` is the most a frame may claim before it is read. The receiver+ passes HELLO_MAX_BYTES for the first frame: until that frame's tag has+ been checked the peer has proved nothing, so it must not be able to make+ this side buffer a clipboard-sized frame per connection. `deadline`+ bounds the whole read the same way, for the same reason."""+ header = _recv_exact(sock, HEADER_SIZE, deadline)+ (length,) = struct.unpack(">I", header)+ if length < 1 or length > limit:+ raise ProtocolError(f"invalid message length: {length}")+ return session.open(_recv_exact(sock, length, deadline))+++def hello_msg(return_edge: str = None, resistance_px: int = None) -> dict:+ """The first encrypted frame. It carries no token: decrypting it is the+ proof the sender holds the shared secret.++ `return_edge` and `resistance_px` are the same pair a focus message+ carries, sent here as well so the receiver knows the way home before the+ first crossing rather than after it -- which is what lets the receiver's+ own machine push back across that same border unprompted. Both are+ omitted when None and unknown keys are ignored, so this needs no version+ bump."""+ data = {"version": PROTOCOL_VERSION}+ if return_edge is not None:+ data["return_edge"] = return_edge+ if resistance_px is not None:+ data["resistance_px"] = resistance_px+ return {"type": MSG_HELLO, "data": data}+++def welcome_msg(error: str = None) -> dict:+ """Sent by the receiver to confirm authentication and protocol version.+ `error` (e.g. "version_mismatch") is set when the sender's declared version+ is not supported."""+ data = {"version": PROTOCOL_VERSION}+ if error is not None:+ data["error"] = error+ return {"type": MSG_WELCOME, "data": data}+++def ping_msg() -> dict:+ """Sent by the sender while idle so a dead connection is detected quickly.+ Carries no `seq` and must never be recorded as a processed input event."""+ return {"type": MSG_PING, "data": {}}+++def ack_msg(seq: int, locked: bool = False) -> dict:+ """Sent by the receiver to acknowledge processed input up to `seq`.+ The sender increments `seq` once per outbound input event; the receiver+ echoes back the highest `seq` it has processed. Used as a watchdog+ heartbeat — if the sender doesn't see an ACK for ~2s while redirecting,+ it must force-revert to local input.++ `locked` is set only while Windows is clearing its lock screen, during+ which input is being dropped rather than injected. It is omitted when+ false, and unknown keys are ignored on both sides, so this stays+ compatible in both directions and needs no protocol version bump."""+ data = {"seq": seq}+ if locked:+ data["locked"] = True+ return {"type": MSG_ACK, "data": data}+++def scroll_msg(dy, dx=0.0, mode: str = "line") -> dict:+ """Scroll event. `mode` is "pixel" for continuous trackpad deltas (float+ px) or "line" for discrete wheel clicks. `dx` and `mode` are optional on+ receive for backward tolerance: a missing `dx` means 0, a missing `mode`+ means "line"."""+ return {"type": MSG_SCROLL, "data": {"dy": dy, "dx": dx, "mode": mode}}+++def clipboard_msg(text: str = None, image: bytes = None) -> dict:+ """Whatever was on the clipboard at the switch: `text` as before, and an+ optional PNG under `image` (base64) with `image_format` naming it. Each+ key is omitted when absent. A pre-image receiver ignores the two new keys+ and an image-only message (no `text`) the same way it ignores any other+ unknown data, so this needs no protocol version bump: SecureSession.open+ only requires a JSON object, and neither app validates keys it does not+ read."""+ data = {}+ if text is not None:+ data["text"] = text+ if image is not None:+ data["image"] = base64.b64encode(image).decode("ascii")+ data["image_format"] = CLIPBOARD_IMAGE_PNG+ return {"type": MSG_CLIPBOARD, "data": data}+++def clipboard_image(data) -> bytes:+ """The PNG bytes carried by a clipboard message's `data`, or None when+ there is no image or it is not usable: an unknown format, base64 that+ does not decode, bytes that do not start as a PNG, or more than+ CLIPBOARD_IMAGE_MAX_BYTES. Never raises; the clipboard must never break+ a switch, so junk is dropped here rather than surfaced."""+ if not isinstance(data, dict) or data.get("image_format") != CLIPBOARD_IMAGE_PNG:+ return None+ encoded = data.get("image")+ # Length check before decoding, so an oversized payload costs no decode.+ if not isinstance(encoded, str) or len(encoded) > CLIPBOARD_IMAGE_MAX_BYTES * 4 // 3 + 4:+ return None+ try:+ 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 None+ return image+++def focus_msg(+ target: str,+ edge: str = None,+ offset: float = None,+ return_edge: str = None,+ resistance_px: int = None,+) -> dict:+ """Sent by the sender to move input. `edge` is the receiver edge being+ arrived at and `offset` the fraction along it, both absent when the switch+ came from the shortcut rather than a crossing. `return_edge` and+ `resistance_px` are sent on every switch to the receiver: they are how it+ knows the way home, so nothing about crossing is configured on its side.+ `target` names the machine input is moving to, which is the receiver's own+ name on the way out and the sender's on the way back. All four are omitted when None, and unknown keys are ignored,+ so this needs no protocol version bump."""+ data = {"target": target}+ if edge is not None:+ data["edge"] = edge+ if offset is not None:+ data["offset"] = offset+ if return_edge is not None:+ data["return_edge"] = return_edge+ if resistance_px is not None:+ data["resistance_px"] = resistance_px+ return {"type": MSG_FOCUS, "data": data}+++def switch_msg(target: str, edge: str = None, offset: float = None) -> dict:+ """Sent by the receiver to ask the sender to move input, when the pointer+ has been pushed through the receiver's return edge. `target` is the+ sender's machine -- "mac" on the Mac-to-Windows link, "windows" on the+ Windows-to-Mac one. `edge` is the edge to arrive at there and `offset`+ the fraction along it; both are absent for a plain return with no+ position to carry."""+ data = {"target": target}+ if edge is not None:+ data["edge"] = edge+ if offset is not None:+ data["offset"] = offset+ return {"type": MSG_SWITCH, "data": data}+++def arrangement_msg(mac_edge: str, set_at: int) -> dict:+ """Where the two machines are in relation to each other, as one value:+ the edge of the MAC that leads to the PC. Everything else follows from it+ -- the Mac crosses out by that edge, arrives at the opposite edge of the+ PC, and comes home the same way -- so the two ends cannot describe a+ border that does not exist.++ Either machine may change it, and tells the other with this message.+ `set_at` is unix seconds at the machine that made the change: when two+ ends meet holding different arrangements, because one was changed while+ the other was asleep, the newer one wins rather than whichever spoke+ first. Unknown message types are ignored, so an older Beamer keeps+ working with the arrangement it already has."""+ return {"type": MSG_ARRANGEMENT, "data": {"mac_edge": mac_edge, "set_at": int(set_at)}}+++def read_arrangement(data):+ """(mac_edge, set_at) from an arrangement message's data, or None when it+ carries no edge worth acting on. Never raises: a malformed arrangement+ must not take a working link down."""+ if not isinstance(data, dict):+ return None+ edge = data.get("mac_edge")+ if edge not in ("left", "right", "top", "bottom"):+ return None+ set_at = data.get("set_at")+ if isinstance(set_at, bool) or not isinstance(set_at, (int, float)):+ set_at = 0+ return edge, int(set_at)+++def arrangement_wins(theirs: int, mine: int) -> bool:+ """Whether an arrangement the peer sent should replace the one held here.++ Both ends stamp their own change, so the newer stamp stands: without that,+ an arrangement changed at one machine while the other was asleep would be+ silently undone by the sleeper's hello on the next connection. A peer that+ sends no stamp at all (an older Beamer, or a first connection) loses to any+ stamp of ours, and two ends that have never changed it both hold zero and+ agree anyway."""+ return int(theirs or 0) > int(mine or 0)+++def gesture_msg(name: str) -> dict:+ """One completed system gesture (a GESTURE_* name). Unknown message types are+ ignored by the receiver, so this needs no protocol version bump."""+ return {"type": MSG_GESTURE, "data": {"name": name}}diff --git a/mac_app/receiver.py b/mac_app/receiver.pynew file mode 100644index 0000000..a64691c--- /dev/null+++ b/mac_app/receiver.py@@ -0,0 +1,976 @@+"""Threaded TCP receiver and ACK watchdog for the Windows tray app."""++import logging+import math+import socket+import sys+import threading+import time+from enum import Enum+from typing import Callable, Optional++import return_edge as crossing+import protocol+++LOGGER = logging.getLogger(__name__)+# `config` throughout is whichever settings object the app on this side keeps.+# Only `port` and `auth_token` are ever read from it, and the two apps' classes+# are unrelated types, so it is not annotated or imported here -- importing one+# app's config module would stop this file being the other app's as well.+# The longest an idle link goes without an ACK, so the Mac's watchdog keeps+# seeing a heartbeat when nothing is being typed.+ACK_IDLE_SECONDS = 0.4+# How long an ACK waits after input arrives, batching a burst into one reply.+# A per-event ACK at ~100Hz mouse rates would roughly double the packet count;+# 15ms caps it near 66/s while keeping the round trip the Mac reports honest,+# which a 400ms timer did not -- every reading carried up to 400ms of waiting+# that was never network latency.+ACK_COALESCE_SECONDS = 0.015+HELLO_TIMEOUT_SECONDS = 5.0+SESSION_READ_TIMEOUT_SECONDS = 2.5+INJECTION_ERROR_STATUS_INTERVAL_SECONDS = 5.0+# Windows hands the port back only when whatever holds it lets go — WinNAT's+# dynamic reservations move on every reboot and can land on ours — so a bind+# that fails is waited out rather than ending the listener.+BIND_RETRY_SECONDS = 5.0+# Connections still inside the handshake. Each is bounded to HELLO_TIMEOUT_SECONDS as a whole,+# so a stranger holding these slots loses them within seconds, while the real peer's handshake+# takes milliseconds and always finds one free.+MAX_PENDING_CONNECTIONS = 4+++class ServerState(Enum):+ STOPPED = "Stopped"+ WAITING = "Waiting"+ CONNECTED = "Connected"+ ERROR = "Error"+++class ProcessedSequence:+ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._latest = 0+ self._fallback = 0++ def record(self, message: dict) -> int:+ data = message.get("data", {})+ raw_sequence = message.get("seq")+ if raw_sequence is None and isinstance(data, dict):+ raw_sequence = data.get("seq")+ with self._lock:+ if isinstance(raw_sequence, int) and not isinstance(raw_sequence, bool) and raw_sequence >= 0:+ self._latest = max(self._latest, raw_sequence)+ self._fallback = max(self._fallback, self._latest)+ else:+ self._fallback = max(self._fallback, self._latest) + 1+ self._latest = self._fallback+ return self._latest++ def latest(self) -> int:+ with self._lock:+ return self._latest+++def handle_message(message: dict, injector=None) -> bool:+ """Inject one input event. `injector` defaults to the real input_injector+ module, imported lazily here (not at module load) so receiver.py stays+ importable — and its non-injection logic testable — on a machine without+ ctypes.windll. The Mac copy of this file is handed its own injector at+ construction and never reaches that import. Tests can pass a fake+ injector directly."""+ if injector is None:+ import input_injector as injector+ if not isinstance(message, dict):+ raise protocol.ProtocolError("message body must be a JSON object")+ message_type = message.get("type")+ data = message.get("data", {})+ if not isinstance(data, dict):+ raise protocol.ProtocolError("message data must be a JSON object")+ if message_type == protocol.MSG_KEYDOWN:+ injector.inject_key(data["key"], down=True)+ elif message_type == protocol.MSG_KEYUP:+ injector.inject_key(data["key"], down=False)+ elif message_type == protocol.MSG_MOUSEMOVE:+ injector.inject_mouse_move(int(data["dx"]), int(data["dy"]))+ elif message_type == protocol.MSG_MOUSEDOWN:+ injector.inject_mouse_button(data["button"], down=True)+ elif message_type == protocol.MSG_MOUSEUP:+ injector.inject_mouse_button(data["button"], down=False)+ elif message_type == protocol.MSG_SCROLL:+ injector.inject_scroll(data["dy"], data.get("dx", 0), data.get("mode", "line"))+ elif message_type == protocol.MSG_GESTURE:+ injector.inject_gesture(data["name"])+ else:+ LOGGER.warning("Unknown message type ignored: %r", message_type)+ return False+ return True+++class ReceiverServer:+ def __init__(+ self,+ status_callback: Callable[[ServerState, str], None],+ clipboard=None,+ unlock=None,+ desktop=None,+ pressure_callback: Optional[Callable[[str, float, bool], None]] = None,+ injector=None,+ focus_callback: Optional[Callable[[str], None]] = None,+ peer_callback: Optional[Callable[[str, Optional[str], Optional[int]], None]] = None,+ arrangement_callback: Optional[Callable[[str, int], None]] = None,+ self_name: str = "PC",+ peer_name: str = "Mac",+ self_target: str = "windows",+ peer_target: str = "mac",+ ) -> None:+ # One module serves both machines: this file is byte-identical in+ # win_app and mac_app, which test_receiver_parity enforces. Everything+ # platform-shaped is handed in -- the injector, clipboard, desktop+ # geometry and unlock modules, the two names that appear in status+ # text, and the two wire target words -- so nothing below knows which+ # side it is running on. `focus_callback(target)` fires on every focus+ # message, which is how the app that owns this receiver knows input+ # has arrived or gone home -- and once more with the peer's own target+ # when the link that brought input here ends before the peer has+ # taken it back, because the peer fails open on its side and the+ # message saying so never reaches a dead socket.+ self._injector = injector+ self._focus_callback = focus_callback+ self._peer_driving = False+ # `peer_callback(host, return_edge, resistance_px)` fires once per+ # authenticated connection, with the peer's address and the way home+ # its hello carried. It is how the machine on this side learns which+ # border to push out across without anyone configuring it twice --+ # the way home from there is the way out from here.+ self._peer_callback = peer_callback+ # `arrangement_callback(mac_edge, set_at)` fires when the peer says+ # where the two machines are in relation to each other. Either end may+ # change it, so this is how the change arrives at the end that did not+ # make it.+ self._arrangement_callback = arrangement_callback+ self._self_name = self_name+ self._peer_name = peer_name+ self._self_target = self_target+ self._peer_target = peer_target+ self._status_callback = status_callback+ # `desktop` defaults to the real desktop_win module, imported lazily for+ # the same reason as `clipboard` below. `pressure_callback(edge,+ # pressure, crossed)` is called on the session thread as the pointer+ # is pushed against the return edge; the GUI marshals it to the glow.+ self._desktop = desktop+ self._pressure_callback = pressure_callback+ # The way home. Armed by every focus{target:"windows"} the Mac sends,+ # which carries the return edge and resistance, and None until then.+ self._return_edge: Optional[crossing.ReturnEdge] = None+ # `unlock` defaults to the real unlock_win module, imported lazily for+ # the same reason as `clipboard` below.+ self._unlock = unlock+ # Set while a lock-screen unlock is in flight. Input that arrives in+ # that window is dropped rather than queued: an unlock takes several+ # seconds, and replaying seconds of stale mouse moves and keystrokes+ # onto the desktop the moment it appears is worse than losing them.+ self._unlocking = threading.Event()+ # `clipboard` defaults to the real clipboard_win module, imported+ # lazily (not at module load) so receiver.py stays importable -- and+ # its non-clipboard logic testable -- on a machine without+ # ctypes.windll, e.g. this Mac. Tests can pass a fake directly, the+ # same way handle_message's `injector` argument works.+ self._clipboard = clipboard+ self._lock = threading.RLock()+ self._thread: Optional[threading.Thread] = None+ self._stop_event: Optional[threading.Event] = None+ self._listener: Optional[socket.socket] = None+ self._client: Optional[socket.socket] = None+ # The live session per connection, so a message can be sent to the+ # client from outside its own thread -- which is what an arrangement+ # changed in the window needs.+ self._sessions: dict = {}+ self._connections: set = set()+ self._pending = 0+ self._session_generation = 0+ self._requested_running = False++ @property+ def listening(self) -> bool:+ with self._lock:+ return self._requested_running and self._thread is not None and self._thread.is_alive()++ @property+ def return_edge(self) -> Optional[str]:+ """The Windows edge the Mac last named as the way home, or None."""+ model = self._return_edge+ return model.edge if model is not None else None++ @property+ def return_resistance(self) -> Optional[int]:+ """How many pixels of push the Mac last asked for at the return edge, or None."""+ model = self._return_edge+ return model.resistance_px if model is not None else None++ def start(self, config) -> None:+ with self._lock:+ if self._thread is not None and self._thread.is_alive():+ return+ stop_event = threading.Event()+ thread = threading.Thread(+ target=self._server_thread,+ args=(config, stop_event),+ name="Beamer-server",+ daemon=True,+ )+ self._stop_event = stop_event+ self._thread = thread+ self._requested_running = True+ self._set_status(ServerState.WAITING, f"Starting on port {config.port}")+ try:+ thread.start()+ except Exception:+ with self._lock:+ if self._thread is thread:+ self._thread = None+ self._stop_event = None+ self._requested_running = False+ raise++ def stop(self) -> None:+ with self._lock:+ self._requested_running = False+ stop_event = self._stop_event+ listener = self._listener+ connections = set(self._connections)+ thread = self._thread+ if stop_event is not None:+ stop_event.set()+ for connection in connections:+ self._close_socket(connection)+ self._close_socket(listener)+ # start() publishes the thread under the lock and starts it outside, so a+ # stop() landing in that window would join a thread that never started,+ # which raises rather than returning.+ if thread is not None and thread is not threading.current_thread() and thread.ident is not None:+ thread.join(timeout=2.0)+ if thread is not None and thread.is_alive():+ LOGGER.error("Server thread did not stop within two seconds")+ self._set_status(ServerState.ERROR, "Listener did not stop; see log")+ return+ with self._lock:+ if self._thread is thread:+ self._thread = None+ self._stop_event = None+ self._listener = None+ self._client = None+ self._hand_back("Listening stopped")+ self._set_status(ServerState.STOPPED, "Listening stopped")++ def _server_thread(self, config, stop_event: threading.Event) -> None:+ failed = False+ try:+ self._serve(config, stop_event)+ except Exception as exc:+ if not stop_event.is_set():+ failed = True+ LOGGER.exception("Server thread failed")+ self._set_status(ServerState.ERROR, f"Listener failed: {exc}")+ finally:+ with self._lock:+ listener = self._listener+ connections = set(self._connections)+ self._listener = None+ self._client = None+ if self._thread is threading.current_thread():+ self._thread = None+ self._stop_event = None+ if failed:+ self._requested_running = False+ for connection in connections:+ self._close_socket(connection)+ self._close_socket(listener)+ if stop_event.is_set():+ self._set_status(ServerState.STOPPED, "Listening stopped")++ def _bind(self, config, stop_event: threading.Event):+ """Bind the listening socket, waiting for the port if something holds it."""+ reported = ""+ while not stop_event.is_set():+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ # On the Mac this is what lets the port be taken back straight+ # after a restart, while the last session's connections sit in+ # TIME_WAIT. On Windows the same option means something else: a+ # second bind on a port another listener holds succeeds, and the+ # two split the Mac's connections between them, so the held-port+ # wait below never fired for a zombie Beamer (rig, 22-09-2026).+ # Windows does not need it for TIME_WAIT, so it does without.+ if sys.platform != "win32":+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ try:+ listener.bind(("0.0.0.0", config.port))+ except OSError as exc:+ self._close_socket(listener)+ # Said the way a user can act on it: the log carries the error, the+ # status carries the one thing they can change.+ detail = f"Another program is using port {config.port} — change the port on the Connection page"+ # Only on a change: a retry every few seconds otherwise repeats+ # the same line and the same status for as long as the port is held.+ if detail != reported:+ LOGGER.error("Cannot listen on port %s: %s", config.port, exc)+ reported = detail+ self._set_status(ServerState.ERROR, detail)+ stop_event.wait(BIND_RETRY_SECONDS)+ continue+ return listener+ return None++ def _serve(self, config, stop_event: threading.Event) -> None:+ listener = self._bind(config, stop_event)+ if listener is None:+ return+ # A stale, not-yet-torn-down session must never block a reconnect: a+ # backlog of 2 lets a fresh Mac connection queue up while the previous+ # session's thread is still winding down, instead of the OS refusing+ # it outright.+ listener.listen(2)+ listener.settimeout(0.5)+ with self._lock:+ self._listener = listener+ LOGGER.info("Listening on 0.0.0.0:%s", config.port)+ self._set_status(ServerState.WAITING, f"Waiting on port {config.port}")+ while not stop_event.is_set():+ try:+ connection, address = listener.accept()+ except socket.timeout:+ continue+ except OSError:+ if stop_event.is_set():+ break+ raise+ # Hand the connection to its own thread immediately and go back+ # to accept(): a slow or stuck peer must never stall the listener,+ # which is what used to make a stale session block a reconnect.+ # Bounded, because accept() happens before any proof of the token.+ # Only handshakes count: an authenticated peer never blocks the+ # next one, and a stranger's slot frees itself within seconds.+ with self._lock:+ crowded = self._pending >= MAX_PENDING_CONNECTIONS+ if not crowded:+ self._pending += 1+ if crowded:+ LOGGER.warning("Refusing %s:%s: %d handshakes already in progress", address[0], address[1], MAX_PENDING_CONNECTIONS)+ self._close_socket(connection)+ continue+ thread = threading.Thread(+ target=self._session_thread,+ args=(connection, address, config, stop_event),+ name="Beamer-session",+ daemon=True,+ )+ thread.start()++ def _session_thread(+ self,+ connection: socket.socket,+ address,+ config,+ server_stop: threading.Event,+ ) -> None:+ with self._lock:+ self._connections.add(connection)+ try:+ self._handle_client(connection, address, config, server_stop)+ finally:+ with self._lock:+ self._connections.discard(connection)+ self._close_socket(connection)++ def _handle_client(+ self,+ connection: socket.socket,+ address,+ config,+ server_stop: threading.Event,+ ) -> None:+ peer = f"{address[0]}:{address[1]}"+ LOGGER.info("Connection from %s", peer)+ try:+ handshake = self._handshake(connection, peer, config, server_stop)+ finally:+ with self._lock:+ self._pending -= 1+ if handshake is None:+ return+ session, version, hello = handshake++ if version != protocol.PROTOCOL_VERSION:+ LOGGER.warning(+ "Rejecting %s: unsupported protocol version %r (expected %s)",+ peer,+ version,+ protocol.PROTOCOL_VERSION,+ )+ self._send_message(connection, session, protocol.welcome_msg(error="version_mismatch"))+ self._note_version_mismatch(f"{self._peer_name} app is an older Beamer version — update both apps")+ return++ # The Mac now pings at least once a second while idle, so a read+ # timeout here means the peer is gone, not merely quiet.+ connection.settimeout(SESSION_READ_TIMEOUT_SECONDS)+ connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)+ sequence = ProcessedSequence()+ if not self._send_message(connection, session, protocol.welcome_msg()):+ return++ with self._lock:+ previous_client = self._client+ self._client = connection+ self._sessions[connection] = session+ self._session_generation += 1+ my_generation = self._session_generation+ if previous_client is not None and previous_client is not connection:+ # Preempt: a reconnecting Mac instantly replaces a stale session+ # instead of queueing behind it. Closing it here unblocks that+ # thread's blocked recv so it can exit.+ LOGGER.info("Superseding the previous session for %s", peer)+ self._close_socket(previous_client)++ LOGGER.info("Authenticated %s (protocol v%s)", peer, version)+ # A peer that has just connected has its input at home, whatever the+ # session it replaced was in the middle of.+ self._hand_back(f"{self._peer_name} reconnected")+ self._notify_peer(address[0], hello)+ self._set_status(ServerState.CONNECTED, f"Connected to {address[0]}")++ client_stop = threading.Event()+ ack_due = threading.Event()+ ack_thread = threading.Thread(+ target=self._ack_thread,+ args=(connection, session, sequence, client_stop, server_stop, ack_due),+ name="Beamer-ack",+ daemon=True,+ )+ ack_thread.start()++ last_injection_status_at = 0.0+ try:+ while not server_stop.is_set() and not client_stop.is_set():+ try:+ message = protocol.recv_msg(connection, session)+ except socket.timeout:+ if self._is_current_session(my_generation):+ LOGGER.warning("%s went quiet; treating the connection as dead", peer)+ break+ except protocol.ConnectionClosed:+ if self._is_current_session(my_generation):+ LOGGER.info("%s disconnected", peer)+ break+ except protocol.ProtocolError as exc:+ if self._is_current_session(my_generation):+ LOGGER.warning("Protocol error from %s: %s", peer, exc)+ break+ except OSError as exc:+ if (+ not server_stop.is_set()+ and not client_stop.is_set()+ and self._is_current_session(my_generation)+ ):+ LOGGER.warning("Receive failed for %s: %s", peer, exc)+ break+ message_type = message.get("type") if isinstance(message, dict) else None+ if message_type == protocol.MSG_PING:+ # Liveness only; never recorded or acked as an input event.+ continue+ if message_type == protocol.MSG_FOCUS:+ # Never recorded or acked as an input event, like ping.+ self._handle_focus(message, connection, session, peer, address[0])+ continue+ if message_type == protocol.MSG_CLIPBOARD:+ # Never recorded or acked as an input event, like ping.+ self._handle_inbound_clipboard(message, peer)+ continue+ if message_type == protocol.MSG_ARRANGEMENT:+ # Never recorded or acked as an input event, like ping.+ self._handle_arrangement(message)+ continue+ if self._unlocking.is_set():+ # Dropped, not queued: see _begin_unlock. Still recorded so+ # the ACK sequence stays continuous and the Mac's watchdog+ # does not read the unlock as a dead link.+ sequence.record(message)+ continue+ if message_type == protocol.MSG_MOUSEMOVE and self._return_trip(message, connection, session):+ # Held at the edge or crossed: not injected, but still an+ # input event for the ACK sequence.+ sequence.record(message)+ continue+ try:+ processed = handle_message(message, self._injector)+ except Exception:+ LOGGER.exception("Input event from %s could not be injected", peer)+ now = time.monotonic()+ if now - last_injection_status_at >= INJECTION_ERROR_STATUS_INTERVAL_SECONDS:+ last_injection_status_at = now+ self._set_status(ServerState.CONNECTED, f"Input error from {address[0]}; see log")+ continue+ if not processed:+ continue+ sequence.record(message)+ ack_due.set()+ finally:+ client_stop.set()+ ack_thread.join(timeout=1.0)+ if ack_thread.is_alive():+ LOGGER.error("ACK thread did not stop within one second")+ self._set_status(ServerState.ERROR, "ACK worker did not stop; see log")+ with self._lock:+ self._sessions.pop(connection, None)+ is_current = self._session_generation == my_generation+ if is_current:+ self._client = None+ if is_current:+ self._hand_back(f"{self._peer_name} went away")+ # A preempted (superseded) session must exit silently: only the+ # current-generation session may flip status to WAITING.+ if is_current and not server_stop.is_set():+ self._set_status(ServerState.WAITING, f"Waiting on port {config.port}")++ def _is_current_session(self, generation: int) -> bool:+ with self._lock:+ return self._session_generation == generation++ def _handshake(self, connection: socket.socket, peer: str, config, server_stop: threading.Event):+ """Read the Mac's preamble, answer with ours, then open its hello.+ Returns (session, declared version) or None once the failure has been+ logged. The preamble is read before ours is sent so an older Mac, which+ opens with a cleartext frame instead, gets a cleartext version_mismatch+ it can display rather than bytes it reads as a bogus length."""+ connection.settimeout(HELLO_TIMEOUT_SECONDS)+ # One deadline for the whole handshake, not a timeout per read: a peer+ # trickling a byte at a time would otherwise hold its slot for ever.+ deadline = time.monotonic() + HELLO_TIMEOUT_SECONDS+ session = protocol.SecureSession(config.auth_token)+ try:+ try:+ protocol.recv_preamble(connection, session, deadline=deadline)+ except protocol.VersionMismatch as exc:+ if exc.peer_version is None:+ LOGGER.warning("%s opened with the pre-v4 cleartext protocol", peer)+ connection.sendall(protocol.legacy_frame(protocol.welcome_msg(error="version_mismatch")))+ self._note_version_mismatch(f"{self._peer_name} app is an older Beamer version — update both apps")+ else:+ LOGGER.warning("%s speaks wire version %r, expected %s", peer, exc.peer_version, protocol.PROTOCOL_VERSION)+ connection.sendall(session.preamble())+ self._note_version_mismatch(+ f"{self._peer_name} app is Beamer protocol v{exc.peer_version}, this {self._self_name} is v{protocol.PROTOCOL_VERSION} — update both apps"+ )+ return None+ connection.sendall(session.preamble())+ first = protocol.recv_msg(connection, session, limit=protocol.HELLO_MAX_BYTES, deadline=deadline)+ except socket.timeout:+ LOGGER.warning("Authentication timed out for %s", peer)+ return None+ except protocol.ConnectionClosed:+ LOGGER.info("%s disconnected before authentication", peer)+ return None+ except protocol.AuthenticationError:+ # The one signal that the Mac does not hold the shared token. Nothing is sent back:+ # a reply would tell a guesser it had reached a Beamer.+ LOGGER.warning("Authentication failed for %s: frame failed authentication", peer)+ return None+ except protocol.ProtocolError as exc:+ LOGGER.warning("Protocol error during authentication from %s: %s", peer, exc)+ return None+ except OSError as exc:+ if not server_stop.is_set():+ LOGGER.warning("Authentication receive failed for %s: %s", peer, exc)+ return None+ if first.get("type") != protocol.MSG_HELLO:+ LOGGER.warning("%s authenticated but did not say hello first", peer)+ return None+ data = first.get("data")+ return session, self._hello_version(first), data if isinstance(data, dict) else {}++ def _note_version_mismatch(self, detail: str) -> None:+ with self._lock:+ has_active_client = self._client is not None+ if not has_active_client:+ self._set_status(ServerState.ERROR, detail)++ def _ack_thread(+ self,+ connection: socket.socket,+ session: protocol.SecureSession,+ sequence: ProcessedSequence,+ client_stop: threading.Event,+ server_stop: threading.Event,+ ack_due: threading.Event,+ ) -> None:+ try:+ while not server_stop.is_set():+ woken = ack_due.wait(ACK_IDLE_SECONDS)+ if client_stop.is_set():+ return+ if woken:+ ack_due.clear()+ # Coalesce on client_stop, not sleep, so a disconnect during+ # the batching window still exits promptly.+ if client_stop.wait(ACK_COALESCE_SECONDS):+ return+ ack = protocol.ack_msg(sequence.latest(), locked=self._unlocking.is_set())+ if not self._send_message(connection, session, ack):+ client_stop.set()+ self._close_socket(connection)+ return+ except Exception as exc:+ LOGGER.exception("ACK thread failed")+ self._set_status(ServerState.ERROR, f"ACK worker failed: {exc}")+ client_stop.set()+ self._close_socket(connection)++ def _clipboard_module(self):+ if self._clipboard is not None:+ return self._clipboard+ import clipboard_win+ return clipboard_win++ def _unlock_module(self):+ if self._unlock is not None:+ return self._unlock+ import unlock_win+ return unlock_win++ def _desktop_module(self):+ if self._desktop is not None:+ return self._desktop+ import desktop_win+ return desktop_win++ def _return_trip(self, message: dict, connection: socket.socket, session: protocol.SecureSession) -> bool:+ """The return path. Feeds every mouse move to the pressure model while+ a return edge is armed; True means the move was consumed — the pointer+ was held at the edge, or it broke through and the Mac has been asked+ to take input back — and must not be injected."""+ model = self._return_edge+ if model is None or not model.armed:+ return False+ data = message.get("data")+ if not isinstance(data, dict):+ return False+ try:+ desktop = self._desktop_module()+ outcome = model.feed(desktop.monitors(), desktop.cursor_position(), float(data["dx"]), float(data["dy"]))+ if outcome.action == crossing.HOLD:+ desktop.set_cursor_position(*outcome.position)+ elif outcome.action == crossing.CROSS:+ LOGGER.info("Pointer pushed through the %s edge; returning input to the %s", model.edge, self._peer_name)+ self._send_message(connection, session, protocol.switch_msg(self._peer_target, outcome.edge, outcome.offset))+ except Exception:+ # Logged once, not at 100Hz: the return edge is dropped until the+ # Mac's next switch re-arms it, and input keeps flowing normally.+ LOGGER.exception("Return edge failed; crossing back is off until the next switch")+ self._return_edge = None+ return False+ if outcome.action == crossing.PASS:+ return False+ self._notify_pressure(model.edge, outcome.pressure, outcome.action == crossing.CROSS)+ return True++ def send_arrangement(self, mac_edge: str, set_at: int) -> bool:+ """Tell the peer where the machines are, over the connection it opened+ to this one. Used when the change was made at this end: the outward+ link may be down, or may not exist on this machine at all, and this+ one is up by definition whenever there is anyone to tell."""+ with self._lock:+ connection = self._client+ session = self._session_for(connection)+ if connection is None or session is None:+ return False+ return self._send_message(connection, session, protocol.arrangement_msg(mac_edge, set_at))++ def send_home(self) -> bool:+ """Send the peer's input back to it from this end, as its own return+ edge would. The escape that does not depend on that edge: the owner+ calls it when someone here asks to switch while the peer is driving,+ which was refused outright until the 23-09-2026 afternoon a push+ through the edge never fired and the PC's mouse stayed on the Mac.+ The send runs on its own thread, because the callers are a hook and+ an event tap that must never block on a socket."""+ with self._lock:+ connection = self._client+ session = self._session_for(connection)+ if not self._peer_driving or connection is None or session is None:+ return False+ self._return_edge = None+ LOGGER.info("Switch asked for here; sending input home to the %s", self._peer_name)+ threading.Thread(+ target=self._send_message,+ args=(connection, session, protocol.switch_msg(self._peer_target)),+ name="Beamer-send-home",+ daemon=True,+ ).start()+ return True++ def _session_for(self, connection):+ return self._sessions.get(connection) if connection is not None else None++ def _handle_arrangement(self, message: dict) -> None:+ read = protocol.read_arrangement(message.get("data"))+ if read is None or self._arrangement_callback is None:+ return+ try:+ self._arrangement_callback(*read)+ except Exception:+ LOGGER.exception("Arrangement callback failed")++ def _notify_peer(self, host: str, hello: dict) -> None:+ if self._peer_callback is None:+ return+ edge = hello.get("return_edge")+ if edge not in crossing.EDGES:+ edge = None+ resistance = hello.get("resistance_px")+ if isinstance(resistance, bool) or not isinstance(resistance, (int, float)):+ resistance = None+ try:+ self._peer_callback(host, edge, None if resistance is None else int(resistance))+ except Exception:+ LOGGER.exception("Peer callback failed")++ def _notify_focus(self, target) -> None:+ if self._focus_callback is None or not isinstance(target, str):+ return+ if target == self._self_target:+ self._peer_driving = True+ elif target == self._peer_target:+ self._peer_driving = False+ try:+ self._focus_callback(target)+ except Exception:+ LOGGER.exception("Focus callback failed")++ def _hand_back(self, why: str) -> None:+ """The peer's input was on this machine and the link that carried it+ is over. The peer has already failed open on its own side; the focus+ that would have said so died with the socket, so it is raised here.+ Otherwise the owner of this receiver keeps treating the peer as+ driving, and its own edge and shortcut stay dead until the peer next+ crosses in and back."""+ if not self._peer_driving:+ return+ self._return_edge = None+ LOGGER.info("%s while its input was here; input returned to this %s", why, self._self_name)+ self._release_peer_keys()+ self._notify_focus(self._peer_target)++ def _release_peer_keys(self) -> None:+ """Let go of whatever the peer was holding here. A modifier or button+ injected for the peer and never released -- a chord in flight when+ input went home or the link died -- would otherwise stay down on this+ machine, turning every later local keystroke into a shortcut."""+ injector = self._injector+ if injector is None:+ try:+ import input_injector as injector+ except Exception:+ LOGGER.exception("Injector unavailable; keys the peer held may still be down")+ return+ release = getattr(injector, "release_all", None)+ if release is None:+ return+ try:+ release()+ except Exception:+ LOGGER.exception("Could not release the keys the %s was holding", self._peer_name)++ def _notify_pressure(self, edge: str, pressure: float, crossed: bool) -> None:+ if self._pressure_callback is None:+ return+ try:+ self._pressure_callback(edge, pressure, crossed)+ except Exception:+ LOGGER.exception("Pressure callback failed")++ def _arm_return(self, data: dict) -> None:+ """Every switch to Windows says which edge leads home and how hard to+ push; an older Mac that says neither gets no return edge, so nothing+ it does not expect can fire."""+ edge = data.get("return_edge")+ if edge not in crossing.EDGES:+ self._return_edge = None+ return+ resistance = data.get("resistance_px", crossing.DEFAULT_RESISTANCE_PX)+ # json.loads accepts Infinity and NaN, and int() of either raises, which+ # nothing above this catches: a bad number gets the default instead.+ if isinstance(resistance, bool) or not isinstance(resistance, (int, float)) or not math.isfinite(resistance):+ resistance = crossing.DEFAULT_RESISTANCE_PX+ self._return_edge = crossing.ReturnEdge(edge, int(resistance))++ def _place_pointer(self, data: dict) -> None:+ edge = data.get("edge")+ offset = data.get("offset")+ if edge not in crossing.EDGES or isinstance(offset, bool) or not isinstance(offset, (int, float)):+ return+ try:+ desktop = self._desktop_module()+ desktop.set_cursor_position(*crossing.arrival_position(desktop.monitors(), edge, offset))+ except Exception:+ LOGGER.exception("Could not place the pointer at the %s edge on arrival", edge)++ def _begin_unlock(self, peer: str, host: str) -> None:+ """Take the console off the lock screen, if it is on one, so the input+ about to arrive has somewhere to land. Beamer cannot type on the secure+ desktop at all -- see unlock_win -- so without this, switching to a+ locked PC silently injects into nothing.++ The lock test is a cheap in-process snapshot, so the common case (an+ unlocked PC) stays inline and costs nothing. Only a real unlock goes to+ a thread, because it takes seconds and this runs on the message loop+ that has to keep draining pings."""+ try:+ unlock = self._unlock_module()+ except Exception:+ LOGGER.exception("Unlock support unavailable")+ return+ if unlock.is_locked() is not True:+ return+ if self._unlocking.is_set():+ return+ self._unlocking.set()+ LOGGER.info("%s switched to a locked PC; asking the provider to unlock", peer)+ self._set_status(ServerState.CONNECTED, "Unlocking Windows…")+ with self._lock:+ generation = self._session_generation+ threading.Thread(+ target=self._unlock_worker,+ args=(unlock, peer, host, generation),+ name="Beamer-unlock",+ daemon=True,+ ).start()++ def _unlock_worker(self, unlock, peer: str, host: str, generation: int) -> None:+ try:+ unlocked = unlock.ensure_unlocked()+ except Exception:+ LOGGER.exception("Unlock failed for %s", peer)+ unlocked = False+ finally:+ self._unlocking.clear()+ # An unlock takes seconds, so the Mac may have gone in the meantime and+ # the session's own exit already have set WAITING. Only the session+ # that asked for this unlock may report its outcome.+ if not self._is_current_session(generation):+ return+ if unlocked:+ self._set_status(ServerState.CONNECTED, f"Connected to {host}")+ else:+ self._set_status(+ ServerState.CONNECTED, "Windows is locked — unlock it at the PC"+ )++ def _handle_focus(+ self,+ message: dict,+ connection: socket.socket,+ session: protocol.SecureSession,+ peer: str,+ host: str,+ ) -> None:+ """`focus{target:"mac"}` means the Mac just switched input back to+ itself: reply with this Windows clipboard's text so the Mac's+ pasteboard picks up whatever was last copied here.+ `target:"windows"` means input is coming here: learn the way home+ from it, land the pointer where a crossing says, and clear the lock+ screen out of its way."""+ data = message.get("data")+ target = data.get("target") if isinstance(data, dict) else None+ if target == self._peer_target:+ # Released before the owner hears input is home: the Mac's tap+ # comes back on at that notice, and a modifier still down would+ # chord with the first local keystroke.+ self._return_edge = None+ self._release_peer_keys()+ self._notify_focus(target)+ if target == self._self_target:+ self._arm_return(data)+ self._place_pointer(data)+ self._begin_unlock(peer, host)+ return+ if target != self._peer_target:+ return+ clipboard = self._clipboard_module()+ try:+ text, image = clipboard.get_contents()+ except Exception:+ LOGGER.exception("Failed to read the local clipboard for %s", peer)+ return+ if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:+ LOGGER.warning("Local clipboard text too large; skipping the text for %s", peer)+ text = None+ if image is not None and len(image) > protocol.CLIPBOARD_IMAGE_MAX_BYTES:+ LOGGER.warning(+ "Local clipboard image is %d bytes, over the %d cap; skipping the image for %s",+ len(image),+ protocol.CLIPBOARD_IMAGE_MAX_BYTES,+ peer,+ )+ image = None+ if not text and image is None:+ return+ self._send_message(connection, session, protocol.clipboard_msg(text or None, image))++ def _handle_inbound_clipboard(self, message: dict, peer: str) -> None:+ data = message.get("data")+ text = data.get("text") if isinstance(data, dict) else None+ if not isinstance(text, str) or not text:+ text = None+ elif len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:+ LOGGER.warning("Ignoring oversized inbound clipboard text from %s", peer)+ text = None+ image = protocol.clipboard_image(data)+ if text is None and image is None:+ return+ clipboard = self._clipboard_module()+ try:+ if not clipboard.set_contents(text, image):+ LOGGER.warning("Failed to set the local clipboard for %s", peer)+ except Exception:+ LOGGER.exception("Failed to set the local clipboard for %s", peer)++ @staticmethod+ def _hello_version(message: dict):+ data = message.get("data", {})+ if not isinstance(data, dict):+ return None+ return data.get("version")++ @staticmethod+ def _send_message(+ connection: socket.socket,+ session: protocol.SecureSession,+ message: dict,+ ) -> bool:+ """The session's own lock serialises the seal and the write together,+ so frames reach the wire in counter order from every thread."""+ try:+ protocol.send_msg(connection, session, message)+ return True+ except (OSError, protocol.ProtocolError) as exc:+ LOGGER.warning("Send failed: %s", exc)+ return False++ def _set_status(self, state: ServerState, detail: str) -> None:+ try:+ self._status_callback(state, detail)+ except Exception:+ LOGGER.exception("Status callback failed")++ @staticmethod+ def _close_socket(sock: Optional[socket.socket]) -> None:+ if sock is None:+ return+ try:+ sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+ try:+ sock.close()+ except OSError:+ passdiff --git a/mac_app/requirements-mac.txt b/mac_app/requirements-mac.txtnew file mode 100644index 0000000..a1df8f0--- /dev/null+++ b/mac_app/requirements-mac.txt@@ -0,0 +1,6 @@+setuptools>=68,<81+pyobjc-framework-Quartz==12.2.2+pyobjc-framework-ApplicationServices==12.2.2+rumps==0.4.0+py2app==0.28.10+cryptography>=42diff --git a/mac_app/return_edge.py b/mac_app/return_edge.pynew file mode 100644index 0000000..d565fdb--- /dev/null+++ b/mac_app/return_edge.py@@ -0,0 +1,227 @@+"""Return-edge geometry and the pressure model for crossing back to the Mac.++Pure: no ctypes, no Qt, no Windows. The receiver feeds it the monitor+rectangles, the pointer position, each incoming movement delta and a clock, and it+answers with what to do — inject the delta, hold the pointer at the edge, or+cross. The model mirrors the Mac's so the two boundaries feel like one:+outward travel at the edge accumulates as pressure, inward travel subtracts,+time decays it to nothing over DECAY_SECONDS, and at `resistance_px` of net+outward travel the edge gives.+"""++import time+from dataclasses import dataclass+from typing import Callable, Iterable, List, Optional, Tuple++EDGES = ("left", "right", "top", "bottom")+OPPOSITE = {"left": "right", "right": "left", "top": "bottom", "bottom": "top"}+DEFAULT_RESISTANCE_PX = 120+DECAY_SECONDS = 0.4+# How near a corner counts as being in it. The Mac's own engine uses the same+# 8 pixels, and the two boundaries are meant to feel like one.+CORNER_PX = 8+CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")++PASS = "pass"+HOLD = "hold"+CROSS = "cross"+++@dataclass(frozen=True)+class Rect:+ """A monitor or the virtual desktop, in virtual-desktop pixels. `x`/`y` may+ be negative: the primary monitor is at the origin, not the bounding box."""++ x: int+ y: int+ width: int+ height: int++ @property+ def right(self) -> int:+ return self.x + self.width - 1++ @property+ def bottom(self) -> int:+ return self.y + self.height - 1+++def union(monitors: Iterable[Rect]) -> Rect:+ rects = list(monitors)+ x = min(r.x for r in rects)+ y = min(r.y for r in rects)+ return Rect(x, y, max(r.right for r in rects) - x + 1, max(r.bottom for r in rects) - y + 1)+++@dataclass(frozen=True)+class Outcome:+ action: str+ pressure: float = 0.0+ position: Optional[Tuple[int, int]] = None+ edge: Optional[str] = None+ offset: Optional[float] = None+++def _clamp(value, low, high):+ return max(low, min(high, value))+++def _contains(rect: Rect, point: Tuple[int, int]) -> bool:+ return rect.x <= point[0] <= rect.right and rect.y <= point[1] <= rect.bottom+++def edge_offset(bounds: Rect, edge: str, pointer: Tuple[int, int]) -> float:+ """Fraction along `edge`, top to bottom or left to right, against the+ bounding box — the convention the Mac measures its own departures in."""+ if edge in ("left", "right"):+ return _clamp((pointer[1] - bounds.y) / max(bounds.height, 1), 0.0, 1.0)+ return _clamp((pointer[0] - bounds.x) / max(bounds.width, 1), 0.0, 1.0)+++def owning_monitor(monitors: List[Rect], edge: str) -> Rect:+ """The monitor that reaches the bounding box on `edge`; ties go to the+ first enumerated, which on Windows is the primary."""+ if edge == "left":+ return min(monitors, key=lambda r: r.x)+ if edge == "right":+ return max(monitors, key=lambda r: r.right)+ if edge == "top":+ return min(monitors, key=lambda r: r.y)+ return max(monitors, key=lambda r: r.bottom)+++def arrival_position(monitors: List[Rect], edge: str, offset: float) -> Tuple[int, int]:+ """Where a pointer arriving at `edge`, `offset` of the way along it, lands.+ The fraction is applied against the whole bounding box, then clamped into+ the owning monitor so a staggered arrangement never lands it in a gap."""+ bounds = union(monitors)+ owner = owning_monitor(monitors, edge)+ offset = _clamp(float(offset), 0.0, 1.0)+ if edge in ("left", "right"):+ x = owner.x if edge == "left" else owner.right+ y = _clamp(int(round(bounds.y + offset * bounds.height)), owner.y, owner.bottom)+ else:+ y = owner.y if edge == "top" else owner.bottom+ x = _clamp(int(round(bounds.x + offset * bounds.width)), owner.x, owner.right)+ return x, y+++class ReturnEdge:+ """Pressure against one edge of the Windows virtual desktop. Armed by the+ Mac on every switch (it sends `return_edge` and `resistance_px`), and+ disarmed once a crossing has been sent, so a burst of deltas still in+ flight after breakthrough cannot send a second one."""++ def __init__(self, edge: str, resistance_px: int = DEFAULT_RESISTANCE_PX, clock: Callable[[], float] = time.monotonic) -> None:+ if edge not in EDGES:+ raise ValueError(f"unknown edge {edge!r}")+ self.edge = edge+ self.resistance_px = max(0, int(resistance_px))+ self._clock = clock+ self._travel = 0.0+ self._last_at = clock()+ self.armed = True++ @property+ def pressure(self) -> float:+ if self.resistance_px == 0:+ return 1.0 if self._travel > 0 else 0.0+ return _clamp(self._travel / self.resistance_px, 0.0, 1.0)++ def reset(self) -> None:+ self._travel = 0.0+ self._last_at = self._clock()++ def _outward(self, dx: float, dy: float) -> float:+ if self.edge == "left":+ return -dx+ if self.edge == "right":+ return dx+ if self.edge == "top":+ return -dy+ return dy++ def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:+ """On a monitor, with no monitor one pixel beyond it: the pointer is+ against a wall. Testing the bounding box instead made the edge of a+ shorter monitor in a staggered arrangement unreachable — on the rig,+ pushing down on the LG, whose bottom stops 204px above the ultrawide's,+ never went home."""+ x, y = pointer+ step_x, step_y = {"left": (-1, 0), "right": (1, 0), "top": (0, -1), "bottom": (0, 1)}[self.edge]+ beyond = (x + step_x, y + step_y)+ return any(_contains(m, pointer) for m in monitors) and not any(_contains(m, beyond) for m in monitors)++ def feed(self, monitors: List[Rect], pointer: Tuple[int, int], dx: float, dy: float) -> Outcome:+ bounds = union(monitors)+ now = self._clock()+ elapsed = max(0.0, now - self._last_at)+ self._last_at = now+ # Decay runs against the wall clock between deltas, pushing or not. A+ # brisk push outruns it; a slow lean on the edge to reach a menu never+ # accumulates, which is the whole point of the resistance.+ self._travel = max(0.0, self._travel - self.resistance_px * elapsed / DECAY_SECONDS)+ if not self.armed:+ return Outcome(PASS, self.pressure)+ outward = self._outward(dx, dy)+ if outward <= 0 or not self._at_edge(monitors, pointer):+ if outward < 0:+ self._travel = max(0.0, self._travel + outward)+ return Outcome(PASS, self.pressure)+ self._travel += outward+ if self._travel >= self.resistance_px:+ self.armed = False+ offset = edge_offset(bounds, self.edge, pointer)+ self._travel = 0.0+ return Outcome(CROSS, 1.0, edge=OPPOSITE[self.edge], offset=offset)+ x, y = pointer+ if self.edge in ("left", "right"):+ position = (x, _clamp(int(y + dy), bounds.y, bounds.bottom))+ else:+ position = (_clamp(int(x + dx), bounds.x, bounds.right), y)+ return Outcome(HOLD, self.pressure, position=position)+++class CornerPush(ReturnEdge):+ """The same pressure model gated to one corner, for a machine whose whole+ edge is busy with something else. The push has to be diagonal: travel that+ leaves by only one of the corner's two sides is not a corner push and+ counts for nothing, which is what stops a slide along an edge triggering+ the corner it ends at.++ `edge` is still the side that leads to the other machine, so a corner+ crossing arrives where an edge crossing would, at the end of that edge the+ corner sits at."""++ def __init__(self, corner: str, edge: str, resistance_px: int = DEFAULT_RESISTANCE_PX, clock=time.monotonic) -> None:+ if corner not in CORNERS:+ raise ValueError(f"unknown corner {corner!r}")+ super().__init__(edge, resistance_px, clock)+ self.corner = corner+ self.vertical, self.horizontal = corner.split("_")++ def _outward(self, dx: float, dy: float) -> float:+ out_x = -dx if self.horizontal == "left" else dx+ out_y = -dy if self.vertical == "top" else dy+ if out_x > 0 and out_y > 0:+ return (out_x * out_x + out_y * out_y) ** 0.5+ inward = (min(0.0, out_x) ** 2 + min(0.0, out_y) ** 2) ** 0.5+ return -inward++ def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:+ """In the corner's own box, and against at least one of its two walls.+ The box is measured on the monitor the pointer is on, for the same+ reason the edge test is: on a staggered arrangement the bounding box+ has corners no display reaches."""+ x, y = pointer+ home = next((m for m in monitors if _contains(m, pointer)), None)+ if home is None:+ return False+ near_x = x <= home.x + CORNER_PX if self.horizontal == "left" else x >= home.right - CORNER_PX+ near_y = y <= home.y + CORNER_PX if self.vertical == "top" else y >= home.bottom - CORNER_PX+ if not (near_x and near_y):+ return False+ return any(+ not any(_contains(m, beyond) for m in monitors)+ for beyond in ((x + (-1 if self.horizontal == "left" else 1), y), (x, y + (-1 if self.vertical == "top" else 1)))+ )diff --git a/mac_app/settings_store.py b/mac_app/settings_store.pynew file mode 100644index 0000000..6046410--- /dev/null+++ b/mac_app/settings_store.py@@ -0,0 +1,204 @@+import json+import os+import shutil+import tempfile+from dataclasses import replace+from pathlib import Path++import config as config_module+import protocol++from crossing import CORNERS, EDGES, GLOW_COLOURS, GLOW_STYLES, HAPTIC_FEELS, HAPTIC_STEPS, METHODS, NOTCH_STYLES+from key_codes import KEY_NAME_TO_CODE+from wake import parse_mac+++APP_SUPPORT_DIRECTORY = Path.home() / "Library" / "Application Support" / "Beamer"+DEFAULT_SETTINGS_PATH = APP_SUPPORT_DIRECTORY / "config.json"++# The OpenKB-era directory, kept only as a migration source now the app is+# Beamer.+LEGACY_APP_SUPPORT_DIRECTORY = Path.home() / "Library" / "Application Support" / "OpenKB"+LEGACY_SETTINGS_PATH = LEGACY_APP_SUPPORT_DIRECTORY / "config.json"+++def migrate_legacy_config():+ """Copy the OpenKB config.json into the new Beamer directory if Beamer has+ none yet. Never moves or deletes the old file, so a downgrade still finds+ it."""+ if DEFAULT_SETTINGS_PATH.exists() or not LEGACY_SETTINGS_PATH.exists():+ return False+ APP_SUPPORT_DIRECTORY.mkdir(parents=True, exist_ok=True, mode=0o700)+ try:+ os.chmod(APP_SUPPORT_DIRECTORY, 0o700)+ except OSError:+ pass+ # Copied beside, then renamed into place: a copy cut short would otherwise+ # leave a truncated config that shadows the intact old one for ever.+ staged = DEFAULT_SETTINGS_PATH.with_name(".config.migrating")+ shutil.copyfile(LEGACY_SETTINGS_PATH, staged)+ os.chmod(staged, 0o600)+ os.replace(staged, DEFAULT_SETTINGS_PATH)+ return True+++class SettingsError(Exception):+ pass+++def editable_default_config():+ return config_module.Config(+ # Learned by pairing. Nothing about the PC is known on a fresh install.+ host="",+ port=protocol.DEFAULT_PORT,+ auth_token="",+ trigger_key="alt_r",+ double_tap_ms=300,+ key_map=dict(config_module.DEFAULT_KEY_MAP),+ reconnect_interval_s=2.0,+ trigger_style="double_tap",+ crossing=dict(config_module.DEFAULT_CROSSING),+ pc_name="",+ mac_address="",+ send_to_windows=True,+ allow_windows_to_drive=True,+ )+++def config_to_raw(cfg):+ return {+ "host": cfg.host,+ "port": cfg.port,+ "auth_token": cfg.auth_token,+ "trigger_key": cfg.trigger_key,+ "double_tap_ms": cfg.double_tap_ms,+ "key_map": config_module.key_map_style(cfg.key_map) or dict(cfg.key_map),+ "reconnect_interval_s": cfg.reconnect_interval_s,+ "trigger_style": cfg.trigger_style,+ "crossing": {+ **cfg.crossing,+ "methods": list(cfg.crossing["methods"]),+ },+ "pc_name": cfg.pc_name,+ "mac_address": cfg.mac_address,+ "send_to_windows": cfg.send_to_windows,+ "allow_windows_to_drive": cfg.allow_windows_to_drive,+ }+++class SettingsStore:+ def __init__(self, path=None):+ self.path = Path(path).expanduser() if path else DEFAULT_SETTINGS_PATH++ def load(self):+ try:+ cfg = config_module.load_config(str(self.path))+ except (config_module.ConfigError, json.JSONDecodeError, OSError, TypeError, ValueError) as exc:+ raise SettingsError(str(exc)) from exc+ cfg = self._migrate_port(cfg)+ self._validate(cfg)+ return cfg++ def _migrate_port(self, cfg):+ """Move a config still on the old default port, and write the move down.++ 51820 sat inside the 49152-65535 range both operating systems hand out for+ themselves, so it was never a port anyone could rely on keeping -- WinNAT took it on+ the rig and the PC could not listen at all. Nobody chose that number, it was what the+ app shipped with, so it moves; a port a user typed is theirs and is left alone.+ """+ if cfg.port != protocol.LEGACY_DEFAULT_PORT:+ return cfg+ cfg = replace(cfg, port=protocol.DEFAULT_PORT)+ try:+ self.save(config_to_raw(cfg))+ except SettingsError:+ # The port in hand is what matters; a read-only config directory must not+ # stop the app connecting on it.+ pass+ return cfg++ def save(self, raw):+ self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)+ try:+ os.chmod(self.path.parent, 0o700)+ except OSError:+ pass+ temporary_path = None+ try:+ with tempfile.NamedTemporaryFile(+ mode="w",+ encoding="utf-8",+ dir=self.path.parent,+ prefix=".config.",+ suffix=".tmp",+ delete=False,+ ) as handle:+ temporary_path = Path(handle.name)+ json.dump(raw, handle, indent=2, ensure_ascii=False)+ handle.write("\n")+ handle.flush()+ os.fsync(handle.fileno())+ os.chmod(temporary_path, 0o600)+ cfg = config_module.load_config(str(temporary_path))+ self._validate(cfg)+ os.replace(temporary_path, self.path)+ temporary_path = None+ os.chmod(self.path, 0o600)+ return cfg+ except (config_module.ConfigError, json.JSONDecodeError, OSError, TypeError, ValueError) as exc:+ raise SettingsError(str(exc)) from exc+ finally:+ if temporary_path is not None:+ try:+ temporary_path.unlink()+ except FileNotFoundError:+ pass++ def _validate(self, cfg):+ if not isinstance(cfg.host, str):+ raise SettingsError("Windows host must be text")+ if not 1 <= cfg.port <= 65535:+ raise SettingsError("Port must be between 1 and 65535")+ if cfg.trigger_key not in KEY_NAME_TO_CODE:+ supported = ", ".join(sorted(KEY_NAME_TO_CODE))+ raise SettingsError(f"Unsupported trigger key. Choose one of: {supported}")+ if not 50 <= cfg.double_tap_ms <= 2000:+ raise SettingsError("Double-tap threshold must be between 50 and 2000 ms")+ if not isinstance(cfg.key_map, dict):+ raise SettingsError("key_map must be a JSON object")+ if not all(isinstance(key, str) and isinstance(value, str) for key, value in cfg.key_map.items()):+ raise SettingsError("key_map keys and values must be strings")+ if cfg.reconnect_interval_s <= 0:+ raise SettingsError("Reconnect interval must be greater than zero")+ if cfg.trigger_style not in ("double_tap", "hold"):+ raise SettingsError("trigger_style must be double_tap or hold")+ crossing = cfg.crossing+ methods = crossing["methods"]+ if not isinstance(methods, list) or not set(methods) <= set(METHODS):+ raise SettingsError(f"crossing.methods must only contain: {', '.join(METHODS)}")+ if crossing["edge"] not in EDGES:+ raise SettingsError(f"crossing.edge must be one of: {', '.join(EDGES)}")+ if crossing["corner"] not in CORNERS:+ raise SettingsError(f"crossing.corner must be one of: {', '.join(CORNERS)}")+ if isinstance(crossing["resistance_px"], bool) or not 0 <= crossing["resistance_px"] <= 500:+ raise SettingsError("crossing.resistance_px must be a whole number between 0 and 500")+ if crossing["notch_style"] not in NOTCH_STYLES:+ raise SettingsError(f"crossing.notch_style must be one of: {', '.join(NOTCH_STYLES)}")+ after = crossing["notch_after_ms"]+ if isinstance(after, bool) or not isinstance(after, int) or not 300 <= after <= 3000:+ raise SettingsError("crossing.notch_after_ms must be a whole number between 300 and 3000")+ choices = (+ ("haptic_feel", HAPTIC_FEELS),+ ("haptic_steps", HAPTIC_STEPS),+ ("glow_style", GLOW_STYLES),+ ("glow_colour", GLOW_COLOURS),+ )+ for name, allowed in choices:+ if crossing[name] not in allowed:+ raise SettingsError(f"crossing.{name} must be one of: {', '.join(allowed)}")+ for name in ("haptics", "glow", "block_while_dragging"):+ if not isinstance(crossing[name], bool):+ raise SettingsError(f"crossing.{name} must be true or false")+ if cfg.mac_address and parse_mac(cfg.mac_address) is None:+ raise SettingsError("mac_address must be six hex pairs, such as 02:1A:2B:3C:0D:4E")diff --git a/mac_app/setup.py b/mac_app/setup.pynew file mode 100644index 0000000..89a165e--- /dev/null+++ b/mac_app/setup.py@@ -0,0 +1,81 @@+import os+import sys+from pathlib import Path++from setuptools import setup+++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+++VERSION = (Path(__file__).resolve().parent.parent / "VERSION").read_text().strip()+BUILD = os.environ.get("BEAMER_BUILD", "1")+++setup(+ name="Beamer",+ version=VERSION,+ app=["kvm_bridge_app.py"],+ py_modules=[+ "bridge",+ "clipboard_mac",+ "config",+ "crossing",+ "desktop_mac",+ "gestures",+ "input_injector_mac",+ "key_codes",+ "link_state",+ "media_keys",+ "notch_beam",+ "notch_island",+ "pages",+ "previews",+ "no_unlock",+ "pairing",+ "protocol",+ "receiver",+ "return_edge",+ "settings_store",+ "theme",+ "tokens",+ "wake",+ "widgets",+ "windows_input",+ ],+ # No Mac ships Hanken Grotesk or B612 Mono. macOS registers anything under+ # ATSApplicationFontsPath before the app runs, so the bundle carries the same files the+ # Windows receiver does rather than a second copy of them.+ data_files=[(+ "Fonts",+ [+ "../win_app/assets/HankenGrotesk-Variable.ttf",+ "../win_app/assets/B612Mono-Regular.ttf",+ "../win_app/assets/B612Mono-Bold.ttf",+ ],+ ), ("", ["../VERSION"])],+ options={+ "py2app": {+ "argv_emulation": False,+ # cryptography ships a compiled _rust extension plus cffi; py2app's own recipe pulls+ # both in, but naming the package keeps its data files and submodules in the bundle.+ "packages": ["rumps", "cryptography", "cffi"],+ "includes": ["objc", "AppKit", "ApplicationServices", "Quartz"],+ "iconfile": "../Beamer.icns",+ "plist": {+ "CFBundleDisplayName": "Beamer",+ "CFBundleIdentifier": "uk.co.kalkman.beamer",+ "CFBundleName": "Beamer",+ "CFBundleShortVersionString": VERSION,+ "CFBundleVersion": BUILD,+ "LSMinimumSystemVersion": "13.0",+ "LSUIElement": False,+ "NSHighResolutionCapable": True,+ "NSPrincipalClass": "NSApplication",+ "ATSApplicationFontsPath": "Fonts",+ "NSHumanReadableCopyright": "Copyright 2026 Toby Kalkman",+ "NSLocalNetworkUsageDescription": "Beamer needs to reach the Windows PC on your local network to forward keyboard and mouse input.",+ },+ }+ },+)diff --git a/mac_app/tests/test_arm_return_resistance.py b/mac_app/tests/test_arm_return_resistance.pynew file mode 100644index 0000000..1affa54--- /dev/null+++ b/mac_app/tests/test_arm_return_resistance.py@@ -0,0 +1,33 @@+import json+import unittest++import return_edge+from receiver import ReceiverServer+++class ArmReturnResistanceTest(unittest.TestCase):+ """json.loads accepts the bare Infinity and NaN tokens, so an authenticated+ peer can put either in `resistance_px`; int() of them raises, and nothing+ above _arm_return caught it, so the session thread died unlogged. A bad+ number now gets the default and the session carries on."""++ def _armed_with(self, literal):+ server = ReceiverServer(status_callback=lambda state, text: None)+ server._arm_return(json.loads('{"target": "windows", "return_edge": "left", "resistance_px": %s}' % literal))+ return server._return_edge++ def test_infinite_resistance_falls_back_to_the_default(self):+ model = self._armed_with("Infinity")+ self.assertEqual(model.edge, "left")+ self.assertEqual(model.resistance_px, return_edge.DEFAULT_RESISTANCE_PX)++ def test_nan_resistance_falls_back_to_the_default(self):+ model = self._armed_with("NaN")+ self.assertEqual(model.resistance_px, return_edge.DEFAULT_RESISTANCE_PX)++ def test_a_real_resistance_is_kept(self):+ self.assertEqual(self._armed_with("40").resistance_px, 40)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.pynew file mode 100644index 0000000..f05f03f--- /dev/null+++ b/mac_app/tests/test_bridge.py@@ -0,0 +1,1994 @@+import errno+import json+import logging+import os+import queue+import struct+import threading+import types+import unittest++import config+import media_keys+import protocol+from bridge import (+ ACK_TIMEOUT_SECONDS,+ AUTH_FAILED_STATUS,+ CONNECT_TIMEOUT_SECONDS,+ OLD_RECEIVER_STATUS,+ PING_INTERVAL_SECONDS,+ ROUND_TRIP_MAX_AGE_SECONDS,+ ROUND_TRIP_SAMPLES,+ SOCKET_IO_TIMEOUT_SECONDS,+ FrameDecoder,+ KVMController,+ QuartzEventTranslator,+ connection_error_message,+)+from gestures import DOCK_CONTROL_TYPE, MAGNIFY_TYPE, SWIPE_TYPE+from input_injector_mac import INJECTED_MARK+++def receiver_for(controller, token="synthetic-token"):+ """A receiver-side session that can open what `controller` seals."""+ peer = protocol.SecureSession(token)+ peer.accept_preamble(controller.session.preamble())+ return peer+++def sent_messages(controller, sock):+ """Open every frame `controller` sent over a FakeSocket, in order --+ counters must advance, so a frame can only be read in sequence."""+ peer = receiver_for(controller)+ return [peer.open(payload[protocol.HEADER_SIZE:]) for payload in sock.sent]+++def seed_receiver_reply(sock, *messages, token="synthetic-token"):+ """Queue a receiver's preamble and sealed replies on a FakeSocket, as a+ Windows receiver holding `token` would send them."""+ peer = protocol.SecureSession(token)+ sock.inbound.extend(peer.preamble())+ for message in messages:+ sock.inbound.extend(peer.seal(message))+ return peer+++class FakeQuartz:+ kCGEventKeyDown = 10+ kCGEventKeyUp = 11+ kCGEventFlagsChanged = 12+ kCGEventMouseMoved = 5+ kCGEventLeftMouseDragged = 6+ kCGEventRightMouseDragged = 7+ kCGEventOtherMouseDragged = 27+ kCGEventLeftMouseDown = 1+ kCGEventLeftMouseUp = 2+ kCGEventRightMouseDown = 3+ kCGEventRightMouseUp = 4+ kCGEventOtherMouseDown = 25+ kCGEventOtherMouseUp = 26+ kCGEventScrollWheel = 22+ kCGEventTapDisabledByTimeout = 0xFFFFFFFE+ kCGEventTapDisabledByUserInput = 0xFFFFFFFF+ kCGEventSourceUserData = 42+ kCGKeyboardEventKeycode = 9+ kCGKeyboardEventAutorepeat = 8+ kCGMouseEventDeltaX = 4+ kCGMouseEventDeltaY = 5+ kCGMouseEventButtonNumber = 3+ kCGScrollWheelEventDeltaAxis1 = 11+ kCGScrollWheelEventDeltaAxis2 = 12+ kCGScrollWheelEventIsContinuous = 13+ kCGScrollWheelEventPointDeltaAxis1 = 96+ kCGScrollWheelEventPointDeltaAxis2 = 97+ kCGEventFlagMaskAlphaShift = 1 << 16+ kCGEventFlagMaskShift = 1 << 17+ kCGEventFlagMaskControl = 1 << 18+ kCGEventFlagMaskAlternate = 1 << 19+ kCGEventFlagMaskCommand = 1 << 20++ @staticmethod+ def CGEventGetIntegerValueField(event, field):+ return event.get(field, 0)++ @staticmethod+ def CGEventGetDoubleValueField(event, field):+ return float(event.get(field, 0))++ @staticmethod+ def CGEventGetFlags(event):+ return event.get("flags", 0)++ @staticmethod+ def CGEventKeyboardGetUnicodeString(event, maximum, length, characters):+ value = event.get("unicode", "")+ return len(value.encode("utf-16-le")) // 2, value++ # -- Cursor pinning (Bug 1: belt-and-braces warp) --------------------+ # Call lists are class-level so every KVMController built against+ # FakeQuartz in a test shares them; tests that care about counts reset+ # these in setUp, matching how InjectScrollDispatchTests (win_app) resets+ # its own module-level accumulator.+ cursor_pin_location = (111.0, 222.0)+ associate_calls = []+ warp_calls = []+ tap_enable_calls = []++ @classmethod+ def reset_cursor_spies(cls):+ cls.associate_calls = []+ cls.warp_calls = []+ cls.tap_enable_calls = []++ @staticmethod+ def CGEventCreate(source):+ return {"_fake_probe_event": True}++ @classmethod+ def CGEventGetLocation(cls, event):+ return event.get("location", cls.cursor_pin_location)++ @classmethod+ def CGAssociateMouseAndMouseCursorPosition(cls, follows):+ cls.associate_calls.append(follows)+ return 0++ @classmethod+ def CGWarpMouseCursorPosition(cls, point):+ cls.warp_calls.append(point)+ return 0++ @classmethod+ def CGEventTapEnable(cls, tap, enabled):+ cls.tap_enable_calls.append((tap, enabled))+++class FakeGestureEvent:+ """Stands in for bridge.py's `_GestureEventView` (the object a converted+ NSEvent is wrapped in): exposes exactly the plain attribute surface+ GestureTranslator reads, with no AppKit involved."""++ def __init__(self, magnification=0.0, deltaX=0.0, deltaY=0.0, phase=0):+ self.magnification = magnification+ self.deltaX = deltaX+ self.deltaY = deltaY+ self.phase = phase+++class FakeClock:+ def __init__(self, value=10.0):+ self.value = value++ def __call__(self):+ return self.value+++class FakeSocket:+ def __init__(self):+ self.timeout = None+ self.sent = []+ self.closed = False+ self.shutdown_called = False+ self.inbound = bytearray()++ def settimeout(self, value):+ self.timeout = value++ def setsockopt(self, level, option, value):+ return None++ def sendall(self, payload):+ self.sent.append(payload)++ def recv(self, size):+ if not self.inbound:+ raise TimeoutError("no synthetic reply")+ chunk = bytes(self.inbound[:size])+ del self.inbound[:size]+ return chunk++ def shutdown(self, how):+ self.shutdown_called = True++ def close(self):+ self.closed = True+++def make_config():+ return config.Config(+ host="192.0.2.10",+ port=51820,+ auth_token="synthetic-token",+ trigger_key="alt_r",+ double_tap_ms=300,+ key_map=dict(config.DEFAULT_KEY_MAP),+ reconnect_interval_s=0.1,+ )+++def crossing_config(**overrides):+ cfg = make_config()+ cfg.crossing = dict(config.DEFAULT_CROSSING, **overrides)+ return cfg+++def quiet_logger():+ logger = logging.getLogger("kvm-bridge-tests")+ logger.handlers = [logging.NullHandler()]+ logger.propagate = False+ return logger+++FAKE_PNG = protocol.PNG_SIGNATURE + b"\x00" * 64+++class FakeClipboard:+ """Drop-in replacement for clipboard_mac, injected via+ KVMController(clipboard=...) so tests never touch the real macOS+ pasteboard."""++ def __init__(self, text=None, image=None):+ self.text = text+ self.image = image+ self.set_calls = []++ def get_contents(self):+ return self.text, self.image++ def set_contents(self, text, image):+ self.set_calls.append((text, image))+ return True+++class FrameDecoderTests(unittest.TestCase):+ def setUp(self):+ self.windows = protocol.SecureSession("synthetic-token")+ self.mac = protocol.SecureSession("synthetic-token")+ self.mac.accept_preamble(self.windows.preamble())+ self.decoder = FrameDecoder(self.mac)++ def test_decodes_fragmented_frames(self):+ message = protocol.ack_msg(42)+ frame = self.windows.seal(message)+ self.assertEqual(self.decoder.feed(frame[:3]), [])+ self.assertEqual(self.decoder.feed(frame[3:8]), [])+ self.assertEqual(self.decoder.feed(frame[8:]), [message])++ def test_round_trip_through_the_framing(self):+ messages = [protocol.ack_msg(1), protocol.clipboard_msg("copied"), protocol.switch_msg("mac", "left", 0.25)]+ stream = b"".join(self.windows.seal(m) for m in messages)+ self.assertEqual(self.decoder.feed(stream), messages)+ self.assertNotIn(b"copied", stream)++ def test_largest_clipboard_fits_the_reply_stream(self):+ image = protocol.PNG_SIGNATURE + os.urandom(protocol.CLIPBOARD_IMAGE_MAX_BYTES - len(protocol.PNG_SIGNATURE))+ text = "x" * protocol.CLIPBOARD_MAX_BYTES+ message = protocol.clipboard_msg(text, image)+ self.assertEqual(self.decoder.feed(self.windows.seal(message)), [message])++ def test_wrong_token_fails_authentication(self):+ stranger = protocol.SecureSession("another-token", prefix=self.windows.prefix)+ with self.assertRaises(protocol.AuthenticationError):+ self.decoder.feed(stranger.seal(protocol.ack_msg(1)))++ def test_replayed_frame_is_rejected(self):+ frame = self.windows.seal(protocol.ack_msg(1))+ self.decoder.feed(frame)+ with self.assertRaises(protocol.ProtocolError) as caught:+ self.decoder.feed(frame)+ self.assertNotIsInstance(caught.exception, protocol.AuthenticationError)++ def test_counter_going_backwards_is_rejected(self):+ first = self.windows.seal(protocol.ack_msg(1))+ second = self.windows.seal(protocol.ack_msg(2))+ self.assertEqual(self.decoder.feed(first), [protocol.ack_msg(1)])+ self.assertEqual(self.decoder.feed(second), [protocol.ack_msg(2)])+ # Counter 1 arriving after counter 2 has been opened -- a rewound stream.+ with self.assertRaises(protocol.ProtocolError) as caught:+ self.decoder.feed(first)+ self.assertNotIsInstance(caught.exception, protocol.AuthenticationError)++ def test_rejects_oversized_frame(self):+ with self.assertRaises(protocol.ProtocolError):+ self.decoder.feed(struct.pack(">I", protocol.MAX_FRAME_BYTES + 1))+++class TranslatorTests(unittest.TestCase):+ def setUp(self):+ self.translator = QuartzEventTranslator(FakeQuartz)+ self.key_map = dict(config.DEFAULT_KEY_MAP)++ def test_option_held_sends_the_key_not_the_composed_character(self):+ # Option+V composes U+221A on macOS; Windows needs "v" or the Alt+V+ # chord does not exist there.+ self.translator.modifier_down.add(0x3A)+ event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x09,+ FakeQuartz.kCGKeyboardEventAutorepeat: 0,+ "unicode": "\u221a",+ }+ result = self.translator.key_result(+ FakeQuartz.kCGEventKeyDown, event, 0x3D, self.key_map+ )+ self.assertEqual(result.messages, [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "v"}}+ ])++ def test_shift_still_composes_its_character(self):+ self.translator.modifier_down.add(0x38)+ event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x09,+ FakeQuartz.kCGKeyboardEventAutorepeat: 0,+ "unicode": "V",+ }+ result = self.translator.key_result(+ FakeQuartz.kCGEventKeyDown, event, 0x3D, self.key_map+ )+ self.assertEqual(result.messages, [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "V"}}+ ])++ def test_printable_key_uses_unicode(self):+ event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x00,+ FakeQuartz.kCGKeyboardEventAutorepeat: 0,+ "unicode": "å",+ }+ result = self.translator.key_result(+ FakeQuartz.kCGEventKeyDown,+ event,+ 0x3D,+ self.key_map,+ )+ self.assertEqual(result.messages, [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "å"}}+ ])++ def test_printable_keyup_reuses_keydown_character(self):+ down = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x00,+ FakeQuartz.kCGKeyboardEventAutorepeat: 0,+ "unicode": "A",+ }+ up = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x00,+ FakeQuartz.kCGKeyboardEventAutorepeat: 0,+ "unicode": "",+ }+ self.translator.key_result(FakeQuartz.kCGEventKeyDown, down, 0x3D, self.key_map)+ result = self.translator.key_result(FakeQuartz.kCGEventKeyUp, up, 0x3D, self.key_map)+ self.assertEqual(result.messages, [+ {"type": protocol.MSG_KEYUP, "data": {"key": "A"}}+ ])++ def test_command_modifier_uses_configured_mapping(self):+ event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x37,+ "flags": FakeQuartz.kCGEventFlagMaskCommand,+ }+ result = self.translator.key_result(+ FakeQuartz.kCGEventFlagsChanged,+ event,+ 0x3D,+ self.key_map,+ )+ self.assertTrue(result.is_down)+ self.assertEqual(result.messages, [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}}+ ])++ def test_control_modifier_sends_the_windows_key(self):+ event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x3B,+ "flags": FakeQuartz.kCGEventFlagMaskControl,+ }+ result = self.translator.key_result(+ FakeQuartz.kCGEventFlagsChanged,+ event,+ 0x3D,+ self.key_map,+ )+ self.assertTrue(result.is_down)+ self.assertEqual(result.messages, [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "cmd"}}+ ])++ def test_right_option_flags_changed_is_the_trigger(self):+ event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x3D,+ "flags": FakeQuartz.kCGEventFlagMaskAlternate,+ }+ result = self.translator.key_result(+ FakeQuartz.kCGEventFlagsChanged,+ event,+ 0x3D,+ self.key_map,+ )+ self.assertTrue(result.is_trigger)+ self.assertTrue(result.is_down)+ self.assertEqual(result.messages, [])++ def test_missed_keyup_does_not_desync_the_next_keydown(self):+ # The old toggle-based tracking flipped is_down by membership in+ # modifier_down; if a key-up was ever missed (tap timeout/restart),+ # every subsequent transition for that key was inverted. Detection+ # must now be derived from the event's own flags instead.+ down_event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x3D,+ "flags": FakeQuartz.kCGEventFlagMaskAlternate | 0x0040, # + right-alt device bit+ }+ first = self.translator.key_result(+ FakeQuartz.kCGEventFlagsChanged, down_event, 0x00, self.key_map+ )+ self.assertTrue(first.is_down)+ # Simulate the missed key-up: bookkeeping is left stuck as if the key+ # were still held.+ self.assertIn(0x3D, self.translator.modifier_down)+ second = self.translator.key_result(+ FakeQuartz.kCGEventFlagsChanged, down_event, 0x00, self.key_map+ )+ self.assertTrue(second.is_down)++ def test_mouse_delta_and_middle_button_match_wire_vocabulary(self):+ movement = {+ FakeQuartz.kCGMouseEventDeltaX: 4,+ FakeQuartz.kCGMouseEventDeltaY: -3,+ }+ self.assertEqual(+ self.translator.mouse_messages(FakeQuartz.kCGEventMouseMoved, movement),+ [{"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 4, "dy": -3}}],+ )+ middle = {FakeQuartz.kCGMouseEventButtonNumber: 2}+ self.assertEqual(+ self.translator.mouse_messages(FakeQuartz.kCGEventOtherMouseDown, middle),+ [{"type": protocol.MSG_MOUSEDOWN, "data": {"button": "middle"}}],+ )++ def test_subpixel_mouse_deltas_accumulate_and_carry_remainder(self):+ # Slow, precise trackpad motion reports fractional per-event deltas.+ # Reading them as integers (the old behaviour) truncates every one of+ # these to zero and the motion is lost outright.+ tiny_move = {+ FakeQuartz.kCGMouseEventDeltaX: 0.4,+ FakeQuartz.kCGMouseEventDeltaY: 0.0,+ }+ self.assertEqual(+ self.translator.mouse_messages(FakeQuartz.kCGEventMouseMoved, tiny_move), []+ )+ self.assertEqual(+ self.translator.mouse_messages(FakeQuartz.kCGEventMouseMoved, tiny_move), []+ )+ # 0.4 + 0.4 + 0.4 = 1.2 -> emits the whole pixel, carries 0.2.+ self.assertEqual(+ self.translator.mouse_messages(FakeQuartz.kCGEventMouseMoved, tiny_move),+ [{"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 1, "dy": 0}}],+ )+ # 0.2 + 0.4 = 0.6 -> still below a whole pixel.+ self.assertEqual(+ self.translator.mouse_messages(FakeQuartz.kCGEventMouseMoved, tiny_move), []+ )++ def test_reset_mouse_accumulators_clears_carried_remainder(self):+ tiny_move = {+ FakeQuartz.kCGMouseEventDeltaX: 0.4,+ FakeQuartz.kCGMouseEventDeltaY: -0.4,+ }+ self.translator.mouse_messages(FakeQuartz.kCGEventMouseMoved, tiny_move)+ self.assertNotEqual(self.translator._move_accum_x, 0.0)+ self.assertNotEqual(self.translator._move_accum_y, 0.0)+ self.translator.reset_mouse_accumulators()+ self.assertEqual(self.translator._move_accum_x, 0.0)+ self.assertEqual(self.translator._move_accum_y, 0.0)+ # The carried 0.4 is gone: another 0.4 alone must not yet round up.+ self.assertEqual(+ self.translator.mouse_messages(FakeQuartz.kCGEventMouseMoved, tiny_move), []+ )++ def test_discrete_scroll_wheel_is_line_mode_with_horizontal_delta(self):+ event = {+ FakeQuartz.kCGScrollWheelEventIsContinuous: 0,+ FakeQuartz.kCGScrollWheelEventDeltaAxis1: 2,+ FakeQuartz.kCGScrollWheelEventDeltaAxis2: -1,+ }+ self.assertEqual(+ self.translator.mouse_messages(FakeQuartz.kCGEventScrollWheel, event),+ [{"type": protocol.MSG_SCROLL, "data": {"dy": 2, "dx": -1, "mode": "line"}}],+ )++ def test_continuous_scroll_wheel_is_pixel_mode_with_float_deltas(self):+ event = {+ FakeQuartz.kCGScrollWheelEventIsContinuous: 1,+ FakeQuartz.kCGScrollWheelEventPointDeltaAxis1: 12.5,+ FakeQuartz.kCGScrollWheelEventPointDeltaAxis2: -3.25,+ }+ self.assertEqual(+ self.translator.mouse_messages(FakeQuartz.kCGEventScrollWheel, event),+ [{"type": protocol.MSG_SCROLL, "data": {"dy": 12.5, "dx": -3.25, "mode": "pixel"}}],+ )++ def test_scroll_wheel_with_no_motion_on_either_axis_is_dropped(self):+ event = {+ FakeQuartz.kCGScrollWheelEventIsContinuous: 0,+ FakeQuartz.kCGScrollWheelEventDeltaAxis1: 0,+ FakeQuartz.kCGScrollWheelEventDeltaAxis2: 0,+ }+ self.assertEqual(+ self.translator.mouse_messages(FakeQuartz.kCGEventScrollWheel, event), []+ )+++class ControllerTests(unittest.TestCase):+ def setUp(self):+ self.clock = FakeClock()+ self.controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ )++ def test_local_event_passes_through(self):+ event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x00,+ FakeQuartz.kCGKeyboardEventAutorepeat: 0,+ "unicode": "a",+ }+ returned = self.controller._event_tap_callback(+ None,+ FakeQuartz.kCGEventKeyDown,+ event,+ None,+ )+ self.assertIs(returned, event)+ self.assertTrue(self.controller.outbound.empty())++ def test_redirected_event_is_queued_and_swallowed(self):+ event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x00,+ FakeQuartz.kCGKeyboardEventAutorepeat: 0,+ "unicode": "a",+ }+ self.controller.redirecting = True+ returned = self.controller._event_tap_callback(+ None,+ FakeQuartz.kCGEventKeyDown,+ event,+ None,+ )+ self.assertIsNone(returned)+ self.assertEqual(+ self.controller.outbound.get_nowait(),+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}},+ )++ def test_queue_failure_restores_local_before_returning_event(self):+ event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x00,+ FakeQuartz.kCGKeyboardEventAutorepeat: 0,+ "unicode": "a",+ }+ self.controller.outbound = queue.Queue(maxsize=1)+ self.controller.outbound.put_nowait({"full": True})+ self.controller.redirecting = True+ returned = self.controller._event_tap_callback(+ None,+ FakeQuartz.kCGEventKeyDown,+ event,+ None,+ )+ self.assertIs(returned, event)+ self.assertFalse(self.controller.redirecting)++ def test_double_tap_right_option_only_flips_redirect_flag(self):+ sock = FakeSocket()+ self.controller.sock = sock+ down = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x3D,+ "flags": FakeQuartz.kCGEventFlagMaskAlternate,+ }+ up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}+ first_down = self.controller._event_tap_callback(+ None, FakeQuartz.kCGEventFlagsChanged, down, None+ )+ first_up = self.controller._event_tap_callback(+ None, FakeQuartz.kCGEventFlagsChanged, up, None+ )+ self.clock.value = 10.2+ second_down = self.controller._event_tap_callback(+ None, FakeQuartz.kCGEventFlagsChanged, down, None+ )+ second_up = self.controller._event_tap_callback(+ None, FakeQuartz.kCGEventFlagsChanged, up, None+ )+ self.assertIs(first_down, down)+ self.assertIs(first_up, up)+ self.assertIsNone(second_down)+ self.assertIsNone(second_up)+ self.assertTrue(self.controller.redirecting)+ self.assertIs(self.controller.sock, sock)++ def test_sequence_is_added_once_per_outbound_event(self):+ first = self.controller._prepare_outbound(+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}}+ )+ second = self.controller._prepare_outbound(+ {"type": protocol.MSG_KEYUP, "data": {"key": "a"}}+ )+ self.assertEqual(first["data"]["seq"], 1)+ self.assertEqual(second["data"]["seq"], 2)++ def test_watchdog_drops_connection_after_two_seconds_without_ack(self):+ alerts = []+ self.controller.on_user_alert = lambda title, message: alerts.append((title, message))+ sock = FakeSocket()+ self.controller.sock = sock+ self.controller.redirecting = True+ self.controller.connected_at = 10.0+ self.controller.last_ack_at = 10.0+ self.clock.value = 10.0 + ACK_TIMEOUT_SECONDS + 0.01+ self.assertTrue(self.controller._watchdog_tick())+ self.assertFalse(self.controller.redirecting)+ self.assertTrue(sock.closed)+ self.assertEqual(self.controller.connection_status, "Windows stopped responding")+ # Killing an active redirect must alert the user immediately, since+ # otherwise input would simply vanish into a dead connection.+ self.assertEqual(alerts, [("Beamer", "Input returned to this Mac")])++ def test_watchdog_detects_a_dead_socket_while_not_redirecting(self):+ # Previously the watchdog only ran while redirecting, so a half-open+ # connection was invisible while idle: the UI stayed green and a+ # double-tap would "succeed" into a void. It must now be detected and+ # torn down the same way regardless of redirect state.+ sock = FakeSocket()+ self.controller.sock = sock+ self.controller.redirecting = False+ self.controller.connected_at = 10.0+ self.controller.last_ack_at = 10.0+ self.clock.value = 10.0 + ACK_TIMEOUT_SECONDS + 0.01+ self.assertTrue(self.controller._watchdog_tick())+ self.assertFalse(self.controller.redirecting)+ self.assertIsNone(self.controller.sock)+ self.assertTrue(sock.closed)+ self.assertEqual(self.controller.connection_status, "Windows stopped responding")++ def test_watchdog_sends_idle_ping_after_a_second_of_silence(self):+ sock = FakeSocket()+ self.controller.sock = sock+ self.controller.connected_at = 10.0+ self.controller.last_ack_at = 10.0+ self.controller.last_send_at = 10.0+ self.clock.value = 10.0 + PING_INTERVAL_SECONDS+ self.assertFalse(self.controller._watchdog_tick())+ self.assertEqual(len(sock.sent), 1)+ self.assertEqual(sent_messages(self.controller, sock)[-1], protocol.ping_msg())+ self.assertEqual(self.controller.last_send_at, self.clock.value)++ def test_watchdog_suppresses_idle_ping_while_traffic_flows(self):+ sock = FakeSocket()+ self.controller.sock = sock+ self.controller.connected_at = 10.0+ self.controller.last_ack_at = 10.0+ self.controller.last_send_at = 11.5+ self.clock.value = 11.6+ self.assertFalse(self.controller._watchdog_tick())+ self.assertEqual(sock.sent, [])++ def test_set_redirecting_true_refuses_while_receiving(self):+ # Invariant 2: redirecting and receiving must never both be True.+ # set_receiving enforces this by turning redirecting off first+ # (bridge.py:709-710); set_redirecting has no matching check, so a+ # manual switch (the menu bar's toggleRedirect_, kvm_bridge_app.py:1703)+ # while Windows is already driving this Mac corrupts the pair. This+ # asserts the invariant, which the current code violates.+ sock = FakeSocket()+ self.controller.sock = sock+ self.controller.receiving = True+ self.controller.set_redirecting(True)+ self.assertFalse(+ self.controller.redirecting and self.controller.receiving,+ "redirecting and receiving are both True at once",+ )++ def test_switching_while_receiving_sends_the_pcs_input_home(self):+ # 23-09-2026: the PC's mouse was on this Mac, its push back through+ # the edge never fired, and the menu's switch only said Windows was+ # already driving. Switching now sends the PC's input home instead.+ sent_home = []+ self.controller.sock = FakeSocket()+ self.controller.receiving = True+ self.controller.send_peer_home = lambda: sent_home.append(True) or True+ self.assertTrue(self.controller.set_redirecting(True))+ self.assertEqual(sent_home, [True])+ self.assertFalse(self.controller.redirecting)++ def test_switching_while_receiving_with_the_pc_unreachable_is_refused(self):+ self.controller.sock = FakeSocket()+ self.controller.receiving = True+ self.controller.send_peer_home = lambda: False+ self.assertFalse(self.controller.set_redirecting(True))+ self.assertFalse(self.controller.redirecting)++ def test_this_macs_trigger_sends_the_pcs_input_home_while_receiving(self):+ sent_home = []+ self.controller.sock = FakeSocket()+ self.controller.receiving = True+ self.controller.send_peer_home = lambda: sent_home.append(True) or True+ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": FakeQuartz.kCGEventFlagMaskAlternate}+ up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}+ tap = self.controller._event_tap_callback+ tap(None, FakeQuartz.kCGEventFlagsChanged, down, None)+ tap(None, FakeQuartz.kCGEventFlagsChanged, up, None)+ self.clock.value = 10.2+ self.assertIsNone(tap(None, FakeQuartz.kCGEventFlagsChanged, down, None))+ self.assertIsNone(tap(None, FakeQuartz.kCGEventFlagsChanged, up, None))+ self.assertEqual(sent_home, [True])+ self.assertFalse(self.controller.redirecting)++ def test_the_pcs_injected_trigger_is_not_this_macs_while_receiving(self):+ sent_home = []+ self.controller.sock = FakeSocket()+ self.controller.receiving = True+ self.controller.send_peer_home = lambda: sent_home.append(True) or True+ down = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x3D,+ "flags": FakeQuartz.kCGEventFlagMaskAlternate,+ FakeQuartz.kCGEventSourceUserData: INJECTED_MARK,+ }+ tap = self.controller._event_tap_callback+ for _ in range(2):+ self.assertIs(tap(None, FakeQuartz.kCGEventFlagsChanged, down, None), down)+ self.assertEqual(sent_home, [])++ def test_sending_to_windows_switched_off_refuses_the_switch(self):+ self.controller.sock = FakeSocket()+ self.controller.cfg.send_to_windows = False+ self.assertFalse(self.controller.set_redirecting(True))+ self.assertFalse(self.controller.redirecting)++ def test_sending_to_windows_switched_off_still_sends_the_pcs_input_home(self):+ # Each switch covers one direction: the PC's input on this Mac still goes home.+ sent_home = []+ self.controller.sock = FakeSocket()+ self.controller.cfg.send_to_windows = False+ self.controller.receiving = True+ self.controller.send_peer_home = lambda: sent_home.append(True) or True+ self.assertTrue(self.controller.set_redirecting(True))+ self.assertEqual(sent_home, [True])++ def test_alert_fired_when_double_tap_cannot_switch_because_disconnected(self):+ alerts = []+ self.controller.on_user_alert = lambda title, message: alerts.append((title, message))+ self.controller.connection_status = "Waiting to connect"+ self.assertFalse(self.controller.set_redirecting(True))+ self.assertEqual(+ alerts,+ [("Beamer", "Cannot switch — Waiting to connect")],+ )++ def test_alert_callback_exception_does_not_propagate(self):+ def boom(title, message):+ raise RuntimeError("synthetic notification failure")++ self.controller.on_user_alert = boom+ self.controller.connection_status = "Waiting to connect"+ # Must not raise even though the callback is broken.+ self.assertFalse(self.controller.set_redirecting(True))++ def test_double_tap_survives_a_missed_key_up(self):+ # Regression: the old toggle-based modifier tracking desynced when a+ # key-up went missing (e.g. a tap restart never delivered it), which+ # silently killed the double-tap trigger on the very next press.+ sock = FakeSocket()+ self.controller.sock = sock+ down = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x3D,+ "flags": FakeQuartz.kCGEventFlagMaskAlternate | 0x0040,+ }+ # Simulate the effect of the missed key-up: stale bookkeeping left+ # over as if the trigger key were still held down.+ self.controller.translator.modifier_down.add(0x3D)+ first_down = self.controller._event_tap_callback(+ None, FakeQuartz.kCGEventFlagsChanged, down, None+ )+ self.clock.value = 10.2+ second_down = self.controller._event_tap_callback(+ None, FakeQuartz.kCGEventFlagsChanged, down, None+ )+ self.assertIs(first_down, down)+ self.assertIsNone(second_down)+ self.assertTrue(self.controller.redirecting)++ def test_handle_inbound_unknown_type_refreshes_liveness_and_is_ignored(self):+ self.controller.last_ack_at = 0.0+ self.clock.value = 42.0+ self.controller._handle_inbound({"type": protocol.MSG_FOCUS, "data": {"target": "windows"}})+ self.assertEqual(self.controller.last_ack_at, 42.0)+ # Bookkeeping used to validate real ACKs must be untouched.+ self.assertEqual(self.controller.last_ack_seq, -1)++ def test_handle_inbound_malformed_message_drops_connection(self):+ with self.assertRaises(protocol.ProtocolError):+ self.controller._handle_inbound({"data": {}})++ def test_worker_exception_forces_local(self):+ self.controller.redirecting = True++ def fail():+ raise RuntimeError("synthetic failure")++ self.controller._thread_entry("synthetic", fail)+ self.assertFalse(self.controller.redirecting)++ def test_outbound_worker_survives_a_bad_message(self):+ # The only thread that drains the queue is never restarted, so a raise+ # inside one message (the clipboard read every switch does) must force+ # input local and leave the worker running for the next message.+ self.controller.redirecting = True+ self.controller.clipboard = types.SimpleNamespace(+ get_contents=lambda: (_ for _ in ()).throw(RuntimeError("synthetic clipboard failure"))+ )+ self.controller.outbound.put_nowait({"type": "_local_clipboard", "data": {}})+ self.controller.stop_event.clear()++ def stop_after_one():+ self.controller.outbound.join()+ self.controller.stop_event.set()++ threading.Thread(target=stop_after_one, daemon=True).start()+ self.controller._outbound_worker()+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(self.controller.outbound.qsize(), 0)++ def test_an_ack_without_an_object_body_drops_the_connection_not_the_reader(self):+ sock = FakeSocket()+ self.controller.sock = sock+ with self.assertRaises(protocol.ProtocolError):+ self.controller._handle_inbound({"type": protocol.MSG_ACK, "data": None})++ def test_every_way_home_tells_windows_while_the_link_is_up(self):+ # Windows keeps treating this Mac as driving, with whatever keys it was+ # holding still down, until it hears otherwise.+ for way_home in (+ lambda: self.controller._force_local("synthetic"),+ lambda: self.controller._event_tap_callback(None, FakeQuartz.kCGEventTapDisabledByTimeout, {}, None),+ ):+ with self.subTest(way_home=way_home):+ self.controller.sock = FakeSocket()+ self.controller.event_tap = object()+ self.controller.set_redirecting(True)+ self.controller._drain_outbound()+ way_home()+ queued = []+ while not self.controller.outbound.empty():+ queued.append(self.controller.outbound.get_nowait())+ self.assertIn(protocol.focus_msg("mac"), queued)++ def test_every_way_home_reassociates_the_cursor(self):+ # A path that only cleared `redirecting` left the pointer decoupled+ # from the hand: keyboard back, pointer frozen.+ for way_home in (+ lambda: self.controller._connection_failed("synthetic drop"),+ lambda: self.controller._force_local("synthetic"),+ lambda: self.controller.update_config(crossing_config()),+ lambda: self.controller._thread_entry("synthetic", lambda: (_ for _ in ()).throw(RuntimeError())),+ ):+ with self.subTest(way_home=way_home):+ self.controller.sock = FakeSocket()+ self.controller.set_redirecting(True)+ FakeQuartz.reset_cursor_spies()+ way_home()+ self.assertFalse(self.controller.redirecting)+ self.assertIn(True, FakeQuartz.associate_calls)++ def test_connect_and_hello_use_explicit_timeouts(self):+ sock = FakeSocket()+ seed_receiver_reply(sock, protocol.welcome_msg())+ calls = []++ def socket_factory(address, timeout):+ calls.append((address, timeout))+ return sock++ controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ socket_factory=socket_factory,+ )+ self.assertTrue(controller._connect_once())+ self.assertEqual(calls, [(('192.0.2.10', 51820), CONNECT_TIMEOUT_SECONDS)])+ self.assertEqual(sock.timeout, SOCKET_IO_TIMEOUT_SECONDS)+ self.assertEqual(sock.sent[0], controller.session.preamble())+ # The hello carries the way home, which is how Windows knows which of+ # its own edges leads back here before this Mac has ever crossed.+ self.assertEqual(+ sent_messages(controller, types.SimpleNamespace(sent=sock.sent[1:])),+ [protocol.hello_msg(return_edge="left", resistance_px=120)],+ )+ self.assertNotIn(b"synthetic-token", b"".join(sock.sent))+ self.assertEqual(controller.connected_at, self.clock.value)+ self.assertEqual(controller.last_send_at, self.clock.value)++ def test_silent_receiver_after_connect_reports_old_receiver(self):+ # A pre-v4 receiver reads our preamble as a bogus frame length and waits+ # for a hello that never comes; it says nothing, and never will.+ sock = FakeSocket()+ controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ socket_factory=lambda address, timeout: sock,+ )+ self.assertFalse(controller._connect_once())+ self.assertEqual(controller.connection_status, OLD_RECEIVER_STATUS)+ self.assertTrue(sock.closed)+ self.assertIsNone(controller.sock)++ def test_other_wire_version_in_the_preamble_is_reported(self):+ sock = FakeSocket()+ sock.inbound.extend(protocol.WIRE_MAGIC + bytes([protocol.PROTOCOL_VERSION + 1]) + b"\x02" * protocol.NONCE_PREFIX_SIZE)+ controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ socket_factory=lambda address, timeout: sock,+ )+ self.assertFalse(controller._connect_once())+ self.assertIn(f"v{protocol.PROTOCOL_VERSION + 1}", controller.connection_status)+ self.assertIn("update both apps", controller.connection_status)+ self.assertTrue(sock.closed)++ def test_wrong_token_reports_authentication_failure(self):+ sock = FakeSocket()+ seed_receiver_reply(sock, protocol.welcome_msg(), token="a-different-token")+ controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ socket_factory=lambda address, timeout: sock,+ )+ self.assertFalse(controller._connect_once())+ self.assertEqual(controller.connection_status, AUTH_FAILED_STATUS)+ self.assertTrue(sock.closed)+ self.assertIsNone(controller.sock)++ def test_every_connection_draws_a_fresh_nonce_prefix(self):+ prefixes = []+ for _ in range(2):+ sock = FakeSocket()+ seed_receiver_reply(sock, protocol.welcome_msg())+ controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ socket_factory=lambda address, timeout, sock=sock: sock,+ )+ initial = controller.session.prefix+ self.assertTrue(controller._connect_once())+ # _connect_once builds and installs a brand-new session, so the+ # prefix it connects with differs from the one it was born holding.+ self.assertNotEqual(controller.session.prefix, initial)+ prefixes.append(controller.session.prefix)+ self.assertNotEqual(prefixes[0], prefixes[1])++ def test_handshake_welcome_version_mismatch_reports_old_receiver(self):+ sock = FakeSocket()+ seed_receiver_reply(sock, protocol.welcome_msg(error="version_mismatch"))++ controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ socket_factory=lambda address, timeout: sock,+ )+ self.assertFalse(controller._connect_once())+ self.assertEqual(controller.connection_status, OLD_RECEIVER_STATUS)++ def test_handshake_welcome_with_other_error_is_surfaced(self):+ sock = FakeSocket()+ seed_receiver_reply(sock, protocol.welcome_msg(error="rate_limited"))++ controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ socket_factory=lambda address, timeout: sock,+ )+ self.assertFalse(controller._connect_once())+ self.assertIn("rate_limited", controller.connection_status)++ def test_no_route_uses_existing_ssh_fallback_and_authenticates_over_localhost(self):+ sock = FakeSocket()+ seed_receiver_reply(sock, protocol.welcome_msg())+ socket_calls = []++ def socket_factory(address, timeout):+ socket_calls.append((address, timeout))+ if len(socket_calls) == 1:+ raise OSError(errno.EHOSTUNREACH, "No route to host")+ return sock++ controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ socket_factory=socket_factory,+ )+ self.assertTrue(controller._connect_once())+ self.assertEqual(socket_calls[1][0], ("127.0.0.1", 24822))+ self.assertEqual(+ controller.connection_status,+ "Connected to Windows via secure macOS 27 fallback",+ )++ def test_set_redirecting_off_resets_mouse_accumulators(self):+ sock = FakeSocket()+ self.controller.sock = sock+ self.controller.redirecting = True+ self.controller.translator._move_accum_x = 0.4+ self.controller.translator._move_accum_y = -0.4+ self.controller.set_redirecting(False)+ self.assertEqual(self.controller.translator._move_accum_x, 0.0)+ self.assertEqual(self.controller.translator._move_accum_y, 0.0)++ def test_no_route_error_explains_the_network_failure(self):+ error = OSError(65, "No route to host")+ self.assertEqual(+ connection_error_message(error),+ "Windows is unreachable from this Mac. Check that both devices can communicate on the local network.",+ )+++class ClipboardSyncTests(unittest.TestCase):+ def setUp(self):+ self.clock = FakeClock()+ self.controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ )+ self.sock = FakeSocket()+ self.controller.sock = self.sock++ def _drain_outbound(self):+ while not self.controller.outbound.empty():+ self.controller._process_outbound(self.controller.outbound.get_nowait())++ def test_control_message_bypasses_the_gate_while_not_redirecting(self):+ self.controller.redirecting = False+ self.controller._process_outbound(protocol.focus_msg("mac"))+ self.assertEqual(sent_messages(self.controller, self.sock)[-1], protocol.focus_msg("mac"))++ def test_non_control_message_is_dropped_while_not_redirecting(self):+ self.controller.redirecting = False+ self.controller._process_outbound({"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}})+ self.assertEqual(self.sock.sent, [])++ def test_control_messages_do_not_consume_a_sequence_number(self):+ self.controller.redirecting = True+ self.controller._process_outbound(protocol.focus_msg("windows", return_edge="left", resistance_px=120))+ self.assertEqual(self.controller.last_sent_seq, 0)+ self.assertNotIn("seq", sent_messages(self.controller, self.sock)[-1]["data"])++ def test_switch_to_windows_sends_clipboard_then_focus_in_order(self):+ self.controller.clipboard = FakeClipboard("hello from the Mac")+ self.assertTrue(self.controller.set_redirecting(True))+ self._drain_outbound()+ sent = sent_messages(self.controller, self.sock)+ self.assertEqual(+ sent,+ [protocol.clipboard_msg("hello from the Mac"), protocol.focus_msg("windows", return_edge="left", resistance_px=120)],+ )++ def test_switch_to_windows_with_empty_clipboard_sends_focus_only(self):+ self.controller.clipboard = FakeClipboard("")+ self.controller.set_redirecting(True)+ self._drain_outbound()+ sent = sent_messages(self.controller, self.sock)+ self.assertEqual(sent, [protocol.focus_msg("windows", return_edge="left", resistance_px=120)])++ def test_switch_to_windows_skips_oversized_clipboard_but_still_sends_focus(self):+ self.controller.clipboard = FakeClipboard("z" * (protocol.CLIPBOARD_MAX_BYTES + 1))+ self.controller.set_redirecting(True)+ self._drain_outbound()+ sent = sent_messages(self.controller, self.sock)+ self.assertEqual(sent, [protocol.focus_msg("windows", return_edge="left", resistance_px=120)])++ def test_switch_back_to_mac_queues_a_focus_message(self):+ self.controller.redirecting = True+ self.controller.set_redirecting(False)+ self.assertEqual(self.controller.outbound.get_nowait(), protocol.focus_msg("mac"))++ def test_switch_back_focus_message_survives_the_closed_gate(self):+ # set_redirecting(False) flips redirecting False before the worker+ # ever dequeues the focus message it just queued -- the gate must+ # still let this specific message through.+ self.controller.redirecting = True+ self.controller.set_redirecting(False)+ self.assertFalse(self.controller.redirecting)+ message = self.controller.outbound.get_nowait()+ self.controller._process_outbound(message)+ self.assertEqual(sent_messages(self.controller, self.sock)[-1], protocol.focus_msg("mac"))++ def test_handle_inbound_clipboard_sets_the_local_pasteboard(self):+ fake = FakeClipboard()+ self.controller.clipboard = fake+ self.controller._handle_inbound(protocol.clipboard_msg("copied on Windows"))+ self.assertEqual(fake.set_calls, [("copied on Windows", None)])++ def test_handle_inbound_clipboard_ignores_oversized_payload(self):+ fake = FakeClipboard()+ self.controller.clipboard = fake+ oversized = "y" * (protocol.CLIPBOARD_MAX_BYTES + 1)+ self.controller._handle_inbound(protocol.clipboard_msg(oversized))+ self.assertEqual(fake.set_calls, [])++ def test_handle_inbound_clipboard_refreshes_liveness(self):+ fake = FakeClipboard()+ self.controller.clipboard = fake+ self.controller.last_ack_at = 0.0+ self.clock.value = 42.0+ self.controller._handle_inbound(protocol.clipboard_msg("hi"))+ self.assertEqual(self.controller.last_ack_at, 42.0)++ def test_switch_to_windows_sends_text_and_image_together(self):+ self.controller.clipboard = FakeClipboard("shot.png", FAKE_PNG)+ self.controller.set_redirecting(True)+ self._drain_outbound()+ sent = sent_messages(self.controller, self.sock)+ self.assertEqual(sent[0], protocol.clipboard_msg("shot.png", FAKE_PNG))+ self.assertEqual(sent[1]["type"], protocol.MSG_FOCUS)++ def test_switch_to_windows_with_image_only_sends_no_text_key(self):+ self.controller.clipboard = FakeClipboard(None, FAKE_PNG)+ self.controller.set_redirecting(True)+ self._drain_outbound()+ self.assertEqual(sent_messages(self.controller, self.sock)[0], protocol.clipboard_msg(None, FAKE_PNG))++ def test_switch_to_windows_drops_an_oversized_image_but_sends_the_text(self):+ big = protocol.PNG_SIGNATURE + b"\x00" * protocol.CLIPBOARD_IMAGE_MAX_BYTES+ self.controller.clipboard = FakeClipboard("shot.png", big)+ self.controller.set_redirecting(True)+ self._drain_outbound()+ self.assertEqual(sent_messages(self.controller, self.sock)[0], protocol.clipboard_msg("shot.png"))++ def test_handle_inbound_clipboard_sets_text_and_image(self):+ fake = FakeClipboard()+ self.controller.clipboard = fake+ self.controller._handle_inbound(protocol.clipboard_msg("shot.png", FAKE_PNG))+ self.assertEqual(fake.set_calls, [("shot.png", FAKE_PNG)])++ def test_handle_inbound_clipboard_ignores_a_malformed_image_but_keeps_the_text(self):+ fake = FakeClipboard()+ self.controller.clipboard = fake+ for image in ("not base64!", 42, "", protocol.clipboard_msg(None, b"GIF89a")["data"]["image"]):+ message = {"type": protocol.MSG_CLIPBOARD, "data": {"text": "t", "image": image, "image_format": "png"}}+ self.controller._handle_inbound(message)+ self.controller._handle_inbound({"type": protocol.MSG_CLIPBOARD, "data": {"image": "AAAA", "image_format": "bmp"}})+ self.assertEqual(fake.set_calls, [("t", None)] * 4)+++class CursorPinningTests(unittest.TestCase):+ """Bug: on some macOS versions (seen on 27 beta)+ CGAssociateMouseAndMouseCursorPosition(False) doesn't hold, so the Mac+ cursor keeps moving even while input is redirected to Windows.+ KVMController compensates belt-and-braces: it pins the cursor location+ captured at redirect start and warps back to it on every captured mouse+ move/drag while redirecting."""++ def setUp(self):+ FakeQuartz.reset_cursor_spies()+ self.clock = FakeClock()+ self.controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ )+ self.sock = FakeSocket()+ self.controller.sock = self.sock++ def test_pin_captured_and_association_disabled_at_redirect_start(self):+ self.assertTrue(self.controller.set_redirecting(True))+ self.assertEqual(self.controller.cursor_pin_point, FakeQuartz.cursor_pin_location)+ self.assertEqual(FakeQuartz.associate_calls, [False])++ def test_warp_called_on_every_mouse_move_while_redirecting(self):+ self.controller.set_redirecting(True)+ move_event = {+ FakeQuartz.kCGMouseEventDeltaX: 4,+ FakeQuartz.kCGMouseEventDeltaY: -3,+ }+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved, move_event, None)+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved, move_event, None)+ self.assertEqual(FakeQuartz.warp_calls, [FakeQuartz.cursor_pin_location] * 2)++ def test_warp_called_on_mouse_drag_while_redirecting(self):+ self.controller.set_redirecting(True)+ drag_event = {+ FakeQuartz.kCGMouseEventDeltaX: 1,+ FakeQuartz.kCGMouseEventDeltaY: 1,+ }+ self.controller._event_tap_callback(+ None, FakeQuartz.kCGEventLeftMouseDragged, drag_event, None+ )+ self.assertEqual(FakeQuartz.warp_calls, [FakeQuartz.cursor_pin_location])++ def test_warp_not_called_when_local(self):+ move_event = {+ FakeQuartz.kCGMouseEventDeltaX: 4,+ FakeQuartz.kCGMouseEventDeltaY: -3,+ }+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved, move_event, None)+ self.assertEqual(FakeQuartz.warp_calls, [])++ def test_warp_not_called_for_key_events_while_redirecting(self):+ self.controller.set_redirecting(True)+ key_event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x00,+ FakeQuartz.kCGKeyboardEventAutorepeat: 0,+ "unicode": "a",+ }+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventKeyDown, key_event, None)+ self.assertEqual(FakeQuartz.warp_calls, [])++ def test_pin_and_association_cleared_on_redirect_end(self):+ self.controller.set_redirecting(True)+ self.controller.set_redirecting(False)+ self.assertIsNone(self.controller.cursor_pin_point)+ self.assertEqual(FakeQuartz.associate_calls, [False, True])++ def test_association_status_logged_once_not_every_toggle(self):+ logger = logging.getLogger("kvm-bridge-tests.cursor-assoc")+ logger.setLevel(logging.INFO)+ controller = KVMController(+ make_config(), logger=logger, quartz=FakeQuartz, clock=self.clock,+ )+ controller.sock = FakeSocket()+ with self.assertLogs(logger, level="INFO") as captured:+ controller.set_redirecting(True)+ controller.set_redirecting(False)+ assoc_logs = [+ line for line in captured.output+ if "CGAssociateMouseAndMouseCursorPosition" in line+ ]+ self.assertEqual(len(assoc_logs), 1)++ def test_tap_disabled_while_redirecting_gives_the_cursor_back(self):+ # Input is forced local when macOS disables the tap, so the cursor+ # follows the hand again; it used to be re-pinned, which left the+ # pointer frozen while the keyboard already worked here.+ self.controller.set_redirecting(True)+ FakeQuartz.reset_cursor_spies()+ self.controller.event_tap = object()+ self.controller._event_tap_callback(+ None, FakeQuartz.kCGEventTapDisabledByTimeout, {}, None+ )+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(FakeQuartz.tap_enable_calls, [(self.controller.event_tap, True)])+ self.assertEqual(FakeQuartz.associate_calls, [True])++ def test_warp_error_logged_once_not_spammed(self):+ logger = logging.getLogger("kvm-bridge-tests.warp-error")+ logger.setLevel(logging.WARNING)++ class ErroringQuartz(FakeQuartz):+ @classmethod+ def CGWarpMouseCursorPosition(cls, point):+ cls.warp_calls.append(point)+ return 1 # non-zero: a synthetic CGError++ ErroringQuartz.reset_cursor_spies()+ controller = KVMController(+ make_config(), logger=logger, quartz=ErroringQuartz, clock=self.clock,+ )+ controller.sock = FakeSocket()+ controller.set_redirecting(True)+ move_event = {+ ErroringQuartz.kCGMouseEventDeltaX: 4,+ ErroringQuartz.kCGMouseEventDeltaY: -3,+ }+ with self.assertLogs(logger, level="WARNING") as captured:+ controller._event_tap_callback(None, ErroringQuartz.kCGEventMouseMoved, move_event, None)+ controller._event_tap_callback(None, ErroringQuartz.kCGEventMouseMoved, move_event, None)+ warp_warnings = [line for line in captured.output if "CGWarpMouseCursorPosition" in line]+ self.assertEqual(len(warp_warnings), 1)+ self.assertEqual(len(ErroringQuartz.warp_calls), 2)+++class OverlayGestureTests(unittest.TestCase):+ """Bug 3: the CGEventTap-based gesture path (event types 29-32) is+ best-effort and was observed to never deliver on macOS 27 beta at all.+ KVMController.handle_overlay_gesture is the counterpart entry point fed+ by the invisible overlay NSPanel's ordinary AppKit responder methods+ (see kvm_bridge_app.py's GestureOverlay/_GestureCaptureView), which is+ fully-supported API and actually receives gestures."""++ def setUp(self):+ self.clock = FakeClock()+ self.controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ )+ self.sock = FakeSocket()+ self.controller.sock = self.sock++ def test_overlay_gesture_translated_and_enqueued_while_redirecting(self):+ self.controller.redirecting = True+ self.controller.handle_overlay_gesture(MAGNIFY_TYPE, FakeGestureEvent(magnification=0.05))+ drained = []+ while not self.controller.outbound.empty():+ drained.append(self.controller.outbound.get_nowait())+ self.assertEqual(drained, [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},+ protocol.scroll_msg(dy=1, dx=0, mode="line"),+ {"type": protocol.MSG_KEYUP, "data": {"key": "ctrl"}},+ ])+ # Fed back through the normal outbound path, these get a `seq` the+ # same way any other input event does.+ for message in drained:+ self.controller._process_outbound(message)+ sent = sent_messages(self.controller, self.sock)+ self.assertEqual([entry["data"]["seq"] for entry in sent], [1, 2, 3])++ def test_overlay_gesture_ignored_when_not_redirecting(self):+ self.controller.redirecting = False+ self.controller.handle_overlay_gesture(MAGNIFY_TYPE, FakeGestureEvent(magnification=0.05))+ self.assertTrue(self.controller.outbound.empty())++ def test_overlay_gesture_translator_exception_does_not_raise(self):+ self.controller.redirecting = True++ def boom(event_type, ns_event):+ raise RuntimeError("synthetic overlay translation failure")++ self.controller.gesture_translator.translate = boom+ # Must not raise even though the translator is broken.+ self.controller.handle_overlay_gesture(MAGNIFY_TYPE, FakeGestureEvent(magnification=0.05))+ self.assertTrue(self.controller.outbound.empty())++ def test_overlay_gesture_capture_logged_once_on_first_gesture(self):+ logger = logging.getLogger("kvm-bridge-tests.overlay-gesture-capture")+ logger.setLevel(logging.INFO)+ controller = KVMController(+ make_config(),+ logger=logger,+ quartz=FakeQuartz,+ clock=self.clock,+ )+ controller.redirecting = True+ with self.assertLogs(logger, level="INFO") as captured:+ controller.handle_overlay_gesture(MAGNIFY_TYPE, FakeGestureEvent(magnification=0.01))+ controller.handle_overlay_gesture(MAGNIFY_TYPE, FakeGestureEvent(magnification=0.01))+ overlay_logs = [+ line for line in captured.output if "gesture capture active (overlay)" in line+ ]+ self.assertEqual(len(overlay_logs), 1)++ def test_overlay_gesture_swipe_translated_while_redirecting(self):+ self.controller.redirecting = True+ self.controller.handle_overlay_gesture(SWIPE_TYPE, FakeGestureEvent(deltaX=1.0))+ drained = []+ while not self.controller.outbound.empty():+ drained.append(self.controller.outbound.get_nowait())+ self.assertEqual(drained, [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "left"}},+ {"type": protocol.MSG_KEYUP, "data": {"key": "left"}},+ {"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},+ ])+++class MediaKeyWiringTests(unittest.TestCase):+ """Exercises _event_tap_callback's NSSystemDefined branch with an+ injected system_event_converter, standing in for the real AppKit+ conversion, exactly as GestureWiringTests does for gestures."""++ SYSDEFINED = media_keys.NX_SYSDEFINED_EVENT_TYPE++ def _controller(self, converter):+ return KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=FakeClock(),+ system_event_converter=converter,+ )++ @staticmethod+ def _data1(nx_code, down=True):+ return (nx_code << 16) | ((0x0A if down else 0x0B) << 8)++ def test_play_pause_is_forwarded_and_swallowed(self):+ controller = self._controller(lambda event: (8, self._data1(16)))+ controller.redirecting = True+ self.assertIsNone(+ controller._event_tap_callback(None, self.SYSDEFINED, object(), None)+ )+ self.assertEqual(+ controller.outbound.get_nowait(),+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "media_play_pause"}},+ )++ def test_volume_key_up_sends_keyup(self):+ controller = self._controller(lambda event: (8, self._data1(0, down=False)))+ controller.redirecting = True+ controller._event_tap_callback(None, self.SYSDEFINED, object(), None)+ self.assertEqual(+ controller.outbound.get_nowait(),+ {"type": protocol.MSG_KEYUP, "data": {"key": "volume_up"}},+ )++ def test_non_media_system_event_passes_through(self):+ # NX code 3 is brightness-up, which Windows has no equivalent for.+ controller = self._controller(lambda event: (8, self._data1(3)))+ controller.redirecting = True+ raw_event = object()+ self.assertIs(+ controller._event_tap_callback(None, self.SYSDEFINED, raw_event, None),+ raw_event,+ )+ self.assertTrue(controller.outbound.empty())++ def test_not_redirecting_passes_through_without_converting(self):+ calls = []++ def converter(event):+ calls.append(event)+ return (8, self._data1(16))++ controller = self._controller(converter)+ controller.redirecting = False+ raw_event = object()+ self.assertIs(+ controller._event_tap_callback(None, self.SYSDEFINED, raw_event, None),+ raw_event,+ )+ self.assertEqual(calls, [])++ def test_failed_conversion_passes_through_rather_than_disconnecting(self):+ def converter(event):+ raise RuntimeError("boom")++ controller = self._controller(converter)+ controller.redirecting = True+ raw_event = object()+ self.assertIs(+ controller._event_tap_callback(None, self.SYSDEFINED, raw_event, None),+ raw_event,+ )+ self.assertTrue(controller.redirecting)+++class GestureWiringTests(unittest.TestCase):+ """Exercises _event_tap_callback's gesture branch with an injected+ gesture_event_converter, standing in for the real AppKit conversion.+ Never touches AppKit/Quartz gesture APIs, matching how the rest of this+ file fakes Quartz."""++ def setUp(self):+ self.clock = FakeClock()++ def _controller(self, converter):+ return KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ gesture_event_converter=converter,+ )++ def test_gesture_while_redirecting_is_translated_enqueued_and_swallowed(self):+ controller = self._controller(lambda event: FakeGestureEvent(deltaX=1.0))+ controller.redirecting = True+ sock = FakeSocket()+ controller.sock = sock+ returned = controller._event_tap_callback(None, SWIPE_TYPE, object(), None)+ self.assertIsNone(returned)+ drained = []+ while not controller.outbound.empty():+ drained.append(controller.outbound.get_nowait())+ self.assertEqual(drained, [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "left"}},+ {"type": protocol.MSG_KEYUP, "data": {"key": "left"}},+ {"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},+ ])+ # Fed back through the normal outbound path, these get a `seq` the+ # same way any other input event does.+ for message in drained:+ controller._process_outbound(message)+ sent = sent_messages(controller, sock)+ self.assertEqual([entry["data"]["seq"] for entry in sent], [1, 2, 3, 4])++ def test_gesture_while_not_redirecting_is_passed_through_untouched(self):+ calls = []++ def converter(event):+ calls.append(event)+ return FakeGestureEvent(deltaX=1.0)++ controller = self._controller(converter)+ controller.redirecting = False+ raw_event = object()+ returned = controller._event_tap_callback(None, SWIPE_TYPE, raw_event, None)+ self.assertIs(returned, raw_event)+ self.assertTrue(controller.outbound.empty())+ # "Passed through untouched" means conversion is never even+ # attempted while not redirecting.+ self.assertEqual(calls, [])++ def test_gesture_conversion_failure_passes_through_and_capture_continues(self):+ def converter(event):+ raise RuntimeError("synthetic AppKit failure")++ controller = self._controller(converter)+ controller.redirecting = True+ raw_event = object()+ returned = controller._event_tap_callback(None, SWIPE_TYPE, raw_event, None)+ self.assertIs(returned, raw_event)+ self.assertTrue(controller.outbound.empty())+ # Fail open: a broken conversion must not force a full disconnect.+ self.assertTrue(controller.redirecting)+ # An ordinary keyboard event right afterwards proves capture as a+ # whole is unaffected by the failed gesture conversion.+ key_event = {+ FakeQuartz.kCGKeyboardEventKeycode: 0x00,+ FakeQuartz.kCGKeyboardEventAutorepeat: 0,+ "unicode": "a",+ }+ keyboard_returned = controller._event_tap_callback(+ None, FakeQuartz.kCGEventKeyDown, key_event, None+ )+ self.assertIsNone(keyboard_returned)+ self.assertEqual(+ controller.outbound.get_nowait(),+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}},+ )++ def test_swipe_while_redirecting_is_translated_and_swallowed(self):+ controller = self._controller(lambda event: FakeGestureEvent(deltaX=1.0))+ controller.redirecting = True+ returned = controller._event_tap_callback(None, SWIPE_TYPE, object(), None)+ self.assertIsNone(returned)+ drained = []+ while not controller.outbound.empty():+ drained.append(controller.outbound.get_nowait())+ self.assertEqual(drained, [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "left"}},+ {"type": protocol.MSG_KEYUP, "data": {"key": "left"}},+ {"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},+ ])++ def test_gesture_capture_active_logged_once_on_first_success(self):+ logger = logging.getLogger("kvm-bridge-tests.gesture-capture")+ logger.setLevel(logging.INFO)+ controller = KVMController(+ make_config(),+ logger=logger,+ quartz=FakeQuartz,+ clock=self.clock,+ gesture_event_converter=lambda event: FakeGestureEvent(magnification=0.01),+ )+ controller.redirecting = True+ with self.assertLogs(logger, level="INFO") as captured:+ # 0.01 stays below the 0.05 zoom step both times, so no+ # keydown/scroll/keyup messages are emitted at all -- the log+ # must still fire, since it only proves a gesture event arrived+ # and converted, not that it produced output.+ controller._event_tap_callback(None, SWIPE_TYPE, object(), None)+ controller._event_tap_callback(None, SWIPE_TYPE, object(), None)+ active_logs = [line for line in captured.output if "gesture capture active" in line]+ self.assertEqual(len(active_logs), 1)+ self.assertTrue(controller.outbound.empty())+++++class WindowsLockStatusTests(unittest.TestCase):+ """Windows sets `locked` on its ACKs while it clears the lock screen, so+ the Mac can explain the pause instead of just looking dead."""++ def setUp(self):+ self.controller = KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=FakeClock(),+ )+ self.controller.connection_status = "Connected to 192.168.1.3:51820"++ def test_locked_ack_shows_the_unlock_and_clearing_it_restores_the_status(self):+ self.controller._note_windows_lock(True)+ self.assertTrue(self.controller.windows_locked)+ self.assertEqual(self.controller.connection_status, "Unlocking Windows…")+ self.controller._note_windows_lock(False)+ self.assertFalse(self.controller.windows_locked)+ self.assertEqual(self.controller.connection_status, "Connected to 192.168.1.3:51820")++ def test_the_ssh_fallback_wording_survives_an_unlock(self):+ """The status is restored verbatim, not rebuilt, so the macOS 27+ fallback does not silently become an ordinary connection."""+ self.controller.connection_status = "Connected to Windows via secure macOS 27 fallback"+ self.controller._note_windows_lock(True)+ self.controller._note_windows_lock(False)+ self.assertEqual(+ self.controller.connection_status,+ "Connected to Windows via secure macOS 27 fallback",+ )++ def test_repeated_locked_acks_do_not_overwrite_the_saved_status(self):+ """An ACK lands every 400ms; only transitions may touch the status, or+ the saved one becomes 'Unlocking Windows…' and is lost."""+ self.controller._note_windows_lock(True)+ self.controller._note_windows_lock(True)+ self.controller._note_windows_lock(False)+ self.assertEqual(self.controller.connection_status, "Connected to 192.168.1.3:51820")++ def test_an_ack_without_the_field_is_not_a_lock(self):+ self.controller._record_ack(protocol.ack_msg(0))+ self.assertFalse(self.controller.windows_locked)+++class DockControlWiringTests(unittest.TestCase):+ """The tap's type-30 event is a system swipe (DockControl), read through+ an injected dock_event_reader standing in for the private CGEvent+ fields. While redirecting it is always swallowed, so Mission Control+ and Spaces stay shut on the Mac; classified or not."""++ def _controller(self, reader):+ return KVMController(+ make_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=FakeClock(),+ dock_event_reader=reader,+ macos_major=26,+ )++ def _ended(self, motion, progress):+ return types.SimpleNamespace(hid=23, motion=motion, phase=4, progress=progress, velocity=0.0)++ def test_swipe_up_while_redirecting_becomes_one_gesture_message_and_is_swallowed(self):+ controller = self._controller(lambda event: self._ended(motion=2, progress=-0.4))+ controller.redirecting = True+ returned = controller._event_tap_callback(None, DOCK_CONTROL_TYPE, object(), None)+ self.assertIsNone(returned)+ self.assertEqual(controller.outbound.get_nowait(), protocol.gesture_msg("swipe_up"))+ self.assertTrue(controller.outbound.empty())++ def test_dock_event_while_not_redirecting_is_passed_through_unread(self):+ calls = []++ def reader(event):+ calls.append(event)+ return self._ended(motion=2, progress=-0.4)++ controller = self._controller(reader)+ controller.redirecting = False+ raw_event = object()+ self.assertIs(controller._event_tap_callback(None, DOCK_CONTROL_TYPE, raw_event, None), raw_event)+ self.assertEqual(calls, [])+ self.assertTrue(controller.outbound.empty())++ def test_unreadable_dock_event_is_still_swallowed_and_capture_continues(self):+ def reader(event):+ raise RuntimeError("synthetic field failure")++ controller = self._controller(reader)+ controller.redirecting = True+ self.assertIsNone(controller._event_tap_callback(None, DOCK_CONTROL_TYPE, object(), None))+ self.assertTrue(controller.outbound.empty())+ self.assertTrue(controller.redirecting)+++class CrossingWiringTests(unittest.TestCase):+ """The engine is exercised in test_crossing.py; these prove the bridge+ feeds it the right things at the right moment and acts on the answer."""++ BOUNDS = (0, 0, 1728, 1117)++ def setUp(self):+ FakeQuartz.reset_cursor_spies()+ self.clock = FakeClock()+ self.feedback = []+ self.controller = self._controller(crossing_config())++ def _controller(self, cfg):+ controller = KVMController(+ cfg,+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ desktop_bounds=lambda: self.BOUNDS,+ )+ controller.sock = FakeSocket()+ controller.on_crossing = lambda kind, step: self.feedback.append((kind, step))+ return controller++ def _move(self, x, y, dx, dy=0, event_type=FakeQuartz.kCGEventMouseMoved):+ event = {+ "location": (x, y),+ FakeQuartz.kCGMouseEventDeltaX: dx,+ FakeQuartz.kCGMouseEventDeltaY: dy,+ }+ self.clock.value += 0.01+ return event, self.controller._event_tap_callback(None, event_type, event, None)++ def _push(self, times, x=1727.0, y=558.0, dx=30, dy=0, event_type=FakeQuartz.kCGEventMouseMoved):+ returned = None+ for _ in range(times):+ event, returned = self._move(x, y, dx, dy, event_type)+ if self.controller.redirecting:+ break+ return event, returned++ def _sent(self):+ messages = []+ while not self.controller.outbound.empty():+ messages.append(self.controller.outbound.get_nowait())+ return messages++ def test_movement_away_from_the_edge_passes_through(self):+ event, returned = self._move(800.0, 500.0, 30)+ self.assertIs(returned, event)+ self.assertEqual(FakeQuartz.warp_calls, [])+ self.assertFalse(self.controller.redirecting)++ def test_pushing_the_edge_swallows_and_warps_then_crosses_with_the_offset(self):+ self._move(1727.0, 558.0, 30)+ event, returned = self._move(1727.0, 558.0, 30)+ self.assertIsNone(returned, "the push is swallowed")+ self.assertEqual(FakeQuartz.warp_calls, [(1727.0, 558.0)])+ self.assertFalse(self.controller.redirecting)+ _event, returned = self._push(10)+ self.assertIsNone(returned)+ self.assertTrue(self.controller.redirecting)+ focus = [m for m in self._sent() if m["type"] == protocol.MSG_FOCUS]+ self.assertEqual(+ focus,+ [protocol.focus_msg("windows", edge="left", offset=0.5, return_edge="left", resistance_px=120)],+ )+ kinds = [kind for kind, _ in self.feedback]+ self.assertEqual(kinds[-1], "cross")+ self.assertEqual(kinds.count("tick"), 3)++ def test_no_crossing_while_disconnected(self):+ self.controller.sock = None+ event, returned = self._push(10)+ self.assertIs(returned, event)+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(FakeQuartz.warp_calls, [])++ def test_no_crossing_while_a_button_is_held(self):+ event, returned = self._push(10, event_type=FakeQuartz.kCGEventLeftMouseDragged)+ self.assertIs(returned, event)+ self.assertFalse(self.controller.redirecting)++ def test_a_mouse_button_resets_the_push(self):+ self._push(3)+ self.assertGreater(self.controller.crossing.pressure, 0)+ event = {"location": (1727.0, 558.0)}+ returned = self.controller._event_tap_callback(None, FakeQuartz.kCGEventLeftMouseDown, event, None)+ self.assertIs(returned, event)+ self.assertEqual(self.controller.crossing.pressure, 0)++ def test_shortcut_only_leaves_the_edge_alone(self):+ self.controller = self._controller(crossing_config(methods=["shortcut"]))+ event, returned = self._push(10)+ self.assertIs(returned, event)+ self.assertFalse(self.controller.redirecting)++ def test_a_failure_in_the_crossing_path_returns_the_event_and_disarms(self):+ self.controller.desktop_bounds = lambda: (_ for _ in ()).throw(RuntimeError("no displays"))+ self.controller._bounds_cache = None+ event, returned = self._move(1727.0, 558.0, 30)+ self.assertIs(returned, event)+ self.assertFalse(self.controller.redirecting)+ self.assertTrue(self.controller._crossing_failed)+ event, returned = self._move(1727.0, 558.0, 30)+ self.assertIs(returned, event)+ self.controller.update_config(crossing_config())+ self.assertFalse(self.controller._crossing_failed)++ def test_applying_settings_keeps_the_link(self):+ sock = self.controller.sock+ self.controller.apply_settings(crossing_config(resistance_px=40, methods=["shortcut", "notch"]))+ self.assertIs(self.controller.sock, sock)+ self.assertEqual(self.controller.crossing.resistance_px, 40)+ self.assertEqual(self.controller.crossing.home_edge(), "bottom")++ def test_shortcut_switch_sends_the_way_home_but_no_arrival(self):+ self.controller.set_redirecting(True)+ focus = [m for m in self._sent() if m["type"] == protocol.MSG_FOCUS]+ self.assertEqual(focus, [protocol.focus_msg("windows", return_edge="left", resistance_px=120)])++ def test_shortcut_switch_with_only_the_notch_on_sends_the_notch_way_home(self):+ self.controller = self._controller(crossing_config(methods=["shortcut", "notch"]))+ self.controller.set_redirecting(True)+ focus = [m for m in self._sent() if m["type"] == protocol.MSG_FOCUS]+ self.assertEqual(focus, [protocol.focus_msg("windows", return_edge="bottom", resistance_px=120)])++ def test_inbound_switch_returns_input_and_lands_the_pointer(self):+ self.controller.set_redirecting(True)+ self._sent()+ FakeQuartz.reset_cursor_spies()+ self.controller._handle_inbound(protocol.switch_msg("mac", "right", 0.5))+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(FakeQuartz.warp_calls, [(1725.0, 558.0)])+ self.assertEqual([m["type"] for m in self._sent()], [protocol.MSG_FOCUS])+ self.assertEqual(self.feedback[-1][0], "arrive")++ def test_inbound_switch_without_a_position_still_returns_input(self):+ self.controller.set_redirecting(True)+ FakeQuartz.reset_cursor_spies()+ self.controller._handle_inbound(protocol.switch_msg("mac"))+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(FakeQuartz.warp_calls, [])++ def test_inbound_switch_to_an_unknown_target_is_ignored(self):+ self.controller.set_redirecting(True)+ self.controller._handle_inbound(protocol.switch_msg("toaster", "right", 0.5))+ self.assertTrue(self.controller.redirecting)++ def test_hold_style_redirects_only_while_the_key_is_down(self):+ cfg = crossing_config()+ cfg.trigger_style = "hold"+ self.controller = self._controller(cfg)+ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": FakeQuartz.kCGEventFlagMaskAlternate}+ up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}+ self.assertIsNone(self.controller._event_tap_callback(None, FakeQuartz.kCGEventFlagsChanged, down, None))+ self.assertTrue(self.controller.redirecting)+ self.assertIsNone(self.controller._event_tap_callback(None, FakeQuartz.kCGEventFlagsChanged, up, None))+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(+ [m["type"] for m in self._sent()],+ ["_local_clipboard", protocol.MSG_FOCUS, protocol.MSG_FOCUS],+ )++ def test_default_desktop_bounds_is_the_union_of_every_display(self):+ class DisplayQuartz(FakeQuartz):+ @staticmethod+ def CGGetActiveDisplayList(limit, displays, count):+ return 0, [1, 2], 2++ @staticmethod+ def CGDisplayBounds(display):+ rects = {+ 1: types.SimpleNamespace(+ origin=types.SimpleNamespace(x=0.0, y=0.0),+ size=types.SimpleNamespace(width=1728.0, height=1117.0),+ ),+ 2: types.SimpleNamespace(+ origin=types.SimpleNamespace(x=1728.0, y=-300.0),+ size=types.SimpleNamespace(width=1920.0, height=1080.0),+ ),+ }+ return rects[display]++ controller = KVMController(crossing_config(), logger=quiet_logger(), quartz=DisplayQuartz, clock=self.clock)+ self.assertEqual(controller._default_desktop_bounds(), (0.0, -300.0, 3648.0, 1117.0))++ def test_paused_crossing_leaves_the_edge_alone_while_the_shortcut_still_switches(self):+ self.controller.crossing_paused = True+ event, returned = self._push(10)+ self.assertIs(returned, event)+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(FakeQuartz.warp_calls, [])+ self._double_tap()+ self.assertTrue(self.controller.redirecting)+ self.controller.set_redirecting(False)+ self.controller.crossing_paused = False+ self._push(10)+ self.assertTrue(self.controller.redirecting, "resuming re-arms the edge with no other change")++ def test_a_full_screen_app_inhibits_the_pointer_methods_but_not_the_shortcut(self):+ self.controller.full_screen_app = "Steam"+ event, returned = self._push(10)+ self.assertIs(returned, event)+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(FakeQuartz.warp_calls, [])+ self._double_tap()+ self.assertTrue(self.controller.redirecting)+ self.controller.set_redirecting(False)+ self.controller.full_screen_app = None+ self._push(10)+ self.assertTrue(self.controller.redirecting)++ def _double_tap(self):+ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": FakeQuartz.kCGEventFlagMaskAlternate}+ up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}+ for event in (down, up, down, up):+ self.clock.value += 0.05+ self.controller._event_tap_callback(None, FakeQuartz.kCGEventFlagsChanged, event, None)+++class RoundTripTests(unittest.TestCase):+ """The smoothed round trip shown in the control window: measured from the send of the+ event an ACK names, upper-median smoothed, and blank whenever it would be stale."""++ def setUp(self):+ self.clock = FakeClock(10.0)+ self.controller = KVMController(+ crossing_config(), logger=quiet_logger(), quartz=FakeQuartz, clock=self.clock+ )+ self.controller.sock = FakeSocket()+ self.controller.redirecting = True++ def _send(self):+ self.controller._process_outbound({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 1, "dy": 0}})+ return self.controller.last_sent_seq++ def _ack(self, seq, after):+ self.clock.value += after+ self.controller._handle_inbound(protocol.ack_msg(seq))++ def test_nothing_to_show_before_anything_is_acknowledged(self):+ self.assertIsNone(self.controller.round_trip_ms)+ self._send()+ self.assertIsNone(self.controller.round_trip_ms)++ def test_one_trip_is_measured_from_the_send_of_the_acknowledged_event(self):+ first = self._send()+ self.clock.value += 0.3+ second = self._send()+ self._ack(second, 0.05)+ self.assertEqual(self.controller.round_trip_ms, 50, "the ACK names seq 2, sent 50ms ago, not seq 1")+ self.assertNotEqual(first, second)++ def test_the_reading_is_the_upper_median_of_the_last_few_trips(self):+ for delay in (0.010, 0.040, 0.020, 0.030):+ seq = self._send()+ self._ack(seq, delay)+ self.assertEqual(self.controller.round_trip_ms, 30)++ def test_a_repeated_ack_of_the_same_seq_adds_no_sample(self):+ seq = self._send()+ self._ack(seq, 0.02)+ self._ack(seq, 1.0)+ self._ack(seq, 1.0)+ self.assertEqual(self.controller.round_trip_ms, 20)++ def test_only_the_last_handful_of_trips_count(self):+ for _ in range(ROUND_TRIP_SAMPLES):+ self._ack(self._send(), 0.5)+ for _ in range(ROUND_TRIP_SAMPLES):+ self._ack(self._send(), 0.01)+ self.assertEqual(self.controller.round_trip_ms, 10)++ def test_nothing_is_shown_when_input_is_not_on_windows(self):+ self._ack(self._send(), 0.02)+ self.controller.set_redirecting(False)+ self.assertIsNone(self.controller.round_trip_ms)+ self.controller.set_redirecting(True)+ self.assertIsNone(self.controller.round_trip_ms, "the last session's figure does not carry over")++ def test_nothing_is_shown_when_the_link_is_down(self):+ self._ack(self._send(), 0.02)+ self.controller._connection_failed("Windows stopped responding")+ self.controller.sock = FakeSocket()+ self.controller.redirecting = True+ self.assertIsNone(self.controller.round_trip_ms)++ def test_a_figure_goes_stale_after_a_few_seconds_without_a_fresh_ack(self):+ self._ack(self._send(), 0.02)+ self.clock.value += ROUND_TRIP_MAX_AGE_SECONDS - 0.1+ self.assertEqual(self.controller.round_trip_ms, 20)+ self.clock.value += 0.2+ self.assertIsNone(self.controller.round_trip_ms)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_clipboard_mac.py b/mac_app/tests/test_clipboard_mac.pynew file mode 100644index 0000000..3d94921--- /dev/null+++ b/mac_app/tests/test_clipboard_mac.py@@ -0,0 +1,98 @@+"""clipboard_mac's pasteboard logic against a fake pasteboard, plus the one+real AppKit conversion (TIFF to PNG) run on data that never touches the+general pasteboard, so the suite leaves the machine's clipboard alone."""++import struct+import unittest+import zlib++import clipboard_mac+import protocol+++def tiny_png(width=2, height=2):+ """A valid 8-bit RGBA PNG with no filtering, built from the standard+ library so the tests need no imaging dependency."""+ rgba = bytes(range(width * height * 4))[: width * height * 4]+ raw = b"".join(b"\x00" + rgba[y * width * 4:(y + 1) * width * 4] for y in range(height))++ def chunk(kind, body):+ return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))++ header = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)+ return protocol.PNG_SIGNATURE + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")+++class FakePasteboard:+ def __init__(self, data=None, string=None):+ self.data = data or {}+ self.string = string+ self.cleared = 0+ self.written = []++ def stringForType_(self, kind):+ return self.string++ def dataForType_(self, kind):+ return self.data.get(kind)++ def clearContents(self):+ self.cleared += 1++ def setString_forType_(self, text, kind):+ self.written.append((kind, text))+ return True++ def setData_forType_(self, data, kind):+ self.written.append((kind, bytes(data)))+ return True++[email protected](clipboard_mac.AppKit is None, "AppKit is only available on macOS")+class PasteboardImageTests(unittest.TestCase):+ def test_png_on_the_pasteboard_is_returned_as_is(self):+ png = tiny_png()+ board = FakePasteboard({clipboard_mac.AppKit.NSPasteboardTypePNG: png})+ self.assertEqual(clipboard_mac._png_from_pasteboard(board), png)++ def test_tiff_only_is_normalised_to_png(self):+ AppKit = clipboard_mac.AppKit+ png = tiny_png()+ rep = AppKit.NSBitmapImageRep.imageRepWithData_(AppKit.NSData.dataWithBytes_length_(png, len(png)))+ board = FakePasteboard({AppKit.NSPasteboardTypeTIFF: rep.TIFFRepresentation()})+ out = clipboard_mac._png_from_pasteboard(board)+ self.assertTrue(out.startswith(protocol.PNG_SIGNATURE))+ back = AppKit.NSBitmapImageRep.imageRepWithData_(AppKit.NSData.dataWithBytes_length_(out, len(out)))+ self.assertEqual((back.pixelsWide(), back.pixelsHigh()), (2, 2))++ def test_junk_tiff_gives_no_image(self):+ board = FakePasteboard({clipboard_mac.AppKit.NSPasteboardTypeTIFF: b"not a tiff"})+ self.assertIsNone(clipboard_mac._png_from_pasteboard(board))++ def test_empty_pasteboard_gives_no_image(self):+ self.assertIsNone(clipboard_mac._png_from_pasteboard(FakePasteboard()))++ def test_set_contents_writes_text_and_png_after_one_clear(self):+ AppKit = clipboard_mac.AppKit+ board = FakePasteboard()+ fake_appkit = type("FakeAppKit", (), {})()+ fake_appkit.NSPasteboard = type("NSPasteboard", (), {"generalPasteboard": staticmethod(lambda: board)})+ fake_appkit.NSData = AppKit.NSData+ fake_appkit.NSPasteboardTypeString = AppKit.NSPasteboardTypeString+ fake_appkit.NSPasteboardTypePNG = AppKit.NSPasteboardTypePNG+ png = tiny_png()+ real = clipboard_mac.AppKit+ clipboard_mac.AppKit = fake_appkit+ try:+ self.assertTrue(clipboard_mac.set_contents("hello", png))+ finally:+ clipboard_mac.AppKit = real+ self.assertEqual(board.cleared, 1)+ self.assertEqual(board.written, [(AppKit.NSPasteboardTypeString, "hello"), (AppKit.NSPasteboardTypePNG, png)])++ def test_set_contents_with_nothing_writes_nothing(self):+ self.assertFalse(clipboard_mac.set_contents(None, None))+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_config_key_map_override.py b/mac_app/tests/test_config_key_map_override.pynew file mode 100644index 0000000..bd80ad1--- /dev/null+++ b/mac_app/tests/test_config_key_map_override.py@@ -0,0 +1,36 @@+import json+import os+import tempfile+import unittest++import config+++class PartialKeyMapOverrideTest(unittest.TestCase):+ def test_single_entry_matching_legacy_positional_value_is_not_discarded(self):+ """A deliberate one-entry override ("cmd": "cmd") happens to equal the legacy+ positional value for that key, so `not all(...)` is False and the override is+ silently dropped in favour of the full semantic default."""+ raw = {+ "host": "192.168.1.3",+ "port": 24820,+ "auth_token": "t",+ "key_map": {"cmd": "cmd"},+ }+ fd, path = tempfile.mkstemp(suffix=".json")+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as f:+ json.dump(raw, f)+ cfg = config.load_config(path)+ finally:+ os.unlink(path)++ self.assertEqual(+ cfg.key_map["cmd"],+ "cmd",+ "user's deliberate override was discarded and replaced with the semantic default",+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_crossing.py b/mac_app/tests/test_crossing.pynew file mode 100644index 0000000..2db78d7--- /dev/null+++ b/mac_app/tests/test_crossing.py@@ -0,0 +1,289 @@+import unittest++from crossing import DECAY_S, CrossingEngine++BOUNDS = (0, 0, 1728, 1117)+RIGHT_X = 1727.0+++def engine(**overrides):+ settings = dict(methods=("edge",), edge="right", resistance_px=120)+ settings.update(overrides)+ return CrossingEngine(**settings)+++def drive(machine, x, y, dx, dy, times, bounds=BOUNDS, notch_range=None, dragging=False):+ """The pointer is already against an edge, so the OS keeps reporting it there while the+ deltas keep coming, 10ms apart. Returns the step that crossed, or the last one."""+ result = None+ for index in range(times):+ result = machine.feed(x, y, dx, dy, bounds, 1.0 + index * 0.01, notch_range, dragging)+ if result.crossed:+ break+ return result+++def push_right(machine, times, dx=20, y=500.0, dragging=False):+ return drive(machine, RIGHT_X, y, dx, 0, times, dragging=dragging)+++class TickStepsTests(unittest.TestCase):+ def test_which_quarter_ticks_are_felt(self):+ from crossing import tick_fires++ quarters = (0.25, 0.5, 0.75)+ self.assertTrue(all(tick_fires("quarters", p) for p in quarters))+ self.assertEqual([tick_fires("halves", p) for p in quarters], [False, True, False])+ self.assertFalse(any(tick_fires("breakthrough", p) for p in quarters))+++class TouchingTests(unittest.TestCase):+ def test_touching_survives_pressure_draining_away_but_not_leaving(self):+ machine = engine()+ machine.feed(RIGHT_X, 500.0, 2, 0, BOUNDS, 1.0)+ # Half a second later with no outward travel: pressure has drained and released.+ step = machine.feed(RIGHT_X, 500.0, 0, 0, BOUNDS, 1.5)+ self.assertEqual(step.pressure, 0.0)+ self.assertIsNone(machine.pin)+ self.assertTrue(machine.touching)+ machine.feed(800.0, 500.0, -20, 0, BOUNDS, 1.6)+ self.assertFalse(machine.touching)+++class ResistanceTests(unittest.TestCase):+ def test_outward_travel_accumulates_and_holds_the_pointer(self):+ machine = engine()+ first = machine.feed(RIGHT_X, 500.0, 20, 0, BOUNDS, 1.0)+ self.assertFalse(first.hold, "the first touch passes so the pointer visibly arrives")+ second = machine.feed(RIGHT_X, 500.0, 20, 0, BOUNDS, 1.01)+ self.assertTrue(second.hold)+ self.assertEqual(second.pin, (RIGHT_X, 500.0))+ self.assertEqual(second.mac_edge, "right")+ self.assertGreater(second.pressure, first.pressure)+ self.assertFalse(second.crossed)++ def test_arriving_at_the_edge_counts_only_the_overshoot(self):+ machine = engine()+ machine.feed(1700.0, 500.0, 0, 0, BOUNDS, 1.0)+ step = machine.feed(RIGHT_X, 500.0, 40, 0, BOUNDS, 1.01)+ self.assertAlmostEqual(machine.pressure, 13.0, places=3)+ self.assertFalse(step.hold)++ def test_pressure_decays_over_time(self):+ machine = engine()+ push_right(machine, 4)+ full = machine.pressure+ self.assertGreater(full, 0)+ self.assertLess(machine.pressure_at(1.03 + DECAY_S / 2), full / 120)+ self.assertEqual(machine.pressure_at(1.03 + DECAY_S * 2), 0.0)+ step = machine.feed(RIGHT_X, 500.0, 0, 0, BOUNDS, 1.03 + DECAY_S * 2)+ self.assertEqual(machine.pressure, 0.0)+ self.assertFalse(step.hold)++ def test_a_slow_lean_never_builds(self):+ machine = engine()+ step = push_right(machine, 200, dx=1)+ self.assertFalse(step.crossed)+ self.assertFalse(step.hold)++ def test_inward_movement_subtracts(self):+ machine = engine()+ push_right(machine, 4)+ before = machine.pressure+ step = machine.feed(RIGHT_X, 500.0, -30, 0, BOUNDS, 1.04)+ self.assertLess(machine.pressure, before)+ self.assertTrue(step.hold)+ released = machine.feed(RIGHT_X, 500.0, -200, 0, BOUNDS, 1.05)+ self.assertEqual(machine.pressure, 0.0)+ self.assertFalse(released.hold)+ self.assertIsNone(machine.pin)++ def test_movement_along_the_edge_does_not_count(self):+ machine = engine()+ push_right(machine, 3)+ before = machine.pressure+ machine.feed(RIGHT_X, 600.0, 0, 40, BOUNDS, 1.03)+ self.assertLess(machine.pressure, before, "only decay applied")++ def test_quarter_ticks_fire_once_each(self):+ machine = engine()+ ticks = 0+ for index in range(12):+ step = machine.feed(RIGHT_X, 500.0, 12, 0, BOUNDS, 1.0 + index * 0.005)+ ticks += step.tick+ if step.crossed:+ break+ self.assertTrue(step.crossed)+ self.assertEqual(ticks, 3)++ def test_a_quarter_boundary_does_not_tick_twice_when_decay_dips_under_it(self):+ machine = engine()+ machine.feed(RIGHT_X, 500.0, 30, 0, BOUNDS, 1.0)+ step = machine.feed(RIGHT_X, 500.0, 2, 0, BOUNDS, 1.02)+ self.assertLess(machine.pressure, 30.0)+ self.assertFalse(step.tick)+ step = machine.feed(RIGHT_X, 500.0, 10, 0, BOUNDS, 1.03)+ self.assertGreater(machine.pressure, 30.0)+ self.assertFalse(step.tick)+++class BreakthroughTests(unittest.TestCase):+ def test_breakthrough_carries_the_windows_edge_and_offset(self):+ machine = engine()+ step = push_right(machine, 8, dx=30, y=558.0)+ self.assertTrue(step.crossed)+ self.assertEqual(step.edge, "left")+ self.assertEqual(step.mac_edge, "right")+ self.assertAlmostEqual(step.offset, 0.5, places=3)+ self.assertEqual(machine.pressure, 0.0)+ self.assertIsNone(machine.pin)++ def test_offset_is_measured_from_where_the_push_started(self):+ machine = engine()+ machine.feed(RIGHT_X, 0.0, 20, 0, BOUNDS, 1.0)+ machine.feed(RIGHT_X, 0.0, 20, 0, BOUNDS, 1.01)+ step = machine.feed(RIGHT_X, 900.0, 200, 0, BOUNDS, 1.02)+ self.assertTrue(step.crossed)+ self.assertEqual(step.offset, 0.0)++ def test_zero_resistance_switches_on_contact(self):+ machine = engine(resistance_px=0)+ step = machine.feed(RIGHT_X, 100.0, 1, 0, BOUNDS, 1.0)+ self.assertTrue(step.crossed)+ self.assertEqual(step.edge, "left")++ def test_decayed_pressure_cannot_cross_without_a_push(self):+ machine = engine(resistance_px=10)+ machine.feed(RIGHT_X, 100.0, 9, 0, BOUNDS, 1.0)+ step = machine.feed(RIGHT_X, 100.0, 0, 0, BOUNDS, 1.001)+ self.assertFalse(step.crossed)++ def test_each_edge_maps_to_its_opposite_with_the_right_offset(self):+ cases = {+ "left": ((0.0, 279.0), (-30, 0), "right", 0.25),+ "top": ((431.75, 0.0), (0, -30), "bottom", 0.25),+ "bottom": ((1295.25, 1116.0), (0, 30), "top", 0.75),+ }+ for edge, ((x, y), (dx, dy), windows_edge, offset) in cases.items():+ with self.subTest(edge=edge):+ machine = engine(edge=edge)+ step = drive(machine, x, y, dx, dy, 8)+ self.assertTrue(step.crossed)+ self.assertEqual(step.edge, windows_edge)+ self.assertAlmostEqual(step.offset, offset, places=3)++ def test_home_edge(self):+ machine = engine(edge="right")+ self.assertEqual(machine.home_edge(), "left")+ self.assertEqual(machine.home_edge("top"), "bottom")++ def test_shortcut_home_edge_follows_the_method_that_is_on(self):+ # `edge` stays "right" in config with the edge method off; it must not arm Windows' left.+ self.assertEqual(engine(methods=("shortcut", "notch"), edge="right").home_edge(), "bottom")+ self.assertEqual(engine(methods=("corner",), corner="top_left").home_edge(), "right")+ self.assertIsNone(engine(methods=("shortcut",)).home_edge())++ def test_arrival_point_sits_just_inside_the_edge(self):+ self.assertEqual(CrossingEngine.arrival_point("left", 0.5, BOUNDS), (2.0, 558.0))+ self.assertEqual(CrossingEngine.arrival_point("right", 0.0, BOUNDS), (1725.0, 0.0))+ self.assertEqual(CrossingEngine.arrival_point("top", 1.0, BOUNDS), (1727.0, 2.0))+ self.assertEqual(CrossingEngine.arrival_point("bottom", 0.5, BOUNDS), (863.5, 1114.0))+ self.assertEqual(CrossingEngine.arrival_point("left", 7.0, BOUNDS)[1], 1116.0)+++class GuardTests(unittest.TestCase):+ def test_no_crossing_while_a_button_is_held(self):+ machine = engine()+ step = push_right(machine, 10, dx=40, dragging=True)+ self.assertFalse(step.crossed)+ self.assertFalse(step.hold)+ self.assertEqual(machine.pressure, 0.0)++ def test_dragging_is_allowed_when_the_block_is_off(self):+ machine = engine(block_while_dragging=False)+ step = push_right(machine, 10, dx=40, dragging=True)+ self.assertTrue(step.crossed)++ def test_an_internal_edge_between_two_mac_displays_never_triggers(self):+ wide = (0, 0, 1728 + 1920, 1117)+ machine = engine()+ step = drive(machine, RIGHT_X, 500.0, 40, 0, 10, bounds=wide)+ self.assertFalse(step.crossed)+ self.assertFalse(step.hold)+ self.assertEqual(machine.pressure, 0.0)++ def test_other_edges_are_inert(self):+ machine = engine(edge="right")+ step = drive(machine, 0.0, 500.0, -40, 0, 10)+ self.assertFalse(step.crossed)+ self.assertEqual(machine.pressure, 0.0)++ def test_shortcut_only_is_not_armed(self):+ self.assertFalse(engine(methods=("shortcut",)).armed)+ self.assertTrue(engine(methods=("shortcut", "notch")).armed)++ def test_reset_clears_the_push(self):+ machine = engine()+ push_right(machine, 4)+ machine.reset()+ self.assertEqual(machine.pressure, 0.0)+ self.assertEqual(machine.pressure_at(5.0), 0.0)+++class CornerTests(unittest.TestCase):+ def test_diagonal_push_in_the_corner_box_crosses(self):+ machine = engine(methods=("corner",), corner="top_right")+ step = drive(machine, RIGHT_X, 0.0, 30, -30, 10)+ self.assertTrue(step.crossed)+ self.assertEqual(step.mac_edge, "right")+ self.assertEqual(step.edge, "left")+ self.assertEqual(step.offset, 0.0)+ self.assertEqual(step.via, "corner")++ def test_straight_push_in_the_corner_box_does_not_count(self):+ machine = engine(methods=("corner",), corner="top_right")+ step = drive(machine, RIGHT_X, 3.0, 40, 0, 10)+ self.assertFalse(step.crossed)+ self.assertEqual(machine.pressure, 0.0)++ def test_diagonal_push_outside_the_box_does_not_count(self):+ machine = engine(methods=("corner",), corner="top_right")+ step = drive(machine, RIGHT_X, 20.0, 30, -30, 10)+ self.assertFalse(step.crossed)+ self.assertEqual(machine.pressure, 0.0)++ def test_bottom_left_corner(self):+ machine = engine(methods=("corner",), corner="bottom_left")+ step = drive(machine, 0.0, 1116.0, -30, 30, 10)+ self.assertTrue(step.crossed)+ self.assertEqual(step.edge, "right")+ self.assertEqual(step.offset, 1.0)+ self.assertEqual(step.region, (0, 1109.0, 8.0, 8.0))+++class NotchTests(unittest.TestCase):+ NOTCH = (771.0, 956.0)++ def test_push_up_within_the_notch_crosses(self):+ machine = engine(methods=("notch",))+ step = drive(machine, 860.0, 0.0, 0, -30, 10, notch_range=self.NOTCH)+ self.assertTrue(step.crossed)+ self.assertEqual(step.mac_edge, "top")+ self.assertEqual(step.edge, "bottom")+ self.assertEqual(step.region, (771.0, 0, 185.0, 1))+ self.assertEqual(step.via, "notch")++ def test_push_up_beside_the_notch_does_nothing(self):+ machine = engine(methods=("notch",))+ step = drive(machine, 400.0, 0.0, 0, -30, 10, notch_range=self.NOTCH)+ self.assertFalse(step.crossed)+ self.assertEqual(machine.pressure, 0.0)++ def test_no_notch_means_no_target(self):+ machine = engine(methods=("notch",))+ step = drive(machine, 860.0, 0.0, 0, -30, 10)+ self.assertFalse(step.crossed)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_full_screen.py b/mac_app/tests/test_full_screen.pynew file mode 100644index 0000000..2691a5e--- /dev/null+++ b/mac_app/tests/test_full_screen.py@@ -0,0 +1,46 @@+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import kvm_bridge_app++# The 16" MacBook this was found on: a 1728x1117 display whose menu bar is the 33pt notch inset.+DISPLAYS = [(0.0, 0.0, 1728.0, 1117.0)]+++def window(pid, layer, x, y, width, height):+ return {+ "kCGWindowOwnerPID": pid,+ "kCGWindowLayer": layer,+ "kCGWindowBounds": {"X": x, "Y": y, "Width": width, "Height": height},+ }+++class CoversADisplayTest(unittest.TestCase):+ def test_a_zoomed_window_under_the_menu_bar_is_not_full_screen(self):+ self.assertFalse(+ kvm_bridge_app._covers_a_display([window(9, 0, 0, 33, 1728, 1084)], 9, DISPLAYS)+ )++ def test_the_desktop_window_is_not_full_screen(self):+ self.assertFalse(+ kvm_bridge_app._covers_a_display(+ [window(9, -2147483603, 0, 0, 1728, 1117)], 9, DISPLAYS+ )+ )++ def test_a_borderless_window_sized_to_the_display_is(self):+ self.assertTrue(+ kvm_bridge_app._covers_a_display([window(9, 0, 0, 0, 1728, 1117)], 9, DISPLAYS)+ )++ def test_another_process_does_not_count(self):+ self.assertFalse(+ kvm_bridge_app._covers_a_display([window(4, 0, 0, 0, 1728, 1117)], 9, DISPLAYS)+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_gestures.py b/mac_app/tests/test_gestures.pynew file mode 100644index 0000000..a75f3cf--- /dev/null+++ b/mac_app/tests/test_gestures.py@@ -0,0 +1,237 @@+import unittest++import protocol+from gestures import (+ DOCK_PHASE_ENDED,+ DOCK_SWIPE_HID_TYPE,+ GESTURE_TYPE,+ MAGNIFY_TYPE,+ MOTION_HORIZONTAL,+ MOTION_PINCH,+ MOTION_VERTICAL,+ SMART_MAGNIFY_TYPE,+ SWIPE_TYPE,+ NS_EVENT_PHASE_CANCELLED,+ NS_EVENT_PHASE_ENDED,+ DockSwipeClassifier,+ GestureTranslator,+ sign_table_for,+)+++class FakeNSEvent:+ """Fakes the surface GestureTranslator reads off a converted NSEvent:+ `.magnification`, `.deltaX`, `.deltaY`, `.phase`. Kept independent of+ AppKit/Quartz entirely, per the module's design."""++ def __init__(self, magnification=0.0, deltaX=0.0, deltaY=0.0, phase=0):+ self.magnification = magnification+ self.deltaX = deltaX+ self.deltaY = deltaY+ self.phase = phase+++class BrokenNSEvent:+ """Raises when any attribute is read, simulating an unreadable/converted+ event (e.g. an OS version whose NSEvent bridging doesn't support this+ accessor for this event subtype)."""++ def __getattr__(self, name):+ raise RuntimeError(f"synthetic failure reading {name!r}")+++def zoom_in_triple():+ return [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},+ protocol.scroll_msg(dy=1, dx=0, mode="line"),+ {"type": protocol.MSG_KEYUP, "data": {"key": "ctrl"}},+ ]+++def zoom_out_triple():+ return [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "ctrl"}},+ protocol.scroll_msg(dy=-1, dx=0, mode="line"),+ {"type": protocol.MSG_KEYUP, "data": {"key": "ctrl"}},+ ]+++class GestureTranslatorWantsTests(unittest.TestCase):+ def test_wants_all_four_reserved_gesture_types(self):+ translator = GestureTranslator()+ for event_type in (GESTURE_TYPE, MAGNIFY_TYPE, SWIPE_TYPE, SMART_MAGNIFY_TYPE):+ self.assertTrue(translator.wants(event_type))++ def test_does_not_want_ordinary_event_types(self):+ translator = GestureTranslator()+ for event_type in (1, 5, 10, 11, 12, 22, 28, 33):+ self.assertFalse(translator.wants(event_type))+++class MagnifyTranslationTests(unittest.TestCase):+ def setUp(self):+ self.translator = GestureTranslator()++ def test_single_event_crossing_the_step_emits_one_zoom_in_triple(self):+ messages = self.translator.translate(MAGNIFY_TYPE, FakeNSEvent(magnification=0.05))+ self.assertEqual(messages, zoom_in_triple())++ def test_negative_magnification_emits_zoom_out(self):+ messages = self.translator.translate(MAGNIFY_TYPE, FakeNSEvent(magnification=-0.05))+ self.assertEqual(messages, zoom_out_triple())++ def test_remainder_is_carried_across_events(self):+ # 0.03 alone is below the 0.05 step -- nothing fires yet.+ first = self.translator.translate(MAGNIFY_TYPE, FakeNSEvent(magnification=0.03))+ self.assertEqual(first, [])+ # 0.03 + 0.03 = 0.06 -- crosses the step once, 0.01 remainder carried.+ second = self.translator.translate(MAGNIFY_TYPE, FakeNSEvent(magnification=0.03))+ self.assertEqual(second, zoom_in_triple())+ self.assertAlmostEqual(self.translator._magnify_accum, 0.01)++ def test_large_single_event_emits_multiple_steps(self):+ messages = self.translator.translate(MAGNIFY_TYPE, FakeNSEvent(magnification=0.12))+ self.assertEqual(messages, zoom_in_triple() * 2)+ self.assertAlmostEqual(self.translator._magnify_accum, 0.02)++ def test_phase_ended_resets_accumulation_even_below_threshold(self):+ below_threshold = self.translator.translate(+ MAGNIFY_TYPE, FakeNSEvent(magnification=0.02, phase=NS_EVENT_PHASE_ENDED)+ )+ self.assertEqual(below_threshold, [])+ self.assertEqual(self.translator._magnify_accum, 0.0)+ # A fresh 0.04 alone must not fire: the prior 0.02 was dropped by the+ # phase-ended reset rather than still being carried.+ after_reset = self.translator.translate(MAGNIFY_TYPE, FakeNSEvent(magnification=0.04))+ self.assertEqual(after_reset, [])++ def test_phase_cancelled_also_resets_accumulation(self):+ self.translator.translate(MAGNIFY_TYPE, FakeNSEvent(magnification=0.02))+ self.translator.translate(+ MAGNIFY_TYPE, FakeNSEvent(magnification=0.0, phase=NS_EVENT_PHASE_CANCELLED)+ )+ self.assertEqual(self.translator._magnify_accum, 0.0)++ def test_unknown_phase_attribute_defaults_defensively_to_zero(self):+ # An event exposing no usable `.phase` at all (getattr default) must+ # not raise and must not reset accumulation.+ class NoPhaseEvent:+ def __init__(self, magnification):+ self.magnification = magnification++ messages = self.translator.translate(MAGNIFY_TYPE, NoPhaseEvent(0.02))+ self.assertEqual(messages, [])+ self.assertAlmostEqual(self.translator._magnify_accum, 0.02)+++class SwipeTranslationTests(unittest.TestCase):+ def setUp(self):+ self.translator = GestureTranslator()++ def test_positive_delta_x_is_back(self):+ messages = self.translator.translate(SWIPE_TYPE, FakeNSEvent(deltaX=1.0))+ self.assertEqual(messages, [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "left"}},+ {"type": protocol.MSG_KEYUP, "data": {"key": "left"}},+ {"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},+ ])++ def test_negative_delta_x_is_forward(self):+ messages = self.translator.translate(SWIPE_TYPE, FakeNSEvent(deltaX=-1.0))+ self.assertEqual(messages, [+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "alt"}},+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "right"}},+ {"type": protocol.MSG_KEYUP, "data": {"key": "right"}},+ {"type": protocol.MSG_KEYUP, "data": {"key": "alt"}},+ ])++ def test_vertical_only_swipe_is_ignored(self):+ messages = self.translator.translate(SWIPE_TYPE, FakeNSEvent(deltaX=0.0, deltaY=1.0))+ self.assertEqual(messages, [])+++class ReservedGestureTypeTests(unittest.TestCase):+ def test_gesture_and_smart_magnify_are_reserved_no_ops(self):+ translator = GestureTranslator()+ self.assertEqual(translator.translate(GESTURE_TYPE, FakeNSEvent()), [])+ self.assertEqual(translator.translate(SMART_MAGNIFY_TYPE, FakeNSEvent()), [])+++class FakeDockFields:+ def __init__(self, motion, progress, phase=DOCK_PHASE_ENDED, velocity=0.0, hid=DOCK_SWIPE_HID_TYPE):+ self.hid = hid+ self.motion = motion+ self.phase = phase+ self.progress = progress+ self.velocity = velocity+++class DockSwipeClassifierTests(unittest.TestCase):+ """Signs as measured on macOS 26.6.2 (docs/gestures-scope-06-09-2026.md)."""++ def setUp(self):+ self.classifier = DockSwipeClassifier(macos_major=26)++ def classify(self, **kwargs):+ messages = self.classifier.translate(FakeDockFields(**kwargs))+ return [m["data"]["name"] for m in messages]++ def test_vertical_negative_is_up_and_positive_is_down(self):+ self.assertEqual(self.classify(motion=MOTION_VERTICAL, progress=-0.32), ["swipe_up"])+ self.assertEqual(self.classify(motion=MOTION_VERTICAL, progress=0.33), ["swipe_down"])++ def test_horizontal_positive_is_left_and_negative_is_right(self):+ self.assertEqual(self.classify(motion=MOTION_HORIZONTAL, progress=0.9), ["swipe_left"])+ self.assertEqual(self.classify(motion=MOTION_HORIZONTAL, progress=-0.81), ["swipe_right"])++ def test_pinch_axis_negative_is_spread_and_positive_is_pinch(self):+ self.assertEqual(self.classify(motion=MOTION_PINCH, progress=-0.81), ["spread"])+ self.assertEqual(self.classify(motion=MOTION_PINCH, progress=1.08), ["pinch"])++ def test_only_the_ended_phase_fires(self):+ for phase in (1, 2, 8):+ self.assertEqual(self.classify(motion=MOTION_VERTICAL, progress=-0.4, phase=phase), [])++ def test_a_twitch_below_threshold_uses_velocity_or_nothing(self):+ self.assertEqual(self.classify(motion=MOTION_VERTICAL, progress=-0.05), [])+ self.assertEqual(+ self.classify(motion=MOTION_VERTICAL, progress=-0.05, velocity=2.0), ["swipe_down"]+ )++ def test_other_hid_types_and_unknown_axes_are_ignored(self):+ self.assertEqual(self.classify(motion=MOTION_VERTICAL, progress=-0.4, hid=6), [])+ self.assertEqual(self.classify(motion=9, progress=-0.4), [])++ def test_macos_27_flips_only_the_horizontal_axis(self):+ classifier = DockSwipeClassifier(macos_major=27)+ names = [m["data"]["name"] for m in classifier.translate(FakeDockFields(MOTION_HORIZONTAL, 0.9))]+ self.assertEqual(names, ["swipe_right"])+ names = [m["data"]["name"] for m in classifier.translate(FakeDockFields(MOTION_VERTICAL, -0.4))]+ self.assertEqual(names, ["swipe_up"])++ def test_unknown_version_takes_the_newest_table(self):+ self.assertIs(sign_table_for(99), sign_table_for(27))++ def test_broken_fields_never_raise(self):+ self.assertEqual(self.classifier.translate(BrokenNSEvent()), [])+ self.assertEqual(self.classify(motion=MOTION_VERTICAL, progress=-0.4), ["swipe_up"])+++class ErrorHandlingTests(unittest.TestCase):+ def test_broken_event_never_raises_and_returns_empty(self):+ translator = GestureTranslator()+ self.assertEqual(translator.translate(MAGNIFY_TYPE, BrokenNSEvent()), [])+ self.assertEqual(translator.translate(SWIPE_TYPE, BrokenNSEvent()), [])++ def test_broken_event_does_not_corrupt_later_accumulation(self):+ translator = GestureTranslator()+ translator.translate(MAGNIFY_TYPE, BrokenNSEvent())+ # A normal event afterwards must translate exactly as if the broken+ # one had never happened.+ messages = translator.translate(MAGNIFY_TYPE, FakeNSEvent(magnification=0.05))+ self.assertEqual(messages, zoom_in_triple())+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_handshake_deadline.py b/mac_app/tests/test_handshake_deadline.pynew file mode 100644index 0000000..8193a6e--- /dev/null+++ b/mac_app/tests/test_handshake_deadline.py@@ -0,0 +1,97 @@+import socket+import struct+import threading+import time+import unittest++import protocol+import receiver+from receiver import ReceiverServer, ServerState+++class HandshakeDeadlineTests(unittest.TestCase):+ """The handshake is bounded as a whole, and only handshakes count against+ the pending cap, so a stranger trickling bytes cannot hold a slot for+ long and the real peer never finds every slot taken by strangers."""++ def test_a_trickled_read_ends_at_the_deadline_not_per_byte(self):+ a, b = socket.socketpair()+ self.addCleanup(a.close)+ self.addCleanup(b.close)+ b.settimeout(1.0)+ deadline = time.monotonic() + 0.3++ def trickle():+ for _ in range(6):+ time.sleep(0.1)+ try:+ a.send(b"\0")+ except OSError:+ return++ threading.Thread(target=trickle, daemon=True).start()+ started = time.monotonic()+ with self.assertRaises(socket.timeout):+ protocol._recv_exact(b, 64, deadline)+ self.assertLess(time.monotonic() - started, 0.9)++ def test_strangers_free_their_slots_and_the_peer_gets_in(self):+ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))+ self.addCleanup(server.stop)+ with unittest_patch(receiver, "HELLO_TIMEOUT_SECONDS", 0.3):+ server.start(_config(port=0))+ port = _wait_for_port(server)+ strangers = []+ for _ in range(receiver.MAX_PENDING_CONNECTIONS):+ s = socket.create_connection(("127.0.0.1", port), timeout=2.0)+ s.sendall(b"\0")+ strangers.append(s)+ self.addCleanup(lambda: [s.close() for s in strangers])+ # Every slot is a stranger's, so a fifth connection is refused at once.+ refused = socket.create_connection(("127.0.0.1", port), timeout=2.0)+ self.addCleanup(refused.close)+ refused.settimeout(2.0)+ self.assertEqual(refused.recv(1), b"")+ # Their handshakes time out, and the next connection is served.+ time.sleep(0.6)+ served = socket.create_connection(("127.0.0.1", port), timeout=2.0)+ self.addCleanup(served.close)+ session = protocol.SecureSession("shared-token")+ served.sendall(session.preamble())+ served.settimeout(2.0)+ protocol.recv_preamble(served, session)+++class unittest_patch:+ def __init__(self, module, name, value):+ self.module, self.name, self.value = module, name, value++ def __enter__(self):+ self.old = getattr(self.module, self.name)+ setattr(self.module, self.name, self.value)++ def __exit__(self, *exc):+ setattr(self.module, self.name, self.old)+++def _config(port):+ class Config:+ auth_token = "shared-token"++ Config.port = port+ return Config()+++def _wait_for_port(server, timeout=2.0):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ listener = server._listener+ if listener is not None:+ return listener.getsockname()[1]+ time.sleep(0.01)+ raise AssertionError("the listener did not come up")+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_hello_limit.py b/mac_app/tests/test_hello_limit.pynew file mode 100644index 0000000..ec0bb6e--- /dev/null+++ b/mac_app/tests/test_hello_limit.py@@ -0,0 +1,47 @@+import socket+import struct+import threading+import unittest++import protocol+++class HelloFrameLimitTests(unittest.TestCase):+ """Before the first frame's tag is checked the peer has proved nothing, so+ the receiver reads that frame under HELLO_MAX_BYTES rather than the+ clipboard-sized MAX_FRAME_BYTES a stranger could otherwise make it buffer+ per connection."""++ def _pair(self):+ a, b = socket.socketpair()+ self.addCleanup(a.close)+ self.addCleanup(b.close)+ return a, b++ def test_an_oversized_first_frame_is_refused_before_it_is_read(self):+ sender, receiver = self._pair()+ session = protocol.SecureSession("t")+ sender.sendall(struct.pack(">I", protocol.HELLO_MAX_BYTES + 1))+ with self.assertRaises(protocol.ProtocolError):+ protocol.recv_msg(receiver, session, limit=protocol.HELLO_MAX_BYTES)++ def test_a_real_hello_fits_under_the_limit(self):+ sender, receiver = self._pair()+ theirs = protocol.SecureSession("t")+ mine = protocol.SecureSession("t")+ mine.accept_preamble(theirs.preamble())+ frame = theirs.seal(protocol.hello_msg(return_edge="left", resistance_px=120))+ self.assertLess(len(frame) - protocol.HEADER_SIZE, protocol.HELLO_MAX_BYTES)+ sender.sendall(frame)+ self.assertEqual(protocol.recv_msg(receiver, mine, limit=protocol.HELLO_MAX_BYTES)["type"], protocol.MSG_HELLO)++ def test_the_default_limit_is_still_the_frame_cap(self):+ sender, receiver = self._pair()+ session = protocol.SecureSession("t")+ sender.sendall(struct.pack(">I", protocol.MAX_FRAME_BYTES + 1))+ with self.assertRaises(protocol.ProtocolError):+ protocol.recv_msg(receiver, session)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_input_injector_mac.py b/mac_app/tests/test_input_injector_mac.pynew file mode 100644index 0000000..c596246--- /dev/null+++ b/mac_app/tests/test_input_injector_mac.py@@ -0,0 +1,87 @@+"""The planning half of the Mac injector: which key code a wire name lands on,+when a character is typed as text instead, where a move is clamped to, and+when a click counts as a double. No Quartz — everything here is arithmetic and+table lookup, which is exactly the part that can be wrong without crashing."""++import unittest++import input_injector_mac as injector+from return_edge import Rect+++class KeyPlanTests(unittest.TestCase):+ def plan(self, name, down=True, mods=None):+ return injector.plan_key_event(name, down, set() if mods is None else mods)++ def test_a_named_key_lands_on_its_key_code(self):+ self.assertEqual(self.plan("enter"), (0x24, None))+ self.assertEqual(self.plan("left"), (0x7B, None))++ def test_ctrl_on_the_pc_arrives_as_command(self):+ # The Windows capture has already made the swap, so the injector's job+ # is only to place "cmd" on the Command key -- but if that table ever+ # moved, every shortcut would land on the wrong modifier silently.+ self.assertEqual(self.plan("cmd"), (0x37, None))+ self.assertEqual(self.plan("ctrl"), (0x3B, None))+ self.assertEqual(self.plan("alt"), (0x3A, None))++ def test_a_letter_uses_the_key_its_layout_produces(self):+ self.assertEqual(self.plan("c"), (0x08, None))+ self.assertEqual(self.plan("a"), (0x00, None))++ def test_a_shortcut_keeps_the_key_code_rather_than_typing_text(self):+ # A Unicode event carries no key code, so Cmd+C sent as text copies+ # nothing at all.+ mods = {"cmd"}+ self.assertEqual(injector.plan_key_event("c", True, mods), (0x08, None))++ def test_a_character_off_the_table_is_typed_as_text(self):+ self.assertEqual(self.plan("é"), (0, "é"))++ def test_modifiers_are_tracked_in_both_directions(self):+ mods = set()+ injector.plan_key_event("shift", True, mods)+ self.assertEqual(mods, {"shift"})+ injector.plan_key_event("shift", False, mods)+ self.assertEqual(mods, set())++ def test_an_unknown_name_sends_nothing(self):+ self.assertIsNone(self.plan("nonsense_key"))+++class ClampTests(unittest.TestCase):+ SCREENS = [Rect(0, 0, 1000, 1000), Rect(1000, 200, 800, 600)]++ def test_a_point_on_a_display_is_left_alone(self):+ self.assertEqual(injector.clamp_to_displays(500, 500, self.SCREENS), (500, 500))++ def test_a_point_past_the_edge_comes_back_to_it(self):+ self.assertEqual(injector.clamp_to_displays(-40, 500, self.SCREENS), (0, 500))++ def test_a_point_in_the_gap_beside_a_shorter_display_lands_on_one(self):+ # Level with the second screen's dead space above it: the pointer must+ # end up on a real display, not hovering in the bounding box.+ x, y = injector.clamp_to_displays(1400, 50, self.SCREENS)+ self.assertTrue(any(r.x <= x <= r.right and r.y <= y <= r.bottom for r in self.SCREENS))+++class ClickStateTests(unittest.TestCase):+ def test_two_quick_clicks_in_one_place_are_a_double(self):+ last = {}+ self.assertEqual(injector.plan_click_state("left", 100, 100, 1.0, last), 1)+ self.assertEqual(injector.plan_click_state("left", 101, 100, 1.2, last), 2)+ self.assertEqual(injector.plan_click_state("left", 101, 100, 1.4, last), 3)++ def test_a_slow_second_click_starts_again(self):+ last = {}+ injector.plan_click_state("left", 100, 100, 1.0, last)+ self.assertEqual(injector.plan_click_state("left", 100, 100, 3.0, last), 1)++ def test_a_second_click_somewhere_else_starts_again(self):+ last = {}+ injector.plan_click_state("left", 100, 100, 1.0, last)+ self.assertEqual(injector.plan_click_state("left", 400, 100, 1.1, last), 1)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_link_state.py b/mac_app/tests/test_link_state.pynew file mode 100644index 0000000..31bed75--- /dev/null+++ b/mac_app/tests/test_link_state.py@@ -0,0 +1,103 @@+import sys+import unittest+from pathlib import Path+from types import SimpleNamespace++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++import link_state+import widgets+from bridge import AUTH_FAILED_STATUS, OLD_RECEIVER_STATUS, connection_error_message+from wake import NOT_WOKEN_STATUS+++def controller(status="Connected to 192.168.1.3:51820", connected=True, **overrides):+ values = dict(+ cfg=SimpleNamespace(host="192.168.1.3", port=51820, auth_token="t", pc_name="STUDIO-PC"),+ connection_status=status,+ connected=connected,+ waking=False,+ windows_locked=False,+ redirecting=False,+ crossing=SimpleNamespace(armed=True),+ crossing_paused=False,+ full_screen_app=None,+ receiving=False,+ )+ values.update(overrides)+ return SimpleNamespace(**values)+++class ErrnoError(OSError):+ pass+++class LinkStateTest(unittest.TestCase):+ def assertState(self, expected_key, tone, **kwargs):+ state = link_state.describe(controller(**kwargs))+ self.assertEqual((state.key, state.tone), (expected_key, tone))+ self.assertTrue(state.word and state.tag and state.detail)++ def test_the_pc_driving_this_mac_beats_every_other_state(self):+ # Whatever this Mac's own link is doing, the keyboard in the hand is+ # the PC's: nothing else the status could say is more true than that.+ self.assertState("receiving", "signal", receiving=True)+ self.assertState("receiving", "signal", receiving=True, redirecting=True)+ self.assertState("receiving", "signal", receiving=True, connected=False)++ def test_connected_states(self):+ self.assertState("mac", "ink")+ self.assertState("windows", "signal", redirecting=True)+ self.assertState("unlocking", "amber", status="Unlocking Windows…", windows_locked=True, redirecting=True)+ self.assertState("paused", "ink", crossing_paused=True)+ self.assertState("full_screen", "ink", full_screen_app="Final Cut Pro")+ self.assertState("waking", "amber", waking=True, connected=False)++ def test_tunnel_is_tagged(self):+ state = link_state.describe(controller(status=link_state.TUNNEL_STATUS))+ self.assertEqual((state.key, state.tag), ("mac", "Tunnel"))++ def test_every_failure_status_has_a_word(self):+ cases = {+ AUTH_FAILED_STATUS: "token",+ OLD_RECEIVER_STATUS: "version",+ "Windows receiver speaks Beamer protocol v3, this Mac v4 — update both apps": "version",+ "Windows rejected the connection: busy": "rejected",+ NOT_WOKEN_STATUS: "not_woken",+ connection_error_message(OSError(65, "No route")): "unreachable",+ connection_error_message(OSError(65, "Open /Applications/Beamer Tunnel.command")): "blocked",+ connection_error_message(OSError(61, "Refused")): "not_listening",+ connection_error_message(TimeoutError()): "unreachable",+ "Windows stopped responding": "stopped",+ "Connecting to 192.168.1.3:51820": "waiting",+ "Waiting to connect": "waiting",+ "Settings saved; reconnecting": "waiting",+ "Windows closed the connection": "dropped",+ "send failed: broken pipe": "dropped",+ "": "dropped",+ }+ for status, key in cases.items():+ with self.subTest(status=status):+ self.assertState(key, "amber" if key == "waiting" else "fault", status=status, connected=False)++ def test_unpaired(self):+ cfg = SimpleNamespace(host="192.168.1.3", port=51820, auth_token="", pc_name="")+ self.assertEqual(link_state.describe(controller(connected=False, cfg=cfg)).key, "unpaired")+++class RulerScaleTest(unittest.TestCase):+ def test_square_root_gives_the_useful_band_half_the_travel(self):+ low = widgets.scale_fraction(150, 50, 1000, "sqrt")+ high = widgets.scale_fraction(600, 50, 1000, "sqrt")+ self.assertGreaterEqual(high - low, 0.49)++ def test_round_trip_and_pinning(self):+ for value in (50, 300, 1000):+ fraction = widgets.scale_fraction(value, 50, 1000, "sqrt")+ self.assertAlmostEqual(widgets.scale_value(fraction, 50, 1000, "sqrt"), value)+ self.assertEqual(widgets.scale_fraction(2000, 50, 1000, "sqrt"), 1.0)+ self.assertEqual(widgets.scale_fraction(250, 0, 500), 0.5)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_notch_beam.py b/mac_app/tests/test_notch_beam.pynew file mode 100644index 0000000..a5dbc13--- /dev/null+++ b/mac_app/tests/test_notch_beam.py@@ -0,0 +1,92 @@+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++import notch_beam+++class TurnTest(unittest.TestCase):+ def test_travel_quickens_with_pressure_and_stays_in_range(self):+ self.assertEqual(notch_beam.turn_seconds(0.0), notch_beam.SLOW_TURN_S)+ self.assertAlmostEqual(notch_beam.turn_seconds(1.0), notch_beam.FAST_TURN_S)+ self.assertLess(notch_beam.turn_seconds(0.6), notch_beam.turn_seconds(0.3))+ self.assertAlmostEqual(notch_beam.turn_seconds(5.0), notch_beam.FAST_TURN_S)+++class LapFinishTest(unittest.TestCase):+ def test_leaves_by_the_far_end_of_a_lap(self):+ for position in (0.0, 0.4, 0.9, 1.3):+ for after in (0.6, 1.2, 2.0, 3.0):+ with self.subTest(position=position, after=after):+ travel = notch_beam.lap_finish(position, after)+ self.assertGreaterEqual(travel, notch_beam.LAP - position - 1e-9)+ laps = (position + travel) / notch_beam.LAP+ self.assertAlmostEqual(laps, round(laps), places=9)++ def test_longer_durations_run_more_laps(self):+ self.assertGreater(notch_beam.lap_finish(0.3, 3.0), notch_beam.lap_finish(0.3, 0.6))+++class CometTest(unittest.TestCase):+ def test_nothing_shows_at_either_end_of_a_lap(self):+ for position in (0.0, notch_beam.LAP):+ with self.subTest(position=position):+ self.assertTrue(all(end <= start for start, end in notch_beam.comet_segments(position)))++ def test_segments_nest_around_the_head_mid_lap(self):+ spans = notch_beam.comet_segments(notch_beam.LAP / 2.0)+ for (outer_start, outer_end), (inner_start, inner_end) in zip(spans, spans[1:]):+ self.assertLessEqual(outer_start, inner_start)+ self.assertGreaterEqual(outer_end, inner_end)+ head = notch_beam.LAP / 2.0 - notch_beam.COMET_HALF+ self.assertAlmostEqual((spans[-1][0] + spans[-1][1]) / 2.0, head)++ def test_travels_the_border_at_an_even_pace(self):+ # Equal steps in position move the head equal distances along the border, which the+ # angular sweep it replaced did not.+ heads = [sum(notch_beam.comet_segments(p)[-1]) / 2.0 for p in (0.4, 0.5, 0.6, 0.7)]+ steps = [round(b - a, 6) for a, b in zip(heads, heads[1:])]+ self.assertEqual(len(set(steps)), 1)+++class EdgeCometTest(unittest.TestCase):+ def test_edge_is_brightest_at_the_comet_and_all_lit_at_breakthrough(self):+ self.assertEqual(notch_beam.edge_comet_alpha(0.5, 0.5, 0.0), 1.0)+ self.assertEqual(notch_beam.edge_comet_alpha(0.0, 0.5, 0.0), notch_beam.EDGE_BASE)+ self.assertEqual(notch_beam.edge_comet_alpha(0.0, 0.5, 1.0), 1.0)+ self.assertLess(notch_beam.edge_traverse_seconds(0.8), notch_beam.edge_traverse_seconds(0.2))+++class PaletteTest(unittest.TestCase):+ def test_every_colour_choice_is_a_palette_a_gradient_can_use(self):+ import crossing+ import tokens++ self.assertEqual(crossing.GLOW_COLOURS, tuple(tokens.PALETTES))+ for name in crossing.GLOW_COLOURS:+ with self.subTest(colour=name):+ self.assertGreaterEqual(len(notch_beam.palette_colours(name)), 2)+ closed = notch_beam.palette_colours("colourful", closed=True)+ self.assertEqual(len(closed), len(tokens.PALETTES["colourful"]) + 1)+++class ApproachTest(unittest.TestCase):+ def test_rises_faster_than_it_fades_and_never_overshoots(self):+ up = notch_beam.approach(0.0, 1.0, 0.06)+ down = 1.0 - notch_beam.approach(1.0, 0.0, 0.06)+ self.assertGreater(up, down)+ self.assertEqual(notch_beam.approach(0.9, 1.0, 1.0), 1.0)+ self.assertEqual(notch_beam.approach(0.1, 0.0, 1.0), 0.0)++ def test_a_released_push_fades_out_within_half_a_second(self):+ strength = 1.0+ for _ in range(30):+ strength = notch_beam.approach(strength, 0.0, 1 / 60)+ self.assertEqual(strength, 0.0)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_notch_island.py b/mac_app/tests/test_notch_island.pynew file mode 100644index 0000000..dd84012--- /dev/null+++ b/mac_app/tests/test_notch_island.py@@ -0,0 +1,87 @@+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++import notch_island+++class BreakthroughPhaseTest(unittest.TestCase):+ def test_full_size_from_the_first_frame_even_after_a_flick(self):+ level, flash = notch_island.breakthrough_phase(0.0)+ self.assertEqual(level, 1.0)+ self.assertEqual(flash, 1.0)++ def test_flash_fades_while_the_island_holds_full_size(self):+ level, flash = notch_island.breakthrough_phase(notch_island.BREAKTHROUGH_GROW_S / 2)+ self.assertEqual(level, 1.0)+ self.assertAlmostEqual(flash, 0.5)+ level, flash = notch_island.breakthrough_phase(notch_island.BREAKTHROUGH_GROW_S + 0.01)+ self.assertEqual(level, 1.0)+ self.assertEqual(flash, 0.0)++ def test_the_sequence_lasts_long_enough_to_see(self):+ total = notch_island.BREAKTHROUGH_GROW_S + notch_island.BREAKTHROUGH_HOLD_S+ self.assertGreaterEqual(total, 0.5)+ self.assertIsNotNone(notch_island.breakthrough_phase(total - 0.001))+ self.assertIsNone(notch_island.breakthrough_phase(total))+ self.assertIsNone(notch_island.breakthrough_phase(-0.01))++ def test_plays_for_as_long_as_the_setting_says(self):+ self.assertEqual(notch_island.breakthrough_phase(2.5, 3.0)[0], 1.0)+ self.assertIsNone(notch_island.breakthrough_phase(3.0, 3.0))+++class HeldTest(unittest.TestCase):+ class Controller:+ class Crossing:+ touching = True++ crossing = Crossing()++ def setUp(self):+ self.controller = self.Controller()+ self.island = notch_island.NotchIsland(self.controller, logger=None)++ def test_repositioning_at_the_notch_keeps_the_last_pressure_showing(self):+ self.assertEqual(self.island._held(0.6, 10.0), 0.6)+ self.assertEqual(self.island._held(0.0, 10.5), 0.6)+ self.assertEqual(self.island._held(0.3, 10.8), 0.6)+ self.assertEqual(self.island._held(0.8, 10.85), 0.8)++ def test_a_slow_push_that_drains_between_events_keeps_showing(self):+ for frame in range(30):+ now = 10.0 + frame / 60+ level = 0.04 if frame % 3 == 0 else 0.0+ self.assertGreater(self.island._held(level, now), 0.0, f"dropped at frame {frame}")++ def test_lets_go_after_the_grace_period(self):+ self.island._held(0.6, 10.0)+ self.assertEqual(self.island._held(0.0, 10.0 + notch_island.GRACE_S + 0.01), 0.0)++ def test_leaving_the_notch_lets_go_at_once(self):+ self.island._held(0.6, 10.0)+ self.controller.crossing = None+ self.assertEqual(self.island._held(0.0, 10.1), 0.0)+++class TraceTest(unittest.TestCase):+ def test_finishes_off_the_end_of_the_rim_and_stays_there(self):+ end = 1.0 + notch_island.TRACE_LENGTH+ for after in (0.6, 1.2, 2.0, 3.0):+ with self.subTest(after=after):+ self.assertEqual(notch_island.trace_head(0.0, after), 0.0)+ self.assertAlmostEqual(notch_island.trace_head(0.8, after), end)+ self.assertAlmostEqual(notch_island.trace_head(0.95, after), end)++ def test_runs_whole_passes_that_fit_the_duration(self):+ # 3s makes three passes of 0.8s; half way through the first it is part way along the rim.+ middle = notch_island.trace_head(0.8 / 6, 3.0)+ self.assertGreater(middle, 0.0)+ self.assertLess(middle, 1.0 + notch_island.TRACE_LENGTH)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_notify_user_thread.py b/mac_app/tests/test_notify_user_thread.pynew file mode 100644index 0000000..992579f--- /dev/null+++ b/mac_app/tests/test_notify_user_thread.py@@ -0,0 +1,77 @@+import logging+import threading+import unittest+from unittest import mock++import AppKit+import rumps+from PyObjCTools import AppHelper++from kvm_bridge_app import TrayApp+++class _FakeTrayApp:+ """Stand-in with just what TrayApp.notify_user reads from self."""++ _notify_user_main = TrayApp._notify_user_main++ def __init__(self):+ self.logger = logging.getLogger("test-notify-user")+++class NotifyUserMainThreadTest(unittest.TestCase):+ def test_notify_user_marshals_appkit_calls_to_the_main_thread(self):+ """Every other controller callback in TrayApp (crossing_feedback,+ _arrangement, on_mac_learned) hops to the main thread with+ AppHelper.callAfter before touching AppKit. notify_user is wired+ straight to controller.on_user_alert, which bridge.py's _alert()+ invokes from the event-tap thread (see set_redirecting calls in+ _handle_trigger and the crossing-feed path) -- so it must do the+ same hop instead of calling AppKit.NSBeep()/rumps.notification+ directly on the calling thread.+ """+ calling_threads = []++ def record_and_beep():+ calling_threads.append(threading.current_thread())++ def record_and_notify(*_args, **_kwargs):+ calling_threads.append(threading.current_thread())++ call_after_uses = []+ real_call_after = AppHelper.callAfter++ def tracking_call_after(callback, *args, **kwargs):+ call_after_uses.append(callback)+ return real_call_after(callback, *args, **kwargs)++ fake_self = _FakeTrayApp()+ background = threading.Thread(+ target=TrayApp.notify_user,+ args=(fake_self, "Beamer", "background alert"),+ )++ with mock.patch.object(AppKit, "NSBeep", side_effect=record_and_beep), mock.patch.object(+ rumps, "notification", side_effect=record_and_notify+ ), mock.patch.object(AppHelper, "callAfter", side_effect=tracking_call_after):+ background.start()+ background.join(timeout=2)++ self.assertFalse(background.is_alive(), "notify_user did not return")+ self.assertTrue(+ call_after_uses,+ "notify_user must hop to the main thread via AppHelper.callAfter, "+ "like _crossing_feedback_main/_persist_mac/apply_arrangement, before "+ "touching AppKit",+ )+ self.assertEqual(+ calling_threads,+ [],+ "AppKit.NSBeep/rumps.notification ran synchronously on the calling "+ "(background) thread instead of being marshalled onto the main thread "+ "via AppHelper.callAfter",+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_pages.py b/mac_app/tests/test_pages.pynew file mode 100644index 0000000..2095eb6--- /dev/null+++ b/mac_app/tests/test_pages.py@@ -0,0 +1,40 @@+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import pages+++class PagesTest(unittest.TestCase):+ def test_order(self):+ self.assertEqual(+ pages.KEYS, ("overview", "crossing", "design", "keyboard", "pairing", "connection", "permissions")+ )++ def test_first_open(self):+ self.assertEqual(pages.opening_page(None, True, True), "overview")+ self.assertEqual(pages.opening_page(None, False, True), "permissions")+ self.assertEqual(pages.opening_page(None, True, False), "permissions")++ def test_later_opens_keep_the_last_page(self):+ self.assertEqual(pages.opening_page("keyboard", False, False), "keyboard")+ self.assertEqual(pages.opening_page("overview", False, True), "overview")++ def test_dots(self):+ self.assertEqual(pages.dots(True, True, "mac"), {})+ self.assertEqual(pages.dots(True, False, "mac"), {"permissions": "amber"})+ self.assertEqual(pages.dots(True, True, "token"), {"pairing": "fault"})+ self.assertEqual(pages.dots(False, False, "token"), {"permissions": "amber", "pairing": "fault"})+ self.assertEqual(pages.dots(True, True, "unreachable"), {})++ def test_step_stops_at_the_ends(self):+ self.assertEqual(pages.step("overview", -1), "overview")+ self.assertEqual(pages.step("overview", 1), "crossing")+ self.assertEqual(pages.step("permissions", 1), "permissions")+ self.assertEqual(pages.step("pairing", -1), "keyboard")+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_pairing.py b/mac_app/tests/test_pairing.pynew file mode 100644index 0000000..1c06a48--- /dev/null+++ b/mac_app/tests/test_pairing.py@@ -0,0 +1,126 @@+import filecmp+import logging+import os+import socket+import time+import unittest++import pairing+from pairing import Announcer, Discovery, PairingClient, PairingHost, beacon_msg, encode+++_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))+_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))+++def quiet_logger():+ logger = logging.getLogger("pairing-tests")+ logger.handlers = [logging.NullHandler()]+ logger.propagate = False+ return logger+++def free_udp_port():+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ sock.bind(("127.0.0.1", 0))+ port = sock.getsockname()[1]+ sock.close()+ return port+++def wait_until(predicate, timeout=5.0):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return True+ time.sleep(0.02)+ return False+++class ParityTests(unittest.TestCase):+ def test_both_copies_are_identical(self):+ mac = os.path.join(_REPO_ROOT, "mac_app", "pairing.py")+ win = os.path.join(_REPO_ROOT, "win_app", "pairing.py")+ self.assertTrue(filecmp.cmp(mac, win, shallow=False), "mac_app/pairing.py and win_app/pairing.py differ")+++class ExchangeTests(unittest.TestCase):+ def test_wire_never_carries_the_code_or_the_token(self):+ host = PairingHost()+ code = host.begin()+ client = PairingClient(host.pair_id, code, "Test Mac")+ request = client.request()+ reply = host.handle(request)+ token = client.accept(reply)+ self.assertEqual(token, host.paired[0])+ wire = encode(beacon_msg("PC", 51820, host.pair_id)) + encode(request) + encode(reply)+ self.assertNotIn(code.encode(), wire)+ self.assertNotIn(token.encode(), wire)++ def test_wrong_code_fails_closed_for_the_client_too(self):+ host = PairingHost()+ code = host.begin()+ wrong = str((int(code) + 7) % 10**6).zfill(6)+ client = PairingClient(host.pair_id, wrong, "Test Mac")+ with self.assertRaises(pairing.PairingError) as caught:+ client.accept(host.handle(client.request()))+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ self.assertFalse(host.active)+++class LoopbackTests(unittest.TestCase):+ """The two socket loops against each other on 127.0.0.1, with the broadcast address+ replaced so nothing leaves this machine."""++ def setUp(self):+ self.pc_port = free_udp_port()+ self.mac_port = free_udp_port()+ self.paired = []+ self.announcer = Announcer(+ lambda: 51820,+ lambda token, name, address: self.paired.append((token, name, address)),+ logger=quiet_logger(),+ bind_port=self.pc_port,+ announce_to=("127.0.0.1", self.mac_port),+ name="TEST-PC",+ )+ self.discovery = Discovery(logger=quiet_logger(), bind_port=self.mac_port)+ self.discovery.start()+ self.announcer.start()+ self.addCleanup(self.announcer.stop)+ self.addCleanup(self.discovery.stop)++ def test_discovers_pairs_and_stores_one_token_each_side(self):+ self.assertTrue(wait_until(lambda: self.discovery.pcs()))+ pc = self.discovery.pcs()[0]+ self.assertEqual((pc["name"], pc["port"], pc["address"], pc["reply_port"]), ("TEST-PC", 51820, "127.0.0.1", self.pc_port))+ self.assertIsNone(pc["pair_id"])+ code = self.announcer.begin_pairing()+ self.assertTrue(wait_until(lambda: self.discovery.pcs()[0]["pair_id"] is not None))+ pc = self.discovery.pcs()[0]+ token = self.discovery.pair(pc, code, name="Loopback Mac")+ self.assertTrue(wait_until(lambda: self.paired))+ self.assertEqual(self.paired[0], (token, "Loopback Mac", "127.0.0.1"))+ self.assertIsNone(self.announcer.code)++ def test_wrong_code_over_the_wire_is_refused(self):+ self.assertTrue(wait_until(lambda: self.discovery.pcs()))+ code = self.announcer.begin_pairing()+ self.assertTrue(wait_until(lambda: self.discovery.pcs()[0]["pair_id"] is not None))+ wrong = str((int(code) + 1) % 10**6).zfill(6)+ with self.assertRaises(pairing.PairingError) as caught:+ self.discovery.pair(self.discovery.pcs()[0], wrong)+ self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)+ self.assertEqual(self.paired, [])+ self.assertIsNone(self.announcer.code)++ def test_pairing_without_a_code_on_the_pc_says_so(self):+ self.assertTrue(wait_until(lambda: self.discovery.pcs()))+ pc = dict(self.discovery.pcs()[0], pair_id="00000000")+ with self.assertRaises(pairing.PairingError) as caught:+ self.discovery.pair(pc, "123456")+ self.assertEqual(str(caught.exception), pairing.ERROR_NOT_PAIRING)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_pairing_announcer_error.py b/mac_app/tests/test_pairing_announcer_error.pynew file mode 100644index 0000000..7916a36--- /dev/null+++ b/mac_app/tests/test_pairing_announcer_error.py@@ -0,0 +1,101 @@+import logging+import socket+import unittest++from pairing import Announcer, Discovery+++def quiet_logger():+ logger = logging.getLogger("test-announcer-error")+ logger.addHandler(logging.NullHandler())+ logger.propagate = False+ return logger+++class _ScriptedSocket:+ """Stands in for the bound UDP socket: `recvfrom` raises each entry of+ `script` in turn, then the announcer is asked to stop."""++ def __init__(self, script, stop):+ self.script = list(script)+ self.stop = stop+ self.calls = 0+ self.sent = 0+ self.closed = False++ def sendto(self, data, addr):+ self.sent += 1+ return len(data)++ def recvfrom(self, bufsize):+ self.calls += 1+ if self.script:+ raise self.script.pop(0)+ self.stop.set()+ raise socket.timeout()++ def close(self):+ self.closed = True+++def run_announcer(script):+ announcer = Announcer(+ lambda: 24820,+ lambda token, name, address: None,+ logger=quiet_logger(),+ bind_port=0,+ announce_to=("127.0.0.1", 1),+ name="TEST-PC",+ )+ sock = _ScriptedSocket(script, announcer._stop)+ announcer._run.__globals__["_udp_socket"] = lambda bind_port: sock+ try:+ announcer._run()+ finally:+ del announcer._run.__globals__["_udp_socket"]+ return announcer, sock+++class AnnouncerSocketErrorTests(unittest.TestCase):+ def test_a_datagram_reset_is_survived(self):+ # Windows reports an ICMP port-unreachable for a datagram this socket+ # sent as ConnectionResetError on the next receive. The socket is fine.+ announcer, sock = run_announcer(+ [socket.timeout(), ConnectionResetError(10054, "An existing connection was forcibly closed")]+ )+ self.assertIsNone(announcer.error)+ self.assertGreaterEqual(sock.calls, 3, "the loop stopped at the reset instead of carrying on")+ self.assertTrue(sock.closed)++ def test_any_other_socket_error_is_reported_not_swallowed(self):+ announcer, sock = run_announcer([socket.timeout(), OSError(10022, "An invalid argument was supplied")])+ self.assertFalse(announcer._stop.is_set())+ self.assertIsNotNone(announcer.error, "a dead announcer must not look like an idle one")+ self.assertIn("invalid argument", announcer.error)+ self.assertTrue(sock.closed)+++class DiscoverySocketErrorTests(unittest.TestCase):+ def _run(self, script):+ discovery = Discovery(logger=quiet_logger(), bind_port=0)+ sock = _ScriptedSocket(script, discovery._stop)+ discovery._run.__globals__["_udp_socket"] = lambda bind_port: sock+ try:+ discovery._run()+ finally:+ del discovery._run.__globals__["_udp_socket"]+ return discovery, sock++ def test_a_datagram_reset_is_survived(self):+ discovery, sock = self._run([ConnectionResetError(54, "Connection reset by peer")])+ self.assertIsNone(discovery.error)+ self.assertGreaterEqual(sock.calls, 2)++ def test_any_other_socket_error_is_reported(self):+ discovery, sock = self._run([OSError(9, "Bad file descriptor")])+ self.assertIsNotNone(discovery.error)+ self.assertIn("Bad file descriptor", discovery.error)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_previews.py b/mac_app/tests/test_previews.pynew file mode 100644index 0000000..984501e--- /dev/null+++ b/mac_app/tests/test_previews.py@@ -0,0 +1,25 @@+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++import previews+++class PreviewFrameTest(unittest.TestCase):+ def test_a_push_builds_goes_through_plays_and_rests(self):+ self.assertEqual(previews.preview_frame(0.0, 1.2), (0.0, "push"))+ self.assertLess(previews.preview_frame(0.5, 1.2)[0], previews.preview_frame(1.5, 1.2)[0])+ self.assertEqual(previews.preview_frame(previews.PUSH_S + 0.1, 1.2), (0.0, "after"))+ self.assertEqual(previews.preview_frame(previews.PUSH_S + 1.3, 1.2), (0.0, "rest"))++ def test_loops_and_plays_for_as_long_as_keep_animating_says(self):+ cycle = previews.PUSH_S + 3.0 + previews.REST_S+ self.assertEqual(previews.preview_frame(previews.PUSH_S + 2.5, 3.0)[1], "after")+ self.assertEqual(previews.preview_frame(cycle + 0.1, 3.0)[1], "push")+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_protocol_parity.py b/mac_app/tests/test_protocol_parity.pynew file mode 100644index 0000000..18e74fe--- /dev/null+++ b/mac_app/tests/test_protocol_parity.py@@ -0,0 +1,118 @@+"""Protocol parity test: mac_app/protocol.py and win_app/protocol.py are two+independent copies of the same wire protocol (see the module docstring in+either file) and must never be allowed to silently drift apart -- a v2+sender talking to a stale v1-ish receiver (or vice versa) is exactly the+failure mode protocol.py's own version handshake exists to catch, and this+test exists to catch the same class of problem one step earlier, at review+time, before either app ships.++Both files are loaded via importlib file-path loading rather than a normal+`import protocol`, so this test has no dependency on sys.path/PYTHONPATH+ordering -- it always compares these two specific files on disk, not+whichever `protocol` module happens to be importable first. Dependency-free:+only the standard library (importlib, inspect, unittest).+"""++import importlib.util+import inspect+import os+import types+import unittest+++_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))+_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))+MAC_PROTOCOL_PATH = os.path.join(_REPO_ROOT, "mac_app", "protocol.py")+WIN_PROTOCOL_PATH = os.path.join(_REPO_ROOT, "win_app", "protocol.py")+++def _load_module_from_path(module_name, path):+ spec = importlib.util.spec_from_file_location(module_name, path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _public_attribute_names(module):+ """Names protocol.py itself defines and exposes: everything not starting+ with "_", excluding re-exported stdlib modules (json, socket, struct)+ that show up in dir() purely because they were imported at module level+ -- those aren't part of the protocol surface being compared here."""+ return {+ name+ for name in dir(module)+ if not name.startswith("_") and not isinstance(getattr(module, name), types.ModuleType)+ }+++class ProtocolParityTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ if not os.path.isfile(MAC_PROTOCOL_PATH):+ raise unittest.SkipTest(f"mac_app/protocol.py not found at {MAC_PROTOCOL_PATH}")+ if not os.path.isfile(WIN_PROTOCOL_PATH):+ raise unittest.SkipTest(f"win_app/protocol.py not found at {WIN_PROTOCOL_PATH}")+ # Distinct module names, so this never collides with (or is+ # satisfied by) an already-imported `protocol` module from either+ # app's own test suite / sys.path setup.+ cls.mac = _load_module_from_path("_protocol_parity_mac", MAC_PROTOCOL_PATH)+ cls.win = _load_module_from_path("_protocol_parity_win", WIN_PROTOCOL_PATH)++ def test_public_names_match(self):+ self.assertEqual(+ _public_attribute_names(self.mac),+ _public_attribute_names(self.win),+ "mac_app/protocol.py and win_app/protocol.py expose different public names",+ )++ def test_constants_have_identical_values(self):+ for name in sorted(_public_attribute_names(self.mac)):+ mac_value = getattr(self.mac, name)+ if not isinstance(mac_value, (int, float, str, bytes, bool)):+ continue+ win_value = getattr(self.win, name)+ with self.subTest(name=name):+ self.assertEqual(+ mac_value,+ win_value,+ f"constant {name!r} differs between mac_app and win_app protocol.py",+ )++ def test_function_signatures_match(self):+ for name in sorted(_public_attribute_names(self.mac)):+ mac_value = getattr(self.mac, name)+ if not inspect.isfunction(mac_value):+ continue+ win_value = getattr(self.win, name)+ with self.subTest(name=name):+ self.assertTrue(+ inspect.isfunction(win_value),+ f"{name!r} is a function in mac_app/protocol.py but not in win_app/protocol.py",+ )+ self.assertEqual(+ inspect.signature(mac_value),+ inspect.signature(win_value),+ f"signature of {name!r} differs between mac_app and win_app protocol.py",+ )++ def test_classes_match(self):+ for name in sorted(_public_attribute_names(self.mac)):+ mac_value = getattr(self.mac, name)+ if not inspect.isclass(mac_value):+ continue+ win_value = getattr(self.win, name)+ with self.subTest(name=name):+ self.assertTrue(+ inspect.isclass(win_value),+ f"{name!r} is a class in mac_app/protocol.py but not in win_app/protocol.py",+ )+ self.assertEqual(mac_value.__name__, win_value.__name__)+ self.assertEqual(+ [base.__name__ for base in mac_value.__mro__],+ [base.__name__ for base in win_value.__mro__],+ f"MRO of {name!r} differs between mac_app and win_app protocol.py",+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_settings_store.py b/mac_app/tests/test_settings_store.pynew file mode 100644index 0000000..8123fa2--- /dev/null+++ b/mac_app/tests/test_settings_store.py@@ -0,0 +1,232 @@+import json+import os+import tempfile+import unittest+from pathlib import Path+from unittest import mock++import config as config_module+import protocol+import settings_store+from settings_store import SettingsError, SettingsStore, config_to_raw, migrate_legacy_config+++class SettingsStoreTests(unittest.TestCase):+ def valid_raw(self):+ return {+ "host": "192.0.2.10",+ "port": 24820,+ "auth_token": "synthetic-token",+ "trigger_key": "alt_r",+ "double_tap_ms": 300,+ "key_map": {"cmd": "ctrl", "cmd_r": "ctrl"},+ "reconnect_interval_s": 2.0,+ }++ def test_save_is_private_and_round_trips_shared_schema(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "config.json"+ store = SettingsStore(path)+ saved = store.save(self.valid_raw())+ loaded = store.load()+ self.assertEqual(saved, loaded)+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)+ raw = json.loads(path.read_text(encoding="utf-8"))+ self.assertEqual(raw["trigger_key"], "alt_r")++ def test_both_directions_default_on_and_each_switch_round_trips(self):+ with tempfile.TemporaryDirectory() as directory:+ store = SettingsStore(Path(directory) / "config.json")+ loaded = store.save(self.valid_raw())+ self.assertTrue(loaded.send_to_windows)+ self.assertTrue(loaded.allow_windows_to_drive)+ raw = config_to_raw(loaded)+ raw["send_to_windows"] = False+ loaded = store.save(raw)+ self.assertFalse(loaded.send_to_windows)+ self.assertTrue(loaded.allow_windows_to_drive)+ self.assertFalse(store.load().send_to_windows)++ def test_legacy_positional_key_map_is_replaced_by_the_semantic_default(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "config.json"+ raw = self.valid_raw()+ raw["key_map"] = {+ "alt": "alt", "alt_r": "alt",+ "ctrl": "ctrl", "ctrl_r": "ctrl",+ "cmd": "cmd", "cmd_r": "cmd",+ }+ loaded = SettingsStore(path).save(raw)+ self.assertEqual(loaded.key_map["cmd"], "ctrl")+ self.assertEqual(loaded.key_map["ctrl"], "cmd")++ def test_hand_edited_key_map_survives(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "config.json"+ raw = self.valid_raw()+ raw["key_map"] = {"cmd": "cmd", "ctrl": "alt"}+ loaded = SettingsStore(path).save(raw)+ self.assertEqual(loaded.key_map["cmd"], "cmd")+ self.assertEqual(loaded.key_map["ctrl"], "alt")++ def test_rejects_placeholder_token(self):+ with tempfile.TemporaryDirectory() as directory:+ raw = self.valid_raw()+ raw["auth_token"] = "CHANGE_ME"+ with self.assertRaises(SettingsError):+ SettingsStore(Path(directory) / "config.json").save(raw)++ def test_rejects_unknown_trigger(self):+ with tempfile.TemporaryDirectory() as directory:+ raw = self.valid_raw()+ raw["trigger_key"] = "not_a_key"+ with self.assertRaises(SettingsError):+ SettingsStore(Path(directory) / "config.json").save(raw)++ def test_config_without_crossing_keys_loads_the_defaults(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "config.json"+ path.write_text(json.dumps(self.valid_raw()), encoding="utf-8")+ loaded = SettingsStore(path).load()+ self.assertEqual(loaded.trigger_style, "double_tap")+ self.assertEqual(loaded.crossing, config_module.DEFAULT_CROSSING)+ self.assertIsNot(loaded.crossing, config_module.DEFAULT_CROSSING)++ def test_partial_crossing_object_keeps_the_other_defaults(self):+ with tempfile.TemporaryDirectory() as directory:+ raw = self.valid_raw()+ raw["crossing"] = {"edge": "left", "resistance_px": 40}+ raw["trigger_style"] = "hold"+ loaded = SettingsStore(Path(directory) / "config.json").save(raw)+ self.assertEqual(loaded.crossing["edge"], "left")+ self.assertEqual(loaded.crossing["resistance_px"], 40)+ self.assertEqual(loaded.crossing["methods"], ["shortcut", "edge"])+ self.assertTrue(loaded.crossing["haptics"])+ self.assertEqual(loaded.trigger_style, "hold")++ def test_rejects_bad_crossing_values_by_field(self):+ cases = [+ ({"methods": ["edge", "telepathy"]}, "crossing.methods"),+ ({"edge": "sideways"}, "crossing.edge"),+ ({"corner": "middle"}, "crossing.corner"),+ ({"resistance_px": 501}, "crossing.resistance_px"),+ ({"resistance_px": -1}, "crossing.resistance_px"),+ ({"glow": "yes"}, "crossing.glow"),+ ({"notch_style": "sparkle"}, "crossing.notch_style"),+ ({"notch_after_ms": 50}, "crossing.notch_after_ms"),+ ({"notch_after_ms": 1.5}, "crossing.notch_after_ms"),+ ({"haptic_feel": "thunderous"}, "crossing.haptic_feel"),+ ({"haptic_steps": "thirds"}, "crossing.haptic_steps"),+ ({"glow_style": "sparkle"}, "crossing.glow_style"),+ ({"glow_colour": "tartan"}, "crossing.glow_colour"),+ ]+ with tempfile.TemporaryDirectory() as directory:+ for crossing, field in cases:+ with self.subTest(field=field):+ raw = self.valid_raw()+ raw["crossing"] = crossing+ with self.assertRaises(SettingsError) as caught:+ SettingsStore(Path(directory) / "config.json").save(raw)+ self.assertIn(field, str(caught.exception))++ def test_rejects_unknown_trigger_style(self):+ with tempfile.TemporaryDirectory() as directory:+ raw = self.valid_raw()+ raw["trigger_style"] = "triple_tap"+ with self.assertRaises(SettingsError):+ SettingsStore(Path(directory) / "config.json").save(raw)++ def test_key_map_style_names_round_trip(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "config.json"+ raw = self.valid_raw()+ raw["key_map"] = "positional"+ loaded = SettingsStore(path).save(raw)+ self.assertEqual(loaded.key_map, config_module.LEGACY_POSITIONAL_KEY_MAP)+ self.assertEqual(config_to_raw(loaded)["key_map"], "positional")+ self.assertEqual(json.loads(path.read_text(encoding="utf-8"))["key_map"], "positional")+ raw["key_map"] = "semantic"+ self.assertEqual(SettingsStore(path).save(raw).key_map, config_module.DEFAULT_KEY_MAP)+ raw["key_map"] = "chaotic"+ with self.assertRaises(SettingsError):+ SettingsStore(path).save(raw)++ def test_migrate_legacy_config_copies_without_touching_the_old_file(self):+ with tempfile.TemporaryDirectory() as directory:+ legacy_dir = Path(directory) / "OpenKB"+ legacy_dir.mkdir()+ legacy_path = legacy_dir / "config.json"+ legacy_path.write_text(json.dumps(self.valid_raw()), encoding="utf-8")+ os.chmod(legacy_path, 0o600)+ new_dir = Path(directory) / "Beamer"+ new_path = new_dir / "config.json"+ with mock.patch.multiple(+ settings_store,+ LEGACY_APP_SUPPORT_DIRECTORY=legacy_dir,+ LEGACY_SETTINGS_PATH=legacy_path,+ APP_SUPPORT_DIRECTORY=new_dir,+ DEFAULT_SETTINGS_PATH=new_path,+ ):+ self.assertTrue(migrate_legacy_config())+ self.assertTrue(legacy_path.exists())+ self.assertEqual(+ json.loads(new_path.read_text(encoding="utf-8")),+ json.loads(legacy_path.read_text(encoding="utf-8")),+ )+ self.assertEqual(new_path.stat().st_mode & 0o777, 0o600)+ # A second run must not overwrite the now-existing new config.+ new_path.write_text(json.dumps({"changed": True}), encoding="utf-8")+ self.assertFalse(migrate_legacy_config())+ self.assertEqual(json.loads(new_path.read_text(encoding="utf-8")), {"changed": True})++ def test_migrate_legacy_config_is_a_noop_with_no_legacy_file(self):+ with tempfile.TemporaryDirectory() as directory:+ legacy_dir = Path(directory) / "OpenKB"+ new_dir = Path(directory) / "Beamer"+ with mock.patch.multiple(+ settings_store,+ LEGACY_APP_SUPPORT_DIRECTORY=legacy_dir,+ LEGACY_SETTINGS_PATH=legacy_dir / "config.json",+ APP_SUPPORT_DIRECTORY=new_dir,+ DEFAULT_SETTINGS_PATH=new_dir / "config.json",+ ):+ self.assertFalse(migrate_legacy_config())+ self.assertFalse(new_dir.exists())+++if __name__ == "__main__":+ unittest.main()+++class LegacyPortTests(unittest.TestCase):+ def raw(self, port):+ return {+ "host": "192.0.2.10",+ "port": port,+ "auth_token": "synthetic-token",+ "trigger_key": "alt_r",+ "double_tap_ms": 300,+ "key_map": {"cmd": "ctrl", "cmd_r": "ctrl"},+ "reconnect_interval_s": 2.0,+ }++ def test_the_old_default_port_is_moved_and_the_move_is_written_down(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "config.json"+ store = SettingsStore(path)+ store.save(self.raw(protocol.LEGACY_DEFAULT_PORT))+ self.assertEqual(store.load().port, protocol.DEFAULT_PORT)+ on_disk = json.loads(path.read_text(encoding="utf-8"))+ self.assertEqual(on_disk["port"], protocol.DEFAULT_PORT)++ def test_a_port_someone_chose_is_left_alone(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "config.json"+ store = SettingsStore(path)+ store.save(self.raw(9000))+ self.assertEqual(store.load().port, 9000)++ def test_both_ports_are_below_the_range_the_system_hands_out(self):+ self.assertLess(protocol.DEFAULT_PORT, 49152)+ self.assertLess(protocol.PAIRING_PORT, 49152)+diff --git a/mac_app/tests/test_shared_copies.py b/mac_app/tests/test_shared_copies.pynew file mode 100644index 0000000..70d23eb--- /dev/null+++ b/mac_app/tests/test_shared_copies.py@@ -0,0 +1,61 @@+"""The files both apps share are kept byte-identical, not merely similar.++`protocol.py`, `receiver.py` and `return_edge.py` each exist once in mac_app+and once in win_app because neither app can import across the other's+directory -- both are packaged as self-contained bundles. Everything+platform-shaped in them is injected at construction instead, so there is no+legitimate reason for the two copies to differ by a byte, and a diff is+always drift. This test is byte-for-byte on purpose: a structural comparison+would pass while the two sides' return-edge arithmetic or status wording+quietly diverged.++This file is itself one of those copies, and checks itself.+"""++import hashlib+import os+import unittest++_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))+_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))++SHARED_MODULES = ("protocol.py", "receiver.py", "return_edge.py")+SHARED_TESTS = ("test_shared_copies.py",)+++def _digest(path):+ with open(path, "rb") as handle:+ return hashlib.sha256(handle.read()).hexdigest()+++class SharedCopyTests(unittest.TestCase):+ def _assert_identical(self, mac_path, win_path, name):+ if not os.path.isfile(mac_path) or not os.path.isfile(win_path):+ self.skipTest(f"{name} is missing from one side; nothing to compare")+ self.assertEqual(+ _digest(mac_path),+ _digest(win_path),+ f"mac_app and win_app copies of {name} have drifted apart",+ )++ def test_shared_modules_are_identical(self):+ for name in SHARED_MODULES:+ with self.subTest(module=name):+ self._assert_identical(+ os.path.join(_REPO_ROOT, "mac_app", name),+ os.path.join(_REPO_ROOT, "win_app", name),+ name,+ )++ def test_shared_tests_are_identical(self):+ for name in SHARED_TESTS:+ with self.subTest(module=name):+ self._assert_identical(+ os.path.join(_REPO_ROOT, "mac_app", "tests", name),+ os.path.join(_REPO_ROOT, "win_app", "tests", name),+ name,+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_update_config_redirecting.py b/mac_app/tests/test_update_config_redirecting.pynew file mode 100644index 0000000..39b8280--- /dev/null+++ b/mac_app/tests/test_update_config_redirecting.py@@ -0,0 +1,40 @@+import unittest++from bridge import KVMController+from test_bridge import FakeClock, FakeQuartz, FakeSocket, crossing_config, quiet_logger+++class UpdateConfigWhileRedirectingTests(unittest.TestCase):+ """mac-sender-1: update_config sets self.redirecting = False directly+ instead of going through set_redirecting(False), so it skips+ _set_cursor_follows_mouse(True) when settings are applied mid-redirect."""++ def setUp(self):+ FakeQuartz.reset_cursor_spies()+ self.controller = KVMController(+ crossing_config(),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=FakeClock(),+ desktop_bounds=lambda: (0.0, 0.0, 1728.0, 1117.0),+ )+ self.controller.sock = FakeSocket()++ def test_update_config_while_redirecting_restores_cursor_association(self):+ self.controller.set_redirecting(True)+ self.assertTrue(self.controller.redirecting)+ FakeQuartz.reset_cursor_spies()++ self.controller.update_config(crossing_config())++ self.assertFalse(self.controller.redirecting)+ self.assertIn(+ True,+ FakeQuartz.associate_calls,+ "update_config must re-enable CGAssociateMouseAndMouseCursorPosition "+ "when it forces redirecting False mid-redirect, same as set_redirecting(False) does",+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/tests/test_wake.py b/mac_app/tests/test_wake.pynew file mode 100644index 0000000..8c4de2d--- /dev/null+++ b/mac_app/tests/test_wake.py@@ -0,0 +1,164 @@+import logging+import threading+import unittest++import config+import wake+from test_bridge import FakeQuartz, quiet_logger+from wake import NOT_WOKEN_STATUS, WAKING_STATUS, WakingController, mac_from_arp_output, magic_packet, parse_mac+++WINDOWS_ARP = """+Interface: 192.168.1.5 --- 0x10+ Internet Address Physical Address Type+ 192.168.1.1 a8-5e-45-1c-22-f0 dynamic+ 192.168.1.3 02-1a-2b-3c-0d-4e dynamic+ 192.168.1.30 00-11-22-33-44-55 dynamic+ 224.0.0.22 01-00-5e-00-00-16 static+"""++MAC_ARP = "? (192.168.1.3) at 2:1a:2b:3c:d:4e on en0 ifscope [ethernet]\n"+++class FakeClock:+ def __init__(self, value=1000.0):+ self.value = value++ def __call__(self):+ return self.value+++def make_config(mac="02:1A:2B:3C:0D:4E"):+ return config.Config(+ host="192.0.2.10",+ port=51820,+ auth_token="synthetic-token",+ reconnect_interval_s=0.1,+ mac_address=mac,+ )+++class ParsingTests(unittest.TestCase):+ def test_parse_mac_normalises_both_platforms(self):+ self.assertEqual(parse_mac("02-1a-2b-3c-0d-4e"), "02:1A:2B:3C:0D:4E")+ self.assertEqual(parse_mac("2:1a:2b:3c:d:4e"), "02:1A:2B:3C:0D:4E")+ self.assertEqual(parse_mac(" 02:1A:2B:3C:0D:4E "), "02:1A:2B:3C:0D:4E")+ self.assertIsNone(parse_mac("02:1a:2b:3c:0d"))+ self.assertIsNone(parse_mac("not a mac"))+ self.assertIsNone(parse_mac(""))+ self.assertIsNone(parse_mac(None))++ def test_windows_arp_line_yields_the_right_host(self):+ self.assertEqual(mac_from_arp_output(WINDOWS_ARP, "192.168.1.3"), "02:1A:2B:3C:0D:4E")+ # 192.168.1.3 is a prefix of 192.168.1.30; the match must be the whole address.+ self.assertEqual(mac_from_arp_output(WINDOWS_ARP, "192.168.1.30"), "00:11:22:33:44:55")+ self.assertIsNone(mac_from_arp_output(WINDOWS_ARP, "192.168.1.9"))++ def test_macos_arp_line_is_padded(self):+ self.assertEqual(mac_from_arp_output(MAC_ARP, "192.168.1.3"), "02:1A:2B:3C:0D:4E")+ self.assertIsNone(mac_from_arp_output("? (192.168.1.3) at (incomplete) on en0 ifscope [ethernet]\n", "192.168.1.3"))+++class MagicPacketTests(unittest.TestCase):+ def test_layout_is_six_ff_then_the_address_sixteen_times(self):+ packet = magic_packet("02-1a-2b-3c-0d-4e")+ address = bytes.fromhex("021a2b3c0d4e")+ self.assertEqual(len(packet), 102)+ self.assertEqual(packet[:6], b"\xff" * 6)+ self.assertEqual(packet[6:], address * 16)+ for index in range(16):+ self.assertEqual(packet[6 + index * 6 : 12 + index * 6], address)++ def test_rejects_a_bad_address(self):+ with self.assertRaises(ValueError):+ magic_packet("nope")+++class WakingControllerTests(unittest.TestCase):+ def setUp(self):+ self.clock = FakeClock()+ self.sent = []+ self.learned = []++ def socket_factory(address, timeout):+ raise OSError("synthetic: host asleep")++ self.controller = WakingController(+ make_config(),+ wake_sender=lambda mac, host: self.sent.append((mac, host)),+ mac_lookup=lambda host: "AA:BB:CC:DD:EE:FF",+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ socket_factory=socket_factory,+ )+ self.controller.WAKE_POLL_SECONDS = 0.01+ self.alerts = []+ self.controller.on_user_alert = lambda title, message: self.alerts.append(message)+ self.controller.on_mac_learned = self.learned.append++ def _wait_for_wake_thread(self):+ for thread in threading.enumerate():+ if thread.name == "wake":+ thread.join(timeout=5)++ def test_switch_while_unreachable_sends_the_packet_and_shows_waking(self):+ # The wake thread must see the packet as sent before the window is checked.+ self.controller.stop_event.set()+ self.assertFalse(self.controller.set_redirecting(True))+ self._wait_for_wake_thread()+ self.assertEqual(self.sent, [("02:1A:2B:3C:0D:4E", "192.0.2.10")])+ self.assertFalse(self.controller.redirecting)+ self.assertTrue(self.controller.outbound.empty())+ self.assertIn(WAKING_STATUS, self.alerts)++ def test_gives_up_after_the_window_with_nothing_queued(self):+ self.assertTrue(self.controller.wake())+ self.assertTrue(self.controller.waking)+ self.assertEqual(self.controller.connection_status, WAKING_STATUS)+ self.assertFalse(self.controller.wake(), "a second wake while one is in flight is refused")+ self.clock.value += wake.WAKE_WINDOW_SECONDS+ self._wait_for_wake_thread()+ self.assertFalse(self.controller.waking)+ self.assertEqual(self.controller.connection_status, NOT_WOKEN_STATUS)+ self.assertEqual(self.alerts[-1], NOT_WOKEN_STATUS)+ self.assertEqual(len(self.sent), 1)+ self.assertTrue(self.controller.outbound.empty())++ def test_status_written_underneath_a_wake_shows_through_afterwards(self):+ self.controller.wake()+ self.controller.connection_status = "Windows is unreachable from this Mac"+ self.assertEqual(self.controller.connection_status, WAKING_STATUS)+ self.clock.value += wake.WAKE_WINDOW_SECONDS+ self._wait_for_wake_thread()+ self.assertEqual(self.controller.connection_status, NOT_WOKEN_STATUS)++ def test_without_a_hardware_address_the_switch_fails_as_before(self):+ controller = WakingController(+ make_config(mac=""),+ wake_sender=lambda mac, host: self.sent.append((mac, host)),+ logger=quiet_logger(),+ quartz=FakeQuartz,+ clock=self.clock,+ )+ controller.on_user_alert = lambda title, message: self.alerts.append(message)+ self.assertFalse(controller.set_redirecting(True))+ self.assertEqual(self.sent, [])+ self.assertFalse(controller.can_wake)+ self.assertTrue(self.alerts[0].startswith("Cannot switch"))++ def test_successful_connection_learns_and_reports_a_new_address(self):+ from test_bridge import FakeSocket, seed_receiver_reply+ import protocol++ sock = FakeSocket()+ seed_receiver_reply(sock, protocol.welcome_msg())+ self.controller.socket_factory = lambda address, timeout: sock+ self.assertTrue(self.controller._connect_once())+ self.assertEqual(self.learned, ["AA:BB:CC:DD:EE:FF"])+ self.assertEqual(self.controller.cfg.mac_address, "AA:BB:CC:DD:EE:FF")+ self.assertFalse(self.controller.can_wake)+++if __name__ == "__main__":+ unittest.main()diff --git a/mac_app/wake.py b/mac_app/wake.pynew file mode 100644index 0000000..2e61190--- /dev/null+++ b/mac_app/wake.py@@ -0,0 +1,185 @@+"""Wake-on-LAN for the PC, and the controller that sends it when a switch finds the PC asleep.++The hardware address is never typed. It is read from this Mac's ARP table whenever a+connection succeeds -- the Mac has just exchanged packets with the PC, so the entry is fresh --+and stored with the rest of that PC's settings.+"""++from __future__ import annotations++import re+import socket+import subprocess+import threading++from bridge import KVMController++WOL_PORT = 9+# Sleep answers in a few seconds; hibernate and a cold boot take most of a minute. Past this+# the PC is reported as not woken rather than the switch waiting forever.+WAKE_WINDOW_SECONDS = 60.0+WAKING_STATUS = "Waking Windows…"+NOT_WOKEN_STATUS = "Windows did not wake"++# Six groups of one or two hex digits: Windows pads and joins with "-", macOS leaves a leading+# zero off and joins with ":".+_MAC_PATTERN = re.compile(r"(?<![0-9A-Fa-f])([0-9A-Fa-f]{1,2}(?:[:-][0-9A-Fa-f]{1,2}){5})(?![0-9A-Fa-f])")+++def parse_mac(text: str):+ """The address as six upper-case, zero-padded pairs joined with ":", or None."""+ match = _MAC_PATTERN.fullmatch(text.strip()) if isinstance(text, str) else None+ if match is None:+ return None+ return ":".join(part.zfill(2).upper() for part in re.split(r"[:-]", match.group(1)))+++def mac_from_arp_output(output: str, ip: str):+ """The hardware address `arp` printed for `ip`, from either platform's layout:++ Windows 192.168.1.3 02-1a-2b-3c-0d-4e dynamic+ macOS ? (192.168.1.3) at 2:1a:2b:3c:d:4e on en0 ifscope [ethernet]+ """+ ip_pattern = re.compile(r"(?<![\d.])" + re.escape(ip) + r"(?![\d.])")+ for line in output.splitlines():+ if not ip_pattern.search(line):+ continue+ match = _MAC_PATTERN.search(line)+ if match is not None:+ return parse_mac(match.group(1))+ return None+++def lookup_mac(host: str):+ """The hardware address this Mac's ARP table holds for `host`, or None. Only useful right+ after talking to the host, which is the only time it is called."""+ try:+ ip = socket.gethostbyname(host)+ completed = subprocess.run(["arp", "-n", ip], capture_output=True, text=True, timeout=3.0, check=False)+ except (OSError, subprocess.SubprocessError):+ return None+ return mac_from_arp_output(completed.stdout, ip)+++def magic_packet(mac: str) -> bytes:+ address = parse_mac(mac)+ if address is None:+ raise ValueError(f"not a hardware address: {mac!r}")+ return b"\xff" * 6 + bytes.fromhex(address.replace(":", "")) * 16+++def send_magic_packet(mac: str, host: str = None) -> None:+ """Broadcast the packet, and also send it straight at the host's last address, which is+ what gets through on a network that filters broadcasts."""+ packet = magic_packet(mac)+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)+ sock.sendto(packet, ("255.255.255.255", WOL_PORT))+ if host:+ try:+ sock.sendto(packet, (host, WOL_PORT))+ except OSError:+ pass+ finally:+ sock.close()+++class WakingController(KVMController):+ """KVMController plus wake-on-LAN. A switch attempted while the PC is unreachable sends the+ magic packet and shows WAKING_STATUS until the connection worker gets through, the same+ shape as the receiver's "Unlocking Windows…" -- and, like that path, nothing is queued: the+ switch is refused, and the person switches again once the PC is up. Completing it for them+ a 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."""++ WAKE_POLL_SECONDS = 0.5++ def __init__(self, cfg, wake_sender=send_magic_packet, mac_lookup=lookup_mac, **kwargs):+ self._waking = False+ self._wake_lock = threading.Lock()+ self.wake_sender = wake_sender+ self.mac_lookup = mac_lookup+ self.on_mac_learned = None+ super().__init__(cfg, **kwargs)++ @property+ def connection_status(self):+ return WAKING_STATUS if self._waking else self._connection_status++ @connection_status.setter+ def connection_status(self, value):+ self._connection_status = value++ @property+ def waking(self) -> bool:+ return self._waking++ @property+ def can_wake(self) -> bool:+ return bool(self.cfg.mac_address) and not self.connected++ def set_redirecting(self, value, edge=None, offset=None):+ if value and not self.redirecting and not self.connected and self.cfg.mac_address:+ self.wake()+ return False+ return super().set_redirecting(value, edge, offset)++ def wake(self) -> bool:+ """Sends the packet and starts waiting, unless a wake is already in flight."""+ with self._wake_lock:+ if self._waking or self.connected:+ return False+ self._waking = True+ threading.Thread(target=self._wake_worker, name="wake", daemon=True).start()+ return True++ def _wake_worker(self):+ started = self.clock()+ try:+ self.wake_sender(self.cfg.mac_address, self.cfg.host)+ except (OSError, ValueError) as exc:+ self.logger.warning("wake-on-LAN packet not sent: %s", exc)+ self._waking = False+ self.connection_status = NOT_WOKEN_STATUS+ self._alert("Beamer", "Could not send the wake-up packet")+ return+ self.logger.info("sent wake-on-LAN to %s", self.cfg.host)+ self._alert("Beamer", WAKING_STATUS)+ while not self.stop_event.wait(self.WAKE_POLL_SECONDS):+ if self.connected:+ self._waking = False+ self.logger.info("Windows woke and connected")+ self._alert("Beamer", "Windows is awake — switch again to send input")+ return+ if self.clock() - started >= WAKE_WINDOW_SECONDS:+ break+ self._waking = False+ self.connection_status = NOT_WOKEN_STATUS+ self.logger.warning("Windows did not answer within %.0fs of the wake-on-LAN packet", WAKE_WINDOW_SECONDS)+ self._alert("Beamer", NOT_WOKEN_STATUS)++ def _connect_once(self):+ connected = super()._connect_once()+ if connected:+ self._learn_mac()+ return connected++ def _learn_mac(self):+ try:+ mac = self.mac_lookup(self.cfg.host)+ except Exception:+ self.logger.exception("hardware address lookup failed")+ return+ if not mac or mac == self.cfg.mac_address:+ return+ self.cfg.mac_address = mac+ self.logger.info("learned the PC's hardware address from the ARP table")+ callback = self.on_mac_learned+ if callback is not None:+ try:+ callback(mac)+ except Exception:+ self.logger.exception("on_mac_learned callback failed")diff --git a/mac_app/widgets.py b/mac_app/widgets.pynew file mode 100644index 0000000..a62c368--- /dev/null+++ b/mac_app/widgets.py@@ -0,0 +1,1368 @@+"""Vernier's components for the macOS control window, in AppKit.++Everything lays out with Auto Layout constraints and never a frame, so a longer string, a fallback+face or a different display scale reflows instead of clipping. The custom controls draw with the+palette from theme.py; anything clickable takes keyboard focus, answers Space and shows a signal+focus ring.+"""++from __future__ import annotations++import math++import AppKit+import Quartz+import objc++import theme+from key_codes import KEY_NAME_TO_CODE, SPECIAL_KEY_NAMES+++def _autolayout(view):+ view.setTranslatesAutoresizingMaskIntoConstraints_(False)+ return view+++def stack(vertical: bool = True, spacing: float = 10.0):+ view = _autolayout(AppKit.NSStackView.alloc().init())+ view.setOrientation_(+ AppKit.NSUserInterfaceLayoutOrientationVertical if vertical else AppKit.NSUserInterfaceLayoutOrientationHorizontal+ )+ view.setSpacing_(spacing)+ view.setAlignment_(AppKit.NSLayoutAttributeLeading if vertical else AppKit.NSLayoutAttributeCenterY)+ view.setDistribution_(AppKit.NSStackViewDistributionFill)+ return view+++def add(parent, view, full_width: bool = True):+ """Adds an arranged subview, stretched to the stack's width. NSStackView aligns its children+ but does not stretch them, and a control that stops short of the module edge is the giveaway."""+ parent.addArrangedSubview_(view)+ if full_width:+ view.widthAnchor().constraintEqualToAnchor_(parent.widthAnchor()).setActive_(True)+ return view+++def pin(view, container, insets=(0, 0, 0, 0)):+ top, leading, bottom, trailing = insets+ AppKit.NSLayoutConstraint.activateConstraints_([+ view.topAnchor().constraintEqualToAnchor_constant_(container.topAnchor(), top),+ view.leadingAnchor().constraintEqualToAnchor_constant_(container.leadingAnchor(), leading),+ container.bottomAnchor().constraintEqualToAnchor_constant_(view.bottomAnchor(), bottom),+ container.trailingAnchor().constraintEqualToAnchor_constant_(view.trailingAnchor(), trailing),+ ])+ return view+++def size(view, width=None, height=None):+ if width is not None:+ view.widthAnchor().constraintEqualToConstant_(width).setActive_(True)+ if height is not None:+ view.heightAnchor().constraintEqualToConstant_(height).setActive_(True)+ return view+++def hug(view, priority=AppKit.NSLayoutPriorityRequired, horizontal=True):+ orientation = AppKit.NSLayoutConstraintOrientationHorizontal if horizontal else AppKit.NSLayoutConstraintOrientationVertical+ view.setContentHuggingPriority_forOrientation_(priority, orientation)+ if isinstance(view, AppKit.NSStackView):+ view.setHuggingPriority_forOrientation_(priority, orientation)+ return view+++def squeeze(view, priority=AppKit.NSLayoutPriorityDefaultLow):+ view.setContentCompressionResistancePriority_forOrientation_(priority, AppKit.NSLayoutConstraintOrientationHorizontal)+ return view+++def box(fill=None, stroke=None, radius=0.0, cls=None):+ view = _autolayout((cls or AppKit.NSView).alloc().init())+ view.setWantsLayer_(True)+ paint(view, fill, stroke, radius)+ return view+++def paint(view, fill=None, stroke=None, radius=None):+ layer = view.layer()+ layer.setBackgroundColor_(theme.colour(fill).CGColor() if fill else None)+ layer.setBorderColor_(theme.colour(stroke).CGColor() if stroke else None)+ layer.setBorderWidth_(1 if stroke else 0)+ if radius is not None:+ layer.setCornerRadius_(radius)+++def attributed(text, size, weight=400, ink="ink", mono=False, tracking=0.0, upper=False, align=None, wrap=False):+ paragraph = AppKit.NSMutableParagraphStyle.alloc().init()+ paragraph.setAlignment_(AppKit.NSTextAlignmentNatural if align is None else align)+ paragraph.setLineBreakMode_(AppKit.NSLineBreakByWordWrapping if wrap else AppKit.NSLineBreakByTruncatingTail)+ return AppKit.NSAttributedString.alloc().initWithString_attributes_(+ text.upper() if upper else text,+ {+ AppKit.NSFontAttributeName: theme.mono_font(size, weight) if mono else theme.font(size, weight),+ AppKit.NSForegroundColorAttributeName: theme.colour(ink),+ AppKit.NSKernAttributeName: size * tracking,+ AppKit.NSParagraphStyleAttributeName: paragraph,+ },+ )+++class Label:+ """A label that keeps its style, so the text, colour or size can change without restating it.+ NSFont has no letter spacing, so tracking is NSKern in the attributed string."""++ def __init__(self, text="", size=None, weight=400, ink="ink", wrap=False, mono=False, tracking=0.0,+ upper=False, align=None):+ self.text = text+ self.size = size or theme.TYPE["body"]+ self.weight = weight+ self.ink = ink+ self.wrap = wrap+ self.mono = mono+ self.tracking = tracking+ self.upper = upper+ self.align = align+ maker = AppKit.NSTextField.wrappingLabelWithString_ if wrap else AppKit.NSTextField.labelWithString_+ self.view = _autolayout(maker(""))+ if wrap:+ squeeze(self.view)+ self._render()++ def set(self, text=None, ink=None, size=None, weight=None):+ changed = False+ for name, value in (("text", text), ("ink", ink), ("size", size), ("weight", weight)):+ if value is not None and value != getattr(self, name):+ setattr(self, name, value)+ changed = True+ if changed:+ self._render()++ def _render(self):+ self.view.setAttributedStringValue_(attributed(+ self.text, self.size, self.weight, self.ink, self.mono, self.tracking, self.upper, self.align, self.wrap+ ))+++def label(text, size=None, weight=400, ink="ink", wrap=False, mono=False):+ return Label(text, size, weight, ink, wrap, mono).view+++def eyebrow(text, ink="ink_3"):+ return Label(text, theme.TYPE["eyebrow"], 700, ink, tracking=theme.TRACKING["eyebrow"], upper=True).view+++def note(text="", ink="ink_2", align=None):+ label = Label(text, theme.TYPE["note"], ink=ink, wrap=True, align=align)+ label.view.widthAnchor().constraintLessThanOrEqualToConstant_(theme.READING_WIDTH).setActive_(True)+ return label+++def hairline():+ rule = box("rule")+ rule.heightAnchor().constraintEqualToConstant_(1).setActive_(True)+ return rule+++class Module:+ """One panel in a rack: padded body stack on `panel`. The module is only as tall as its content+ wants, but a rack may stretch it to match the tallest neighbour in its row."""++ def __init__(self, spacing=12.0):+ self.view = box("panel")+ self.body = stack(spacing=spacing)+ self.view.addSubview_(self.body)+ vertical, horizontal = theme.MODULE_PADDING+ AppKit.NSLayoutConstraint.activateConstraints_([+ self.body.topAnchor().constraintEqualToAnchor_constant_(self.view.topAnchor(), vertical),+ self.body.leadingAnchor().constraintEqualToAnchor_constant_(self.view.leadingAnchor(), horizontal),+ self.view.trailingAnchor().constraintEqualToAnchor_constant_(self.body.trailingAnchor(), horizontal),+ self.view.bottomAnchor().constraintGreaterThanOrEqualToAnchor_constant_(self.body.bottomAnchor(), horizontal),+ ])+ collapse = self.view.heightAnchor().constraintEqualToConstant_(0)+ collapse.setPriority_(AppKit.NSLayoutPriorityFittingSizeCompression)+ collapse.setActive_(True)++ def add(self, view, full_width=True):+ return add(self.body, view, full_width)+++class Rack:+ """Modules on the `rule` colour with RACK_GAP between them, so the gaps read as hairlines, or+ on nothing with a wider `gap`. `arrange` takes rows of (module index, column span) against a+ column count, and swaps the whole constraint set, so the window can reflow between its wide+ and narrow grids."""++ def __init__(self, modules, bottom_rule=True, gap=None, fill="rule"):+ self.view = box(fill)+ self.gap = theme.RACK_GAP if gap is None else gap+ self.bottom_rule = bottom_rule+ self.modules = modules+ for module in modules:+ self.view.addSubview_(module.view)+ self.constraints = []+ self.layout = None++ def arrange(self, rows, columns):+ key = (tuple(tuple(row) for row in rows), columns)+ if key == self.layout:+ return+ self.layout = key+ AppKit.NSLayoutConstraint.deactivateConstraints_(self.constraints)+ gap = self.gap+ constraints = []+ above = None+ for row in rows:+ first = previous = None+ for position, (index, span) in enumerate(row):+ view = self.modules[index].view+ top = above.bottomAnchor() if above is not None else self.view.topAnchor()+ constraints.append(view.topAnchor().constraintEqualToAnchor_constant_(top, gap if above is not None else 0))+ leading = previous.trailingAnchor() if previous is not None else self.view.leadingAnchor()+ constraints.append(view.leadingAnchor().constraintEqualToAnchor_constant_(leading, gap if previous is not None else 0))+ if position == len(row) - 1:+ constraints.append(self.view.trailingAnchor().constraintEqualToAnchor_(view.trailingAnchor()))+ else:+ constant = gap * ((span - 1) - span * (columns - 1) / columns)+ constraints.append(view.widthAnchor().constraintEqualToAnchor_multiplier_constant_(+ self.view.widthAnchor(), span / columns, constant+ ))+ if first is None:+ first = view+ else:+ constraints.append(view.heightAnchor().constraintEqualToAnchor_(first.heightAnchor()))+ previous = view+ above = first+ constraints.append(self.view.bottomAnchor().constraintEqualToAnchor_constant_(+ above.bottomAnchor(), gap if self.bottom_rule else 0+ ))+ AppKit.NSLayoutConstraint.activateConstraints_(constraints)+ self.constraints = constraints+++def grid(views, columns):+ """Views in equal columns on the `rule` colour, 1pt apart inside a 1pt border, each row as tall+ as its tallest view."""+ frame = box("rule")+ rows = stack(spacing=1)+ for start in range(0, len(views), columns):+ row = stack(vertical=False, spacing=1)+ row.setDistribution_(AppKit.NSStackViewDistributionFillEqually)+ row.setAlignment_(AppKit.NSLayoutAttributeTop)+ for view in views[start:start + columns]:+ row.addArrangedSubview_(view)+ view.heightAnchor().constraintEqualToAnchor_(row.heightAnchor()).setActive_(True)+ add(rows, row)+ frame.addSubview_(rows)+ pin(rows, frame, (1, 1, 1, 1))+ return frame+++def flipped(cls):+ return _autolayout(cls.alloc().init())+++class Figure:+ """A mono figure and its unit as one attributed string. Two labels in a baseline-aligned stack+ let the smaller unit drift below the figure once the row is squeezed; one string cannot."""++ def __init__(self, text, size, unit="", unit_size=None, tracking=0.0, ink="ink"):+ self.text, self.size, self.unit, self.ink, self.tracking = text, size, unit, ink, tracking+ self.unit_size = unit_size or theme.TYPE["small"]+ self.view = squeeze(_autolayout(AppKit.NSTextField.labelWithString_("")))+ self._render()++ def set(self, text=None, ink=None, size=None):+ changed = False+ for name, value in (("text", text), ("ink", ink), ("size", size)):+ if value is not None and value != getattr(self, name):+ setattr(self, name, value)+ changed = True+ if changed:+ self._render()++ def _render(self):+ string = AppKit.NSMutableAttributedString.alloc().initWithAttributedString_(+ attributed(self.text, self.size, ink=self.ink, mono=True, tracking=self.tracking)+ )+ if self.unit:+ string.appendAttributedString_(attributed(" " + self.unit, self.unit_size, ink="ink_3", mono=True))+ self.view.setAttributedStringValue_(string)+++class Readout:+ """A figure in a `ground` well: the tracked key, the value in mono with its unit, then a footer+ such as a spark strip or a scale, kept at the bottom whatever the well's height. `sizes` is the+ value's size at the wide and the narrow grid."""++ def __init__(self, key, unit, footer, sizes=None):+ self.sizes = sizes or (theme.TYPE["readout"], theme.TYPE["readout_narrow"])+ self.view = box("ground")+ column = stack(spacing=6)+ column.setDistribution_(AppKit.NSStackViewDistributionEqualSpacing)+ add(column, Label(key, theme.TYPE["readout_key"], 700, "ink_3", tracking=theme.TRACKING["readout_key"], upper=True).view)+ self.value = Figure("—", self.sizes[0], unit, tracking=theme.TIGHT["readout"])+ add(column, self.value.view)+ add(column, footer)+ self.view.addSubview_(column)+ pin(column, self.view, (9, 10, 8, 10))++ def set_narrow(self, narrow):+ self.value.set(size=self.sizes[1 if narrow else 0])+++class LED:+ def __init__(self, diameter=8.0):+ self.view = size(box(radius=diameter / 2), diameter, diameter)+ self.tone = None+ self.blink = False+ self.set("off")++ def set(self, tone, blink=False):+ if (tone, blink) == (self.tone, self.blink):+ return+ self.tone, self.blink = tone, blink+ layer = self.view.layer()+ layer.setBackgroundColor_(theme.colour(tone).CGColor())+ glow = tone == "signal"+ layer.setMasksToBounds_(False)+ layer.setShadowColor_(theme.colour("signal").CGColor())+ layer.setShadowOffset_((0, 0))+ layer.setShadowRadius_(4 if glow else 0)+ layer.setShadowOpacity_(0.55 if glow else 0)+ layer.removeAnimationForKey_("blink")+ if blink:+ animation = Quartz.CABasicAnimation.animationWithKeyPath_("opacity")+ animation.setFromValue_(1.0)+ animation.setToValue_(0.25)+ animation.setDuration_(0.55)+ animation.setAutoreverses_(True)+ animation.setRepeatCount_(float("inf"))+ layer.addAnimation_forKey_(animation, "blink")+++class Pressable(AppKit.NSView):+ """A view that acts on a click or Space, the base for every custom control here. A focus ring in+ `signal` is drawn as its own sublayer, outside the view unless `ring_inset` says inside."""++ def acceptsFirstResponder(self):+ return getattr(self, "enabled", True) and getattr(self, "callback", None) is not None++ def acceptsFirstMouse_(self, _event):+ return True++ def mouseDown_(self, _event):+ pass++ def mouseUp_(self, event):+ point = self.convertPoint_fromView_(event.locationInWindow(), None)+ if AppKit.NSPointInRect(point, self.bounds()):+ self.press()++ def keyDown_(self, event):+ if event.charactersIgnoringModifiers() in (" ", "\r"):+ self.press()+ else:+ objc.super(Pressable, self).keyDown_(event)++ def accessibilityPerformPress(self):+ self.press()+ return True++ def isAccessibilityElement(self):+ return True++ @objc.python_method+ def press(self):+ if getattr(self, "enabled", True) and getattr(self, "callback", None) is not None:+ self.callback()++ def becomeFirstResponder(self):+ self._ring(True)+ return True++ def resignFirstResponder(self):+ self._ring(False)+ return True++ def layout(self):+ objc.super(Pressable, self).layout()+ ring = getattr(self, "ring", None)+ if ring is not None:+ inset = getattr(self, "ring_inset", -3.0)+ ring.setFrame_(AppKit.NSInsetRect(self.bounds(), inset, inset))++ @objc.python_method+ def _ring(self, on):+ if getattr(self, "ring", None) is None:+ self.setWantsLayer_(True)+ ring = Quartz.CALayer.layer()+ ring.setBorderColor_(theme.colour("signal").CGColor())+ ring.setBorderWidth_(2)+ ring.setCornerRadius_(self.layer().cornerRadius() + 2)+ self.layer().addSublayer_(ring)+ self.ring = ring+ self.setNeedsLayout_(True)+ self.ring.setHidden_(not on)+++def pressable(callback, fill=None, stroke=None, radius=0.0, role=AppKit.NSAccessibilityButtonRole):+ view = box(fill, stroke, radius, cls=Pressable)+ view.callback = callback+ view.enabled = True+ view.setAccessibilityRole_(role)+ return view+++class Button:+ """A Vernier button. Wraps NSButton rather than subclassing it: its width is recomputed from the+ rendered title on every change, and an AppKit object has nowhere to keep that constraint.+ Styles are `plain` (well, edge border), `primary` (ink) and `live` (signal)."""++ HEIGHTS = {"small": 24, "regular": 30, "big": 40}++ def __init__(self, title, target, action, style="plain", scale="regular", full_width=False):+ self.view = _autolayout(AppKit.NSButton.buttonWithTitle_target_action_(title, target, action))+ self.view.setBordered_(False)+ self.view.setWantsLayer_(True)+ self.view.layer().setCornerRadius_(theme.RADIUS["button"])+ self.view.heightAnchor().constraintEqualToConstant_(self.HEIGHTS[scale]).setActive_(True)+ self.style = style+ self.scale = scale+ self.full_width = full_width+ self.title = title+ self.enabled = True+ self.width = None+ self._restyle()++ def set_title(self, title):+ if title != self.title:+ self.title = title+ self._restyle()++ def set_style(self, style):+ if style != self.style:+ self.style = style+ self._restyle()++ def set_enabled(self, enabled):+ self.view.setEnabled_(enabled)+ if enabled != self.enabled:+ self.enabled = enabled+ self._restyle()++ def _restyle(self):+ fill, ink = {"primary": ("ink", "ground"), "live": ("signal", "ground")}.get(self.style, ("well", "ink"))+ stroke = "edge" if self.style == "plain" else fill+ if not self.enabled:+ # Faded, a filled button turns into a grey slab with its words lost in it; every style+ # disables to the same quiet outline instead.+ fill, stroke, ink = "panel", "rule", "ink_3"+ text_size = theme.TYPE["small"] if self.scale == "small" else theme.TYPE["button"]+ title = attributed(self.title, text_size, 600, ink, align=AppKit.NSTextAlignmentCenter)+ self.view.setAttributedTitle_(title)+ paint(self.view, fill, stroke)+ if self.full_width:+ return+ # Width comes from the rendered title, not a measured pixel, so a longer word or a+ # fallback face widens the button instead of clipping it.+ if self.width is not None:+ self.width.setActive_(False)+ padding = 20 if self.scale == "small" else 26+ self.width = self.view.widthAnchor().constraintEqualToConstant_(math.ceil(title.size().width) + padding)+ self.width.setActive_(True)+++class _Target(AppKit.NSObject):+ """An NSObject that turns a control's action into a Python callback, so the widgets below+ can hand back plain functions instead of making every window a target for every control."""++ def initWithCallback_(self, callback):+ self = objc.super(_Target, self).init()+ if self is None:+ return None+ self.callback = callback+ return self++ def fire_(self, sender):+ self.callback(sender)+++def field(secure=False, mono=True):+ """A text input on `ground` with an `edge` border and the text inset off it. Returns+ (container, control): add the container, read the control."""+ control = _autolayout((AppKit.NSSecureTextField if secure else AppKit.NSTextField).alloc().init())+ control.setBordered_(False)+ control.setDrawsBackground_(False)+ control.setFocusRingType_(AppKit.NSFocusRingTypeNone)+ control.setFont_(theme.mono_font() if mono else theme.font(theme.TYPE["body"]))+ control.setTextColor_(theme.colour("ink"))+ control.cell().setUsesSingleLineMode_(True)+ control.cell().setScrollable_(True)+ squeeze(control)+ container = box("ground", "edge", theme.RADIUS["field"])+ container.addSubview_(control)+ pin(control, container, (5, 8, 5, 8))+ return container, control+++def field_row(caption, control):+ """Caption on the left in a fixed column, control filling the rest. Returns (row, caption)."""+ line = stack(vertical=False, spacing=10)+ words = Label(caption, theme.TYPE["note"], ink="ink_2", wrap=True)+ size(words.view, width=116)+ line.addArrangedSubview_(words.view)+ line.addArrangedSubview_(control)+ hug(control, AppKit.NSLayoutPriorityDefaultLow)+ return line, words+++class _Tick(AppKit.NSView):+ def isFlipped(self):+ return True++ def drawRect_(self, _rect):+ on = getattr(self, "on", False)+ bounds = AppKit.NSInsetRect(self.bounds(), 0.5, 0.5)+ outline = AppKit.NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(bounds, 3, 3)+ if on:+ theme.colour("signal").setFill()+ outline.fill()+ check = AppKit.NSBezierPath.bezierPath()+ check.moveToPoint_((3.5, 7.8))+ check.lineToPoint_((6.3, 10.6))+ check.lineToPoint_((11.5, 4.6))+ check.setLineWidth_(1.8)+ check.setLineCapStyle_(AppKit.NSLineCapStyleRound)+ check.setLineJoinStyle_(AppKit.NSLineJoinStyleRound)+ theme.colour("ground").setStroke()+ check.stroke()+ else:+ theme.colour("well").setFill()+ outline.fill()+ theme.colour("edge").setStroke()+ outline.stroke()+++class WayTile:+ """A way in: a checkbox, its name and a line saying what it is, the whole tile clickable."""++ def __init__(self, title, detail="", on_change=None):+ self.on_change = on_change+ self._value = False+ self.enabled = True+ self.view = pressable(self._toggle, "ground", role=AppKit.NSAccessibilityCheckBoxRole)+ self.view.setAccessibilityLabel_(title)+ self.view.ring_inset = 1.0+ self.tick = size(_autolayout(_Tick.alloc().init()), 15, 15)+ self.name = Label(title, theme.TYPE["body"], 600)+ self.detail = Label(detail, theme.TYPE["small"], ink="ink_3", wrap=True)+ words = stack(spacing=2)+ add(words, self.name.view)+ add(words, self.detail.view)+ line = stack(vertical=False, spacing=9)+ line.setAlignment_(AppKit.NSLayoutAttributeTop)+ line.addArrangedSubview_(self.tick)+ line.addArrangedSubview_(words)+ hug(words, AppKit.NSLayoutPriorityDefaultLow)+ self.view.addSubview_(line)+ pin(line, self.view, (9, 10, 9, 10))++ @property+ def value(self):+ return self._value++ @value.setter+ def value(self, value):+ self._value = bool(value)+ self.tick.on = self._value+ self.tick.setNeedsDisplay_(True)+ self.view.setAccessibilityValue_(1 if self._value else 0)++ def set_enabled(self, enabled):+ self.enabled = enabled+ self.view.enabled = enabled+ self.name.set(ink="ink" if enabled else "ink_3")+ self.tick.setAlphaValue_(1.0 if enabled else 0.45)++ def set_detail(self, text):+ self.detail.set(text)++ def _toggle(self):+ self.value = not self._value+ if self.on_change is not None:+ self.on_change(self._value)+++class _Track(AppKit.NSView):+ def isFlipped(self):+ return True++ def drawRect_(self, _rect):+ on = getattr(self, "on", False)+ track = AppKit.NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(AppKit.NSInsetRect(self.bounds(), 0.5, 0.5), 8.5, 8.5)+ theme.colour("well").setFill()+ track.fill()+ theme.colour("signal" if on else "edge").setStroke()+ track.stroke()+ knob = AppKit.NSBezierPath.bezierPathWithOvalInRect_(((18 if on else 3, 3), (12, 12)))+ theme.colour("signal" if on else "ink_3").setFill()+ knob.fill()+++class Switch:+ """A labelled on/off switch: the words on the left, the track on the right, the row clickable."""++ def __init__(self, title, on_change=None):+ self.on_change = on_change+ self._value = False+ self.view = pressable(self._toggle, role=AppKit.NSAccessibilityCheckBoxRole)+ self.view.setAccessibilityLabel_(title)+ self.track = size(_autolayout(_Track.alloc().init()), 34, 18)+ words = Label(title, theme.TYPE["body"], wrap=True)+ line = stack(vertical=False, spacing=12)+ line.addArrangedSubview_(words.view)+ line.addArrangedSubview_(self.track)+ hug(words.view, AppKit.NSLayoutPriorityDefaultLow)+ self.view.addSubview_(line)+ pin(line, self.view, (3, 0, 3, 0))++ @property+ def value(self):+ return self._value++ @value.setter+ def value(self, value):+ self._value = bool(value)+ self.track.on = self._value+ self.track.setNeedsDisplay_(True)+ self.view.setAccessibilityValue_(1 if self._value else 0)++ def _toggle(self):+ self.value = not self._value+ if self.on_change is not None:+ self.on_change(self._value)+++class Segmented:+ """One choice of several, laid out `columns` across in as many rows as it takes. `.value` reads+ and writes the value rather than the index; a value that is not a choice selects nothing."""++ def __init__(self, choices, columns=None, on_change=None):+ self.choices = list(choices)+ self.on_change = on_change+ self._value = None+ self.enabled = True+ columns = columns or len(self.choices)+ self.view = box("edge", "edge", theme.RADIUS["segment"])+ self.view.layer().setMasksToBounds_(True)+ grid = stack(spacing=1)+ grid.setDistribution_(AppKit.NSStackViewDistributionFillEqually)+ self.cells = []+ for start in range(0, len(self.choices), columns):+ row = stack(vertical=False, spacing=1)+ row.setDistribution_(AppKit.NSStackViewDistributionFillEqually)+ for value, title in self.choices[start:start + columns]:+ cell = pressable(lambda value=value: self._choose(value), "well", role=AppKit.NSAccessibilityRadioButtonRole)+ cell.setAccessibilityLabel_(title)+ cell.ring_inset = 2.0+ words = Label(title, theme.TYPE["small"], ink="ink_2", align=AppKit.NSTextAlignmentCenter)+ squeeze(words.view)+ cell.addSubview_(words.view)+ pin(words.view, cell, (6, 4, 6, 4))+ row.addArrangedSubview_(cell)+ self.cells.append((value, cell, words))+ add(grid, row)+ self.view.addSubview_(grid)+ pin(grid, self.view, (1, 1, 1, 1))++ @property+ def value(self):+ return self._value++ @value.setter+ def value(self, value):+ self._value = value+ for candidate, cell, words in self.cells:+ chosen = candidate == value+ # Disabled, the choice stays marked by weight but loses the ink fill, which would+ # otherwise still read as live through the fade.+ lit = chosen and self.enabled+ paint(cell, "ink" if lit else "well")+ words.set(ink="ground" if lit else "ink_2", weight=600 if chosen else 400)+ cell.setAccessibilityValue_(1 if chosen else 0)++ def set_enabled(self, enabled):+ self.enabled = enabled+ self.view.setAlphaValue_(1.0 if enabled else 0.45)+ for _value, cell, _words in self.cells:+ cell.enabled = enabled+ self.value = self._value++ def _choose(self, value):+ if value == self._value:+ return+ self.value = value+ if self.on_change is not None:+ self.on_change(value)+++class Selector:+ """The MAC / WINDOWS indicator: shows where input is, and is not itself a control."""++ def __init__(self):+ self.view = box(stroke="edge", radius=theme.RADIUS["field"])+ self.view.layer().setMasksToBounds_(True)+ row = stack(vertical=False, spacing=0)+ row.setDistribution_(AppKit.NSStackViewDistributionFillEqually)+ self.halves = {}+ for side, title in (("mac", "Mac"), ("windows", "Windows")):+ half = box()+ words = Label(title, theme.TYPE["eyebrow"], 700, "ink_3", tracking=theme.TRACKING["selector"], upper=True,+ align=AppKit.NSTextAlignmentCenter)+ half.addSubview_(words.view)+ pin(words.view, half, (7, 4, 7, 4))+ bar = box()+ half.addSubview_(bar)+ AppKit.NSLayoutConstraint.activateConstraints_([+ bar.leadingAnchor().constraintEqualToAnchor_(half.leadingAnchor()),+ bar.trailingAnchor().constraintEqualToAnchor_(half.trailingAnchor()),+ bar.bottomAnchor().constraintEqualToAnchor_(half.bottomAnchor()),+ bar.heightAnchor().constraintEqualToConstant_(2),+ ])+ row.addArrangedSubview_(half)+ self.halves[side] = (half, words, bar)+ self.view.addSubview_(row)+ pin(row, self.view, (1, 1, 1, 1))+ self.side = None+ self.set("mac")++ def set(self, side):+ if side == self.side:+ return+ self.side = side+ for name, (half, words, bar) in self.halves.items():+ on = name == side+ accent = "signal" if name == "windows" else "ink_2"+ paint(half, "well" if on else None)+ paint(bar, accent if on else None)+ words.set(ink=("signal" if name == "windows" else "ink") if on else "ink_3")+++class _Flipped(AppKit.NSView):+ def isFlipped(self):+ return True+++def _fill(name, rect):+ theme.colour(name).setFill()+ AppKit.NSBezierPath.fillRect_(rect)+++class Spark(_Flipped):+ """The last 24 round-trip samples as bars, the newest lit when live."""++ SAMPLES = 24++ def drawRect_(self, _rect):+ samples = list(getattr(self, "samples", ()))[-self.SAMPLES:]+ live = getattr(self, "live", False)+ width, height = self.bounds().size.width, self.bounds().size.height+ gap = 2.0+ bar = (width - gap * (self.SAMPLES - 1)) / self.SAMPLES+ peak = max(samples) if samples else 1+ padded = [None] * (self.SAMPLES - len(samples)) + samples+ for index, sample in enumerate(padded):+ tall = 1.0 if sample is None else max(1.0, height * min(1.0, sample / max(peak, 1)))+ colour = "ink_3"+ if live and sample is not None:+ colour = "signal" if index == self.SAMPLES - 1 else "signal_dim"+ _fill(colour, ((index * (bar + gap), height - tall), (bar, tall)))+++class Scale(_Flipped):+ """A short tick scale with a marker at `fraction`, the resistance readout's vernier."""++ def drawRect_(self, _rect):+ width, height = self.bounds().size.width, self.bounds().size.height+ for step in range(11):+ x = min(width - 1, step * width / 10)+ major = step % 5 == 0+ tall = 9 if major else 5+ _fill("ink_3" if major else "edge", ((x, height - tall), (1, tall)))+ x = 5 + getattr(self, "fraction", 0.0) * (width - 10)+ marker = AppKit.NSBezierPath.bezierPath()+ marker.moveToPoint_((x - 5, 0))+ marker.lineToPoint_((x + 5, 0))+ marker.lineToPoint_((x, 6))+ marker.closePath()+ theme.colour("signal").setFill()+ marker.fill()+++def scale_fraction(value, low, high, scale="linear"):+ """Where `value` sits along a ruler from 0 to 1, pinned to the ends outside the range."""+ value = min(max(value, low), high)+ if scale == "sqrt":+ return (math.sqrt(value) - math.sqrt(low)) / (math.sqrt(high) - math.sqrt(low))+ return (value - low) / (high - low)+++def scale_value(fraction, low, high, scale="linear"):+ fraction = min(max(fraction, 0.0), 1.0)+ if scale == "sqrt":+ root = math.sqrt(low) + fraction * (math.sqrt(high) - math.sqrt(low))+ return root * root+ return low + fraction * (high - low)+++class _RulerView(_Flipped):+ TRACK = 30.0+ TOP = 4.0++ def acceptsFirstResponder(self):+ return self.owner.enabled++ def acceptsFirstMouse_(self, _event):+ return True++ def becomeFirstResponder(self):+ self.setNeedsDisplay_(True)+ return True++ def resignFirstResponder(self):+ self.setNeedsDisplay_(True)+ return True++ def mouseDown_(self, event):+ self._drag(event)++ def mouseDragged_(self, event):+ self._drag(event)++ @objc.python_method+ def _drag(self, event):+ if not self.owner.enabled:+ return+ self.window().makeFirstResponder_(self)+ point = self.convertPoint_fromView_(event.locationInWindow(), None)+ span = max(1.0, self.bounds().size.width - 3)+ self.owner.move_to((point.x - 1.5) / span)++ def keyDown_(self, event):+ keys = event.charactersIgnoringModifiers()+ steps = {AppKit.NSLeftArrowFunctionKey: -1, AppKit.NSDownArrowFunctionKey: -1,+ AppKit.NSRightArrowFunctionKey: 1, AppKit.NSUpArrowFunctionKey: 1}+ direction = steps.get(ord(keys[0])) if keys else None+ if direction is None or not self.owner.enabled:+ objc.super(_RulerView, self).keyDown_(event)+ return+ self.owner.nudge(direction)++ def isAccessibilityElement(self):+ return True++ def accessibilityRole(self):+ return AppKit.NSAccessibilitySliderRole++ def accessibilityValue(self):+ return self.owner.value++ def accessibilityPerformIncrement(self):+ self.owner.nudge(1)+ return True++ def accessibilityPerformDecrement(self):+ self.owner.nudge(-1)+ return True++ def drawRect_(self, _rect):+ owner = self.owner+ width = self.bounds().size.width+ base = self.TOP + self.TRACK+ span = width - 3+ thumb = 1.5 + owner.fraction() * span+ _fill(owner.fill, ((0, base - 2), (thumb, 2)))+ for step in range(owner.minor + 1):+ _fill("edge", ((min(width - 1, step * width / owner.minor), base - 8), (1, 8)))+ attributes = {+ AppKit.NSFontAttributeName: theme.mono_font(theme.TYPE["eyebrow"]),+ AppKit.NSForegroundColorAttributeName: theme.colour("ink_3"),+ }+ for index, value in enumerate(owner.labels):+ x = 1.5 + scale_fraction(value, owner.low, owner.high, owner.scale) * span+ _fill("ink_3", ((min(width - 1, x - 0.5), base - 16), (1, 16)))+ text = AppKit.NSString.stringWithString_(str(value))+ text_width = text.sizeWithAttributes_(attributes).width+ left = 0 if index == 0 else width - text_width if index == len(owner.labels) - 1 else x - text_width / 2+ text.drawAtPoint_withAttributes_((left, base + 5), attributes)+ focused = self.window() is not None and self.window().firstResponder() == self+ _fill("panel", ((thumb - 4.5, self.TOP), (9, self.TRACK)))+ _fill("signal" if focused else "ink", ((thumb - 1.5, self.TOP), (3, self.TRACK)))+++class Ruler:+ """A slider drawn as a ruler: ticks, a filled run to the thumb, labelled majors. `scale` is+ `linear` or `sqrt`, which gives the low end of a wide range most of the travel. `.value` is the+ true value even when it lies outside the ruler, in which case the thumb pins to the end; it+ only changes when the ruler is moved. `on_change` fires continuously."""++ def __init__(self, low, high, labels, step=1, scale="linear", minor=25, fill="ink_2", on_change=None):+ self.low, self.high, self.labels, self.step, self.scale = low, high, labels, step, scale+ self.minor, self.fill, self.on_change = minor, fill, on_change+ self.enabled = True+ self._value = low+ self.view = _autolayout(_RulerView.alloc().init())+ self.view.owner = self+ self.view.heightAnchor().constraintEqualToConstant_(_RulerView.TOP + _RulerView.TRACK + 16).setActive_(True)++ def fraction(self):+ return scale_fraction(self._value, self.low, self.high, self.scale)++ @property+ def value(self):+ return self._value++ @value.setter+ def value(self, value):+ self._value = int(value)+ self.view.setNeedsDisplay_(True)++ def set_enabled(self, enabled):+ self.enabled = enabled+ self.view.setAlphaValue_(1.0 if enabled else 0.4)++ def move_to(self, fraction):+ raw = scale_value(fraction, self.low, self.high, self.scale)+ self._set(int(round(raw / self.step) * self.step))++ def nudge(self, direction):+ pinned = min(max(self._value, self.low), self.high)+ # Equal steps along the ruler rather than in units, so arrows move evenly across a square+ # root scale; never less than one step, or a rounded step could go nowhere.+ target = scale_value(self.fraction() + direction / self.minor, self.low, self.high, self.scale)+ target = int(round(target / self.step) * self.step)+ if self.scale == "linear" or target == pinned:+ target = pinned + direction * self.step+ self._set(target)++ def _set(self, value):+ value = min(max(value, self.low), self.high)+ if value == self._value:+ return+ self.value = value+ if self.on_change is not None:+ self.on_change(value)+++# What the settings window calls a key. Names the wire and config keep as they are.+KEY_TITLES = {+ "alt": "Left Option",+ "alt_r": "Right Option",+ "cmd": "Left Command",+ "cmd_r": "Right Command",+ "ctrl": "Left Control",+ "ctrl_r": "Right Control",+ "shift": "Left Shift",+ "shift_r": "Right Shift",+ "caps_lock": "Caps Lock",+ "esc": "Escape",+ "page_up": "Page Up",+ "page_down": "Page Down",+}+++def key_title(name):+ return KEY_TITLES.get(name, name.replace("_", " ").title())+++class KeyRecorder:+ """A keycap that records the next key pressed as the trigger. Clicking arms it; the next key+ or modifier press that Beamer can use as a trigger becomes the value, anything else cancels.+ Recorded through a local event monitor rather than the event tap, so it works before either+ Mac permission is granted."""++ RECORDING_TITLE = "Press a key…"+ HINT = "Click, then press the key"+ RECORDING_HINT = "Click again to cancel"++ def __init__(self, value, on_change=None):+ self.value = value+ self.on_change = on_change+ self.monitor = None+ # The keycap's thicker bottom edge is the outer box showing through a 3pt gap.+ self.view = pressable(self._clicked, "edge", radius=theme.RADIUS["keycap"])+ self.view.setAccessibilityLabel_("Trigger key")+ face = box("ground", radius=theme.RADIUS["keycap"] - 1)+ self.view.addSubview_(face)+ pin(face, self.view, (1, 1, 3, 1))+ self.key = Label(key_title(value), theme.TYPE["keycap"], mono=True, tracking=-0.02)+ squeeze(self.key.view)+ self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight)+ line = stack(vertical=False, spacing=10)+ line.addArrangedSubview_(self.key.view)+ line.addArrangedSubview_(self.hint.view)+ hug(self.key.view, AppKit.NSLayoutPriorityDefaultLow)+ face.addSubview_(line)+ pin(line, face, (9, 12, 8, 12))++ def set_value(self, value):+ self.value = value+ self.key.set(key_title(value))++ def _clicked(self):+ if self.monitor is not None:+ self._stop()+ return+ self.key.set(self.RECORDING_TITLE, ink="signal")+ self.hint.set(self.RECORDING_HINT)+ paint(self.view, "signal")+ mask = AppKit.NSEventMaskKeyDown | AppKit.NSEventMaskFlagsChanged+ self.monitor = AppKit.NSEvent.addLocalMonitorForEventsMatchingMask_handler_(mask, self._recorded)++ def _recorded(self, event):+ # Modifier keys arrive as flagsChanged twice, down then up; the first is the press.+ # A key Beamer cannot use as a trigger cancels, so the previous value is what shows.+ name = SPECIAL_KEY_NAMES.get(int(event.keyCode()))+ self._stop()+ if name in KEY_NAME_TO_CODE:+ self.set_value(name)+ if self.on_change is not None:+ self.on_change(name)+ return None++ def cancel(self):+ self._stop()++ def _stop(self):+ if self.monitor is not None:+ AppKit.NSEvent.removeMonitor_(self.monitor)+ self.monitor = None+ self.key.set(key_title(self.value), ink="ink")+ self.hint.set(self.HINT)+ paint(self.view, "edge")+++class _CodeDelegate(AppKit.NSObject):+ def controlTextDidChange_(self, notification):+ self.owner.changed(notification.object())++ def control_textView_doCommandBySelector_(self, control, _text_view, selector):+ return self.owner.command(control, selector)+++class CodeBoxes:+ """Six single-digit boxes for the pairing code. Typing moves on, Backspace in an empty box moves+ back, pasting the whole code fills every box, and Return submits."""++ def __init__(self, digits, on_submit):+ self.on_submit = on_submit+ self.delegate = _CodeDelegate.alloc().init()+ self.delegate.owner = self+ self.view = stack(vertical=False, spacing=4)+ self.view.setDistribution_(AppKit.NSStackViewDistributionFillEqually)+ self.fields = []+ for index in range(digits):+ container, control = field()+ control.setFont_(theme.mono_font(theme.TYPE["keycap"]))+ control.setAlignment_(AppKit.NSTextAlignmentCenter)+ control.setDelegate_(self.delegate)+ control.setAccessibilityLabel_(f"Digit {index + 1}")+ self.view.addArrangedSubview_(container)+ self.fields.append(control)++ @property+ def value(self):+ return "".join(control.stringValue() for control in self.fields)++ def clear(self):+ for control in self.fields:+ control.setStringValue_("")++ def focus(self, window):+ window.makeFirstResponder_(self.fields[0])++ def changed(self, control):+ index = self.fields.index(control)+ digits = "".join(character for character in control.stringValue() if character.isdigit())+ if len(digits) > 1 and index == 0 or len(digits) >= len(self.fields):+ for position, control_at in enumerate(self.fields):+ control_at.setStringValue_(digits[position] if position < len(digits) else "")+ target = self.fields[min(len(digits), len(self.fields) - 1)]+ else:+ control.setStringValue_(digits[-1:] if digits else "")+ target = self.fields[index + 1] if digits and index + 1 < len(self.fields) else None+ if target is not None and control.window() is not None:+ control.window().makeFirstResponder_(target)++ def command(self, control, selector):+ index = self.fields.index(control)+ if selector == "insertNewline:":+ self.on_submit(control)+ return True+ if selector == "deleteBackward:" and not control.stringValue() and index > 0:+ previous = self.fields[index - 1]+ previous.setStringValue_("")+ control.window().makeFirstResponder_(previous)+ return True+ return False+++class _PageList(AppKit.NSView):+ def keyDown_(self, event):+ keys = event.charactersIgnoringModifiers()+ arrows = {AppKit.NSUpArrowFunctionKey: -1, AppKit.NSDownArrowFunctionKey: 1}+ direction = arrows.get(ord(keys[0])) if keys else None+ if direction is None:+ objc.super(_PageList, self).keyDown_(event)+ else:+ self.owner.step(direction)+++class Sidebar:+ """The window's page list under a link block that stays in view whichever page is open: the+ LED, the state word in its tone and the peer. Each row is a focusable control, and while one+ has focus the up and down arrows move the selection. `pages` is (key, name, SF Symbol, ...)+ per row; `on_select` gets the key of a row the user chose."""++ def __init__(self, pages, on_select):+ self.on_select = on_select+ self.keys = [page[0] for page in pages]+ self.selected = None+ self.view = box("ground")+ column = stack(spacing=0)+ self.view.addSubview_(column)+ AppKit.NSLayoutConstraint.activateConstraints_([+ column.topAnchor().constraintEqualToAnchor_(self.view.topAnchor()),+ column.leadingAnchor().constraintEqualToAnchor_(self.view.leadingAnchor()),+ column.trailingAnchor().constraintEqualToAnchor_(self.view.trailingAnchor()),+ ])++ link = box()+ # The LED sits in a slot one word-line tall, so it centres on the first line when a long+ # state word wraps onto a second, and wide enough that its glow is not clipped square.+ slot = size(box(), 16, 20)+ self.led = LED()+ slot.addSubview_(self.led.view)+ AppKit.NSLayoutConstraint.activateConstraints_([+ self.led.view.centerXAnchor().constraintEqualToAnchor_(slot.centerXAnchor()),+ self.led.view.centerYAnchor().constraintEqualToAnchor_(slot.centerYAnchor()),+ ])+ self.word = Label("", theme.SIDEBAR_WORD, 700, wrap=True)+ self.peer = Label("", theme.TYPE["small"], mono=True, ink="ink_3")+ squeeze(self.peer.view)+ words = stack(spacing=3)+ add(words, self.word.view)+ add(words, self.peer.view)+ line = stack(vertical=False, spacing=5)+ line.setAlignment_(AppKit.NSLayoutAttributeTop)+ line.addArrangedSubview_(slot)+ line.addArrangedSubview_(hug(words, AppKit.NSLayoutPriorityDefaultLow))+ link.addSubview_(line)+ pin(line, link, (18, 12, 18, 14))+ add(column, link)+ rule = add(column, hairline())+ column.setCustomSpacing_afterView_(12, rule)++ rows = _autolayout(_PageList.alloc().init())+ rows.owner = self+ list_stack = stack(spacing=2)+ rows.addSubview_(list_stack)+ pin(list_stack, rows)+ symbol_size = AppKit.NSImageSymbolConfiguration.configurationWithPointSize_weight_(13, AppKit.NSFontWeightRegular)+ self.rows = {}+ for index, (key, name, symbol, *_rest) in enumerate(pages):+ row = pressable(lambda key=key: self._choose(key), role=AppKit.NSAccessibilityRadioButtonRole)+ row.setAccessibilityLabel_(name)+ row.setToolTip_(f"{name} ⌘{index + 1}")+ row.ring_inset = 2.0+ icon = size(_autolayout(AppKit.NSImageView.alloc().init()), 18, 18)+ icon.setImage_(AppKit.NSImage.imageWithSystemSymbolName_accessibilityDescription_(symbol, None))+ icon.setSymbolConfiguration_(symbol_size)+ words = Label(name, theme.TYPE["body"], ink="ink_2")+ squeeze(words.view)+ dot = size(box(radius=3), 6, 6)+ dot.setHidden_(True)+ line = stack(vertical=False, spacing=10)+ line.addArrangedSubview_(icon)+ line.addArrangedSubview_(hug(words.view, AppKit.NSLayoutPriorityDefaultLow))+ line.addArrangedSubview_(dot)+ row.addSubview_(line)+ pin(line, row, (8, 16, 8, 16))+ bar = box()+ row.addSubview_(bar)+ AppKit.NSLayoutConstraint.activateConstraints_([+ bar.leadingAnchor().constraintEqualToAnchor_(row.leadingAnchor()),+ bar.topAnchor().constraintEqualToAnchor_(row.topAnchor()),+ bar.bottomAnchor().constraintEqualToAnchor_(row.bottomAnchor()),+ bar.widthAnchor().constraintEqualToConstant_(2),+ ])+ add(list_stack, row)+ self.rows[key] = (name, row, icon, words, bar, dot)+ add(column, rows)++ def select(self, key):+ self.selected = key+ for page, (_name, row, icon, words, bar, _dot) in self.rows.items():+ on = page == key+ paint(row, "well" if on else None)+ paint(bar, "signal" if on else None)+ words.set(ink="ink" if on else "ink_2", weight=600 if on else 400)+ icon.setContentTintColor_(theme.colour("ink" if on else "ink_3"))+ row.setAccessibilityValue_(1 if on else 0)++ def step(self, direction):+ index = min(max(self.keys.index(self.selected) + direction, 0), len(self.keys) - 1)+ key = self.keys[index]+ self._choose(key)+ row = self.rows[key][1]+ if row.window() is not None:+ row.window().makeFirstResponder_(row)++ def _choose(self, key):+ self.select(key)+ self.on_select(key)++ def set_link(self, state, peer):+ self.led.set(state.led, state.blink)+ self.word.set(state.word, ink=state.tone)+ self.peer.set(peer)++ def set_dots(self, marks):+ for page, (name, row, _icon, _words, _bar, dot) in self.rows.items():+ tone = marks.get(page)+ dot.setHidden_(tone is None)+ if tone is not None:+ paint(dot, tone)+ row.setAccessibilityLabel_(name if tone is None else f"{name}, needs attention")+++class ChoiceTiles:+ """One of several, as tiles side by side: each a live preview over its name and a line saying+ what it is, the whole tile clickable. The chosen tile takes a 2pt ink border. `.value` reads and+ writes the value rather than the index, like Segmented."""++ def __init__(self, choices, on_change=None):+ self.on_change = on_change+ self._value = None+ self.enabled = True+ self.tiles = []+ self.view = stack(vertical=False, spacing=10)+ self.view.setDistribution_(AppKit.NSStackViewDistributionFillEqually)+ self.view.setAlignment_(AppKit.NSLayoutAttributeTop)+ for value, title, detail, preview in choices:+ tile = pressable(lambda value=value: self._choose(value), "ground", "rule", theme.RADIUS["segment"],+ role=AppKit.NSAccessibilityRadioButtonRole)+ tile.setAccessibilityLabel_(title)+ column = stack(spacing=6)+ add(column, preview)+ column.setCustomSpacing_afterView_(10, preview)+ name = Label(title, theme.TYPE["body"], 600)+ add(column, name.view)+ add(column, Label(detail, theme.TYPE["small"], ink="ink_3", wrap=True).view)+ tile.addSubview_(column)+ pin(column, tile, (8, 8, 12, 8))+ self.view.addArrangedSubview_(tile)+ tile.heightAnchor().constraintEqualToAnchor_(self.view.heightAnchor()).setActive_(True)+ self.tiles.append((value, tile, name))++ @property+ def value(self):+ return self._value++ @value.setter+ def value(self, value):+ self._value = value+ for candidate, tile, name in self.tiles:+ chosen = candidate == value+ paint(tile, "ground", "ink" if chosen and self.enabled else "rule")+ tile.layer().setBorderWidth_(2 if chosen else 1)+ name.set(ink="ink" if self.enabled else "ink_3")+ tile.setAccessibilityValue_(1 if chosen else 0)++ def set_enabled(self, enabled):+ self.enabled = enabled+ self.view.setAlphaValue_(1.0 if enabled else 0.45)+ for _value, tile, _name in self.tiles:+ tile.enabled = enabled+ self.value = self._value++ def _choose(self, value):+ if value == self._value:+ return+ self.value = value+ if self.on_change is not None:+ self.on_change(value)+++class _Chip(AppKit.NSView):+ def layout(self):+ objc.super(_Chip, self).layout()+ gradient = getattr(self, "gradient", None)+ if gradient is not None:+ Quartz.CATransaction.begin()+ Quartz.CATransaction.setDisableActions_(True)+ gradient.setFrame_(self.bounds())+ Quartz.CATransaction.commit()+++class Swatches:+ """One colour of several from theme.PALETTES: a chip of each palette's gradient over its name,+ the chosen chip ringed in ink. `.value` reads and writes the palette name."""++ def __init__(self, choices, on_change=None):+ self.on_change = on_change+ self._value = None+ self.enabled = True+ self.cells = []+ self.view = stack(vertical=False, spacing=8)+ self.view.setDistribution_(AppKit.NSStackViewDistributionFillEqually)+ for value, title in choices:+ cell = pressable(lambda value=value: self._choose(value), role=AppKit.NSAccessibilityRadioButtonRole)+ cell.setAccessibilityLabel_(title)+ chip = size(box(None, "rule", theme.RADIUS["field"], cls=_Chip), height=24)+ chip.layer().setMasksToBounds_(True)+ colours = list(theme.PALETTES[value])+ if len(colours) == 1:+ colours *= 2+ gradient = Quartz.CAGradientLayer.layer()+ gradient.setColors_([AppKit.NSColor.colorWithSRGBRed_green_blue_alpha_(*theme.rgb(hex_value), 1.0).CGColor() for hex_value in colours])+ gradient.setStartPoint_((0.0, 0.5))+ gradient.setEndPoint_((1.0, 0.5))+ chip.layer().insertSublayer_atIndex_(gradient, 0)+ chip.gradient = gradient+ name = Label(title, theme.TYPE["small"], ink="ink_2", align=AppKit.NSTextAlignmentCenter)+ squeeze(name.view)+ column = stack(spacing=5)+ add(column, chip)+ add(column, name.view)+ cell.addSubview_(column)+ pin(column, cell, (3, 3, 3, 3))+ self.view.addArrangedSubview_(cell)+ self.cells.append((value, cell, chip, name))++ @property+ def value(self):+ return self._value++ @value.setter+ def value(self, value):+ self._value = value+ for candidate, cell, chip, name in self.cells:+ chosen = candidate == value+ paint(chip, None, "ink" if chosen and self.enabled else "rule")+ chip.layer().setBorderWidth_(2 if chosen else 1)+ name.set(ink="ink" if chosen else "ink_2", weight=600 if chosen else 400)+ cell.setAccessibilityValue_(1 if chosen else 0)++ def set_enabled(self, enabled):+ self.enabled = enabled+ self.view.setAlphaValue_(1.0 if enabled else 0.45)+ for _value, cell, _chip, _name in self.cells:+ cell.enabled = enabled+ self.value = self._value++ def _choose(self, value):+ if value == self._value:+ return+ self.value = value+ if self.on_change is not None:+ self.on_change(value)diff --git a/mac_app/windows_input.py b/mac_app/windows_input.pynew file mode 100644index 0000000..28fe6f6--- /dev/null+++ b/mac_app/windows_input.py@@ -0,0 +1,113 @@+"""The other direction: the PC's keyboard and mouse arriving on this Mac.++A listener on the same port number this Mac reaches Windows on -- different+machines, so one number does for both -- running the same receiver.py the PC+runs, with this Mac's own injector, clipboard and display geometry handed to+it. Nothing about the protocol or the crossing is duplicated here; this module+is only the wiring that says which platform's modules to use and what to do+when input arrives.++The two directions never overlap. Every focus message is passed to the+controller, which stops its own tap from reading a pointer the PC is moving as+a push against this Mac's edge.+"""++import logging+import threading++import clipboard_mac+import desktop_mac+import input_injector_mac+import no_unlock+from receiver import ReceiverServer, ServerState++LOGGER = logging.getLogger("Beamer")+++class WindowsInput:+ """Owns the listener and keeps it in step with the settings. `sync` is+ called from the status tick, so a token or port changed in the window+ takes effect without anyone restarting Beamer."""++ def __init__(self, controller, logger=None, arrangement_callback=None):+ self._controller = controller+ self._logger = logger or LOGGER+ # Windows can change the arrangement too, and it reaches this Mac over+ # whichever of the two links is up: this one, or the Mac's own, which+ # bridge.py handles. Both end at the same handler in the app.+ self._arrangement_callback = arrangement_callback+ self._lock = threading.RLock()+ self._running_for = None+ self.state = ServerState.STOPPED+ self.detail = "Not listening"+ self.server = ReceiverServer(+ status_callback=self._on_status,+ clipboard=clipboard_mac,+ unlock=no_unlock,+ desktop=desktop_mac,+ injector=input_injector_mac,+ focus_callback=self._on_focus,+ arrangement_callback=self._on_arrangement,+ self_name="Mac",+ peer_name="PC",+ self_target="mac",+ peer_target="windows",+ )+ controller.send_peer_home = self.server.send_home++ @property+ def receiving(self) -> bool:+ return bool(self._controller.receiving)++ def sync(self, cfg) -> None:+ if not cfg.allow_windows_to_drive:+ # Stopping hands back whatever the PC was driving, the same as a dropped link.+ with self._lock:+ if self._running_for is None:+ return+ self._running_for = None+ self.server.stop()+ return+ wanted = (cfg.port, cfg.auth_token)+ with self._lock:+ if wanted == self._running_for and self.server.listening:+ return+ if not cfg.auth_token or not cfg.port:+ return+ if self._running_for is not None:+ self.server.stop()+ self._running_for = wanted+ try:+ self.server.start(cfg)+ except Exception:+ self._logger.exception("The listener for the PC's input could not start")++ def stop(self) -> None:+ with self._lock:+ self._running_for = None+ self.server.stop()+ self._controller.set_receiving(False)+ try:+ input_injector_mac.release_all()+ except Exception:+ self._logger.exception("Could not release the keys the PC was holding")++ def send_arrangement(self, mac_edge: str, set_at: int) -> bool:+ """Tell the PC over the link it opened to this Mac. Returns False when+ there is nobody connected, which is not a failure worth reporting --+ the hello carries the arrangement on the next connection anyway."""+ return self.server.send_arrangement(mac_edge, int(set_at))++ def _on_arrangement(self, mac_edge, set_at) -> None:+ if self._arrangement_callback is None:+ return+ self._arrangement_callback(mac_edge, set_at)++ def _on_status(self, state, detail) -> None:+ self.state = state+ self.detail = detail++ def _on_focus(self, target) -> None:+ # The receiver itself releases whatever the PC was holding before+ # this fires, on both machines alike.+ self._controller.set_receiving(target == "mac")diff --git a/requirements-mac.txt b/requirements-mac.txtnew file mode 100644index 0000000..122ab4e--- /dev/null+++ b/requirements-mac.txt@@ -0,0 +1,2 @@+pynput>=1.7.6+rumps>=0.4.0diff --git a/requirements-win.txt b/requirements-win.txtnew file mode 100644index 0000000..9c18849--- /dev/null+++ b/requirements-win.txt@@ -0,0 +1,3 @@+# win_receiver.py only uses the Python standard library (socket, ctypes) —+# no third-party packages required. This file is kept for symmetry with+# requirements-mac.txt and as a place to add deps later if needed.diff --git a/theme.py b/theme.pynew file mode 100644index 0000000..c1e476c--- /dev/null+++ b/theme.py@@ -0,0 +1,124 @@+"""Vernier theming for the macOS sender.++Wraps tokens.py, the one home for every colour, size and face both apps draw with, so no hex value+is written twice. Dark only, by design: the window pins to the palette and does not follow the+system appearance.+"""++from __future__ import annotations++from pathlib import Path++import AppKit++import tokens++T: dict[str, str] = tokens.tokens()+PALETTE = tokens.PALETTE+PALETTES = tokens.PALETTES+TYPE = tokens.TYPE+RADIUS = tokens.RADIUS+TRACKING = tokens.TRACKING+MODULE_PADDING = tokens.MODULE_PADDING+RACK_GAP = tokens.RACK_GAP+MIN_WINDOW = tokens.MIN_WINDOW["mac"]++# Derived here rather than added to the shared tokens: the mock's negative tracking on the large+# display figures, the looser tracking on the mono permission state, and the peer name, which has+# to fit a third of the status module at 640.+TIGHT = {"status_word": -0.03, "readout": -0.04, "numeral": -0.05}+STATE_TRACKING = 0.06+PEER_SIZE = 17.0+PEER_SIZE_NARROW = 14.0+# The lit edge of the resistance preview's little screen at rest, so it reads as a screen and+# not as an empty field.+PREVIEW_REST = 0.18+# The sidebar and its pages. The sidebar gives up to 30pt toward the minimum window so the page+# keeps its width; the page title is the one large Hanken Grotesk line on each page. Padding is+# top, leading, bottom, trailing.+SIDEBAR_WIDTH = (150.0, 180.0)+SIDEBAR_WORD = 15.0+PAGE_TITLE = 26.0+PAGE_TITLE_NARROW = 22.0+PAGE_PADDING = (28.0, 32.0, 36.0, 32.0)+PAGE_PADDING_NARROW = (22.0, 22.0, 28.0, 22.0)+MODULE_GAP = 20.0++_sans = "SF Pro Text"+_mono = "SF Mono"++# NSFontManager's 0-15 weight scale, against the numeric weights the tokens name.+_MANAGER_WEIGHTS = {400: 5, 500: 6, 600: 8, 700: 9}+_SYSTEM_WEIGHTS = {+ 400: AppKit.NSFontWeightRegular,+ 500: AppKit.NSFontWeightMedium,+ 600: AppKit.NSFontWeightSemibold,+ 700: AppKit.NSFontWeightBold,+}++_FONT_SOURCE = Path(__file__).resolve().parent / "win_app" / "assets"+++def _register_source_fonts() -> None:+ """The bundle carries the faces under ATSApplicationFontsPath, which macOS registers before the+ app runs. From source nothing does, so the same files the Windows receiver ships are+ registered for this process only."""+ try:+ import CoreText+ import Foundation+ except ImportError:+ return+ for name in tokens.FONT_FILES:+ path = _FONT_SOURCE / name+ if path.exists():+ CoreText.CTFontManagerRegisterFontsForURL(+ Foundation.NSURL.fileURLWithPath_(str(path)), CoreText.kCTFontManagerScopeProcess, None+ )+++def init_fonts() -> None:+ global _sans, _mono+ # Before the first family query: NSFontManager caches the family list on that call, so a face+ # registered after it never appears. In the bundle the source folder is absent and this does+ # nothing.+ _register_source_fonts()+ families = set(AppKit.NSFontManager.sharedFontManager().availableFontFamilies())+ _sans = tokens.UI_FAMILY if tokens.UI_FAMILY in families else "SF Pro Text"+ _mono = tokens.MONO_FAMILY if tokens.MONO_FAMILY in families else "Menlo"+++def sans() -> str:+ return _sans+++def mono() -> str:+ return _mono+++def _named(family: str, size: float, weight: int):+ return AppKit.NSFontManager.sharedFontManager().fontWithFamily_traits_weight_size_(+ family, 0, _MANAGER_WEIGHTS.get(weight, 5), size+ )+++def font(size: float, weight: int = 400):+ return _named(_sans, size, weight) or AppKit.NSFont.systemFontOfSize_weight_(size, _SYSTEM_WEIGHTS[weight])+++def mono_font(size: float | None = None, weight: int = 400):+ size = size if size is not None else TYPE["field_mono"]+ return _named(_mono, size, weight) or AppKit.NSFont.monospacedSystemFontOfSize_weight_(+ size, _SYSTEM_WEIGHTS[weight]+ )+++def rgb(value: str) -> tuple[float, float, float]:+ value = value.lstrip("#")+ return tuple(int(value[index:index + 2], 16) / 255 for index in range(0, 6, 2))+++def colour(name: str):+ return AppKit.NSColor.colorWithSRGBRed_green_blue_alpha_(*rgb(T[name]), 1.0)++# The longest a line of running text may get before it wraps, whatever the window width.+READING_WIDTH = 560.0diff --git a/tokens.py b/tokens.pynew file mode 100644index 0000000..83c7627--- /dev/null+++ b/tokens.py@@ -0,0 +1,109 @@+"""Beamer's design tokens: the Vernier direction, chosen 10-09-2026.++The mock is docs/designs/claude-2-vernier.html and its reasoning docs/designs/claude-2-vernier-notes.md.+This file is the one home for every colour, size, face and spring both apps draw with. The Mac app+reads it through the root theme.py; win_app/tokens.py is a byte-identical copy because PyInstaller+only bundles what sits under the app, and win_app's tests fail if the two drift. Edit this one, then+copy it across.++Dark only. `signal` is the one colour that means something is happening: the link is up, input is on+Windows, pressure is building, a permission is granted. The mock used lime; it was swapped for+cockpit cyan at build time because lime on near-black is the stock developer-tool look, and B612+Mono is a cockpit face. Reverting is this one value and `signal_dim`.+"""++PALETTE = {+ "ground": "#0e0f0d",+ "panel": "#161714",+ "well": "#1f201c",+ "rule": "#2a2b26",+ "edge": "#6e6f66",+ "ink": "#efeee6",+ "ink_2": "#b3b2a7",+ "ink_3": "#8f8e84",+ "signal": "#5fd4f4",+ "signal_dim": "#1f4a55",+ "amber": "#f2b544",+ "fault": "#ff7a66",+ "off": "#4a4b44",+}++# Measured WCAG ratios, for whoever changes a value: ink on panel 15.5, ink_2 on panel 8.4, ink_3 on+# panel 5.5, edge on panel 3.5 (control boundaries), signal on panel 10.4, ground on signal 11.1,+# amber on panel 9.8, fault on panel 7.1.++UI_FAMILY = "Hanken Grotesk"+MONO_FAMILY = "B612 Mono"+FONT_FILES = (+ "HankenGrotesk-Variable.ttf",+ "B612Mono-Regular.ttf",+ "B612Mono-Bold.ttf",+)++# Points on the Mac, logical pixels on Windows. The `_narrow` sizes apply at the 640 minimum width.+TYPE = {+ "eyebrow": 10.5,+ "readout_key": 9.5,+ "small": 11.5,+ "note": 12.5,+ "body": 13.0,+ "button": 13.0,+ "status_word": 38.0,+ "status_word_narrow": 30.0,+ "readout": 34.0,+ "readout_narrow": 26.0,+ "numeral": 52.0,+ "numeral_narrow": 42.0,+ "keycap": 20.0,+ "field_mono": 13.0,+ "code": 92.0,+}++# Colour choices for the crossing feedback on both machines: `crossing.glow_colour` on the Mac and+# `glow_colour` on Windows. `signal` is the Vernier colour; the rest are Border Beam's palettes+# (libraries.dev/beam), each in the order its colours sit round a border.+PALETTES = {+ "signal": (PALETTE["signal"],),+ "colourful": ("#ff3264", "#ff7828", "#f032b4", "#b428f0", "#6446ff", "#288cff", "#1eb9aa", "#32c850"),+ "ocean": ("#288cff", "#6446ff", "#1eb9aa", "#3c6eff"),+ "sunset": ("#ff7828", "#ff3264", "#ffb43c", "#f03278"),+ "mono": ("#ebebeb", "#969696", "#ebebeb"),+}++# Letter spacing as a fraction of the font size, for the uppercase tracked labels.+TRACKING = {+ "eyebrow": 0.14,+ "readout_key": 0.14,+ "selector": 0.12,+}++RADIUS = {+ "field": 4.0,+ "button": 5.0,+ "segment": 5.0,+ "keycap": 6.0,+}++MODULE_PADDING = (14.0, 16.0)+RACK_GAP = 1.0+MIN_WINDOW = {"mac": (640, 540), "windows": (640, 600)}++# Mass-spring parameters (mass 1) for everything that moves. The notch island integrates two of+# these, width and depth; a trackpad tick adds `tick_velocity` points per second to the width.+SPRING = {+ "island": {"stiffness": 300.0, "damping": 20.0},+ "breakthrough": {"stiffness": 600.0, "damping": 28.0, "seconds": 0.32},+ "tick_velocity": 260.0,+ "flash_seconds": 0.14,+}++ISLAND = {+ "grow_width": 40.0,+ "grow_depth": 26.0,+ "meter_segments": 4,+ "meter_after_depth": 14.0,+}+++def tokens() -> dict:+ return dict(PALETTE)diff --git a/win_app/.!55030!kvm_bridge_win.py b/win_app/.!55030!kvm_bridge_win.pynew file mode 100644index 0000000..e69de29diff --git a/win_app/.gitignore b/win_app/.gitignorenew file mode 100644index 0000000..8cc1f89--- /dev/null+++ b/win_app/.gitignore@@ -0,0 +1,6 @@+.venv/+__pycache__/+build/+dist/+*.pyc+config.jsondiff --git a/win_app/Beamer-Setup.iss b/win_app/Beamer-Setup.issnew file mode 100644index 0000000..9c10684--- /dev/null+++ b/win_app/Beamer-Setup.iss@@ -0,0 +1,57 @@+; Inno Setup Script for Beamer Windows Receiver+; Built by build_win_app.ps1 -Release. The version is read from the repo-root VERSION file, the one+; place it is set for both apps.++#define VersionFile FileOpen(AddBackslash(SourcePath) + "..\VERSION")+#define AppVersion Trim(FileRead(VersionFile))+#expr FileClose(VersionFile)++[Setup]+AppId={{9A4E2B1F-4309-4E65-B86D-C7B9F4F64D01}+AppName=Beamer+AppVersion={#AppVersion}+AppPublisher=Kalkman Code+DefaultDirName={localappdata}\Beamer+DisableProgramGroupPage=yes+OutputBaseFilename=Beamer-Setup-{#AppVersion}+Compression=lzma2/max+SolidCompression=yes+; The installer itself still runs per-user; Beamer.exe carries its own requireAdministrator+; manifest (see build.spec) so SendInput can reach elevated windows. Explorer honours that+; manifest automatically (UAC shield on the shortcuts), no change needed here for that part.+PrivilegesRequired=lowest+UninstallDisplayIcon={app}\Beamer.exe+; The single-instance mutex Beamer.exe holds. A running Beamer is elevated, so this per-user setup+; can neither close it nor replace its locked exe; setup asks for it to be quit from the tray first.+AppMutex=Beamer.Receiver+SetupIconFile=Beamer.ico++[Languages]+Name: "english"; MessagesFile: "compiler:Default.isl"++[Tasks]+; Autostart is asked for, never assumed, so it starts unticked.+Name: "autostart"; Description: "Automatically start Beamer at Windows login"; GroupDescription: "Startup options:"; Flags: unchecked++[Files]+Source: "dist\Beamer.exe"; DestDir: "{app}"; Flags: ignoreversion++[Icons]+; The same paths Install-Beamer.ps1 writes, so either installer replaces the other's shortcuts+; instead of adding a second Beamer to the Start Menu.+Name: "{autoprograms}\Beamer"; Filename: "{app}\Beamer.exe"++[Run]+; CreateProcess refuses a requireAdministrator exe from this non-elevated setup (error 740);+; shellexec lets Windows raise the UAC prompt instead.+Filename: "{app}\Beamer.exe"; Description: "{cm:LaunchProgram,Beamer}"; Flags: nowait postinstall skipifsilent shellexec+; A plain Startup-folder shortcut would UAC-prompt on every logon, so autostart is a Scheduled Task+; with RunLevel Highest. Creating one needs elevation this setup does not have, so the step asks+; for it; --hidden brings Beamer up in the tray rather than with a window.+Filename: "schtasks.exe"; Parameters: "/Create /RL HIGHEST /SC ONLOGON /TN Beamer /TR ""\""{app}\Beamer.exe\"" --hidden"" /F"; Tasks: autostart; Flags: runhidden shellexec waituntilterminated; Verb: runas++[UninstallRun]+; The rules and the task were written elevated (by the app, or by the autostart step above), so+; removing them needs elevation the per-user uninstaller does not have: one prompt, one command,+; rather than three deletions that fail silently and leave them behind.+Filename: "cmd.exe"; Parameters: "/c netsh advfirewall firewall delete rule name=""Beamer Receiver (TCP-In)"" & netsh advfirewall firewall delete rule name=""Beamer Pairing (UDP-In)"" & schtasks /Delete /TN Beamer /F"; Flags: runhidden shellexec waituntilterminated; Verb: runas; RunOnceId: "BeamerCleanup"diff --git a/win_app/Beamer.ico b/win_app/Beamer.iconew file mode 100644index 0000000..c1f49c0Binary files /dev/null and b/win_app/Beamer.ico differdiff --git a/win_app/Beamer.png b/win_app/Beamer.pngnew file mode 100644index 0000000..6907690Binary files /dev/null and b/win_app/Beamer.png differdiff --git a/win_app/Install-Beamer.ps1 b/win_app/Install-Beamer.ps1new file mode 100644index 0000000..7f12475--- /dev/null+++ b/win_app/Install-Beamer.ps1@@ -0,0 +1,130 @@+$ErrorActionPreference = 'Stop'++# Over SSH there is nobody to press Enter and no desktop to open a window on: Read-Host fails on+# the null stdin, and a Start-Process lands Beamer in session 0, where it is an invisible,+# tray-less receiver that also holds the SSH pipe open so the install never returns.+$Interactive = [Environment]::UserInteractive -and -not $env:SSH_CLIENT++trap {+ Write-Host $_ -ForegroundColor Red+ if ($Interactive) { Read-Host 'Press Enter to close' }+ break+}++# The app was called OpenKB until 19-08-2026, then Beamy until 10-09-2026. Only+# the display name moved each time until now: this rename also moves the data+# directory, from %LOCALAPPDATA%\OpenKB to %LOCALAPPDATA%\Beamer. app_config.py's+# migrate_legacy_config copies the OpenKB-era config.json across on first run+# rather than moving it, so the old directory and its config.json are never+# touched here.+$LegacyOpenKBDir = Join-Path $env:LOCALAPPDATA 'OpenKB'+$InstallDir = Join-Path $env:LOCALAPPDATA 'Beamer'+$ExeSource = Join-Path $PSScriptRoot 'dist\Beamer.exe'+$ExeDestination = Join-Path $InstallDir 'Beamer.exe'++# Everything the OpenKB name left behind, so the rename does not leave a second+# Start Menu entry, a second logon task, a stale firewall rule for an exe that+# no longer exists, or an OpenKB.exe that still runs alongside this one.+$LegacyName = 'OpenKB'+Get-Process $LegacyName -ErrorAction SilentlyContinue | Stop-Process -Force+# Stop-Process returns before the exe is released, and deleting it straight away then fails silently.+Get-Process $LegacyName -ErrorAction SilentlyContinue | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue+Unregister-ScheduledTask -TaskName $LegacyName -Confirm:$false -ErrorAction SilentlyContinue+Remove-Item -Path (Join-Path $LegacyOpenKBDir "$LegacyName.exe") -Force -ErrorAction SilentlyContinue+Remove-Item -Path (Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\$LegacyName.lnk") -Force -ErrorAction SilentlyContinue+Remove-Item -Path (Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\Startup\$LegacyName.lnk") -Force -ErrorAction SilentlyContinue+Remove-Item -Path (Join-Path ([Environment]::GetFolderPath('Desktop')) "$LegacyName.lnk") -Force -ErrorAction SilentlyContinue+# A rule named plain OpenKB also survived on the rig until 15-09-2026: TCP 51820 for any program on+# every profile, Public included.+Get-NetFirewallRule -DisplayName "$LegacyName Receiver (TCP-In)", $LegacyName -ErrorAction SilentlyContinue | Remove-NetFirewallRule -ErrorAction SilentlyContinue++# Everything the Beamy name left behind. Its data directory was never its own --+# it shared OpenKB's, so Beamy.exe there is removed but config.json stays; it is+# still what migrate_legacy_config reads from.+Get-Process 'Beamy' -ErrorAction SilentlyContinue | Stop-Process -Force+Get-Process 'Beamy' -ErrorAction SilentlyContinue | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue+Remove-Item -Path (Join-Path $LegacyOpenKBDir 'Beamy.exe') -Force -ErrorAction SilentlyContinue+Remove-Item -Path (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Beamy.lnk') -Force -ErrorAction SilentlyContinue+Remove-Item -Path (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Startup\Beamy.lnk') -Force -ErrorAction SilentlyContinue+Remove-Item -Path (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Beamy.lnk') -Force -ErrorAction SilentlyContinue+Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -Name 'Beamy' -ErrorAction SilentlyContinue++# Beamer.exe now carries a requireAdministrator manifest (build.spec uac_admin=True) so+# SendInput can reach elevated windows, e.g. an admin terminal, which UIPI otherwise+# silently discards input for. The firewall rules below need this session elevated too.+$IsElevated = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)++& "$PSScriptRoot\build_win_app.ps1"+if (-not (Test-Path $ExeSource)) { throw 'The Windows build did not produce Beamer.exe' }++New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null+Get-Process 'Beamer' -ErrorAction SilentlyContinue | Stop-Process -Force+Get-Process 'Beamer' -ErrorAction SilentlyContinue | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue+# The exe can stay locked for a moment after the process has gone (23-09-2026: the copy failed+# with "being used by another process" straight after Wait-Process returned, and worked on a rerun).+for ($attempt = 1; ; $attempt++) {+ try {+ Copy-Item -Path $ExeSource -Destination $ExeDestination -Force -ErrorAction Stop+ break+ } catch [System.IO.IOException] {+ if ($attempt -ge 10) { throw }+ Start-Sleep -Milliseconds 500+ }+}++$Shell = New-Object -ComObject WScript.Shell+$StartMenuPath = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Beamer.lnk'+$StartMenuShortcut = $Shell.CreateShortcut($StartMenuPath)+$StartMenuShortcut.TargetPath = $ExeDestination+$StartMenuShortcut.WorkingDirectory = $InstallDir+$StartMenuShortcut.Description = 'Beamer Windows Receiver'+$StartMenuShortcut.Save()++# No installer writes a desktop shortcut; delete any this or an older install left.+Remove-Item -Path (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Beamer.lnk') -Force -ErrorAction SilentlyContinue++# Startup used to be a plain shortcut in the Startup folder. Explorer launches a+# requireAdministrator exe from there with a UAC prompt on every logon instead of+# starting silently, so startup is now a Scheduled Task (RunLevel Highest) instead.+# Remove any shortcut left behind by a previous install so there isn't a second starter.+$StartupPath = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Startup\Beamer.lnk'+Remove-Item -Path $StartupPath -Force -ErrorAction SilentlyContinue++# Defensively remove a legacy Run-key entry too, in case an older install used one instead.+Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -Name 'Beamer' -ErrorAction SilentlyContinue++if ($IsElevated) {+ # Start at logon belongs to the app: the switch on its Overview page writes and removes the+ # Beamer task, and the installer never does, on install or reinstall. A Beamy task is removed,+ # since it starts an exe that no longer exists.+ Unregister-ScheduledTask -TaskName 'Beamy' -Confirm:$false -ErrorAction SilentlyContinue++ try {+ Get-NetFirewallRule -DisplayName 'Beamy Receiver (TCP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRule+ Get-NetFirewallRule -DisplayName 'Beamy Pairing (UDP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRule+ Get-NetFirewallRule -DisplayName 'Beamer Receiver (TCP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRule+ # 24820 and 24821, not the old 51820/51821: those sat inside the 49152-65535 range+ # Windows hands out for itself, and a WinNAT reservation landing on the receiver's port+ # left the PC unable to listen while its outward link carried on working.+ New-NetFirewallRule -DisplayName 'Beamer Receiver (TCP-In)' -Direction Inbound -Protocol TCP -LocalPort 24820 -Action Allow -Profile Private -Program $ExeDestination | Out-Null+ # The pairing beacon answers the Mac on UDP 24821; without this the Mac never sees the PC.+ Get-NetFirewallRule -DisplayName 'Beamer Pairing (UDP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRule+ New-NetFirewallRule -DisplayName 'Beamer Pairing (UDP-In)' -Direction Inbound -Protocol UDP -LocalPort 24821 -Action Allow -Profile Private -Program $ExeDestination | Out-Null+ Write-Host 'Private-network firewall rules installed (TCP 24820 receiver, UDP 24821 pairing).' -ForegroundColor Green+ } catch {+ Write-Host "Could not install the firewall rule: $_" -ForegroundColor Yellow+ }+} else {+ Write-Host 'This session is not elevated, so the firewall rules were not configured. Re-run this installer from an admin PowerShell.' -ForegroundColor Yellow+}++# Beamer.exe is manifested requireAdministrator, so launching it from a non-elevated+# session needs an explicit elevation request; from an already-elevated session this+# just runs it without a further prompt.+if ($Interactive) {+ Start-Process -FilePath $ExeDestination -WorkingDirectory $InstallDir -Verb RunAs+ Write-Host "Beamer installed at $ExeDestination" -ForegroundColor Green+ Read-Host 'Press Enter to close'+} else {+ Write-Host "Beamer installed at $ExeDestination and not started; start it at the PC." -ForegroundColor Green+}diff --git a/win_app/app_config.py b/win_app/app_config.pynew file mode 100644index 0000000..836e259--- /dev/null+++ b/win_app/app_config.py@@ -0,0 +1,291 @@+"""Configuration loading and saving for the Windows tray application."""++import json+import os+import shutil+import tempfile+from dataclasses import dataclass, field+from pathlib import Path++import protocol+++GLOW_STYLES = ("glow", "beam")+GLOW_COLOURS = ("signal", "colourful", "ocean", "sunset", "mono")+EDGES = ("left", "right", "top", "bottom")+CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")+METHODS = ("edge", "corner", "shortcut")+TRIGGER_STYLES = ("double_tap", "hold")+# Wire names, which are Mac-shaped: "cmd_r" is the right Ctrl key on this+# keyboard. Named here so the window can label them in Windows' own words+# without a second table to keep in step.+TRIGGER_KEYS = {+ "cmd_r": "Right Ctrl",+ "cmd": "Left Ctrl",+ "alt_r": "Right Alt",+ "alt": "Left Alt",+ "ctrl_r": "Right Windows",+ "ctrl": "Left Windows",+ "shift_r": "Right Shift",+ "menu": "Menu",+}+class ConfigError(Exception):+ pass+++@dataclass+class Config:+ host: str+ port: int+ auth_token: str+ reconnect_interval_s: float = 2.0+ # The crossing settings that live here are how this PC's own edge looks: the+ # Mac configures the rest and tells this PC the return edge on every switch.+ edge_glow: bool = True+ glow_style: str = "glow"+ glow_colour: str = "signal"+ # The Mac's name from the last pairing, for the window to say who this PC is paired with.+ paired_with: str = ""+ # Whether each machine may take the other's input. Two plain switches: the+ # receiver, and the outward link.+ allow_mac_to_drive: bool = True+ send_to_mac: bool = True+ # How input leaves this PC. Any combination of the methods can be on, and+ # none of them means the PC can only be driven, never drive.+ crossing_methods: list = field(default_factory=lambda: ["edge", "shortcut"])+ crossing_corner: str = "top_left"+ crossing_resistance_px: int = 120+ trigger_key: str = "cmd_r"+ trigger_style: str = "double_tap"+ double_tap_ms: int = 300+ # The Mac's address is learned, never typed: it is the peer address the+ # Mac's own link arrives from.+ mac_host: str = ""+ # The edge of THIS PC that leads to the Mac, which is both the way home+ # and the way out -- one border, walked either way. It can be set at+ # either machine and is synced over the link, so `arrangement_set_at`+ # (unix seconds) says how recently this end changed it and settles which+ # of two ends that disagree is the newer.+ mac_return_edge: str = ""+ arrangement_set_at: int = 0+ # What the Mac asks for at the return edge. The PC's own push out has its+ # own number, above: one slider for each direction, because the hand does+ # not feel a trackpad and a mouse the same way.+ mac_resistance_px: int = 120+++def migrated_port(value) -> int:+ """The port to use for a config that still carries the old default.++ 51820 sits inside the 49152-65535 range Windows hands out for itself, so it was never a+ port anyone could rely on keeping. Nobody chose it -- it was what the app shipped with --+ so it moves; a port a user actually typed is theirs and is left exactly as it is.+ """+ port = int(value)+ return protocol.DEFAULT_PORT if port == protocol.LEGACY_DEFAULT_PORT else port+++def default_config() -> Config:+ # `host` is the address this PC shows the Mac; pairing fills it in with the+ # address that faces the Mac, so a fresh install carries none.+ return Config(host="", port=protocol.DEFAULT_PORT, auth_token="")+++def default_config_path() -> Path:+ base = os.environ.get("LOCALAPPDATA") or os.environ.get("XDG_CONFIG_HOME")+ if base:+ return Path(base) / "Beamer" / "config.json"+ return Path.home() / ".config" / "Beamer" / "config.json"+++def legacy_config_path() -> Path:+ """Where config.json lived under the OpenKB name, before the Beamer rename."""+ base = os.environ.get("LOCALAPPDATA") or os.environ.get("XDG_CONFIG_HOME")+ if base:+ return Path(base) / "OpenKB" / "config.json"+ return Path.home() / ".config" / "OpenKB" / "config.json"+++def migrate_legacy_config() -> bool:+ """Copy the OpenKB-era config.json into the new Beamer location if Beamer+ has none yet. Never moves or deletes the old file."""+ new_path = default_config_path()+ old_path = legacy_config_path()+ if new_path.exists() or not old_path.exists():+ return False+ new_path.parent.mkdir(parents=True, exist_ok=True)+ # Copied beside, then renamed into place: a copy cut short would otherwise+ # leave a truncated config that shadows the intact old one for ever.+ staged = new_path.with_name(".config.migrating")+ shutil.copyfile(old_path, staged)+ os.replace(staged, new_path)+ return True+++def validate_config(config: Config) -> None:+ if not isinstance(config.host, str):+ raise ConfigError("host must be text")+ try:+ port = int(config.port)+ except (TypeError, ValueError) as exc:+ raise ConfigError("port must be an integer from 1 to 65535") from exc+ if isinstance(config.port, bool) or not 1 <= port <= 65535:+ raise ConfigError("port must be an integer from 1 to 65535")+ if not isinstance(config.auth_token, str) or not config.auth_token.strip():+ raise ConfigError("auth_token must not be empty")+ if config.auth_token == "CHANGE_ME":+ raise ConfigError("auth_token is still the placeholder")+ if config.trigger_key not in TRIGGER_KEYS:+ raise ConfigError(f"trigger_key must be one of: {', '.join(TRIGGER_KEYS)}")+ if config.trigger_style not in TRIGGER_STYLES:+ raise ConfigError(f"trigger_style must be one of: {', '.join(TRIGGER_STYLES)}")+ try:+ double_tap_ms = int(config.double_tap_ms)+ except (TypeError, ValueError) as exc:+ raise ConfigError("double_tap_ms must be greater than zero") from exc+ if isinstance(config.double_tap_ms, bool) or double_tap_ms <= 0:+ raise ConfigError("double_tap_ms must be greater than zero")+ if not isinstance(config.crossing_methods, list) or any(+ method not in METHODS for method in config.crossing_methods+ ):+ raise ConfigError(f"crossing_methods must be a list of: {', '.join(METHODS)}")+ if config.crossing_corner not in CORNERS:+ raise ConfigError(f"crossing_corner must be one of: {', '.join(CORNERS)}")+ for name in ("crossing_resistance_px", "mac_resistance_px"):+ value = getattr(config, name)+ try:+ resistance = int(value)+ except (TypeError, ValueError) as exc:+ raise ConfigError(f"{name} must be a whole number of pixels, zero or more") from exc+ if isinstance(value, bool) or resistance < 0:+ raise ConfigError(f"{name} must be a whole number of pixels, zero or more")+ if not isinstance(config.allow_mac_to_drive, bool):+ raise ConfigError("allow_mac_to_drive must be true or false")+ try:+ reconnect_interval_s = float(config.reconnect_interval_s)+ except (TypeError, ValueError) as exc:+ raise ConfigError("reconnect_interval_s must be greater than zero") from exc+ if isinstance(config.reconnect_interval_s, bool) or reconnect_interval_s <= 0:+ raise ConfigError("reconnect_interval_s must be greater than zero")+ if not isinstance(config.edge_glow, bool):+ raise ConfigError("edge_glow must be true or false")+ if config.glow_style not in GLOW_STYLES:+ raise ConfigError(f"glow_style must be one of: {', '.join(GLOW_STYLES)}")+ if config.glow_colour not in GLOW_COLOURS:+ raise ConfigError(f"glow_colour must be one of: {', '.join(GLOW_COLOURS)}")+ if not isinstance(config.paired_with, str):+ raise ConfigError("paired_with must be text")+ if not isinstance(config.send_to_mac, bool):+ raise ConfigError("send_to_mac must be true or false")+ if not isinstance(config.mac_host, str):+ raise ConfigError("mac_host must be text")+ if config.mac_return_edge not in ("",) + EDGES:+ raise ConfigError("mac_return_edge must be an edge name, or empty")+++def config_from_dict(raw: dict) -> Config:+ if not isinstance(raw, dict):+ raise ConfigError("config.json must contain a JSON object")+ missing = [key for key in ("host", "port", "auth_token") if key not in raw]+ if missing:+ raise ConfigError(f"config.json is missing required field(s): {', '.join(missing)}")+ trigger_key = raw.get("trigger_key", "cmd_r")+ try:+ config = Config(+ host=raw["host"],+ port=migrated_port(raw["port"]),+ auth_token=raw["auth_token"],+ reconnect_interval_s=float(raw.get("reconnect_interval_s", 2.0)),+ edge_glow=raw.get("edge_glow", True),+ glow_style=raw.get("glow_style", "glow"),+ glow_colour=raw.get("glow_colour", "signal"),+ paired_with=raw.get("paired_with", "") or "",+ allow_mac_to_drive=raw.get("allow_mac_to_drive", True),+ send_to_mac=raw.get("send_to_mac", True),+ crossing_methods=list(raw.get("crossing_methods", ["edge", "shortcut"])),+ crossing_corner=raw.get("crossing_corner", "top_left"),+ crossing_resistance_px=int(raw.get("crossing_resistance_px", 120)),+ trigger_key=trigger_key,+ trigger_style=raw.get("trigger_style", "double_tap"),+ double_tap_ms=int(raw.get("double_tap_ms", 300)),+ mac_host=raw.get("mac_host", "") or "",+ mac_return_edge=raw.get("mac_return_edge", "") or "",+ arrangement_set_at=int(raw.get("arrangement_set_at", 0)),+ mac_resistance_px=int(raw.get("mac_resistance_px", 120)),+ )+ except (TypeError, ValueError) as exc:+ raise ConfigError(f"config.json contains an invalid value: {exc}") from exc+ validate_config(config)+ return config+++def load_config(path: Path) -> Config:+ if not path.exists():+ raise ConfigError(f"config file not found: {path}")+ try:+ with path.open("r", encoding="utf-8") as handle:+ raw = json.load(handle)+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise ConfigError(f"config file contains invalid JSON: {exc}") from exc+ except OSError as exc:+ raise ConfigError(f"config file could not be read: {exc}") from exc+ config = config_from_dict(raw)+ if config.port != int(raw["port"]):+ try:+ save_config(path, config)+ except (ConfigError, OSError):+ # The port in hand is what matters; a config file that cannot be written must+ # not stop Beamer listening on it.+ pass+ return config+++def config_to_dict(config: Config) -> dict:+ validate_config(config)+ return {+ "host": config.host.strip(),+ "port": int(config.port),+ "auth_token": config.auth_token,+ "reconnect_interval_s": float(config.reconnect_interval_s),+ "edge_glow": config.edge_glow,+ "glow_style": config.glow_style,+ "glow_colour": config.glow_colour,+ "paired_with": config.paired_with,+ "allow_mac_to_drive": config.allow_mac_to_drive,+ "send_to_mac": config.send_to_mac,+ "crossing_methods": list(config.crossing_methods),+ "crossing_corner": config.crossing_corner,+ "crossing_resistance_px": int(config.crossing_resistance_px),+ "trigger_key": config.trigger_key,+ "trigger_style": config.trigger_style,+ "double_tap_ms": int(config.double_tap_ms),+ "mac_host": config.mac_host,+ "mac_return_edge": config.mac_return_edge,+ "arrangement_set_at": int(config.arrangement_set_at),+ "mac_resistance_px": int(config.mac_resistance_px),+ }+++def save_config(path: Path, config: Config) -> None:+ payload = config_to_dict(config)+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary_path = None+ try:+ with tempfile.NamedTemporaryFile(+ mode="w",+ encoding="utf-8",+ dir=path.parent,+ prefix=f".{path.name}.",+ suffix=".tmp",+ delete=False,+ ) as handle:+ temporary_path = Path(handle.name)+ json.dump(payload, handle, indent=2)+ handle.write("\n")+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(temporary_path, path)+ temporary_path = None+ finally:+ if temporary_path is not None:+ temporary_path.unlink(missing_ok=True)diff --git a/win_app/assets/B612Mono-Bold.ttf b/win_app/assets/B612Mono-Bold.ttfnew file mode 100644index 0000000..1072d40Binary files /dev/null and b/win_app/assets/B612Mono-Bold.ttf differdiff --git a/win_app/assets/B612Mono-OFL.txt b/win_app/assets/B612Mono-OFL.txtnew file mode 100644index 0000000..9d0aff0--- /dev/null+++ b/win_app/assets/B612Mono-OFL.txt@@ -0,0 +1,93 @@+Copyright 2012 The B612 Project Authors (https://github.com/polarsys/b612)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/win_app/assets/B612Mono-Regular.ttf b/win_app/assets/B612Mono-Regular.ttfnew file mode 100644index 0000000..32bbdeeBinary files /dev/null and b/win_app/assets/B612Mono-Regular.ttf differdiff --git a/win_app/assets/HankenGrotesk-OFL.txt b/win_app/assets/HankenGrotesk-OFL.txtnew file mode 100644index 0000000..9c8185d--- /dev/null+++ b/win_app/assets/HankenGrotesk-OFL.txt@@ -0,0 +1,94 @@+Copyright 2021 The Hanken Grotesk Project Authors (https://github.com/marcologous/hanken-grotesk)+++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/win_app/assets/HankenGrotesk-Variable.ttf b/win_app/assets/HankenGrotesk-Variable.ttfnew file mode 100644index 0000000..ed6efacBinary files /dev/null and b/win_app/assets/HankenGrotesk-Variable.ttf differdiff --git a/win_app/autostart_win.py b/win_app/autostart_win.pynew file mode 100644index 0000000..aeca5ea--- /dev/null+++ b/win_app/autostart_win.py@@ -0,0 +1,104 @@+"""Start at logon, owned by the app: the scheduled task is the setting, so there is no config+field to disagree with it.++A scheduled task rather than a Run key or a Startup shortcut: Beamer.exe is manifested+requireAdministrator, and Explorer starts such an exe from either of those with a UAC prompt on+every logon. A task with the highest run level starts it elevated and silently. The app is+already elevated when it writes the task, so no prompt appears here either.++Registered from XML, not `schtasks /create /sc onlogon`: that form cannot set a working directory+and gives every task a 72-hour execution limit, which would stop Beamer three days after logon.+"""++from __future__ import annotations++import ctypes+import os+import subprocess+import sys+import tempfile+from typing import Callable, Optional+from xml.sax.saxutils import escape++TASK_NAME = "Beamer"+CREATE_NO_WINDOW = 0x08000000+NAME_SAM_COMPATIBLE = 2++Runner = Callable[[list], "subprocess.CompletedProcess"]+++def _run(args: list) -> subprocess.CompletedProcess:+ return subprocess.run(args, capture_output=True, text=True, creationflags=CREATE_NO_WINDOW)+++def current_user() -> str:+ """DOMAIN\\user as Windows maps it, not USERDOMAIN, which reads WORKGROUP in some sessions and+ maps to no account."""+ size = ctypes.c_ulong(0)+ secur32 = ctypes.windll.secur32+ secur32.GetUserNameExW(NAME_SAM_COMPATIBLE, None, ctypes.byref(size))+ buffer = ctypes.create_unicode_buffer(size.value)+ if not secur32.GetUserNameExW(NAME_SAM_COMPATIBLE, buffer, ctypes.byref(size)):+ raise OSError("could not read the signed-in account name")+ return buffer.value+++def installed_exe() -> Optional[str]:+ """The exe a task can start, or None when running from source, where there is none."""+ return sys.executable if getattr(sys, "frozen", False) else None+++def task_xml(exe: str, user: str) -> str:+ return f"""<?xml version="1.0" encoding="UTF-16"?>+<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">+ <Triggers>+ <LogonTrigger>+ <Enabled>true</Enabled>+ <UserId>{escape(user)}</UserId>+ </LogonTrigger>+ </Triggers>+ <Principals>+ <Principal id="Author">+ <UserId>{escape(user)}</UserId>+ <LogonType>InteractiveToken</LogonType>+ <RunLevel>HighestAvailable</RunLevel>+ </Principal>+ </Principals>+ <Settings>+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>+ <Enabled>true</Enabled>+ </Settings>+ <Actions Context="Author">+ <Exec>+ <Command>{escape(exe)}</Command>+ <Arguments>--hidden</Arguments>+ <WorkingDirectory>{escape(os.path.dirname(exe))}</WorkingDirectory>+ </Exec>+ </Actions>+</Task>+"""+++def is_enabled(run: Runner = _run) -> bool:+ return run(["schtasks", "/query", "/tn", TASK_NAME]).returncode == 0+++def set_enabled(enabled: bool, exe: str, user: Optional[str] = None, run: Runner = _run) -> None:+ """Raises OSError with schtasks' own words when Windows refuses."""+ if not enabled:+ if not is_enabled(run):+ return+ result = run(["schtasks", "/delete", "/tn", TASK_NAME, "/f"])+ else:+ fd, path = tempfile.mkstemp(suffix=".xml")+ try:+ with os.fdopen(fd, "w", encoding="utf-16") as handle:+ handle.write(task_xml(exe, user or current_user()))+ result = run(["schtasks", "/create", "/tn", TASK_NAME, "/xml", path, "/f"])+ finally:+ os.unlink(path)+ if result.returncode != 0:+ raise OSError((result.stderr or result.stdout or "schtasks failed").strip())diff --git a/win_app/build.spec b/win_app/build.specnew file mode 100644index 0000000..3ab7aa5--- /dev/null+++ b/win_app/build.spec@@ -0,0 +1,43 @@+from pathlib import Path+++source_dir = Path(SPECPATH)++analysis = Analysis(+ [str(source_dir / "kvm_bridge_win.py")],+ pathex=[str(source_dir)],+ binaries=[],+ datas=[(str(source_dir / "Beamer.ico"), "."), (str(source_dir / "assets"), "assets"), (str(source_dir.parent / "VERSION"), ".")],+ hiddenimports=["cryptography"],+ hookspath=[],+ hooksconfig={},+ runtime_hooks=[],+ excludes=["PIL", "pystray", "tkinter", "numpy", "PySide6.QtQml", "PySide6.QtQuick", "PySide6.Qt3DCore", "PySide6.QtMultimedia"],+ noarchive=False,+)++python_archive = PYZ(analysis.pure)++executable = EXE(+ python_archive,+ analysis.scripts,+ analysis.binaries,+ analysis.datas,+ [],+ name="Beamer",+ debug=False,+ bootloader_ignore_signals=False,+ strip=False,+ upx=False,+ console=False,+ disable_windowed_traceback=False,+ argv_emulation=False,+ target_arch=None,+ codesign_identity=None,+ entitlements_file=None,+ icon=str(source_dir / "Beamer.ico"),+ # Embeds a requireAdministrator manifest so the receiver always runs elevated.+ # Windows UIPI silently drops SendInput events aimed at a focused elevated+ # window (e.g. an admin terminal) when the sender isn't elevated too.+ uac_admin=True,+)diff --git a/win_app/build_win_app.ps1 b/win_app/build_win_app.ps1new file mode 100644index 0000000..0f3b519--- /dev/null+++ b/win_app/build_win_app.ps1@@ -0,0 +1,60 @@+# Builds dist\Beamer.exe. With -Release it also builds Beamer-Setup-<version>.exe with Inno Setup+# into ..\..\docs\beamer-releases\<version>\, from a clean commit.+param([switch]$Release)++$ErrorActionPreference = 'Stop'++# Windows PowerShell 5.1 turns a native command's stderr into an error record, and with the+# preference above a pip upgrade notice or unittest's own progress -- both ordinary stderr --+# aborts the build with NativeCommandError. Merging with 2>&1 is not enough; the preference has+# to be relaxed for the call itself, which this does inside a function so it stays local. Every+# call checks $LASTEXITCODE afterwards, which survives the function, so nothing is lost.+function Invoke-Native {+ param([Parameter(Mandatory = $true)][scriptblock]$Command)+ $ErrorActionPreference = 'Continue'+ & $Command+}++$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition+if (-not $ScriptDir) { $ScriptDir = Get-Location }+Set-Location $ScriptDir+$ProjectDir = Split-Path -Parent $ScriptDir++if ($Release) {+ # docs\ is not part of the build and other sessions write there; anything else uncommitted would+ # ship code that no commit records.+ $Dirty = git -C $ProjectDir status --porcelain -- . ':(exclude)docs'+ if ($Dirty) { throw 'Uncommitted changes outside docs\ - commit them so the release matches a commit' }+ $Iscc = Join-Path $env:LOCALAPPDATA 'Programs\Inno Setup 6\ISCC.exe'+ if (-not (Test-Path $Iscc)) { throw "Inno Setup 6 is not installed at $Iscc" }+}++$Python = Get-Command python -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source+if (-not $Python) { throw 'Python was not found on PATH' }++if (-not (Test-Path .venv\Scripts\python.exe)) {+ Invoke-Native { & $Python -m venv .venv }+ if ($LASTEXITCODE -ne 0) { throw 'Virtual environment creation failed' }+}++Invoke-Native { & .\.venv\Scripts\python.exe -m pip install -r requirements-win.txt }+if ($LASTEXITCODE -ne 0) { throw 'Dependency installation failed' }++Invoke-Native { & .\.venv\Scripts\python.exe -m unittest discover -s tests -v }+if ($LASTEXITCODE -ne 0) { throw 'Windows tests failed' }++Invoke-Native { & .\.venv\Scripts\python.exe -m PyInstaller --clean --noconfirm --distpath dist --workpath build build.spec }+if ($LASTEXITCODE -ne 0) { throw 'PyInstaller failed' }++$Output = Join-Path $ScriptDir 'dist\Beamer.exe'+if (-not (Test-Path $Output)) { throw 'PyInstaller did not create Beamer.exe' }+Write-Output "Built $Output"++if ($Release) {+ $Version = (Get-Content (Join-Path $ProjectDir 'VERSION') -Raw).Trim()+ $ReleaseDir = [IO.Path]::GetFullPath((Join-Path $ProjectDir "..\docs\beamer-releases\$Version"))+ & $Iscc "/O$ReleaseDir" Beamer-Setup.iss+ if ($LASTEXITCODE -ne 0) { throw 'Inno Setup failed' }+ $Commit = git -C $ProjectDir rev-parse --short HEAD+ Write-Output "Released $(Join-Path $ReleaseDir "Beamer-Setup-$Version.exe") from $Commit"+}diff --git a/win_app/capture_win.py b/win_app/capture_win.pynew file mode 100644index 0000000..84734d2--- /dev/null+++ b/win_app/capture_win.py@@ -0,0 +1,691 @@+"""Low-level keyboard and mouse capture on Windows: the mirror of the Mac's+Quartz event tap.++Two WH_*_LL hooks on a thread of their own, which is the only place a+low-level hook can live -- it needs a message loop, and the Qt main thread's+belongs to the UI. While input is redirected to the Mac the hook callbacks+swallow every event (return 1) and hand it to the sender instead; while it is+not, they pass everything through untouched except a pointer being pushed+against the edge that leads to the Mac, which the same return-edge model the+Mac's own crossing uses holds and finally lets through.++Three things here are safety, not features, and none of them may move off the+callback thread:++- A hook that returns 1 while whatever consumes its events is wedged takes+ Toby's keyboard and mouse away with no way back. So the callback itself+ checks whether redirecting is still live, and the moment the sender says it+ is not -- a dropped link, a missed acknowledgement -- it passes the event+ through. Nothing it does can block.+- Injected events are ignored (LLKHF_INJECTED / LLMHF_INJECTED). Without that,+ every SendInput this PC makes for the Mac's own input would come straight+ back round as a captured event. Raw Input has no such flag, so the injector+ stamps INJECTED_MARK into every SendInput's dwExtraInfo and the WM_INPUT+ reader drops a move carrying it. Without that, the Mac's last deltas after+ a return crossing -- injected here, then reported by Raw Input as the mouse+ moving -- read as this PC's own push against the same edge and sent this+ PC's input straight out to the Mac, which left the Mac's own notch and+ shortcut dead until someone pressed Send input to Windows (19-09-2026).+- The character a key produces is read with only shift and caps lock applied,+ never Ctrl/Alt/Win, exactly as the Mac's translator does it, so a chord+ arrives as a modifier plus the plain key rather than as a control character.++Pointer movement comes from Raw Input, not from the mouse hook, and that is+not a preference. A low-level hook reports the cursor's position, which+Windows has already clamped to the desktop, so at the very edge -- the one+place a crossing has to measure a push -- every further move reports the same+point and the pressure never builds. WM_INPUT carries the mouse's own+relative counts, which the edge does not touch. The hook still owns buttons,+the wheel and swallowing; Raw Input owns how far the hand moved.+"""++import ctypes+import logging+import sys+import threading+import time+from typing import Callable, Dict, List, Optional, Set, Tuple++from input_injector import INJECTED_MARK++LOGGER = logging.getLogger(__name__)++_IS_WINDOWS = sys.platform == "win32"+user32 = ctypes.WinDLL("user32", use_last_error=True) if _IS_WINDOWS else None+kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) if _IS_WINDOWS else None++WM_INPUT = 0x00FF+RID_INPUT = 0x10000003+RIDEV_INPUTSINK = 0x00000100+RIM_TYPEMOUSE = 0+MOUSE_MOVE_ABSOLUTE = 0x01+HWND_MESSAGE = -3++WH_KEYBOARD_LL = 13+WH_MOUSE_LL = 14+HC_ACTION = 0+WM_QUIT = 0x0012+THREAD_PRIORITY_HIGHEST = 2++WM_KEYDOWN = 0x0100+WM_KEYUP = 0x0101+WM_SYSKEYDOWN = 0x0104+WM_SYSKEYUP = 0x0105+WM_MOUSEMOVE = 0x0200+WM_LBUTTONDOWN = 0x0201+WM_LBUTTONUP = 0x0202+WM_RBUTTONDOWN = 0x0204+WM_RBUTTONUP = 0x0205+WM_MBUTTONDOWN = 0x0207+WM_MBUTTONUP = 0x0208+WM_MOUSEWHEEL = 0x020A+WM_MOUSEHWHEEL = 0x020E++LLKHF_INJECTED = 0x10+LLMHF_INJECTED = 0x01++WHEEL_DELTA = 120++KEY_DOWN_MESSAGES = {WM_KEYDOWN, WM_SYSKEYDOWN}+KEY_UP_MESSAGES = {WM_KEYUP, WM_SYSKEYUP}++BUTTON_MESSAGES = {+ WM_LBUTTONDOWN: ("left", True),+ WM_LBUTTONUP: ("left", False),+ WM_RBUTTONDOWN: ("right", True),+ WM_RBUTTONUP: ("right", False),+ WM_MBUTTONDOWN: ("middle", True),+ WM_MBUTTONUP: ("middle", False),+}++# Windows virtual keys to the wire's key names, which are Mac-shaped: the+# semantic mapping happens here, once, so the Mac injects what it is given+# and nothing translates on arrival. Ctrl becomes Command and the Windows key+# becomes Control, the exact inverse of the Mac's own key_map, so the+# shortcuts Toby's fingers know keep working in both directions -- Ctrl+C on+# this keyboard is Cmd+C on the Mac.+VK_TO_NAME: Dict[int, str] = {+ 0x08: "backspace",+ 0x09: "tab",+ 0x0D: "enter",+ 0x13: "pause",+ 0x14: "caps_lock",+ 0x1B: "esc",+ 0x20: "space",+ 0x21: "page_up",+ 0x22: "page_down",+ 0x23: "end",+ 0x24: "home",+ 0x25: "left",+ 0x26: "up",+ 0x27: "right",+ 0x28: "down",+ 0x2C: "print_screen",+ 0x2D: "insert",+ 0x2E: "delete",+ 0x5B: "ctrl",+ 0x5C: "ctrl_r",+ 0x5D: "menu",+ 0x90: "num_lock",+ 0x91: "scroll_lock",+ 0xA0: "shift",+ 0xA1: "shift_r",+ 0xA2: "cmd",+ 0xA3: "cmd_r",+ 0xA4: "alt",+ 0xA5: "alt_r",+ 0xA6: "browser_back",+ 0xA7: "browser_forward",+ 0xAD: "volume_mute",+ 0xAE: "volume_down",+ 0xAF: "volume_up",+ 0xB0: "media_next",+ 0xB1: "media_prev",+ 0xB2: "media_stop",+ 0xB3: "media_play_pause",+ # The undifferentiated modifiers, which a low-level hook does not normally+ # report but a synthetic event can.+ 0x10: "shift",+ 0x11: "cmd",+ 0x12: "alt",+}++for _index in range(1, 13):+ VK_TO_NAME[0x70 + (_index - 1)] = f"f{_index}"+for _index in range(13, 21):+ VK_TO_NAME[0x7C + (_index - 13)] = f"f{_index}"++MODIFIER_NAMES = {+ "shift",+ "shift_r",+ "cmd",+ "cmd_r",+ "alt",+ "alt_r",+ "ctrl",+ "ctrl_r",+ "caps_lock",+}++VK_SHIFT = 0x10+VK_CAPITAL = 0x14+++class KeyboardState:+ """The keyboard bytes ToUnicodeEx is asked to translate against: shift and+ caps lock as they really are, every other modifier cleared. Held as a+ plain dict of virtual key to byte so the translation is testable without+ Windows."""++ def __init__(self) -> None:+ self.shift_down = False+ self.caps_lock = False++ def bytes_for(self) -> Dict[int, int]:+ state = {VK_SHIFT: 0x80 if self.shift_down else 0x00, VK_CAPITAL: 0x01 if self.caps_lock else 0x00}+ return state+++def key_name(vk: int, scan: int, state: KeyboardState, translate: Callable[[int, int, Dict[int, int]], Optional[str]]) -> Optional[str]:+ """The wire name for one key press: a named key where there is one, else+ the character it types with only shift and caps lock applied, else None+ when the layout produces nothing usable (a dead key, or a key with no+ character at all)."""+ named = VK_TO_NAME.get(vk)+ if named is not None:+ return named+ character = translate(vk, scan, state.bytes_for())+ if not character or not character.isprintable():+ return None+ return character+++def wheel_notches(mouse_data: int) -> float:+ """The signed wheel delta a low-level mouse hook packs into the high word+ of mouseData, in notches. Positive is away from the hand on both+ platforms, so the sign travels unchanged."""+ delta = (mouse_data >> 16) & 0xFFFF+ if delta >= 0x8000:+ delta -= 0x10000+ return delta / WHEEL_DELTA+++TOGGLE = "toggle"+REDIRECT = "redirect"+RETURN = "return"+++class Trigger:+ """The shortcut that moves input by hand rather than by pushing the+ pointer, in either of the two styles the Mac offers. `feed` answers with+ TOGGLE, REDIRECT, RETURN or None; the caller decides what to do, and+ swallows the key whenever the answer is not None.++ Double-tap: two presses of `key` inside `window_ms` flip which machine has+ input. Hold: input is on the other machine for exactly as long as the key+ is held, which is the style for reaching across for one keystroke.++ The key is a wire name, so "cmd_r" is the right Ctrl key on this keyboard+ -- the same name the Mac would inject it under. That is deliberate: the+ name the capture produces and the name the setting holds are one thing,+ and cannot drift apart."""++ def __init__(self, key: str = "cmd_r", style: str = "double_tap", window_ms: int = 300) -> None:+ self.key = key+ self.style = style+ self.window_ms = window_ms+ self._last_at: Optional[float] = None+ self._held = False+ self._release_owed = False++ def configure(self, key: str, style: str, window_ms: int) -> None:+ self.key, self.style, self.window_ms = key, style, int(window_ms)+ self._last_at = None+ self._held = False+ self._release_owed = False++ def claims(self, name: str, down: bool, redirecting: bool) -> bool:+ """Whether an event of `name` that `feed` did not act on is still the+ trigger's to swallow. Under hold, every event of the key is: its+ autorepeats and a stray release would otherwise fall through to the+ sender as ordinary keystrokes and reach the Mac as a held modifier+ with no release. Under double-tap the key is the trigger's while+ input is away, the same rule the Mac applies, and for the release of+ the tap that just moved input, whichever way it went; at home a lone+ tap is an ordinary key and passes."""+ if name != self.key:+ return False+ if self.style == "hold":+ return True+ if not down and self._release_owed:+ self._release_owed = False+ return True+ return redirecting++ def feed(self, name: str, down: bool, now: float) -> Optional[str]:+ if name != self.key:+ return None+ if self.style == "hold":+ if down == self._held:+ # Key repeat while held, or a stray release: nothing changes,+ # but the key is still the trigger's and never reaches an app.+ return None+ self._held = down+ return REDIRECT if down else RETURN+ if not down:+ return None+ last = self._last_at+ self._last_at = now+ if last is not None and (now - last) * 1000.0 <= self.window_ms:+ self._last_at = None+ # The second tap's release is the trigger's too, whichever way+ # input just went: at home it would reach Windows as a key-up+ # with no key-down.+ self._release_owed = True+ return TOGGLE+ return None+++class Hooks:+ """The two low-level hooks, the raw-input sink, and the thread that owns+ all three.++ `on_key(name, down)` and `on_mouse(message, x, y, mouse_data)` are called+ on the hook thread and return True when the event has been consumed and+ must not reach the rest of Windows. `on_motion(dx, dy)` is called with+ the mouse's own relative counts and consumes nothing -- raw input is a+ listener, never a filter, which is why the hook is still what swallows a+ move. None of the three may block.+ """++ def __init__(self, on_key, on_mouse, on_motion) -> None:+ self._on_key = on_key+ self._on_mouse = on_mouse+ self._on_motion = on_motion+ self._window = None+ self._thread: Optional[threading.Thread] = None+ self._thread_id: Optional[int] = None+ self._ready = threading.Event()+ self._state = KeyboardState()+ self._failure: Optional[BaseException] = None+ self._handles: List[int] = []+ # Kept alive for as long as the hooks are installed: a callback that+ # is garbage collected while Windows still holds its address crashes+ # the process the next time a key is pressed.+ self._callbacks: List = []++ def start(self) -> None:+ if user32 is None:+ raise RuntimeError("Low-level hooks are only available on Windows")+ if self._thread is not None and self._thread.is_alive():+ return+ self._ready.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")+ # The hook thread signals ready whether it succeeded or failed, so+ # that an installation that cannot work does not hang the caller for+ # five seconds. It must still be the caller that hears about it:+ # silently returning here is a Beamer that says it is connected, takes+ # the shortcut, and does nothing at all.+ if self._failure is not None:+ raise self._failure++ def stop(self) -> None:+ thread_id = self._thread_id+ if thread_id is not None:+ user32.PostThreadMessageW(thread_id, WM_QUIT, 0, 0)+ thread = self._thread+ if thread is not None:+ thread.join(timeout=2.0)+ if thread.is_alive():+ LOGGER.error("The hook thread did not stop within two seconds")+ self._thread = None+ self._thread_id = None++ def _run(self) -> None:+ keyboard = _LL_HOOK_PROC(self._keyboard_proc)+ mouse = _LL_HOOK_PROC(self._mouse_proc)+ window_proc = _WNDPROC(self._window_proc)+ self._callbacks = [keyboard, mouse, window_proc]+ module = kernel32.GetModuleHandleW(None)+ self._thread_id = kernel32.GetCurrentThreadId()+ # Highest within Beamer's above-normal class: this thread answers the+ # hooks, and a callback that misses LowLevelHooksTimeout is removed by+ # Windows without a word, taking the shortcut and the swallow with it.+ if not kernel32.SetThreadPriority(kernel32.GetCurrentThread(), THREAD_PRIORITY_HIGHEST):+ LOGGER.warning("Could not raise the hook thread's priority: %s", ctypes.WinError(ctypes.get_last_error()))+ try:+ self._window = _create_message_window(window_proc, module)+ _register_raw_mouse(self._window)+ for hook_id, proc in ((WH_KEYBOARD_LL, keyboard), (WH_MOUSE_LL, mouse)):+ # NULL, not this process's module handle: a low-level hook+ # whose procedure lives in the calling process takes no+ # module, and naming one that does not contain the procedure+ # -- which a ctypes callback never does -- fails with+ # "The specified module could not be found".+ handle = user32.SetWindowsHookExW(hook_id, proc, None, 0)+ if not handle:+ raise ctypes.WinError(ctypes.get_last_error())+ self._handles.append(handle)+ self._state.caps_lock = read_caps_lock()+ self._ready.set()+ message = MSG()+ while user32.GetMessageW(ctypes.byref(message), None, 0, 0) > 0:+ user32.TranslateMessage(ctypes.byref(message))+ user32.DispatchMessageW(ctypes.byref(message))+ except Exception as exc:+ LOGGER.exception("The input hooks stopped")+ self._failure = exc+ self._ready.set()+ finally:+ for handle in self._handles:+ user32.UnhookWindowsHookEx(handle)+ self._handles = []+ if self._window:+ user32.DestroyWindow(self._window)+ self._window = None+ # The class goes with it. A window class holds the address of the+ # procedure it was registered with, and these callbacks are+ # released on the next line: a second start would skip+ # registration, build a window on the old class, and crash inside+ # a freed callback on its first WM_INPUT.+ _unregister_window_class(module)+ self._callbacks = []++ def _window_proc(self, hwnd, message, wparam, lparam):+ if message == WM_INPUT:+ try:+ motion = _raw_mouse_motion(lparam)+ if motion is not None:+ self._on_motion(*motion)+ except Exception:+ LOGGER.exception("Raw mouse input failed")+ return user32.DefWindowProcW(hwnd, message, wparam, lparam)++ def _keyboard_proc(self, code, wparam, lparam):+ if code != HC_ACTION:+ return user32.CallNextHookEx(None, code, wparam, lparam)+ try:+ data = ctypes.cast(lparam, ctypes.POINTER(KBDLLHOOKSTRUCT)).contents+ if data.flags & LLKHF_INJECTED:+ return user32.CallNextHookEx(None, code, wparam, lparam)+ down = wparam in KEY_DOWN_MESSAGES+ if not down and wparam not in KEY_UP_MESSAGES:+ return user32.CallNextHookEx(None, code, wparam, lparam)+ if data.vkCode in (0xA0, 0xA1, 0x10): # noqa: shift, either side+ self._state.shift_down = down+ elif data.vkCode == VK_CAPITAL and down:+ self._state.caps_lock = not self._state.caps_lock+ name = key_name(data.vkCode, data.scanCode, self._state, _to_unicode)+ if name is None:+ return user32.CallNextHookEx(None, code, wparam, lparam)+ if self._on_key(name, down):+ return 1+ except Exception:+ # Never let an exception here swallow a key: fail open, log once+ # per event, and let Windows have it.+ LOGGER.exception("Keyboard hook failed; passing the key through")+ return user32.CallNextHookEx(None, code, wparam, lparam)++ def _mouse_proc(self, code, wparam, lparam):+ if code != HC_ACTION:+ return user32.CallNextHookEx(None, code, wparam, lparam)+ try:+ data = ctypes.cast(lparam, ctypes.POINTER(MSLLHOOKSTRUCT)).contents+ if data.flags & LLMHF_INJECTED:+ return user32.CallNextHookEx(None, code, wparam, lparam)+ if self._on_mouse(wparam, data.pt.x, data.pt.y, data.mouseData):+ return 1+ except Exception:+ LOGGER.exception("Mouse hook failed; passing the event through")+ return user32.CallNextHookEx(None, code, wparam, lparam)+++if _IS_WINDOWS:+ ULONG_PTR = ctypes.c_size_t++ class POINT(ctypes.Structure):+ _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]++ class KBDLLHOOKSTRUCT(ctypes.Structure):+ _fields_ = [+ ("vkCode", ctypes.c_ulong),+ ("scanCode", ctypes.c_ulong),+ ("flags", ctypes.c_ulong),+ ("time", ctypes.c_ulong),+ ("dwExtraInfo", ULONG_PTR),+ ]++ class MSLLHOOKSTRUCT(ctypes.Structure):+ _fields_ = [+ ("pt", POINT),+ ("mouseData", ctypes.c_ulong),+ ("flags", ctypes.c_ulong),+ ("time", ctypes.c_ulong),+ ("dwExtraInfo", ULONG_PTR),+ ]++ class RAWINPUTHEADER(ctypes.Structure):+ _fields_ = [+ ("dwType", ctypes.c_ulong),+ ("dwSize", ctypes.c_ulong),+ ("hDevice", ctypes.c_void_p),+ ("wParam", ctypes.c_size_t),+ ]++ class RAWMOUSE(ctypes.Structure):+ _fields_ = [+ ("usFlags", ctypes.c_ushort),+ ("usButtonFlags", ctypes.c_ushort),+ ("usButtonData", ctypes.c_short),+ ("ulRawButtons", ctypes.c_ulong),+ ("lLastX", ctypes.c_long),+ ("lLastY", ctypes.c_long),+ ("ulExtraInformation", ctypes.c_ulong),+ ]++ class RAWINPUT(ctypes.Structure):+ _fields_ = [("header", RAWINPUTHEADER), ("mouse", RAWMOUSE)]++ class RAWINPUTDEVICE(ctypes.Structure):+ _fields_ = [+ ("usUsagePage", ctypes.c_ushort),+ ("usUsage", ctypes.c_ushort),+ ("dwFlags", ctypes.c_ulong),+ ("hwndTarget", ctypes.c_void_p),+ ]++ class WNDCLASS(ctypes.Structure):+ _fields_ = [+ ("style", ctypes.c_uint),+ ("lpfnWndProc", ctypes.c_void_p),+ ("cbClsExtra", ctypes.c_int),+ ("cbWndExtra", ctypes.c_int),+ ("hInstance", ctypes.c_void_p),+ ("hIcon", ctypes.c_void_p),+ ("hCursor", ctypes.c_void_p),+ ("hbrBackground", ctypes.c_void_p),+ ("lpszMenuName", ctypes.c_wchar_p),+ ("lpszClassName", ctypes.c_wchar_p),+ ]++ class MSG(ctypes.Structure):+ _fields_ = [+ ("hwnd", ctypes.c_void_p),+ ("message", ctypes.c_uint),+ ("wParam", ctypes.c_size_t),+ ("lParam", ctypes.c_ssize_t),+ ("time", ctypes.c_ulong),+ ("pt", POINT),+ ]++ _LL_HOOK_PROC = ctypes.WINFUNCTYPE(+ ctypes.c_ssize_t, ctypes.c_int, ctypes.c_size_t, ctypes.c_ssize_t+ )+ _WNDPROC = ctypes.WINFUNCTYPE(+ ctypes.c_ssize_t, ctypes.c_void_p, ctypes.c_uint, ctypes.c_size_t, ctypes.c_ssize_t+ )++ user32.SetWindowsHookExW.restype = ctypes.c_void_p+ user32.SetWindowsHookExW.argtypes = [ctypes.c_int, _LL_HOOK_PROC, ctypes.c_void_p, ctypes.c_ulong]+ user32.CallNextHookEx.restype = ctypes.c_ssize_t+ user32.CallNextHookEx.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_size_t, ctypes.c_ssize_t]+ user32.UnhookWindowsHookEx.argtypes = [ctypes.c_void_p]+ user32.ToUnicodeEx.restype = ctypes.c_int+ user32.ToUnicodeEx.argtypes = [+ ctypes.c_uint,+ ctypes.c_uint,+ ctypes.c_char * 256,+ ctypes.c_wchar_p,+ ctypes.c_int,+ ctypes.c_uint,+ ctypes.c_void_p,+ ]+ user32.GetKeyboardLayout.restype = ctypes.c_void_p+ # Handles are pointers: without these, ctypes truncates them to a 32-bit+ # int and a 64-bit module handle comes back as rubbish.+ kernel32.GetModuleHandleW.restype = ctypes.c_void_p+ kernel32.GetModuleHandleW.argtypes = [ctypes.c_wchar_p]+ kernel32.GetCurrentThreadId.restype = ctypes.c_ulong+ kernel32.GetCurrentThread.restype = ctypes.c_void_p+ kernel32.SetThreadPriority.argtypes = [ctypes.c_void_p, ctypes.c_int]+ user32.PostThreadMessageW.argtypes = [ctypes.c_ulong, ctypes.c_uint, ctypes.c_size_t, ctypes.c_ssize_t]+ user32.RegisterClassW.argtypes = [ctypes.POINTER(WNDCLASS)]+ user32.UnregisterClassW.argtypes = [ctypes.c_wchar_p, ctypes.c_void_p]+ user32.GetKeyState.restype = ctypes.c_short+ user32.GetKeyState.argtypes = [ctypes.c_int]+ user32.CreateWindowExW.restype = ctypes.c_void_p+ user32.CreateWindowExW.argtypes = [+ ctypes.c_ulong,+ ctypes.c_wchar_p,+ ctypes.c_wchar_p,+ ctypes.c_ulong,+ ctypes.c_int,+ ctypes.c_int,+ ctypes.c_int,+ ctypes.c_int,+ ctypes.c_void_p,+ ctypes.c_void_p,+ ctypes.c_void_p,+ ctypes.c_void_p,+ ]+ user32.DestroyWindow.argtypes = [ctypes.c_void_p]+ user32.DefWindowProcW.restype = ctypes.c_ssize_t+ user32.DefWindowProcW.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_size_t, ctypes.c_ssize_t]+ user32.RegisterRawInputDevices.argtypes = [ctypes.POINTER(RAWINPUTDEVICE), ctypes.c_uint, ctypes.c_uint]+ user32.GetRawInputData.argtypes = [+ ctypes.c_ssize_t,+ ctypes.c_uint,+ ctypes.c_void_p,+ ctypes.POINTER(ctypes.c_uint),+ ctypes.c_uint,+ ]+else: # pragma: no cover - the structures above are only used on Windows+ POINT = KBDLLHOOKSTRUCT = MSLLHOOKSTRUCT = MSG = None+ RAWINPUT = RAWINPUTDEVICE = WNDCLASS = None+ _LL_HOOK_PROC = _WNDPROC = None+++_WINDOW_CLASS_NAME = "BeamerRawInput"+_window_class_registered = False+++def read_caps_lock() -> bool:+ """Caps lock as Windows has it right now. Read when the hooks go in: the+ hook only ever sees the key being pressed, so starting from a guess means+ a caps-on keyboard types in the wrong case on the Mac until it is toggled+ twice."""+ if user32 is None:+ return False+ return bool(user32.GetKeyState(VK_CAPITAL) & 1)+++def _create_message_window(window_proc, module):+ """A message-only window, which exists for one reason: RIDEV_INPUTSINK+ needs a window to deliver WM_INPUT to, and only a window can receive raw+ input while another application is in the foreground -- which is every+ moment that matters here."""+ global _window_class_registered+ if not _window_class_registered:+ window_class = WNDCLASS()+ window_class.lpfnWndProc = ctypes.cast(window_proc, ctypes.c_void_p)+ window_class.hInstance = module+ window_class.lpszClassName = _WINDOW_CLASS_NAME+ if not user32.RegisterClassW(ctypes.byref(window_class)):+ raise ctypes.WinError(ctypes.get_last_error())+ _window_class_registered = True+ window = user32.CreateWindowExW(+ 0, _WINDOW_CLASS_NAME, _WINDOW_CLASS_NAME, 0, 0, 0, 0, 0, HWND_MESSAGE, None, module, None+ )+ if not window:+ raise ctypes.WinError(ctypes.get_last_error())+ return window+++def _unregister_window_class(module) -> None:+ global _window_class_registered+ if not _window_class_registered:+ return+ if user32.UnregisterClassW(_WINDOW_CLASS_NAME, module):+ _window_class_registered = False+ else:+ LOGGER.warning("The raw-input window class could not be unregistered")+++def _register_raw_mouse(window):+ device = RAWINPUTDEVICE(usUsagePage=0x01, usUsage=0x02, dwFlags=RIDEV_INPUTSINK, hwndTarget=window)+ if not user32.RegisterRawInputDevices(ctypes.byref(device), 1, ctypes.sizeof(RAWINPUTDEVICE)):+ raise ctypes.WinError(ctypes.get_last_error())+++def _raw_mouse_motion(lparam):+ """The hand's relative counts in one WM_INPUT, or None."""+ size = ctypes.c_uint(ctypes.sizeof(RAWINPUT))+ raw = RAWINPUT()+ read = user32.GetRawInputData(+ lparam, RID_INPUT, ctypes.byref(raw), ctypes.byref(size), ctypes.sizeof(RAWINPUTHEADER)+ )+ if read == ctypes.c_uint(-1).value or raw.header.dwType != RIM_TYPEMOUSE:+ return None+ return hand_motion(raw.mouse.usFlags, raw.mouse.lLastX, raw.mouse.lLastY, raw.mouse.ulExtraInformation)+++def hand_motion(flags: int, last_x: int, last_y: int, extra_information: int) -> Optional[Tuple[int, int]]:+ """What one RAWMOUSE says the hand did, or None when it did nothing that+ an edge can measure. A tablet or a remote-desktop pointer reports absolute+ positions instead; there is nothing to measure in those, and the hook's+ own point is the honest reading for them. A move carrying the injector's+ stamp is the Mac's pointer, not the hand's: Raw Input reports a SendInput+ move exactly as it reports the mouse, and the stamp in ulExtraInformation+ is the only difference."""+ if flags & MOUSE_MOVE_ABSOLUTE:+ return None+ if extra_information == INJECTED_MARK:+ return None+ if not last_x and not last_y:+ return None+ return last_x, last_y+++def _to_unicode(vk: int, scan: int, state: Dict[int, int]) -> Optional[str]:+ """The character `vk` types under `state`, or None. Called with the+ non-shift modifiers already cleared, so a chord yields its plain key.++ ToUnicodeEx is asked not to change the keyboard state (the 1<<2 flag):+ without it, translating a dead key here would eat the accent the user is+ actually typing on this PC.+ """+ if user32 is None:+ raise RuntimeError("ToUnicodeEx is only available on Windows")+ key_state = (ctypes.c_char * 256)()+ for key, value in state.items():+ key_state[key] = bytes([value])+ buffer = ctypes.create_unicode_buffer(8)+ layout = user32.GetKeyboardLayout(0)+ count = user32.ToUnicodeEx(vk, scan, key_state, buffer, len(buffer), 1 << 2, layout)+ if count <= 0:+ return None+ return buffer.value[:count]diff --git a/win_app/clipboard_win.py b/win_app/clipboard_win.pynew file mode 100644index 0000000..5f26904--- /dev/null+++ b/win_app/clipboard_win.py@@ -0,0 +1,330 @@+"""Windows clipboard access via ctypes (user32 + kernel32), guarded like+input_injector.py so this module stays importable -- and its orchestration+testable -- on a machine without ctypes.windll, e.g. the Mac this was+developed on.++The clipboard is a contended, system-wide resource: any other process that+briefly holds it makes OpenClipboard fail, which is normal and expected, not+exceptional. `_open_clipboard` retries a handful of times with a short sleep+before giving up. This still wants confirmation on real Windows hardware+under load (see the runtime-verification notes in the task writeup) --+contention behaviour and timing were chosen to match common guidance, not+measured on a real desktop.++Images cross the wire as PNG but live on this clipboard as CF_DIB, so each+direction converts. The DIB half (`dib_to_bgra`, `bgra_to_dib`) is pure+Python over bytes and slices, so it runs and is tested on the Mac; the PNG+codec is Qt's QImage, which the app already ships for its window, imported+lazily so this module needs neither Qt nor Windows to load. No Pillow: it+would be a second imaging library and a binary wheel in the PyInstaller+build for a job QtGui already does.+"""++import ctypes+import logging+import struct+import sys+import time+from typing import Optional, Tuple+++LOGGER = logging.getLogger(__name__)++_IS_WINDOWS = sys.platform == "win32"++user32 = ctypes.WinDLL("user32", use_last_error=True) if _IS_WINDOWS else None+kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) if _IS_WINDOWS else None++if _IS_WINDOWS:+ user32.OpenClipboard.restype = ctypes.c_int+ user32.OpenClipboard.argtypes = [ctypes.c_void_p]+ user32.CloseClipboard.restype = ctypes.c_int+ user32.CloseClipboard.argtypes = []+ user32.EmptyClipboard.restype = ctypes.c_int+ user32.EmptyClipboard.argtypes = []+ user32.GetClipboardData.restype = ctypes.c_void_p+ user32.GetClipboardData.argtypes = [ctypes.c_uint]+ user32.SetClipboardData.restype = ctypes.c_void_p+ user32.SetClipboardData.argtypes = [ctypes.c_uint, ctypes.c_void_p]+ kernel32.GlobalAlloc.restype = ctypes.c_void_p+ kernel32.GlobalAlloc.argtypes = [ctypes.c_uint, ctypes.c_size_t]+ kernel32.GlobalLock.restype = ctypes.c_void_p+ kernel32.GlobalLock.argtypes = [ctypes.c_void_p]+ kernel32.GlobalUnlock.restype = ctypes.c_int+ kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]+ kernel32.GlobalFree.restype = ctypes.c_void_p+ kernel32.GlobalFree.argtypes = [ctypes.c_void_p]+ kernel32.GlobalSize.restype = ctypes.c_size_t+ kernel32.GlobalSize.argtypes = [ctypes.c_void_p]++CF_DIB = 8+CF_UNICODETEXT = 13+GMEM_MOVEABLE = 0x0002++BI_RGB = 0+BI_BITFIELDS = 3+BITMAPINFOHEADER_SIZE = 40+# BITMAPINFOHEADER, V2, V3, V4 and V5. Windows hands a CF_DIBV5 source back+# through CF_DIB with its 124-byte header intact, so the reader must take+# all of them, not just the 40-byte one it writes.+_DIB_HEADER_SIZES = frozenset({40, 52, 56, 108, 124})+_BGR_MASKS = (0x00FF0000, 0x0000FF00, 0x000000FF)+_ALPHA_MASK = 0xFF000000++OPEN_RETRY_ATTEMPTS = 5+OPEN_RETRY_DELAY_SECONDS = 0.05+++def dib_to_bgra(dib: bytes):+ """Decode a CF_DIB payload to (width, height, BGRA bytes, top-down rows),+ or None for anything this does not handle: 24/32-bit BI_RGB and 32-bit+ BI_BITFIELDS with the standard BGR(A) masks are what every screenshot+ tool, browser and Office app writes, so a palette, 16-bit or RLE DIB is+ rare enough to drop rather than decode. Never raises on junk."""+ try:+ if len(dib) < BITMAPINFOHEADER_SIZE:+ return None+ size, width, height, planes, bpp, compression = struct.unpack_from("<IiiHHI", dib, 0)+ clr_used = struct.unpack_from("<I", dib, 32)[0]+ if size not in _DIB_HEADER_SIZES or width <= 0 or height == 0 or bpp not in (24, 32):+ return None+ rows = abs(height)+ offset = size + clr_used * 4+ alpha_declared = False+ if compression == BI_BITFIELDS:+ if bpp != 32:+ return None+ masks = struct.unpack_from("<IIII" if size > BITMAPINFOHEADER_SIZE else "<III", dib, BITMAPINFOHEADER_SIZE)+ if size == BITMAPINFOHEADER_SIZE:+ offset += 12+ if tuple(masks[:3]) != _BGR_MASKS:+ return None+ alpha_declared = len(masks) == 4 and masks[3] == _ALPHA_MASK+ elif compression != BI_RGB:+ return None+ stride = (width * bpp // 8 + 3) & ~3+ if len(dib) < offset + stride * rows:+ return None+ row_bytes = width * bpp // 8+ lines = [dib[offset + i * stride: offset + i * stride + row_bytes] for i in range(rows)]+ if height > 0:+ lines.reverse()+ count = width * rows+ if bpp == 24:+ bgr = b"".join(lines)+ out = bytearray(count * 4)+ out[0::4] = bgr[0::3]+ out[1::4] = bgr[1::3]+ out[2::4] = bgr[2::3]+ out[3::4] = b"\xff" * count+ else:+ out = bytearray(b"".join(lines))+ # Under BI_RGB the fourth byte is officially reserved: GDI leaves+ # it zero, which read as alpha is a fully transparent image, while+ # Chrome and Paint.NET put real alpha there. All-zero means opaque;+ # anything else is taken as alpha, as those readers do.+ if not alpha_declared and out[3::4].count(0) == count:+ out[3::4] = b"\xff" * count+ return width, rows, bytes(out)+ except (struct.error, ValueError, OverflowError, MemoryError):+ return None+++def bgra_to_dib(width: int, height: int, bgra: bytes) -> bytes:+ """Encode top-down BGRA rows as a 32-bit bottom-up BITMAPINFOHEADER DIB,+ the shape Windows' own tools put on the clipboard. Alpha rides in the+ fourth byte under BI_RGB, which the apps that care (Teams, Office,+ browsers) honour; a screenshot is opaque so nothing is lost either way."""+ stride = width * 4+ header = struct.pack(+ "<IiiHHIIiiII", BITMAPINFOHEADER_SIZE, width, height, 1, 32, BI_RGB, stride * height, 2835, 2835, 0, 0+ )+ rows = [bgra[i * stride: (i + 1) * stride] for i in range(height)]+ return header + b"".join(reversed(rows))+++def _png_to_bgra(png: bytes):+ """Decode PNG to (width, height, BGRA top-down) with QImage, or None if it+ will not decode. QImage is safe off the GUI thread and needs no+ application object for the built-in PNG format."""+ from PySide6.QtGui import QImage++ image = QImage.fromData(png, "PNG")+ if image.isNull():+ return None+ image = image.convertToFormat(QImage.Format.Format_ARGB32)+ # ARGB32 is one native-endian uint32 per pixel, which on x86 lands in+ # memory as B, G, R, A: the DIB order, so the bytes are used as they are.+ return image.width(), image.height(), bytes(image.constBits())+++def _bgra_to_png(width: int, height: int, bgra: bytes) -> Optional[bytes]:+ from PySide6.QtCore import QBuffer, QIODevice+ from PySide6.QtGui import QImage++ image = QImage(bgra, width, height, width * 4, QImage.Format.Format_ARGB32)+ buffer = QBuffer()+ buffer.open(QIODevice.OpenModeFlag.WriteOnly)+ if not image.save(buffer, "PNG"):+ return None+ return bytes(buffer.data())+++def png_to_dib(png: bytes) -> Optional[bytes]:+ """PNG bytes to a CF_DIB payload, or None. Never raises."""+ try:+ decoded = _png_to_bgra(png)+ except Exception:+ LOGGER.exception("failed to decode a clipboard PNG")+ return None+ if decoded is None:+ return None+ width, height, bgra = decoded+ if width <= 0 or height <= 0 or len(bgra) != width * height * 4:+ return None+ return bgra_to_dib(width, height, bgra)+++def dib_to_png(dib: bytes) -> Optional[bytes]:+ """CF_DIB payload to PNG bytes, or None. Never raises."""+ decoded = dib_to_bgra(dib)+ if decoded is None:+ return None+ try:+ return _bgra_to_png(*decoded)+ except Exception:+ LOGGER.exception("failed to encode the clipboard image as PNG")+ return None+++def _open_clipboard(win32, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_DELAY_SECONDS, sleep=time.sleep):+ """Try OpenClipboard(None) up to `attempts` times, sleeping `delay`+ seconds between tries. Pure orchestration over an injected `win32` (the+ real user32 WinDLL, or a duck-typed fake) so the retry/backoff decision+ is testable without a real Windows clipboard."""+ for attempt in range(attempts):+ if win32.OpenClipboard(None):+ return True+ if attempt + 1 < attempts:+ sleep(delay)+ return False+++def _read_clipboard_text(win32, mem32):+ """Copy CF_UNICODETEXT out of the (already-open) clipboard, or return None+ if there is none. Caller holds the clipboard open."""+ handle = win32.GetClipboardData(CF_UNICODETEXT)+ if not handle:+ return None+ pointer = mem32.GlobalLock(handle)+ if not pointer:+ return None+ try:+ text = ctypes.wstring_at(pointer)+ finally:+ mem32.GlobalUnlock(handle)+ return text if text else None+++def _read_clipboard_dib(win32, mem32):+ """Copy the CF_DIB payload out of the (already-open) clipboard, or return+ None if there is no image. Windows synthesises CF_DIB from a CF_BITMAP+ or CF_DIBV5 source, so this one format covers them all."""+ handle = win32.GetClipboardData(CF_DIB)+ if not handle:+ return None+ size = mem32.GlobalSize(handle)+ pointer = mem32.GlobalLock(handle)+ if not pointer or not size:+ return None+ try:+ return ctypes.string_at(pointer, size)+ finally:+ mem32.GlobalUnlock(handle)+++def _put_clipboard_data(win32, mem32, clipboard_format, payload):+ """Hand `payload` to the (already-open, already-emptied) clipboard under+ `clipboard_format`. Returns True on success. On success, ownership of the+ allocated global memory handle passes to the system and must not be freed+ here; on failure it is freed before returning."""+ handle = mem32.GlobalAlloc(GMEM_MOVEABLE, len(payload))+ if not handle:+ return False+ pointer = mem32.GlobalLock(handle)+ if not pointer:+ mem32.GlobalFree(handle)+ return False+ try:+ ctypes.memmove(pointer, payload, len(payload))+ finally:+ mem32.GlobalUnlock(handle)+ if not win32.SetClipboardData(clipboard_format, handle):+ mem32.GlobalFree(handle)+ return False+ return True+++def _get_contents(win32, mem32, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_DELAY_SECONDS, sleep=time.sleep):+ if not _open_clipboard(win32, attempts, delay, sleep):+ LOGGER.warning("could not open the clipboard for reading")+ return None, None+ try:+ text = _read_clipboard_text(win32, mem32)+ dib = _read_clipboard_dib(win32, mem32)+ finally:+ win32.CloseClipboard()+ # Converted after the clipboard is closed: a Retina-sized DIB takes+ # tens of milliseconds to encode and nothing else can use the clipboard+ # while it is held.+ return text, dib_to_png(dib) if dib is not None else None+++def _set_contents(win32, mem32, text, png, attempts=OPEN_RETRY_ATTEMPTS, delay=OPEN_RETRY_DELAY_SECONDS, sleep=time.sleep):+ dib = png_to_dib(png) if png is not None else None+ if png is not None and dib is None:+ LOGGER.warning("inbound clipboard image did not decode; setting the text only")+ if text is None and dib is None:+ return False+ if not _open_clipboard(win32, attempts, delay, sleep):+ LOGGER.warning("could not open the clipboard for writing")+ return False+ try:+ win32.EmptyClipboard()+ wrote = False+ if text is not None:+ # CF_UNICODETEXT is CRLF by convention; a Mac's LF alone reads as one+ # line in the older Windows apps.+ text = text.replace("\r\n", "\n").replace("\n", "\r\n")+ wrote |= _put_clipboard_data(win32, mem32, CF_UNICODETEXT, text.encode("utf-16-le") + b"\x00\x00")+ if dib is not None:+ wrote |= _put_clipboard_data(win32, mem32, CF_DIB, dib)+ return wrote+ finally:+ win32.CloseClipboard()+++def get_contents() -> Tuple[Optional[str], Optional[bytes]]:+ """(text, png) from the Windows clipboard, either None when absent, both+ None if this isn't Windows or reading failed for any reason. Never+ raises."""+ if not _IS_WINDOWS:+ return None, None+ try:+ return _get_contents(user32, kernel32)+ except Exception:+ LOGGER.exception("failed to read the Windows clipboard")+ return None, None+++def set_contents(text: Optional[str], png: Optional[bytes]) -> bool:+ """Replace the Windows clipboard with `text` and/or `png`. Returns True+ when at least one was set, False if this isn't Windows or the write+ failed. Never raises."""+ if not _IS_WINDOWS:+ return False+ try:+ return _set_contents(user32, kernel32, text, png)+ except Exception:+ LOGGER.exception("failed to set the Windows clipboard")+ return Falsediff --git a/win_app/config.example.json b/win_app/config.example.jsonnew file mode 100644index 0000000..92d7fbe--- /dev/null+++ b/win_app/config.example.json@@ -0,0 +1,17 @@+{+ "host": "192.168.1.20",+ "port": 24820,+ "auth_token": "CHANGE_ME",+ "trigger_key": "alt_r",+ "double_tap_ms": 300,+ "key_map": {+ "cmd": "ctrl",+ "cmd_r": "ctrl",+ "ctrl": "cmd",+ "ctrl_r": "cmd",+ "alt": "alt",+ "alt_r": "alt"+ },+ "reconnect_interval_s": 2.0,+ "edge_glow": true+}diff --git a/win_app/desktop_win.py b/win_app/desktop_win.pynew file mode 100644index 0000000..f15e19c--- /dev/null+++ b/win_app/desktop_win.py@@ -0,0 +1,92 @@+"""Win32 pointer and monitor geometry, imported lazily by the receiver so the+crossing logic stays testable without ctypes.windll. GetCursorPos, SetCursorPos+and GetSystemMetrics share one coordinate space — virtual-desktop pixels,+DPI-virtualised identically for this process — so values from one feed the+others unconverted."""++import ctypes+import logging+import sys+from typing import List, Tuple++from return_edge import Rect++_IS_WINDOWS = sys.platform == "win32"+user32 = ctypes.WinDLL("user32", use_last_error=True) if _IS_WINDOWS else None+LOGGER = logging.getLogger(__name__)++class POINT(ctypes.Structure):+ _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]+++class RECT(ctypes.Structure):+ _fields_ = [("left", ctypes.c_long), ("top", ctypes.c_long), ("right", ctypes.c_long), ("bottom", ctypes.c_long)]+++if _IS_WINDOWS:+ MONITORENUMPROC = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(RECT), ctypes.c_ssize_t)+ user32.GetCursorPos.argtypes = [ctypes.POINTER(POINT)]+ user32.SetCursorPos.argtypes = [ctypes.c_int, ctypes.c_int]+ user32.EnumDisplayMonitors.argtypes = [ctypes.c_void_p, ctypes.c_void_p, MONITORENUMPROC, ctypes.c_ssize_t]+++def _require() -> None:+ if user32 is None:+ raise RuntimeError("Win32 desktop geometry is only available on Windows")+++def monitors() -> List[Rect]:+ _require()+ found: List[Rect] = []++ def collect(_monitor, _dc, rect, _lparam):+ r = rect.contents+ found.append(Rect(r.left, r.top, r.right - r.left, r.bottom - r.top))+ return 1++ if not user32.EnumDisplayMonitors(None, None, MONITORENUMPROC(collect), 0):+ raise ctypes.WinError(ctypes.get_last_error())+ return found+++def cursor_position() -> Tuple[int, int]:+ _require()+ point = POINT()+ if not user32.GetCursorPos(ctypes.byref(point)):+ raise ctypes.WinError(ctypes.get_last_error())+ return point.x, point.y+++class CURSORINFO(ctypes.Structure):+ _fields_ = [("cbSize", ctypes.c_ulong), ("flags", ctypes.c_ulong), ("hCursor", ctypes.c_void_p), ("ptScreenPos", POINT)]+++SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN = 76, 77, 78, 79+++def _cursor_flags() -> int:+ info = CURSORINFO(cbSize=ctypes.sizeof(CURSORINFO))+ return info.flags if user32.GetCursorInfo(ctypes.byref(info)) else -1+++def set_cursor_position(x: int, y: int) -> None:+ """SetCursorPos failed with no error code for every arrival after the rig+ rebooted on 21-09-2026, while the Mac's relative moves drew nothing either,+ until the physical mouse was touched. An absolute SendInput move takes the+ path real hardware does, so it is the fallback rather than giving up."""+ _require()+ if user32.SetCursorPos(int(x), int(y)):+ return+ error = ctypes.get_last_error()+ import input_injector++ left, top = user32.GetSystemMetrics(SM_XVIRTUALSCREEN), user32.GetSystemMetrics(SM_YVIRTUALSCREEN)+ width, height = user32.GetSystemMetrics(SM_CXVIRTUALSCREEN), user32.GetSystemMetrics(SM_CYVIRTUALSCREEN)+ input_injector.inject_mouse_absolute(+ round((x - left) * 65535 / max(width - 1, 1)),+ round((y - top) * 65535 / max(height - 1, 1)),+ )+ LOGGER.warning(+ "SetCursorPos refused (error %s, cursor flags %s); moved to %s,%s with SendInput instead",+ error, _cursor_flags(), x, y,+ )diff --git a/win_app/edge_glow.py b/win_app/edge_glow.pynew file mode 100644index 0000000..65712f2--- /dev/null+++ b/win_app/edge_glow.py@@ -0,0 +1,185 @@+"""The Windows half of the edge glow, along the return edge, on the monitor that owns it. Click-through,+never focused, above other windows.++Two styles, chosen in this app's own settings with a colour: `glow` is a band whose depth and opacity+track pressure with a flash at breakthrough; `beam` is a thin line along the edge with a comet of+light travelling it, faster as the push builds, the whole edge flashing at breakthrough and the comet+running on off the end rather than stopping where it was, after the Mac's notch beam.++Every frame paints the palette along the edge, then cuts it with alpha masks: a falloff inward from+the edge, and for the beam a profile along it. `signal` with `glow` is the original look.+"""++from __future__ import annotations++import time++from PySide6.QtCore import QRect, Qt, QTimer+from PySide6.QtGui import QColor, QLinearGradient, QPainter+from PySide6.QtWidgets import QApplication, QWidget++import return_edge as crossing+import tokens++BAND_PX = 44+FLASH_SECONDS = tokens.SPRING["flash_seconds"]+STALE_SECONDS = 0.08++COMET = 0.3+BEAM_BASE = 0.2+BEAM_FALLOFF = ((0.0, 1.0), (0.08, 0.85), (0.3, 0.25), (1.0, 0.0))+SLOW_TRAVERSE_S = 2.4+FAST_TRAVERSE_S = 0.8+FINISH_SECONDS = 0.6+FINISH_TRAVERSE_S = 0.35+PROFILE_SAMPLES = 24+++def traverse_seconds(strength: float) -> float:+ """One run of the comet along the whole edge: unhurried at a light lean, quick near breakthrough."""+ strength = max(0.0, min(1.0, strength))+ return SLOW_TRAVERSE_S + (FAST_TRAVERSE_S - SLOW_TRAVERSE_S) * strength+++def comet_alpha(position: float, centre: float, flash: float) -> float:+ """How lit the edge is at `position` (0 to 1 along it) with the comet's head at `centre`: a dim+ base everywhere, raised to `flash` at breakthrough, and a peak that falls away over half the+ comet's length either side."""+ base = max(BEAM_BASE, min(1.0, flash))+ reach = max(0.0, 1.0 - abs(position - centre) / (COMET / 2.0))+ return base + (1.0 - base) * reach * reach+++class EdgeGlow(QWidget):+ def __init__(self) -> None:+ super().__init__(+ None,+ Qt.WindowType.Tool+ | Qt.WindowType.FramelessWindowHint+ | Qt.WindowType.WindowStaysOnTopHint+ | Qt.WindowType.WindowTransparentForInput+ | Qt.WindowType.WindowDoesNotAcceptFocus,+ )+ self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)+ self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)+ self._edge = "left"+ self._style = "glow"+ self._colour = "signal"+ self._pressure = 0.0+ self._flash = 0.0+ self._finish = 0.0+ self._centre = -COMET / 2.0+ self._updated_at = 0.0+ self._ticked_at = 0.0+ self._timer = QTimer(self)+ self._timer.setInterval(16)+ self._timer.timeout.connect(self._tick)++ def configure(self, style: str, colour: str) -> None:+ self._style = style+ self._colour = colour++ def set_pressure(self, edge: str, pressure: float, crossed: bool) -> None:+ now = time.monotonic()+ if edge != self._edge or self.isHidden():+ self._edge = edge+ self._place()+ self._pressure = 0.0 if crossed else max(0.0, min(1.0, pressure))+ if crossed:+ self._flash = 1.0+ self._finish = 1.0+ self._updated_at = now+ if self.isHidden():+ self._ticked_at = now+ self._centre = -COMET / 2.0+ self.show()+ self._timer.start()+ self.update()++ def _place(self) -> None:+ screens = QApplication.screens()+ if not screens:+ return+ rects = [crossing.Rect(s.geometry().x(), s.geometry().y(), s.geometry().width(), s.geometry().height()) for s in screens]+ owner = crossing.owning_monitor(rects, self._edge)+ if self._edge == "left":+ self.setGeometry(QRect(owner.x, owner.y, BAND_PX, owner.height))+ elif self._edge == "right":+ self.setGeometry(QRect(owner.right - BAND_PX + 1, owner.y, BAND_PX, owner.height))+ elif self._edge == "top":+ self.setGeometry(QRect(owner.x, owner.y, owner.width, BAND_PX))+ else:+ self.setGeometry(QRect(owner.x, owner.bottom - BAND_PX + 1, owner.width, BAND_PX))++ def _tick(self) -> None:+ now = time.monotonic()+ elapsed = now - self._ticked_at+ self._ticked_at = now+ # The model only decays when a delta arrives, so once the push stops+ # the glow fades on its own clock, matching the model's 400ms.+ if now - self._updated_at > STALE_SECONDS:+ self._pressure = max(0.0, self._pressure - elapsed / crossing.DECAY_SECONDS)+ self._flash = max(0.0, self._flash - elapsed / FLASH_SECONDS)+ if self._finish > 0.0:+ # Run on off the end of the edge instead of stopping, and never wrap back to the start.+ self._centre = min(1.0 + COMET, self._centre + elapsed / FINISH_TRAVERSE_S)+ self._finish = max(0.0, self._finish - elapsed / FINISH_SECONDS)+ else:+ self._centre += elapsed / traverse_seconds(self._pressure)+ if self._centre > 1.0 + COMET / 2.0:+ self._centre = -COMET / 2.0+ if self._pressure <= 0.0 and self._flash <= 0.0 and self._finish <= 0.0:+ self._timer.stop()+ self.hide()+ return+ self.update()++ def paintEvent(self, _event) -> None:+ beam = self._style == "beam"+ strength = max(self._pressure * 0.85, self._flash, self._finish if beam else 0.0)+ if strength <= 0.0:+ return+ along = self._edge in ("left", "right")+ length = self.height() if along else self.width()+ painter = QPainter(self)+ painter.setOpacity(strength)+ painter.fillRect(self.rect(), self._colours(along, length))+ painter.setOpacity(1.0)+ painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_DestinationIn)+ if beam:+ painter.fillRect(self.rect(), self._falloff(BAND_PX, BEAM_FALLOFF))+ painter.fillRect(self.rect(), self._comet(along, length))+ else:+ depth = BAND_PX * (0.35 + 0.65 * max(self._pressure, self._flash))+ painter.fillRect(self.rect(), self._falloff(depth, ((0.0, 1.0), (1.0, 0.0))))+ painter.end()++ def _gradient_along(self, along: bool, length: int) -> QLinearGradient:+ return QLinearGradient(0, 0, 0, length) if along else QLinearGradient(0, 0, length, 0)++ def _colours(self, along: bool, length: int) -> QLinearGradient:+ gradient = self._gradient_along(along, length)+ palette = tokens.PALETTES.get(self._colour, tokens.PALETTES["signal"])+ if len(palette) == 1:+ palette = palette * 2+ for index, value in enumerate(palette):+ gradient.setColorAt(index / (len(palette) - 1), QColor(value))+ return gradient++ def _falloff(self, depth: float, stops) -> QLinearGradient:+ width, height = self.width(), self.height()+ gradient = {+ "left": lambda: QLinearGradient(0, 0, depth, 0),+ "right": lambda: QLinearGradient(width, 0, width - depth, 0),+ "top": lambda: QLinearGradient(0, 0, 0, depth),+ }.get(self._edge, lambda: QLinearGradient(0, height, 0, height - depth))()+ for at, alpha in stops:+ gradient.setColorAt(at, QColor(0, 0, 0, round(255 * alpha)))+ return gradient++ def _comet(self, along: bool, length: int) -> QLinearGradient:+ gradient = self._gradient_along(along, length)+ for index in range(PROFILE_SAMPLES + 1):+ at = index / PROFILE_SAMPLES+ gradient.setColorAt(at, QColor(0, 0, 0, round(255 * comet_alpha(at, self._centre, self._flash))))+ return gradientdiff --git a/win_app/firewall_win.py b/win_app/firewall_win.pynew file mode 100644index 0000000..baaa4af--- /dev/null+++ b/win_app/firewall_win.py@@ -0,0 +1,358 @@+"""Windows Firewall as it applies to this executable: read it, explain it, repair it.++The only module that talks to the firewall. The shelling-out lives in `_powershell` and the+three public entry points that call it; everything else is pure so the interpretation runs+under unittest on the Mac, the same way receiver.py keeps input_injector at arm's length.+"""++from __future__ import annotations++from dataclasses import dataclass+import json+import logging+import os+import subprocess+import sys+from typing import Iterable, Optional, Sequence++import protocol++LOGGER = logging.getLogger(__name__)++RULE_NAME = "Beamer Receiver (TCP-In)"+# The pairing beacon's UDP port, written alongside the TCP rule by repair() and the installer.+# It is judged separately from the TCP rule because the two fail differently: without TCP the+# Mac cannot reach Beamer at all, while without UDP everything works except that a new Mac never+# sees this PC in its list -- and an install that predates the pairing rule has the first and+# not the second, so reporting only the TCP rule tells that user everything is fine.+PAIRING_RULE_NAME = "Beamer Pairing (UDP-In)"+PAIRING_PORT = protocol.PAIRING_PORT+_IS_WINDOWS = sys.platform == "win32"+++@dataclass(frozen=True)+class FirewallStatus:+ port: int+ allowed: bool+ blocked: bool+ active_profiles: tuple+ lan_profiles: tuple+ covered: bool+ public_interfaces: tuple+ elevated: bool+ error: str = ""+ # Whether the pairing beacon's UDP rule is present. Defaults True so a status built before+ # pairing existed does not claim a missing rule it knows nothing about.+ pairing_allowed: bool = True+++@dataclass(frozen=True)+class Advice:+ sentence: str+ button: str+ action: Optional[str]+ rule_profiles: tuple = ("Private",)+++# ---------------------------------------------------------------- interpretation (pure)+++def _normalise_path(path: str) -> str:+ return os.path.expandvars(path or "").replace("/", "\\").strip().lower()+++def _profiles(value) -> Optional[set]:+ """A rule's Profile as a set of names, or None for Any. Windows PowerShell renders the+ flags enum as "Private, Public"; a raw bitmask arrives if it ever does not."""+ if isinstance(value, int):+ if value == 0:+ return None+ return {name for bit, name in ((1, "Domain"), (2, "Private"), (4, "Public")) if value & bit}+ names = {part.strip() for part in str(value or "").split(",") if part.strip()}+ if not names or "Any" in names:+ return None+ return names+++def _port_matches(entries, port: int) -> bool:+ if entries is None:+ return True+ if isinstance(entries, (str, int)):+ entries = [entries]+ for entry in entries:+ text = str(entry).strip()+ if text.lower() == "any":+ return True+ if "-" in text:+ low, _, high = text.partition("-")+ if low.strip().isdigit() and high.strip().isdigit() and int(low) <= port <= int(high):+ return True+ elif text.isdigit() and int(text) == port:+ return True+ return False+++def _protocol_matches(value, wanted: str = "tcp") -> bool:+ text = str(value or "Any").strip().lower()+ return text in ("any", wanted, {"tcp": "6", "udp": "17"}[wanted])+++def _rule_applies(rule: dict, exe: str, port: int, protocol: str = "tcp") -> bool:+ return (+ str(rule.get("enabled", "")).lower() == "true"+ and str(rule.get("direction", "Inbound")).lower() == "inbound"+ and _normalise_path(str(rule.get("program", ""))) == _normalise_path(exe)+ and _protocol_matches(rule.get("protocol"), protocol)+ and _port_matches(rule.get("localPort"), port)+ )+++def _lan_networks(networks: Sequence[dict]) -> list:+ """The interface(s) the Mac would arrive on. Internet-connected first; a Hyper-V switch on+ Public with no route out is not the LAN and must not trigger the trust offer while Wi-Fi is+ Private, which is the owner's machine today."""+ ranked = {"internet": 3, "localnetwork": 2, "subnet": 1}+ best = 0+ for network in networks:+ score = max(ranked.get(str(network.get(key, "")).lower(), 0) for key in ("ipv4", "ipv6"))+ best = max(best, score)+ if best == 0:+ return list(networks)+ return [+ network+ for network in networks+ if max(ranked.get(str(network.get(key, "")).lower(), 0) for key in ("ipv4", "ipv6")) == best+ ]+++def interpret(payload: dict, exe: str, port: int, elevated: bool = True) -> FirewallStatus:+ rules = [rule for rule in payload.get("rules", []) if _rule_applies(rule, exe, port)]+ networks = list(payload.get("networks", []))+ active = tuple(sorted({str(n.get("category", "")) for n in networks if n.get("category")}))+ lan = _lan_networks(networks)+ lan_profiles = tuple(sorted({str(n.get("category", "")) for n in lan if n.get("category")}))++ allow_profiles = [_profiles(r.get("profile")) for r in rules if str(r.get("action", "")).lower() == "allow"]+ block_profiles = [_profiles(r.get("profile")) for r in rules if str(r.get("action", "")).lower() == "block"]++ def touches(profile_set: Optional[set], wanted: Iterable[str]) -> bool:+ return profile_set is None or any(name in profile_set for name in wanted)++ # A block rule beats an allow rule on any profile they share, so a block scoped to a+ # profile nothing is connected to is harmless and must not send the user chasing it.+ blocked = any(touches(p, active or ("Domain", "Private", "Public")) for p in block_profiles)+ covered = all(any(touches(p, (name,)) for p in allow_profiles) for name in lan_profiles) and bool(allow_profiles)+ public = tuple((int(n.get("index", 0)), str(n.get("alias", ""))) for n in lan if str(n.get("category", "")) == "Public")+ pairing_rules = [+ rule for rule in payload.get("rules", [])+ if _rule_applies(rule, exe, PAIRING_PORT, "udp")+ and str(rule.get("action", "")).lower() == "allow"+ ]+ return FirewallStatus(+ port=port,+ allowed=bool(allow_profiles),+ blocked=blocked,+ active_profiles=active,+ lan_profiles=lan_profiles,+ covered=covered,+ public_interfaces=public,+ elevated=elevated,+ error="",+ pairing_allowed=bool(pairing_rules),+ )+++def advise(status: FirewallStatus) -> Advice:+ """One sentence a non-technical person can act on, and the one button that fixes it."""+ port = status.port+ rule_profiles = ("Private",) + (("Domain",) if "DomainAuthenticated" in status.lan_profiles else ())+ if status.error:+ return Advice(f"Beamer could not read the Windows Firewall: {status.error}", "Check again", "check")+ if status.blocked:+ advice = Advice(+ f"Windows Firewall is blocking Beamer on port {port}. This happens when Cancel was pressed on "+ "Windows' own \"allow this app\" prompt, and a block rule beats any allow rule, so reinstalling "+ "does not clear it. Fixing it removes the block and adds the right rule for private networks.",+ "Fix the firewall",+ "repair",+ rule_profiles,+ )+ elif not status.allowed:+ advice = Advice(+ f"Windows Firewall has no rule letting your Mac reach Beamer on port {port}, so the Mac will say "+ "Windows is unreachable. This happens when the installer was run without administrator rights. "+ "Fixing it adds the rule for private networks.",+ "Fix the firewall",+ "repair",+ rule_profiles,+ )+ elif not status.covered and status.public_interfaces:+ names = ", ".join(alias for _, alias in status.public_interfaces if alias) or "this network"+ advice = Advice(+ f"Windows treats {names} as a public network, so Beamer's firewall rule does not apply on it and "+ "your Mac cannot get in. Trusting it marks the network as private, which lets the Mac in without "+ "opening the port on every other network this PC joins.",+ "Trust this network",+ "trust",+ )+ elif not status.covered:+ names = ", ".join(status.lan_profiles)+ advice = Advice(+ f"Beamer's firewall rule does not apply on this network (Windows calls it {names}). "+ "Fixing it rewrites the rule to cover it.",+ "Fix the firewall",+ "repair",+ rule_profiles,+ )+ elif not status.pairing_allowed:+ advice = Advice(+ f"Windows Firewall lets your Mac reach Beamer on port {port}, but there is no rule for the "+ f"pairing beacon on UDP {PAIRING_PORT}, so a Mac that has not been set up by hand will never "+ "see this PC in its list. Installs made before pairing existed are missing it. Fixing it adds "+ "the missing rule and leaves the working one alone.",+ "Fix the firewall",+ "repair",+ rule_profiles,+ )+ else:+ where = "this private network" if "Private" in status.lan_profiles else "this network"+ return Advice(+ f"Windows Firewall lets your Mac reach Beamer on port {port} on {where}, and lets a new Mac "+ "discover this PC.",+ "Check again",+ "check",+ )+ if not status.elevated:+ return Advice(+ advice.sentence + " Beamer is not running as administrator, so it cannot make this change itself: "+ "quit Beamer and open it again from the Start menu.",+ advice.button,+ None,+ advice.rule_profiles,+ )+ return advice+++# ---------------------------------------------------------------- Windows+++def _quote(value) -> str:+ return "'" + str(value).replace("'", "''") + "'"+++def _powershell(script: str, timeout: float = 60.0) -> str:+ if not _IS_WINDOWS:+ raise RuntimeError("Windows Firewall is only available on Windows")+ exe = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "WindowsPowerShell", "v1.0", "powershell.exe")+ # A GUI app must never flash a console: CREATE_NO_WINDOW plus a hidden STARTUPINFO covers+ # both the console host and any window the child asks for.+ startupinfo = subprocess.STARTUPINFO()+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW+ startupinfo.wShowWindow = subprocess.SW_HIDE+ completed = subprocess.run(+ [exe, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script],+ capture_output=True,+ timeout=timeout,+ creationflags=subprocess.CREATE_NO_WINDOW,+ startupinfo=startupinfo,+ )+ stdout = completed.stdout.decode("utf-8", errors="replace")+ stderr = completed.stderr.decode("utf-8", errors="replace").strip()+ if completed.returncode != 0:+ raise RuntimeError(stderr.splitlines()[0] if stderr else f"PowerShell exited with code {completed.returncode}")+ return stdout+++_PREAMBLE = "$ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8;"++# A bare Remove-NetFirewallRule deletes every rule on the machine, so the repair script only ever+# pipes into it from a non-empty, explicitly counted collection.+# Every rule whose program is a Beamer.exe, wherever it lives: our named rule, the pair Windows+# writes from its own prompt, and any left by an older install path. The exact-path match+# happens in interpret(), so a rule for a stale copy shows up as "no rule" rather than a pass.+_RULES_FOR_LEAF = (+ "$leaf = Split-Path -Leaf $exe; "+ "Get-NetFirewallApplicationFilter | Where-Object { $_.Program -and ($_.Program -like ('*\\' + $leaf)) }"+)++_STATUS_SCRIPT = _PREAMBLE + """+$exe = {exe}+$rules = @()+foreach ($filter in $({filters})) {{+ $rule = $filter | Get-NetFirewallRule+ if ([string]$rule.Direction -ne 'Inbound') {{ continue }}+ $portFilter = $rule | Get-NetFirewallPortFilter+ $rules += [pscustomobject]@{{+ name = $rule.Name; display = $rule.DisplayName; enabled = [string]$rule.Enabled+ action = [string]$rule.Action; direction = [string]$rule.Direction; profile = [string]$rule.Profile+ program = $filter.Program; protocol = [string]$portFilter.Protocol; localPort = @($portFilter.LocalPort)+ }}+}}+$networks = @(Get-NetConnectionProfile | ForEach-Object {{+ [pscustomobject]@{{+ alias = $_.InterfaceAlias; index = [int]$_.InterfaceIndex; category = [string]$_.NetworkCategory+ ipv4 = [string]$_.IPv4Connectivity; ipv6 = [string]$_.IPv6Connectivity+ }}+}})+[pscustomobject]@{{ rules = @($rules); networks = $networks }} | ConvertTo-Json -Depth 4 -Compress+"""++_REPAIR_SCRIPT = _PREAMBLE + """+$exe = {exe}+$stale = @($({filters}) | Get-NetFirewallRule | Where-Object {{ [string]$_.Direction -eq 'Inbound' }})+$stale += @(Get-NetFirewallRule -DisplayName {name} -ErrorAction SilentlyContinue)+$stale += @(Get-NetFirewallRule -DisplayName {pairing_name} -ErrorAction SilentlyContinue)+if ($stale.Count -gt 0) {{ $stale | Remove-NetFirewallRule }}+New-NetFirewallRule -DisplayName {name} -Direction Inbound -Protocol TCP -LocalPort {port} -Action Allow -Profile {profiles} -Program $exe | Out-Null+New-NetFirewallRule -DisplayName {pairing_name} -Direction Inbound -Protocol UDP -LocalPort {pairing_port} -Action Allow -Profile {profiles} -Program $exe | Out-Null+"""++_TRUST_SCRIPT = _PREAMBLE + """+foreach ($index in @({indexes})) {{ Set-NetConnectionProfile -InterfaceIndex $index -NetworkCategory Private }}+"""+++def is_elevated() -> bool:+ if not _IS_WINDOWS:+ return False+ try:+ import ctypes++ return bool(ctypes.windll.shell32.IsUserAnAdmin())+ except Exception:+ LOGGER.debug("Elevation check failed", exc_info=True)+ return False+++def status(exe: str, port: int) -> FirewallStatus:+ elevated = is_elevated()+ try:+ raw = _powershell(_STATUS_SCRIPT.format(exe=_quote(exe), filters=_RULES_FOR_LEAF))+ return interpret(json.loads(raw), exe, port, elevated)+ except Exception as exc:+ LOGGER.exception("Firewall status failed")+ return FirewallStatus(port, False, False, (), (), False, (), elevated, error=str(exc) or type(exc).__name__)+++def repair(exe: str, port: int, profiles: Sequence[str] = ("Private",)) -> None:+ """Drop every inbound rule for this executable, blocking ones included, and write the one+ the installer would have. Never Public: that opens the port on every untrusted network the+ machine ever joins, which is the wrong trade for a KVM; trust_network() is the fix for that."""+ wanted = [p for p in profiles if p in ("Private", "Domain")] or ["Private"]+ _powershell(+ _REPAIR_SCRIPT.format(+ exe=_quote(exe),+ filters=_RULES_FOR_LEAF,+ name=_quote(RULE_NAME),+ port=int(port),+ pairing_name=_quote(PAIRING_RULE_NAME),+ pairing_port=PAIRING_PORT,+ profiles=",".join(wanted),+ )+ )+++def trust_network(interface_indexes: Sequence[int]) -> None:+ if not interface_indexes:+ return+ _powershell(_TRUST_SCRIPT.format(indexes=",".join(str(int(i)) for i in interface_indexes)))diff --git a/win_app/input_injector.py b/win_app/input_injector.pynew file mode 100644index 0000000..f28784d--- /dev/null+++ b/win_app/input_injector.py@@ -0,0 +1,485 @@+"""Win32 SendInput keyboard and mouse injection."""++import ctypes+import functools+import logging+import sys+import threading+from typing import Callable, Dict, List, Optional, Set, Tuple+++LOGGER = logging.getLogger(__name__)++_IS_WINDOWS = sys.platform == "win32"++user32 = ctypes.WinDLL("user32", use_last_error=True) if _IS_WINDOWS else None++if _IS_WINDOWS:+ user32.VkKeyScanW.restype = ctypes.c_short+ user32.VkKeyScanW.argtypes = [ctypes.c_wchar]+ user32.MapVirtualKeyW.restype = ctypes.c_uint+ user32.MapVirtualKeyW.argtypes = [ctypes.c_uint, ctypes.c_uint]++INPUT_MOUSE = 0+INPUT_KEYBOARD = 1++# Stamped into the dwExtraInfo of every INPUT this module sends, and the same+# value the Mac stamps into kCGEventSourceUserData. Raw Input has no injected+# flag: a SendInput move reaches a WM_INPUT sink exactly as the hand's does,+# hDevice NULL, and this value coming back in RAWMOUSE.ulExtraInformation is+# the only thing that tells the two apart (proved on the rig, 19-09-2026).+INJECTED_MARK = 0xBEA3++KEYEVENTF_EXTENDEDKEY = 0x0001+KEYEVENTF_KEYUP = 0x0002+KEYEVENTF_UNICODE = 0x0004++MAPVK_VK_TO_VSC = 0++MOUSEEVENTF_MOVE = 0x0001+MOUSEEVENTF_LEFTDOWN = 0x0002+MOUSEEVENTF_LEFTUP = 0x0004+MOUSEEVENTF_RIGHTDOWN = 0x0008+MOUSEEVENTF_RIGHTUP = 0x0010+MOUSEEVENTF_MIDDLEDOWN = 0x0020+MOUSEEVENTF_MIDDLEUP = 0x0040+MOUSEEVENTF_WHEEL = 0x0800+MOUSEEVENTF_HWHEEL = 0x1000+MOUSEEVENTF_VIRTUALDESK = 0x4000+MOUSEEVENTF_ABSOLUTE = 0x8000++ULONG_PTR = ctypes.c_size_t+++class MOUSEINPUT(ctypes.Structure):+ _fields_ = [+ ("dx", ctypes.c_long),+ ("dy", ctypes.c_long),+ ("mouseData", ctypes.c_ulong),+ ("dwFlags", ctypes.c_ulong),+ ("time", ctypes.c_ulong),+ ("dwExtraInfo", ULONG_PTR),+ ]+++class KEYBDINPUT(ctypes.Structure):+ _fields_ = [+ ("wVk", ctypes.c_ushort),+ ("wScan", ctypes.c_ushort),+ ("dwFlags", ctypes.c_ulong),+ ("time", ctypes.c_ulong),+ ("dwExtraInfo", ULONG_PTR),+ ]+++class _INPUTUNION(ctypes.Union):+ _fields_ = [("mi", MOUSEINPUT), ("ki", KEYBDINPUT)]+++class INPUT(ctypes.Structure):+ _fields_ = [("type", ctypes.c_ulong), ("union", _INPUTUNION)]+++def _send_input(*inputs: INPUT) -> None:+ if user32 is None:+ raise RuntimeError("Win32 SendInput is only available on Windows")+ count = len(inputs)+ array = (INPUT * count)(*inputs)+ sent = user32.SendInput(count, array, ctypes.sizeof(INPUT))+ if sent != count:+ raise ctypes.WinError(ctypes.get_last_error())+++def _vk_key_scan(ch: str) -> int:+ """Look up the VK + shift-state byte for a character via VkKeyScanW.++ Returns the raw 16-bit result (low byte VK, high byte shift state) or+ -1 if the character can't be produced by the current keyboard layout.+ """+ if user32 is None:+ raise RuntimeError("VkKeyScanW is only available on Windows")+ return user32.VkKeyScanW(ch)+++def _map_virtual_key(vk: int) -> int:+ """Look up the hardware scan code for a virtual-key code."""+ if user32 is None:+ raise RuntimeError("MapVirtualKeyW is only available on Windows")+ return user32.MapVirtualKeyW(vk, MAPVK_VK_TO_VSC)+++VK_MAP = {+ "enter": 0x0D,+ "return": 0x0D,+ "esc": 0x1B,+ "escape": 0x1B,+ "tab": 0x09,+ "space": 0x20,+ "backspace": 0x08,+ "delete": 0x2E,+ "home": 0x24,+ "end": 0x23,+ "page_up": 0x21,+ "page_down": 0x22,+ "up": 0x26,+ "down": 0x28,+ "left": 0x25,+ "right": 0x27,+ "shift": 0xA0,+ "shift_r": 0xA1,+ "ctrl": 0xA2,+ "ctrl_r": 0xA3,+ "alt": 0xA4,+ "alt_r": 0xA5,+ "cmd": 0x5B,+ "cmd_r": 0x5C,+ "caps_lock": 0x14,+ "insert": 0x2D,+ "menu": 0x5D,+ "num_lock": 0x90,+ "scroll_lock": 0x91,+ "print_screen": 0x2C,+ "pause": 0x13,+ "media_play_pause": 0xB3,+ "media_next": 0xB0,+ "media_prev": 0xB1,+ "media_stop": 0xB2,+ "volume_mute": 0xAD,+ "volume_down": 0xAE,+ "volume_up": 0xAF,+ "browser_back": 0xA6,+ "browser_forward": 0xA7,+}++for _index in range(1, 13):+ VK_MAP[f"f{_index}"] = 0x70 + (_index - 1)+for _index in range(13, 21):+ VK_MAP[f"f{_index}"] = 0x7C + (_index - 13)++# Named keys that require the extended-key flag (E0 scan prefix) so games,+# RDP sessions and low-level keyboard hooks read them correctly.+EXTENDED_KEYS = {+ "up",+ "down",+ "left",+ "right",+ "insert",+ "delete",+ "home",+ "end",+ "page_up",+ "page_down",+ "ctrl_r",+ "alt_r",+ "cmd",+ "cmd_r",+ "num_lock",+ "print_screen",+ "media_play_pause",+ "media_next",+ "media_prev",+ "media_stop",+ "volume_mute",+ "volume_down",+ "volume_up",+ "browser_back",+ "browser_forward",+}++# Modifier key names that participate in chording with character keys.+MODIFIER_KEYS = {"ctrl", "ctrl_r", "alt", "alt_r", "cmd", "cmd_r", "shift", "shift_r"}++# Either shift key satisfies a VkKeyScanW "shift required" result: the Mac+# forwards shift physically as its own keydown/keyup, so if one is currently+# held, the keyboard state agrees with what VkKeyScanW resolved the+# character from.+SHIFT_KEYS = {"shift", "shift_r"}++VkLookup = Callable[[str], int]+ScanLookup = Callable[[int], int]++# Characters we've already logged an unsupported-combo warning for, so we+# don't spam the log for every repeat keypress.+_warned_chars: Set[str] = set()+++def _keybd_input(vk: int, scan: int, flags: int) -> INPUT:+ key_input = KEYBDINPUT(wVk=vk, wScan=scan, dwFlags=flags, time=0, dwExtraInfo=INJECTED_MARK)+ return INPUT(type=INPUT_KEYBOARD, union=_INPUTUNION(ki=key_input))+++def plan_key_inputs(+ name: str,+ down: bool,+ mods_down: Set[str],+ char_vk_down: Dict[str, int],+ vk_lookup: VkLookup,+ scan_lookup: ScanLookup,+) -> List[Tuple[int, int, int]]:+ """Pure planning logic: decide which (wVk, wScan, flags) tuples to send.++ Mutates mods_down / char_vk_down to track state across calls, exactly+ like inject_key does, so callers (tests) can inspect the bookkeeping.+ Returns an empty list if the key should be dropped.+ """+ keyup_flag = 0 if down else KEYEVENTF_KEYUP+ lowered = name.lower()++ if lowered in MODIFIER_KEYS:+ if down:+ mods_down.add(lowered)+ else:+ mods_down.discard(lowered)++ # Named key (arrows, modifiers, function keys, etc.)+ if lowered in VK_MAP:+ vk = VK_MAP[lowered]+ scan = scan_lookup(vk)+ flags = keyup_flag+ if lowered in EXTENDED_KEYS:+ flags |= KEYEVENTF_EXTENDEDKEY+ return [(vk, scan, flags)]++ # Single character. Prefer the real VK+scan keystroke path whenever the+ # current keyboard layout can produce it plainly, or with only the shift+ # state the Mac is already physically forwarding -- not just when a+ # chord modifier (ctrl/alt/win) happens to be held. A bare character+ # sent purely as KEYEVENTF_UNICODE produces WM_CHAR-style text but no+ # usable keyCode, so anything listening for a real keydown (games, media+ # shortcuts like YouTube's "k" to pause) never sees it, even though a+ # text field happily receives the character. Unicode remains the+ # fallback for whatever the VK path can't safely cover.+ if len(name) == 1:+ ch = name+ if not down:+ if ch in char_vk_down:+ vk = char_vk_down.pop(ch)+ scan = scan_lookup(vk)+ return [(vk, scan, KEYEVENTF_KEYUP)]+ return [(0, ord(ch), KEYEVENTF_UNICODE | KEYEVENTF_KEYUP)]++ result = vk_lookup(ch)+ if result == -1:+ if ch not in _warned_chars:+ LOGGER.warning("Unsupported character for this keyboard layout: %r", ch)+ _warned_chars.add(ch)+ return [(0, ord(ch), KEYEVENTF_UNICODE | keyup_flag)]++ vk = result & 0xFF+ shift_state = (result >> 8) & 0xFF+ shift_only = shift_state == 0x01+ if shift_state == 0 or (shift_only and mods_down & SHIFT_KEYS):+ scan = scan_lookup(vk)+ char_vk_down[ch] = vk+ return [(vk, scan, keyup_flag)]+ if shift_state & 0xFE:+ # Needs ctrl/alt (AltGr) or some other combo bit we can't+ # fabricate without also toggling a modifier the user isn't+ # actually holding.+ if ch not in _warned_chars:+ LOGGER.warning("Combo not possible for this character on this layout: %r", ch)+ _warned_chars.add(ch)+ # else: shift is required but not currently held -- e.g. a capital+ # produced by caps-lock rather than a physical shift press. Trusting+ # the VK here would desync from the real keyboard state, so this+ # falls back to Unicode silently (it's not a broken layout, just a+ # state VkKeyScanW can't be told about); typing stays correct.+ return [(0, ord(ch), KEYEVENTF_UNICODE | keyup_flag)]++ LOGGER.warning("Unknown key name ignored: %r", name)+ return []+++_mods_down: Set[str] = set()+_char_vk_down: Dict[str, int] = {}+# One lock over the held-key bookkeeping and the send it describes: a session+# thread injecting while a reconnect's release_all snapshots and clears would+# otherwise press a key that nothing then remembers to release.+_state_lock = threading.RLock()+++def _locked(function):+ @functools.wraps(function)+ def wrapper(*args, **kwargs):+ with _state_lock:+ return function(*args, **kwargs)++ return wrapper+++@_locked+def inject_key(name: str, down: bool) -> None:+ LOGGER.debug("key %s %s (mods held: %s)", name, "down" if down else "up", sorted(_mods_down))+ plan = plan_key_inputs(name, down, _mods_down, _char_vk_down, _vk_key_scan, _map_virtual_key)+ if not plan:+ return+ _send_input(*(_keybd_input(vk, scan, flags) for vk, scan, flags in plan))+++def _mouse_input(dx: int, dy: int, data: int, flags: int) -> INPUT:+ mouse_input = MOUSEINPUT(dx=dx, dy=dy, mouseData=data, dwFlags=flags, time=0, dwExtraInfo=INJECTED_MARK)+ return INPUT(type=INPUT_MOUSE, union=_INPUTUNION(mi=mouse_input))+++def inject_mouse_move(dx: int, dy: int) -> None:+ _send_input(_mouse_input(dx, dy, 0, MOUSEEVENTF_MOVE))+++def inject_mouse_absolute(nx: int, ny: int) -> None:+ """nx, ny normalised 0-65535 across the whole virtual desktop."""+ _send_input(_mouse_input(nx, ny, 0, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK))+++BUTTON_DOWN_FLAGS = {+ "left": MOUSEEVENTF_LEFTDOWN,+ "right": MOUSEEVENTF_RIGHTDOWN,+ "middle": MOUSEEVENTF_MIDDLEDOWN,+}++BUTTON_UP_FLAGS = {+ "left": MOUSEEVENTF_LEFTUP,+ "right": MOUSEEVENTF_RIGHTUP,+ "middle": MOUSEEVENTF_MIDDLEUP,+}+++_buttons_down: Set[str] = set()+++@_locked+def inject_mouse_button(button: str, down: bool) -> None:+ flags = (BUTTON_DOWN_FLAGS if down else BUTTON_UP_FLAGS).get(button)+ if flags is None:+ LOGGER.warning("Unknown mouse button ignored: %r", button)+ return+ if down:+ _buttons_down.add(button)+ else:+ _buttons_down.discard(button)+ _send_input(_mouse_input(0, 0, 0, flags))+++@_locked+def release_all() -> None:+ """Let go of every key and button this module is holding, the twin of+ input_injector_mac.release_all: the receiver calls it when the peer's+ input goes home or its link dies, so a modifier held through a switch+ does not stay down on this PC."""+ for name in sorted(_mods_down):+ try:+ inject_key(name, down=False)+ except Exception:+ LOGGER.exception("Could not release %r", name)+ for ch in sorted(_char_vk_down):+ try:+ inject_key(ch, down=False)+ except Exception:+ LOGGER.exception("Could not release %r", ch)+ 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)+ _mods_down.clear()+ _char_vk_down.clear()+ _buttons_down.clear()+++# Continuous (trackpad) scroll deltas arrive in points, not wheel "clicks".+# This converts px -> the same 120-per-notch wheel-unit scale a discrete+# click uses, so pixel-mode motion feels proportionate to line-mode motion.+# Tunable: raise it to make trackpad scrolling slower, lower it for faster.+WHEEL_UNITS_PER_PIXEL = 120 / 40 # 3.0++# Fractional wheel units carried across calls, per axis, for pixel-mode+# scroll (see plan_scroll_units). Module state, like _mods_down/_char_vk_down+# above: there is one physical scroll wheel to drive, regardless of how many+# scroll messages arrive.+_scroll_accum = [0.0, 0.0] # [y, x]+++def plan_scroll_units(dy, dx, mode: str, accum: List[float]) -> Tuple[int, int]:+ """Pure planning logic: decide the whole wheel-unit deltas to send for one+ scroll event, given accumulator state `accum` (a mutable [y, x] pair,+ mutated in place so callers/tests can inspect the carried residue exactly+ like inject_scroll does). Returns (whole_y, whole_x); either may be 0,+ meaning nothing to send on that axis for this event.++ mode "line": dy/dx are whole wheel clicks (as sent by a discrete mouse+ wheel); each maps to +/-120 wheel units -- unchanged from before dx/mode+ existed.++ mode "pixel": dy/dx are continuous trackpad point deltas; converted to+ wheel units via WHEEL_UNITS_PER_PIXEL and accumulated across calls so+ slow, precise motion isn't lost to integer truncation.++ Sign convention: the vertical mapping below (dy -> +120 per unit) is+ intentionally unchanged from today's dy*120 behaviour, whatever that+ already works out to with Mac natural scrolling. MOUSEEVENTF_HWHEEL's+ positive mouseData means "scroll right" (the mirror of+ MOUSEEVENTF_WHEEL, where positive means "scroll up/away"); dx is+ forwarded without an extra sign flip, on the assumption that a rightward+ two-finger swipe on the Mac should scroll content right on Windows, the+ same direction it would on the Mac itself. That assumption -- and the+ WHEEL_UNITS_PER_PIXEL constant above -- still needs confirming on real+ trackpad/mouse hardware; both are easy to retune if the felt direction or+ speed is wrong.+ """+ if mode == "pixel":+ accum[0] += dy * WHEEL_UNITS_PER_PIXEL+ accum[1] += dx * WHEEL_UNITS_PER_PIXEL+ else:+ accum[0] += int(dy) * 120+ accum[1] += int(dx) * 120+ whole_y = int(accum[0])+ whole_x = int(accum[1])+ accum[0] -= whole_y+ accum[1] -= whole_x+ return whole_y, whole_x+++def inject_scroll(dy, dx=0.0, mode: str = "line") -> None:+ whole_y, whole_x = plan_scroll_units(dy, dx, mode, _scroll_accum)+ if whole_y:+ _send_input(_mouse_input(0, 0, whole_y, MOUSEEVENTF_WHEEL))+ if whole_x:+ _send_input(_mouse_input(0, 0, whole_x, MOUSEEVENTF_HWHEEL))+++# What each Mac gesture becomes here: first a real touchpad swipe, replayed+# through a synthetic Precision Touchpad so this PC's own Settings > Touchpad+# choices apply and Task View animates as it would under fingers; if that+# device cannot be made, the shortcut that means the same thing by default.+# Finger direction maps 1:1 because content follows the fingers on both+# systems: fingers moving left reveal the desktop on the right, which is+# Win+Ctrl+Right. Launchpad has no touchpad gesture on Windows, so it opens+# Start. "cmd" is the Windows key in VK_MAP.+GESTURE_PLAN: Dict[str, Tuple[Optional[Tuple[int, str]], Tuple[str, ...]]] = {+ "swipe_up": ((3, "up"), ("cmd", "tab")),+ "swipe_down": ((3, "down"), ("cmd", "d")),+ "spread": ((3, "down"), ("cmd", "d")),+ "swipe_left": ((4, "left"), ("cmd", "ctrl", "right")),+ "swipe_right": ((4, "right"), ("cmd", "ctrl", "left")),+ "pinch": (None, ("cmd",)),+}+++def inject_gesture(name: str, swipe=None) -> None:+ """`swipe` is touchpad_injector.swipe unless a test passes its own; it+ returns False when Windows refuses, and the chord is pressed instead."""+ plan = GESTURE_PLAN.get(name)+ if plan is None:+ LOGGER.warning("Unknown gesture ignored: %r", name)+ return+ touchpad, chord = plan+ if touchpad is not None:+ if swipe is None:+ import touchpad_injector++ swipe = touchpad_injector.swipe+ if swipe(*touchpad):+ return+ for key in chord:+ inject_key(key, down=True)+ for key in reversed(chord):+ inject_key(key, down=False)diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.pynew file mode 100644index 0000000..5105c07--- /dev/null+++ b/win_app/kvm_bridge_win.py@@ -0,0 +1,1321 @@+import argparse+import ctypes+from dataclasses import replace+import logging+from logging.handlers import RotatingFileHandler+import os+from pathlib import Path+import sys+import tempfile+import threading+import time+from typing import Optional++from PySide6.QtCore import QObject, QRectF, QSize, QTimer, Qt, Signal+from PySide6.QtGui import QColor, QIcon, QKeySequence, QPainter, QPixmap, QShortcut+from PySide6.QtWidgets import (+ QApplication,+ QCheckBox,+ QFrame,+ QGridLayout,+ QHBoxLayout,+ QLineEdit,+ QMenu,+ QMessageBox,+ QPushButton,+ QScrollArea,+ QSlider,+ QStackedWidget,+ QSystemTrayIcon,+ QVBoxLayout,+ QWidget,+)++from app_config import (+ Config,+ ConfigError,+ TRIGGER_KEYS,+ default_config,+ default_config_path,+ load_config,+ migrate_legacy_config,+ save_config,+)+import autostart_win+import capture_win+from edge_glow import EdgeGlow+import firewall_win+from pairing import PAIRING_PORT, Announcer, local_address_towards+import pages_win+import protocol+from receiver import ReceiverServer, ServerState+import return_edge+import sender+from sender import MacSender+import theme+import tokens+import widgets++LOGGER = logging.getLogger(__name__)++# The repo-root VERSION file is the one place the version is set; build.spec bundles it.+try:+ VERSION = (Path(getattr(sys, "_MEIPASS", None) or Path(__file__).resolve().parent.parent) / "VERSION").read_text().strip()+except OSError:+ VERSION = "dev"++IDLE_CODE = "––– –––"+PAIR_HINT = "Press Pair a Mac, then type this code into Beamer on the Mac."++STATUS_TITLES = {+ ServerState.STOPPED: "Receiver stopped",+ ServerState.WAITING: "Waiting for your Mac",+ ServerState.CONNECTED: "Mac connected",+ ServerState.ERROR: "Receiver needs attention",+}++# The short word beside the sidebar's link dot -- STATUS_TITLES is a sentence, this is one word.+SIDEBAR_LINK_WORDS = {+ ServerState.STOPPED: "Stopped",+ ServerState.WAITING: "Waiting",+ ServerState.CONNECTED: "Linked",+ ServerState.ERROR: "Error",+}++HEADING_ROLE = {+ "signal": "heading",+ "off": "heading",+ "amber": "heading",+ "fault": "heading-fault",+}++EDGE_CHOICES = (("left", "Left"), ("right", "Right"), ("top", "Top"), ("bottom", "Bottom"))+CORNER_CHOICES = (+ ("top_left", "Top-left"),+ ("top_right", "Top-right"),+ ("bottom_left", "Bottom-left"),+ ("bottom_right", "Bottom-right"),+)+TRIGGER_STYLE_CHOICES = (("double_tap", "Double-tap"), ("hold", "Hold"))+GLOW_STYLE_CHOICES = (("glow", "Glow"), ("beam", "Beam"))+GLOW_COLOUR_CHOICES = (+ ("signal", "Signal"),+ ("colourful", "Colourful"),+ ("ocean", "Ocean"),+ ("sunset", "Sunset"),+ ("mono", "Mono"),+)+# How long a dragged slider waits, still, before the value it settled on is written to disk.+SETTLE_MS = 300+++def asset_path(name: str) -> Path:+ """Locate a bundled asset, honouring PyInstaller's onefile extraction dir."""+ if getattr(sys, "frozen", False):+ base = Path(getattr(sys, "_MEIPASS", Path(sys.executable).resolve().parent))+ else:+ base = Path(__file__).resolve().parent+ return base / name+++ICON_PATH = asset_path("Beamer.ico")+++def configure_logging() -> Optional[Path]:+ candidates = [default_config_path().parent, Path(tempfile.gettempdir()) / "Beamer"]+ for directory in candidates:+ try:+ directory.mkdir(parents=True, exist_ok=True)+ log_path = directory / "Beamer.log"+ handler = RotatingFileHandler(log_path, maxBytes=1_000_000, backupCount=3, encoding="utf-8")+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(threadName)s %(message)s"))+ root_logger = logging.getLogger()+ # BEAMER_DEBUG=1 logs every injected key by name, which is the only+ # way to tell a key the Mac never sent from one Windows swallowed.+ root_logger.setLevel(logging.DEBUG if os.environ.get("BEAMER_DEBUG") else logging.INFO)+ root_logger.addHandler(handler)+ return log_path+ except OSError:+ continue+ logging.basicConfig(level=logging.INFO)+ return None+++def status_icon(state: ServerState, size: int = 64) -> QPixmap:+ """The shipped colour mark with the state dot over its lower right corner, as Vernier's tray+ table draws it: signal connected, amber waiting, fault needs attention, off stopped."""+ # Ratio pinned to 1: the plain pixmap(size, size) comes back at the screen's scale (96px at+ # 150%), which once failed a width check and left the tray showing only the dot.+ pixmap = QIcon(str(ICON_PATH)).pixmap(QSize(size, size), 1.0)+ if pixmap.isNull() or pixmap.width() != size:+ pixmap = QPixmap(size, size)+ pixmap.fill(QColor(theme.colour("panel")))+ unit = size / 16+ dot = 6 * unit+ painter = QPainter(pixmap)+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)+ painter.setPen(Qt.PenStyle.NoPen)+ painter.setBrush(QColor(theme.colour("ground")))+ painter.drawEllipse(QRectF(size - dot - 2 * unit, size - dot - 2 * unit, dot + 2 * unit, dot + 2 * unit))+ painter.setBrush(QColor(theme.state_colour(state.value.lower())))+ painter.drawEllipse(QRectF(size - dot - unit, size - dot - unit, dot, dot))+ painter.end()+ return pixmap+++class StatusBridge(QObject):+ """Marshals receiver-thread status callbacks onto the GUI thread."""++ changed = Signal(object, str)+ pressure = Signal(str, float, bool)+ firewall = Signal(object)+ paired = Signal(str, str, str)+ # The other direction: this PC's own input going to the Mac.+ sending = Signal(bool, str)+ redirecting = Signal(bool)+ focus = Signal(str)+ learned = Signal(str, object, object)+ # Either link, telling us the two machines' arrangement changed at the other end.+ arrangement = Signal(str, int)+++class WindowsApplication(QWidget):+ def __init__(self, config_path: Path) -> None:+ super().__init__()+ self.config_path = config_path+ self._status_lock = threading.RLock()+ self._status = ServerState.STOPPED+ self._status_detail = "Initialising"+ self._config = None+ self._closing = False+ self._page = "overview"+ self._apply_serial = 0+ self.bridge = StatusBridge()+ self.bridge.changed.connect(self._on_status)+ self.bridge.pressure.connect(self._on_pressure)+ self.bridge.firewall.connect(self._on_firewall)+ self.bridge.paired.connect(self._on_paired)+ self.bridge.sending.connect(self._on_sending)+ self.bridge.redirecting.connect(self._on_redirecting)+ self.bridge.focus.connect(self._on_focus)+ self.bridge.learned.connect(self._on_learned)+ self.bridge.arrangement.connect(self._on_arrangement)+ # Announces this PC from launch, configured or not: pairing is how a fresh install+ # gets its token, so it cannot wait for the receiver to be listening.+ self.announcer = Announcer(self._announced_port, self.bridge.paired.emit, logger=LOGGER)+ self._code_shown = False+ self._firewall_advice: Optional[firewall_win.Advice] = None+ self._firewall_status: Optional[firewall_win.FirewallStatus] = None+ self._firewall_tone: Optional[str] = None+ self._firewall_busy = False+ self._firewall_again = False+ self._firewall_auto_repaired = False+ self._host = default_config().host+ self._last_seen_state: Optional[ServerState] = None+ self.glow: Optional[EdgeGlow] = None+ self.server = ReceiverServer(+ self._set_status,+ pressure_callback=self.bridge.pressure.emit,+ focus_callback=self.bridge.focus.emit,+ peer_callback=self.bridge.learned.emit,+ arrangement_callback=self.bridge.arrangement.emit,+ )+ # The second link, outwards: this PC's keyboard and mouse on the Mac.+ self.sender = MacSender(+ status_callback=self.bridge.sending.emit,+ redirect_callback=self.bridge.redirecting.emit,+ arrangement_callback=self.bridge.arrangement.emit,+ )+ self.sender.send_peer_home = self.server.send_home+ self.hooks = capture_win.Hooks(self._on_hook_key, self.sender.on_mouse, self.sender.on_motion)+ self._trigger = capture_win.Trigger()+ self._sending_detail = "Not connected to the Mac"+ try:+ self._config = load_config(config_path)+ self._host = self._config.host+ self._status = ServerState.WAITING+ self._status_detail = f"Ready on TCP port {self._config.port}"+ except ConfigError as exc:+ LOGGER.info("Configuration is not ready: %s", exc)+ self._status = ServerState.ERROR+ self._status_detail = "Enter a shared token to finish setup"++ self.setWindowTitle("Beamer")+ self.resize(820, 720)+ self.setMinimumSize(*tokens.MIN_WINDOW["windows"])+ self.setWindowIcon(QIcon(str(ICON_PATH)))+ self._build_window()+ self._apply_theme()+ self._build_tray()++ self.refresh_timer = QTimer(self)+ self.refresh_timer.setInterval(250)+ self.refresh_timer.timeout.connect(self._refresh_window)+ self.refresh_timer.start()+ # Otherwise the heading, the "Input:"/"Now:" readouts and the sidebar dots sit blank+ # for the first 250ms every launch, waiting for the timer's first tick.+ self._refresh_window()+ # start() triggers the first read through the WAITING transition; without a config the+ # receiver never starts, so the row would otherwise say "Checking" forever.+ if self._config is None:+ self._check_firewall()++ # -- window and pages -----------------------------------------------------------------++ def _build_window(self) -> None:+ outer = QVBoxLayout(self)+ outer.setContentsMargins(0, 0, 0, 0)+ outer.setSpacing(0)++ row = QWidget()+ row_layout = QHBoxLayout(row)+ row_layout.setContentsMargins(0, 0, 0, 0)+ row_layout.setSpacing(0)++ self.sidebar = widgets.Sidebar(pages_win.PAGES, self._select_page)+ self.sidebar.setFixedWidth(theme.SIDEBAR_WIDTH)+ row_layout.addWidget(self.sidebar)+ row_layout.addWidget(widgets.rule())++ self.stack = QStackedWidget()+ row_layout.addWidget(self.stack, 1)+ outer.addWidget(row, 1)++ footer = QFrame()+ footer.setProperty("vernier", "commit")+ footer_layout = QHBoxLayout(footer)+ footer_layout.setContentsMargins(16, 10, 16, 10)+ footer_layout.addWidget(+ widgets.label("Closing this window keeps Beamer running in the tray.", "note", wrap=True)+ )+ outer.addWidget(footer)++ current = self._config or default_config()+ builders = {+ "overview": self._overview_page,+ "crossing": self._crossing_page,+ "pairing": self._pairing_page,+ "connection": self._connection_page,+ "firewall": self._firewall_page,+ }+ self._page_indexes: dict = {}+ for key, name, purpose in pages_win.PAGES:+ scroll, layout = self._page_shell(name, purpose)+ builders[key](layout, current)+ layout.addStretch(1)+ self._page_indexes[key] = self.stack.addWidget(scroll)++ for index, key in enumerate(pages_win.KEYS[:9]):+ shortcut = QShortcut(QKeySequence(f"Ctrl+{index + 1}"), self)+ shortcut.activated.connect(lambda k=key: self._select_page(k))++ self._select_page("overview")++ def _page_shell(self, title: str, purpose: str):+ scroll = QScrollArea()+ scroll.setWidgetResizable(True)+ scroll.setFrameShape(QFrame.Shape.NoFrame)+ # Nothing scrolls sideways, at any width.+ scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)+ page = QWidget()+ page.setProperty("vernier", "plain")+ layout = QVBoxLayout(page)+ layout.setContentsMargins(28, 24, 28, 24)+ layout.setSpacing(16)+ heading = widgets.label(title.upper(), "heading")+ heading.setFont(theme.font(theme.HEADING, 700))+ layout.addWidget(heading)+ layout.addWidget(widgets.label(purpose, "note", wrap=True))+ scroll.setWidget(page)+ return scroll, layout++ def _select_page(self, key: str) -> None:+ index = self._page_indexes.get(key)+ if index is None:+ return+ self._page = key+ self.stack.setCurrentIndex(index)+ self.sidebar.select(key)++ # -- Overview ---------------------------------------------------------------------------++ def _overview_page(self, layout, current) -> None:+ layout.addWidget(self._link_module())+ layout.addWidget(self._daily_module(current))++ def _link_module(self) -> QWidget:+ module = widgets.Module("Link")+ led_row = QHBoxLayout()+ led_row.setSpacing(8)+ self.led = widgets.Led()+ led_row.addWidget(self.led, 0, Qt.AlignmentFlag.AlignVCenter)+ led_row.addStretch(1)+ module.body.addLayout(led_row)+ self.status_heading = widgets.label("", "heading", wrap=True)+ self.status_heading.setFont(theme.font(theme.HEADING, 700))+ module.body.addWidget(self.status_heading)+ self.status_detail = widgets.label("", "note", wrap=True)+ module.body.addWidget(self.status_detail)+ where_row = QHBoxLayout()+ where_row.setSpacing(6)+ where_row.addWidget(widgets.label("Input:", "note"))+ self.location_readout = widgets.label("", "readout", wrap=True)+ where_row.addWidget(self.location_readout, 1)+ module.body.addLayout(where_row)+ return module++ def _daily_module(self, current: Config) -> QWidget:+ module = widgets.Module("Every day")+ self.allow_switch = widgets.Switch("Let your Mac drive this PC")+ self.allow_switch.setFont(theme.font(theme.TYPE["body"]))+ self.allow_switch.setChecked(current.allow_mac_to_drive)+ self.allow_switch.toggled.connect(self._set_allow_drive)+ module.body.addWidget(self.allow_switch)+ self.send_switch = widgets.Switch("Send this PC's keyboard and mouse to your Mac")+ self.send_switch.setFont(theme.font(theme.TYPE["body"]))+ self.send_switch.setChecked(current.send_to_mac)+ self.send_switch.toggled.connect(self._toggle_sending)+ module.body.addWidget(self.send_switch)+ self.send_hint = widgets.label("", "note", wrap=True)+ module.body.addWidget(self.send_hint)+ self.logon_switch = widgets.Switch("Start Beamer when you sign in")+ self.logon_switch.setFont(theme.font(theme.TYPE["body"]))+ exe = autostart_win.installed_exe()+ try:+ self.logon_switch.setChecked(exe is not None and autostart_win.is_enabled())+ except OSError:+ LOGGER.exception("Could not read the logon task")+ self.logon_switch.setEnabled(exe is not None)+ self.logon_switch.toggled.connect(self._set_start_at_logon)+ module.body.addWidget(self.logon_switch)+ self.logon_hint = widgets.label(+ "In the tray, with no window." if exe else "Only the installed app can start at sign-in.",+ "note",+ wrap=True,+ )+ module.body.addWidget(self.logon_hint)+ if self._config is None:+ self.allow_switch.setEnabled(False)+ self.send_switch.setEnabled(False)+ return module++ def _set_allow_drive(self, enabled: bool) -> None:+ """Replaces the old Start/Stop receiver button: this switch is what persists."""+ if self._config is None:+ return+ self._config.allow_mac_to_drive = bool(enabled)+ self._persist()+ try:+ if enabled:+ self.server.start(self._config)+ else:+ self.server.stop()+ except Exception as exc:+ LOGGER.exception("Receiver action failed")+ self._set_status(ServerState.ERROR, f"Receiver failed: {exc}")++ def _set_start_at_logon(self, enabled: bool) -> None:+ exe = autostart_win.installed_exe()+ if exe is None:+ return+ try:+ autostart_win.set_enabled(enabled, exe)+ except OSError as exc:+ LOGGER.warning("Could not change the logon task: %s", exc)+ self.logon_switch.blockSignals(True)+ self.logon_switch.setChecked(not enabled)+ self.logon_switch.blockSignals(False)+ self.logon_hint.setText(f"Windows refused: {exc}")+ return+ self.logon_hint.setText("In the tray, with no window.")++ def _toggle_sending(self, enabled: bool) -> None:+ """Takes effect at once: it decides whether this PC's own keyboard is being+ watched, which is not something to leave a person guessing about."""+ if self._config is None:+ return+ self._config.send_to_mac = bool(enabled)+ self._persist()+ if enabled:+ self._start_sending(self._config)+ else:+ self._stop_sending()++ # -- Crossing -----------------------------------------------------------------------------++ def _crossing_page(self, layout, current: Config) -> None:+ layout.addWidget(self._ways_module(current))+ layout.addWidget(self._resistance_module(current))+ layout.addWidget(self._shortcut_module(current))+ layout.addWidget(self._glow_module(current))++ def _ways_module(self, current: Config) -> QWidget:+ module = widgets.Module("Ways in")+ self.way_boxes: dict = {}+ for value, text in (("edge", "Edge"), ("corner", "Corner"), ("shortcut", "Shortcut")):+ box = QCheckBox(text)+ box.setChecked(value in current.crossing_methods)+ box.toggled.connect(self._ways_changed)+ module.body.addWidget(box)+ self.way_boxes[value] = box++ module.body.addWidget(+ widgets.label(+ "Which edge of this PC leads to your Mac. It is the same border both ways, so "+ "setting it here moves it on the Mac too.",+ "note",+ wrap=True,+ )+ )+ module.body.addWidget(widgets.label("Edge", "key"))+ self.edge_choice = widgets.Choice(+ EDGE_CHOICES, columns=4, current=current.mac_return_edge or "right", on_change=self._set_arrangement+ )+ module.body.addWidget(self.edge_choice.view)++ module.body.addWidget(widgets.label("Corner", "key"))+ self.corner_choice = widgets.Choice(+ CORNER_CHOICES, columns=2, current=current.crossing_corner, on_change=self._set_corner+ )+ module.body.addWidget(self.corner_choice.view)+ self.corner_choice.set_enabled("corner" in current.crossing_methods)++ now_row = QHBoxLayout()+ now_row.setSpacing(6)+ # Named, not just "Now": this line is the Mac's half of the border --+ # the edge and push it asks for when it is the one sending -- and under+ # a column of this PC's own controls it reads as one of them otherwise.+ now_row.addWidget(widgets.label("Your Mac asks for:", "note"))+ self.return_readout = widgets.label("", "readout", wrap=True)+ now_row.addWidget(self.return_readout, 1)+ module.body.addLayout(now_row)+ return module++ def _ways_changed(self, *_ignored) -> None:+ if self._config is None:+ return+ self._config.crossing_methods = [value for value, box in self.way_boxes.items() if box.isChecked()]+ self._persist()+ self.corner_choice.set_enabled(self.way_boxes["corner"].isChecked())+ self.sender.update_config(self._config)++ 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:+ return+ self._config.mac_return_edge = pc_edge+ self._config.arrangement_set_at = int(time.time())+ self._persist()+ mac_edge = return_edge.OPPOSITE[pc_edge]+ self.sender.send_arrangement(mac_edge, self._config.arrangement_set_at)+ self.server.send_arrangement(mac_edge, self._config.arrangement_set_at)+ 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)++ def _on_arrangement(self, mac_edge: str, set_at: int) -> None:+ """The Mac changed the arrangement, over either link. `mac_edge` is always the edge of+ the MAC that leads here; an arrival older than what this end already holds is ignored."""+ if self._config is None:+ return+ if self._config.arrangement_set_at and not protocol.arrangement_wins(set_at, self._config.arrangement_set_at):+ LOGGER.info("Ignoring an older arrangement from the Mac (%s vs %s)", set_at, self._config.arrangement_set_at)+ return+ pc_edge = return_edge.OPPOSITE.get(mac_edge)+ if pc_edge is None:+ return+ self._config.mac_return_edge = pc_edge+ self._config.arrangement_set_at = int(set_at)+ self._persist()+ self.sender.update_config(self._config)+ self.edge_choice.set_value(pc_edge)++ def _resistance_module(self, current: Config) -> QWidget:+ module = widgets.Module("Resistance")+ row = QHBoxLayout()+ row.setSpacing(10)+ self.resistance_slider = QSlider(Qt.Orientation.Horizontal)+ self.resistance_slider.setRange(0, 300)+ self.resistance_slider.setValue(current.crossing_resistance_px)+ self.resistance_slider.valueChanged.connect(self._resistance_changed)+ row.addWidget(self.resistance_slider, 1)+ self.resistance_readout = widgets.label(f"{current.crossing_resistance_px} px", "readout")+ row.addWidget(self.resistance_readout)+ module.body.addLayout(row)+ self.resistance_hint = widgets.label("", "note", wrap=True)+ module.body.addWidget(self.resistance_hint)+ self._update_resistance_hint(current.crossing_resistance_px)+ return module++ def _resistance_changed(self, value: int) -> None:+ self.resistance_readout.setText(f"{value} px")+ self._update_resistance_hint(value)+ if self._config is None:+ return+ self._config.crossing_resistance_px = int(value)+ self.sender.update_config(self._config)+ self._debounce_save()++ def _update_resistance_hint(self, value: int) -> None:+ text = (+ "Switches the moment the pointer touches the edge."+ if value == 0+ else "How far to push past the edge before it gives."+ )+ if text != self.resistance_hint.text():+ self.resistance_hint.setText(text)++ def _shortcut_module(self, current: Config) -> QWidget:+ module = widgets.Module("Shortcut")+ module.body.addWidget(+ widgets.label(+ "Use this key to send input to your Mac, and to bring it back.", "note", wrap=True+ )+ )+ self.trigger_key_choice = widgets.Choice(+ tuple(TRIGGER_KEYS.items()), columns=2, current=current.trigger_key, on_change=self._set_trigger_key+ )+ module.body.addWidget(self.trigger_key_choice.view)+ self.trigger_style_choice = widgets.Choice(+ TRIGGER_STYLE_CHOICES, columns=2, current=current.trigger_style, on_change=self._set_trigger_style+ )+ module.body.addWidget(self.trigger_style_choice.view)+ self.style_hint = widgets.label("", "note", wrap=True)+ module.body.addWidget(self.style_hint)+ row = QHBoxLayout()+ row.setSpacing(10)+ self.double_tap_slider = QSlider(Qt.Orientation.Horizontal)+ self.double_tap_slider.setRange(150, 600)+ self.double_tap_slider.setValue(current.double_tap_ms)+ self.double_tap_slider.valueChanged.connect(self._double_tap_changed)+ row.addWidget(self.double_tap_slider, 1)+ self.double_tap_readout = widgets.label(f"{current.double_tap_ms} ms", "readout")+ row.addWidget(self.double_tap_readout)+ module.body.addLayout(row)+ self.double_tap_slider.setEnabled(current.trigger_style != "hold")+ self._update_style_hint(current.trigger_style)+ return module++ def _set_trigger_key(self, value: str) -> None:+ if self._config is None:+ return+ self._config.trigger_key = value+ self._persist()+ self._configure_trigger(self._config)++ def _set_trigger_style(self, value: str) -> None:+ if self._config is None:+ return+ self._config.trigger_style = value+ self._persist()+ self._configure_trigger(self._config)+ self.double_tap_slider.setEnabled(value != "hold")+ self._update_style_hint(value)++ def _update_style_hint(self, style: str) -> None:+ text = (+ "Input is on the Mac for as long as the key is held."+ if style == "hold"+ else "Tap twice to switch; tap twice again to come back."+ )+ if text != self.style_hint.text():+ self.style_hint.setText(text)++ def _double_tap_changed(self, value: int) -> None:+ self.double_tap_readout.setText(f"{value} ms")+ if self._config is None:+ return+ self._config.double_tap_ms = int(value)+ self._configure_trigger(self._config)+ self._debounce_save()++ def _glow_module(self, current: Config) -> QWidget:+ module = widgets.Module("Glow")+ module.body.addWidget(widgets.label("Lights the edge as you push toward your Mac.", "note", wrap=True))+ self.glow_toggle = widgets.Switch("Light up the edge as you push")+ self.glow_toggle.setFont(theme.font(theme.TYPE["body"]))+ self.glow_toggle.setChecked(current.edge_glow)+ self.glow_toggle.toggled.connect(self._apply_look)+ module.body.addWidget(self.glow_toggle)+ module.body.addWidget(widgets.label("Style", "key"))+ self.glow_style_choice = widgets.Choice(+ GLOW_STYLE_CHOICES, columns=2, current=current.glow_style, on_change=self._apply_look+ )+ module.body.addWidget(self.glow_style_choice.view)+ module.body.addWidget(widgets.label("Colour", "key"))+ self.glow_colour_choice = widgets.Choice(+ GLOW_COLOUR_CHOICES, columns=5, current=current.glow_colour, on_change=self._apply_look+ )+ module.body.addWidget(self.glow_colour_choice.view)+ return module++ def _apply_look(self, *_ignored) -> None:+ """The glow's switch, style and colour save and apply the moment they change. They only+ decide how this PC's edge is drawn, so the receiver has no reason to restart for them."""+ if self._config is None:+ return+ self._config.edge_glow = self.glow_toggle.isChecked()+ self._config.glow_style = self.glow_style_choice.value+ self._config.glow_colour = self.glow_colour_choice.value+ self._persist()+ if not self._config.edge_glow and self.glow is not None:+ self.glow.hide()++ def _debounce_save(self) -> None:+ """A ruler being dragged writes once at the end rather than on every step."""+ self._apply_serial += 1+ serial = self._apply_serial+ QTimer.singleShot(SETTLE_MS, lambda: self._settle(serial))++ def _settle(self, serial: int) -> None:+ if serial == self._apply_serial:+ self._persist()++ def _persist(self) -> bool:+ if self._config is None:+ return False+ try:+ save_config(self.config_path, self._config)+ return True+ except (ConfigError, OSError):+ LOGGER.exception("Setting could not be saved")+ return False++ # -- Pairing --------------------------------------------------------------------------++ def _pairing_page(self, layout, current: Config) -> None:+ module = widgets.Module("Pairing code")+ head = QHBoxLayout()+ head.setSpacing(16)+ head.addWidget(module.eyebrow, 0, Qt.AlignmentFlag.AlignTop)+ self.pair_note = widgets.label("", "note", wrap=True)+ self.pair_note.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)+ head.addWidget(self.pair_note, 1)+ module.body.addLayout(head)+ code_row = QHBoxLayout()+ code_row.setSpacing(18)+ self.code_label = widgets.label(IDLE_CODE, "code-idle")+ self.code_label.setFont(theme.mono_font(theme.PAIRING_CODE))+ self.code_label.setAccessibleName("Pairing code")+ # The digits have no descenders, so the line box can be trimmed to the ink.+ self.code_label.setFixedHeight(round(theme.PAIRING_CODE))+ code_row.addWidget(self.code_label, 1, Qt.AlignmentFlag.AlignVCenter)+ count = QVBoxLayout()+ count.setSpacing(8)+ count.addStretch(1)+ self.count_label = widgets.label("1:00", "count-idle")+ self.count_label.setFont(theme.mono_font(theme.COUNT))+ self.count_label.setAlignment(Qt.AlignmentFlag.AlignRight)+ count.addWidget(self.count_label, 0, Qt.AlignmentFlag.AlignRight)+ self.pair_button = QPushButton("Pair a Mac")+ self.pair_button.setProperty("vernier", "primary")+ self.pair_button.setCursor(Qt.CursorShape.PointingHandCursor)+ self.pair_button.clicked.connect(self._toggle_pairing)+ count.addWidget(self.pair_button, 0, Qt.AlignmentFlag.AlignRight)+ count.addStretch(1)+ code_row.addLayout(count)+ module.body.addLayout(code_row)+ self.drain = widgets.Drain()+ module.body.addWidget(self.drain)+ layout.addWidget(module)+ self._say_pairing(f"Paired with {current.paired_with}." if current.paired_with else PAIR_HINT, "note")++ def _toggle_pairing(self) -> None:+ if self.announcer.code is not None:+ self.announcer.cancel_pairing()+ return+ if self.announcer.error:+ self._say_pairing(f"Pairing is not available: {self.announcer.error}", "note-fault")+ return+ self.announcer.begin_pairing()+ self._refresh_pairing()++ def _refresh_pairing(self) -> None:+ code = self.announcer.code+ if code is not None:+ seconds = self.announcer.seconds_left+ self.code_label.setText(f"{code[:3]} {code[3:]}")+ widgets.set_role(self.code_label, "code")+ self.count_label.setText(f"{seconds // 60}:{seconds % 60:02d}")+ widgets.set_role(self.count_label, "count")+ self.drain.set_remaining(seconds)+ self.pair_button.setText("Cancel")+ self._say_pairing(PAIR_HINT, "note")+ self._code_shown = True+ return+ if not self._code_shown:+ return+ self._code_shown = False+ self.code_label.setText(IDLE_CODE)+ widgets.set_role(self.code_label, "code-idle")+ self.count_label.setText("1:00")+ widgets.set_role(self.count_label, "count-idle")+ self.drain.set_remaining(0)+ self.pair_button.setText("Pair a Mac")+ outcome = self.announcer.outcome+ if outcome == "refused":+ self._say_pairing("A wrong code was entered, so that code is cancelled. Press Pair a Mac for a fresh one.", "note-fault")+ elif outcome == "expired":+ self._say_pairing("The code expired. Press Pair a Mac for a fresh one.", "note-amber")+ elif outcome is None:+ self._say_pairing("Pairing cancelled.", "note")++ def _say_pairing(self, text: str, tone: str) -> None:+ if text != self.pair_note.text():+ self.pair_note.setText(text)+ widgets.set_role(self.pair_note, tone)++ def _on_paired(self, token: str, mac_name: str, mac_address: str) -> None:+ current = self._config or default_config()+ host = self.host_entry.text().strip() or self._host+ if not host:+ # A fresh install knows no address of its own; the one facing the Mac is the one+ # to show.+ try:+ host = local_address_towards(mac_address)+ except OSError:+ pass+ try:+ candidate = replace(+ current,+ host=host,+ port=int(self.port_entry.text().strip() or current.port),+ auth_token=token,+ paired_with=mac_name,+ )+ save_config(self.config_path, candidate)+ self._apply_config(candidate)+ except (ConfigError, TypeError, ValueError, OSError) as exc:+ LOGGER.exception("Paired token could not be saved")+ self._say_pairing(f"Paired, but the token could not be saved: {exc}", "note-fault")+ return+ self._host = candidate.host+ self.host_entry.setText(candidate.host)+ self.token_entry.setText(token)+ self._refresh_pairing()+ who = mac_name or "your Mac"+ self._say_pairing(f"Paired with {who}. The receiver restarted with the new token.", "note-live")+ LOGGER.info("Paired with %s", who)++ # -- Connection -------------------------------------------------------------------------++ def _connection_page(self, layout, current: Config) -> None:+ module = widgets.Module("Listening")+ fields = QGridLayout()+ fields.setHorizontalSpacing(10)+ fields.setVerticalSpacing(10)+ fields.setColumnStretch(1, 1)+ # The address the Mac connects to. Pairing fills it in; a hand set-up copies it from here.+ self.host_entry = QLineEdit(self._host)+ fields.addWidget(widgets.label("This PC's address", "key"), 0, 0)+ fields.addWidget(self.host_entry, 0, 1, 1, 2)+ self.port_entry = QLineEdit(str(current.port))+ fields.addWidget(widgets.label("Listen port", "key"), 1, 0)+ fields.addWidget(self.port_entry, 1, 1, 1, 2)+ self.token_entry = QLineEdit(current.auth_token)+ self.token_entry.setEchoMode(QLineEdit.EchoMode.Password)+ self.token_entry.setMinimumWidth(80)+ fields.addWidget(widgets.label("Shared token", "key"), 2, 0)+ fields.addWidget(self.token_entry, 2, 1)+ self.show_token = QPushButton("Show")+ self.show_token.setProperty("vernier", "small")+ self.show_token.setCheckable(True)+ self.show_token.setCursor(Qt.CursorShape.PointingHandCursor)+ self.show_token.setToolTip("Show the shared token in this window")+ self.show_token.toggled.connect(self._update_token_visibility)+ fields.addWidget(self.show_token, 2, 2)+ module.body.addLayout(fields)+ mac_row = QHBoxLayout()+ mac_row.setSpacing(6)+ mac_row.addWidget(widgets.label("Mac address:", "note"))+ self.mac_host_readout = widgets.label(current.mac_host or "Not learned yet", "readout", wrap=True)+ mac_row.addWidget(self.mac_host_readout, 1)+ module.body.addLayout(mac_row)+ self.save_message = widgets.label("", "note", wrap=True)+ module.body.addWidget(self.save_message)+ self.save_button = QPushButton("Save and restart receiver")+ self.save_button.setProperty("vernier", "primary")+ self.save_button.setCursor(Qt.CursorShape.PointingHandCursor)+ self.save_button.clicked.connect(self.save)+ module.body.addWidget(self.save_button, 0, Qt.AlignmentFlag.AlignLeft)+ layout.addWidget(module)++ def _update_token_visibility(self, checked: bool) -> None:+ self.token_entry.setEchoMode(QLineEdit.EchoMode.Normal if checked else QLineEdit.EchoMode.Password)+ self.show_token.setText("Hide" if checked else "Show")++ def save(self) -> None:+ current = self._config or default_config()+ try:+ candidate = replace(+ current,+ host=self.host_entry.text().strip() or self._host,+ port=int(self.port_entry.text().strip()),+ auth_token=self.token_entry.text(),+ )+ save_config(self.config_path, candidate)+ self._apply_config(candidate)+ except (ConfigError, TypeError, ValueError) as exc:+ self.save_message.setText(str(exc))+ widgets.set_role(self.save_message, "note-fault")+ return+ except OSError as exc:+ LOGGER.exception("Configuration could not be saved")+ QMessageBox.critical(self, "Save failed", str(exc))+ return+ self.save_message.setText("Saved.")+ widgets.set_role(self.save_message, "note-live")++ def _apply_config(self, config: Config) -> None:+ if self.server.listening:+ self.server.stop()+ self._config = config+ if not config.edge_glow and self.glow is not None:+ self.glow.hide()+ self.allow_switch.setEnabled(True)+ self.allow_switch.setChecked(config.allow_mac_to_drive)+ if config.allow_mac_to_drive:+ self.server.start(config)+ self.send_switch.setEnabled(True)+ self.send_switch.setChecked(config.send_to_mac)+ if config.send_to_mac:+ self.sender.update_config(config)+ self._start_sending(config)+ else:+ self._stop_sending()+ self.mac_host_readout.setText(config.mac_host or "Not learned yet")++ # -- Firewall ---------------------------------------------------------------------------++ def _firewall_page(self, layout, current: Config) -> None:+ module = widgets.Module("Windows Firewall")+ self.firewall_note = widgets.label("Checking Windows Firewall…", "note", wrap=True)+ module.body.addWidget(self.firewall_note)+ self.firewall_button = QPushButton("Check again")+ self.firewall_button.setCursor(Qt.CursorShape.PointingHandCursor)+ self.firewall_button.setEnabled(False)+ self.firewall_button.clicked.connect(self._firewall_action)+ module.body.addWidget(self.firewall_button, 0, Qt.AlignmentFlag.AlignLeft)+ layout.addWidget(module)++ def _firewall_target(self) -> tuple:+ port = self._config.port if self._config is not None else protocol.DEFAULT_PORT+ return str(Path(sys.executable).resolve()), port++ def _check_firewall(self) -> None:+ self._run_firewall(firewall_win.status, "Checking…")++ def _firewall_action(self) -> None:+ advice = self._firewall_advice+ if advice is None or advice.action is None:+ return+ if advice.action == "repair":+ profiles = advice.rule_profiles++ def job(exe, port):+ firewall_win.repair(exe, port, profiles)+ return firewall_win.status(exe, port)++ elif advice.action == "trust":+ indexes = [index for index, _ in (self._firewall_status.public_interfaces if self._firewall_status else ())]++ def job(exe, port):+ firewall_win.trust_network(indexes)+ return firewall_win.status(exe, port)++ else:+ self._check_firewall()+ return+ self._run_firewall(job, "Fixing…")++ def _run_firewall(self, job, working: str) -> None:+ """One PowerShell at a time, off the GUI thread. A request arriving mid-run is folded+ into one further status read once the current one finishes."""+ if self._closing:+ return+ if self._firewall_busy:+ self._firewall_again = True+ return+ self._firewall_busy = True+ self.firewall_button.setEnabled(False)+ self.firewall_button.setText(working)+ exe, port = self._firewall_target()++ def work():+ try:+ result = job(exe, port)+ except Exception as exc:+ LOGGER.exception("Firewall job failed")+ result = firewall_win.FirewallStatus(port, False, False, (), (), False, (), firewall_win.is_elevated(), error=f"the change failed: {exc}")+ self.bridge.firewall.emit(result)++ threading.Thread(target=work, name="Beamer-firewall", daemon=True).start()++ def _on_firewall(self, status) -> None:+ self._firewall_busy = False+ if self._closing:+ return+ self._firewall_status = status+ advice = firewall_win.advise(status)+ self._firewall_advice = advice+ self.firewall_note.setText(advice.sentence)+ if status.error:+ tone = "note-fault"+ elif advice.action == "check":+ tone = "note"+ else:+ tone = "note-amber"+ # Remembered for the sidebar dot: "check" is the healthy end-state (its button just+ # offers a manual re-check), so `advice.action is not None` alone would mark Firewall+ # as needing attention even when everything is fine.+ self._firewall_tone = tone+ widgets.set_role(self.firewall_note, tone)+ self.firewall_button.setText(advice.button)+ self.firewall_button.setEnabled(advice.action is not None)+ if self._firewall_again:+ self._firewall_again = False+ self._check_firewall()+ return+ # A missing rule with the rights to write one is not a question for the+ # user: the release installer cannot add it, so a fresh install would+ # otherwise sit unreachable until someone found this page. A block rule+ # or a public network is still theirs to decide.+ if (+ advice.action == "repair"+ and status.elevated+ and not status.allowed+ and not status.blocked+ and not self._firewall_auto_repaired+ ):+ self._firewall_auto_repaired = True+ LOGGER.info("No firewall rule for this executable; adding one")+ self._firewall_action()++ # -- theming, tray, lifecycle ------------------------------------------------------------++ def _apply_theme(self) -> None:+ app = QApplication.instance()+ if app is not None:+ app.setStyleSheet(theme.stylesheet())+ self._apply_title_bar()++ def _apply_title_bar(self) -> None:+ """Paint the native title bar in the Vernier ground instead of the user's Windows accent+ colour. Cosmetic only: any failure (older Windows without the attributes, missing dwmapi,+ etc.) is swallowed so the window still opens."""+ if sys.platform != "win32":+ return+ try:+ hwnd = int(self.winId())+ except Exception:+ LOGGER.debug("Title bar styling failed", exc_info=True)+ return+ theme.apply_titlebar(hwnd)++ def _build_tray(self) -> None:+ self.tray = QSystemTrayIcon(QIcon(status_icon(self._status)), self)+ self.tray.setToolTip(self._title())+ menu = QMenu()+ header = menu.addAction(f"Beamer {VERSION}")+ header.setEnabled(False)+ menu.addSeparator()+ self.open_action = menu.addAction("Open Beamer")+ self.open_action.triggered.connect(self.show_window)+ self.status_action = menu.addAction(self._title())+ self.status_action.setEnabled(False)+ menu.addSeparator()+ # One tick per direction, each the same switch the Overview page shows, so either+ # direction can be turned off while the other keeps working and the two never disagree.+ self.drive_action = menu.addAction("Mac drives this PC")+ self.drive_action.setCheckable(True)+ self.drive_action.toggled.connect(self.allow_switch.setChecked)+ self.allow_switch.toggled.connect(self.drive_action.setChecked)+ self.send_action = menu.addAction("This PC drives the Mac")+ self.send_action.setCheckable(True)+ self.send_action.toggled.connect(self.send_switch.setChecked)+ self.send_switch.toggled.connect(self.send_action.setChecked)+ self.drive_action.setChecked(self.allow_switch.isChecked())+ self.send_action.setChecked(self.send_switch.isChecked())+ menu.addSeparator()+ menu.addAction("Quit Beamer").triggered.connect(self.quit)+ self.tray.setContextMenu(menu)+ # Left click opens the window; right click is the+ # context menu Qt already gives QSystemTrayIcon for free.+ self.tray.activated.connect(self._on_tray_activated)+ self.tray.show()++ def _on_tray_activated(self, reason) -> None:+ if reason in (QSystemTrayIcon.ActivationReason.Trigger, QSystemTrayIcon.ActivationReason.DoubleClick):+ self.show_window()++ def start(self) -> None:+ self.announcer.start()+ if self._config is not None:+ self.server.start(self._config)+ self._start_sending(self._config)++ def _configure_trigger(self, config: Config) -> None:+ self._trigger.configure(config.trigger_key, config.trigger_style, config.double_tap_ms)++ def _start_sending(self, config: Config) -> None:+ """The outward link and the hooks that feed it. The hooks go in only+ when sending is on: they are the one part of Beamer that can take this+ PC's own keyboard away, so an install that never sends never installs+ them."""+ if not config.send_to_mac:+ return+ self._configure_trigger(config)+ try:+ self.hooks.start()+ except Exception as exc:+ LOGGER.exception("The input hooks could not be installed")+ self._sending_detail = f"This PC's keyboard could not be captured: {exc}"+ return+ self.sender.start(config)++ def _on_hook_key(self, name: str, down: bool) -> bool:+ """Every key, on the hook thread. The trigger is swallowed as it+ switches; everything else goes to the Mac only while the Mac has+ input."""+ action = self._trigger.feed(name, down, time.monotonic())+ if action is not None:+ if not self.sender.shortcut_armed:+ # The key is still the trigger's, so it never reaches an app,+ # but with the shortcut switched off it moves nothing.+ return True+ if action == capture_win.TOGGLE:+ self.sender.toggle()+ else:+ self.sender.set_redirecting(action == capture_win.REDIRECT)+ return True+ if self._trigger.claims(name, down, self.sender.redirecting):+ return True+ return self.sender.on_key(name, down)++ def _on_focus(self, target: str) -> None:+ """The Mac took input on this PC, or gave it back. Either way the+ outward edge follows: one of the two links owns the keyboard at a+ time, never both."""+ self.sender.set_receiving(target == "windows")++ def _on_learned(self, host, edge, resistance) -> None:+ """The Mac's address and the way home it named in its hello. Saved, so+ this PC can open its own link to the Mac before the Mac has crossed --+ or at all, if the Mac is asleep when Beamer starts here."""+ if self._config is None:+ return+ if sender.is_this_machine(host):+ # The Mac reached this PC through the macOS 27 localhost tunnel,+ # so its "address" is this PC's own. Saving it would point the+ # outward link at this PC's own receiver.+ LOGGER.info("Ignoring %s as the Mac's address: that is this PC", host)+ host = None+ changed = False+ for name, value in (("mac_host", host), ("mac_return_edge", edge or ""), ("mac_resistance_px", resistance)):+ if value in (None, "") or getattr(self._config, name) == value:+ continue+ setattr(self._config, name, value)+ changed = True+ if not changed:+ return+ LOGGER.info("Learned the Mac at %s, coming home through the %s edge", self._config.mac_host, self._config.mac_return_edge)+ if not self._persist():+ return+ self.sender.update_config(self._config)+ self._start_sending(self._config)+ self.mac_host_readout.setText(self._config.mac_host or "Not learned yet")+ self.edge_choice.set_value(self._config.mac_return_edge)++ def _on_sending(self, connected: bool, detail: str) -> None:+ self._sending_detail = detail++ def _on_redirecting(self, redirecting: bool) -> None:+ self._sending_detail = (+ "This PC's keyboard and mouse are on the Mac" if redirecting else self.sender.status+ )++ def _announced_port(self) -> int:+ return self._config.port if self._config is not None else default_config().port++ def show_window(self) -> None:+ self.showNormal()+ self.raise_()+ self.activateWindow()++ def quit(self) -> None:+ if self._closing:+ return+ self._closing = True+ self.refresh_timer.stop()+ self.announcer.stop()+ self.server.stop()+ self._stop_sending()+ if self.glow is not None:+ self.glow.hide()+ self.tray.hide()+ QApplication.quit()++ def closeEvent(self, event) -> None:+ """Closing the window hides to the tray; the tray's Quit ends the process."""+ if self._closing:+ super().closeEvent(event)+ return+ event.ignore()+ self.hide()++ def keyPressEvent(self, event) -> None:+ if event.key() == Qt.Key.Key_Escape:+ self.hide()+ return+ if event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter) and self._page == "connection":+ self.save()+ return+ super().keyPressEvent(event)++ def _stop_sending(self) -> None:+ self.sender.stop()+ self.hooks.stop()+ self._sending_detail = "Off"++ def _on_pressure(self, edge: str, pressure: float, crossed: bool) -> None:+ if self._closing or self._config is None or not self._config.edge_glow:+ return+ if self.glow is None:+ self.glow = EdgeGlow()+ self.glow.configure(self._config.glow_style, self._config.glow_colour)+ self.glow.set_pressure(edge, pressure, crossed)++ def _set_status(self, state: ServerState, detail: str) -> None:+ """Called from the receiver's thread — hand off to the GUI thread."""+ with self._status_lock:+ self._status = state+ self._status_detail = detail+ self.bridge.changed.emit(state, detail)++ def _on_status(self, state, _detail: str) -> None:+ if self._closing:+ return+ try:+ self.tray.setIcon(QIcon(status_icon(state)))+ self.tray.setToolTip(self._title())+ self.status_action.setText(self._title())+ except Exception:+ LOGGER.exception("Tray status update failed")+ # Re-read the firewall each time the receiver starts listening, never on a timer: a+ # Mac dropping and reconnecting flips WAITING <-> CONNECTED and must not trigger it.+ if state is ServerState.WAITING and self._last_seen_state not in (ServerState.WAITING, ServerState.CONNECTED):+ self._check_firewall()+ self._last_seen_state = state++ def _refresh_window(self) -> None:+ if self._closing:+ return+ with self._status_lock:+ state = self._status+ detail = self._status_detail+ tone = theme.state_tone(state.value.lower())+ self.led.set_tone(tone)+ # The Mac's name goes in the detail, not the heading: a long name wrapped the heading onto+ # two lines at 640 wide and made the window scroll.+ if state is ServerState.CONNECTED and detail.startswith("Connected to "):+ who = (self._config.paired_with if self._config is not None else "") or "Your Mac"+ detail = f"{who} at {detail[len('Connected to '):]}"+ heading = STATUS_TITLES[state]+ if heading != self.status_heading.text():+ self.status_heading.setText(heading)+ widgets.set_role(self.status_heading, HEADING_ROLE[tone])+ if detail != self.status_detail.text():+ self.status_detail.setText(detail)+ widgets.set_role(self.status_detail, "note-fault" if state is ServerState.ERROR else "note")+ location = "On your Mac" if self.sender.redirecting else "On this PC"+ if location != self.location_readout.text():+ self.location_readout.setText(location)+ # "On your Mac" above already says this while redirecting; the hint is for the rest --+ # not connected, or the hooks failing to install -- and stays quiet in the boring case.+ send_hint = "" if self.sender.redirecting or self._sending_detail in (+ "Off", "Not connected to the Mac"+ ) else self._sending_detail+ if send_hint != self.send_hint.text():+ self.send_hint.setText(send_hint)+ self.sidebar.set_link(tone, SIDEBAR_LINK_WORDS.get(state, "Unknown"))+ self.sidebar.set_dots(pages_win.dots(self._config is None, self._firewall_tone))+ self._refresh_pairing()+ edge = self.server.return_edge+ resistance = self.server.return_resistance+ if edge and resistance is not None:+ text = f"{edge} edge · {resistance} px"+ else:+ text = "not set yet"+ if text != self.return_readout.text():+ self.return_readout.setText(text)++ def _title(self) -> str:+ with self._status_lock:+ return f"Beamer — {self._status.value}: {self._status_detail}"+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(description="Beamer Windows receiver")+ parser.add_argument("--config", type=Path, default=default_config_path(), help="path to config.json")+ parser.add_argument("--hidden", action="store_true", help="start in the tray without showing the window")+ return parser.parse_args()+++def main() -> None:+ if sys.platform != "win32":+ raise SystemExit("Beamer Windows receiver must run on Windows")+ # use_last_error, then ctypes.get_last_error(): a plain GetLastError() call+ # through windll can read an error ctypes' own marshalling set in between,+ # and 183 (already exists) is the whole single-instance check.+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.CreateMutexW.restype = ctypes.c_void_p+ kernel32.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_wchar_p]+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]+ mutex = kernel32.CreateMutexW(None, False, "Local\\Beamer.Receiver")+ already_running = ctypes.get_last_error() == 183+ if not mutex:+ raise OSError("Beamer could not create its single-instance lock")+ if already_running:+ kernel32.CloseHandle(mutex)+ return+ arguments = parse_args()+ if arguments.config == default_config_path():+ migrate_legacy_config()+ log_path = configure_logging()+ LOGGER.info("Starting Beamer Windows receiver")+ if log_path is not None:+ LOGGER.info("Logging to %s", log_path)+ # Above normal, so a busy rig cannot starve the hooks: Windows removes a+ # low-level hook whose callback misses its timeout, silently and for good,+ # and every Beamer thread must win the CPU for the hook thread to get the+ # GIL. Beamer idles near 0%, so the class costs the rest of the machine+ # nothing (a video pipeline held half the rig on 23-09-2026 when the+ # PC's mouse was stranded on the Mac).+ kernel32.GetCurrentProcess.restype = ctypes.c_void_p+ kernel32.SetPriorityClass.argtypes = [ctypes.c_void_p, ctypes.c_ulong]+ if not kernel32.SetPriorityClass(kernel32.GetCurrentProcess(), 0x8000): # ABOVE_NORMAL_PRIORITY_CLASS+ LOGGER.warning("Could not raise Beamer's priority: %s", ctypes.WinError(ctypes.get_last_error()))+ try:+ app = QApplication(sys.argv)+ app.setApplicationName("Beamer")+ app.setQuitOnLastWindowClosed(False)+ theme.init_fonts()+ app.setFont(theme.font(theme.TYPE["body"]))+ application = WindowsApplication(arguments.config.expanduser().resolve())+ if not arguments.hidden:+ application.show()+ application.start()+ sys.exit(app.exec())+ finally:+ kernel32.CloseHandle(mutex)+++if __name__ == "__main__":+ main()diff --git a/win_app/pages_win.py b/win_app/pages_win.pynew file mode 100644index 0000000..72bf28e--- /dev/null+++ b/win_app/pages_win.py@@ -0,0 +1,38 @@+"""The control window's pages, and which carry a dot in the sidebar.++Pure, so the rules are tested without Qt.+"""++from __future__ import annotations++# (key, name, what the page is for), in sidebar order; Ctrl+1 is the first.+PAGES = (+ ("overview", "Overview",+ "Where input is right now, and the two switches you reach for every day."),+ ("crossing", "Crossing",+ "How input leaves this PC: ways in, the arrangement with your Mac, resistance, and the "+ "shortcut key."),+ ("pairing", "Pairing",+ "Connect a Mac to this PC by typing the code it shows here. Once per Mac."),+ ("connection", "Connection",+ "This PC's address, listen port and shared token, and the Mac address pairing learned."),+ ("firewall", "Firewall",+ "Windows Firewall must let Beamer through before a Mac can connect."),+)+KEYS = tuple(page[0] for page in PAGES)+++def dots(config_error: bool, firewall_tone: str | None) -> dict:+ """Page key to the tone of its sidebar dot, for the pages that need one.++ `firewall_tone` is the note tone the Firewall page is already showing -- "note" is its+ healthy end-state (the button just offers a manual re-check), so only "note-amber" and+ "note-fault" earn a dot; a plain boolean would also mark the healthy state."""+ marks = {}+ if config_error:+ marks["connection"] = "fault"+ if firewall_tone == "note-amber":+ marks["firewall"] = "amber"+ elif firewall_tone == "note-fault":+ marks["firewall"] = "fault"+ return marksdiff --git a/win_app/pairing.py b/win_app/pairing.pynew file mode 100644index 0000000..dfd7925--- /dev/null+++ b/win_app/pairing.py@@ -0,0 +1,590 @@+"""LAN discovery and pairing, shared by mac_app and win_app (two identical copies; the Mac+test suite checks they match byte for byte).++The Windows receiver broadcasts a small UDP beacon -- hostname, Beamer TCP port, and a random+pairing id while a code is on screen -- and the Mac lists what it hears. Pairing then runs as+one datagram each way:++ Mac -> PC pair_request {pair, pub: X25519 public key, proof, name}+ PC -> Mac pair_reply {pair, ok, pub: X25519 public key, proof}++Both proofs are HMACs keyed from the six-digit code (scrypt, salted with the pairing id) over+the transcript, so each side shows the other that it knows the code. The shared token is+HKDF over the X25519 secret: an eavesdropper who records every datagram cannot derive it.++What this protects against, and what it does not:++- The token never crosses the wire, and neither does the code. The beacon carries nothing a+ token or key could be derived from.+- A wrong code fails closed. The PC consumes its code on the first confirmation it receives,+ right or wrong, so one code gives one guess; a fresh code needs a person at the PC to press+ Pair a Mac again, and that is the rate limit. Codes expire after CODE_LIFETIME_SECONDS.+- A passive listener can, offline, brute-force the code out of a recorded proof. That is why+ the code is single-use and why the key stretching is memory-hard: the code is worthless the+ moment it is consumed, and the token does not depend on it anyway.+- An ACTIVE attacker on the LAN during the pairing window is not stopped. One that answers the+ Mac's request in the PC's place receives the Mac's proof, can crack the six digits in the+ time the code is still valid given enough hardware, and pair with either side as the other.+ One that merely sends a junk confirmation burns the code and stops that pairing (a denial,+ not a compromise). A six-digit code without a PAKE cannot do better; the scheme trusts the+ LAN for the minute the code is on screen, and no longer.+"""++from __future__ import annotations++import base64+import hashlib+import hmac+import json+import logging+import queue+import secrets+import socket+import threading+import time++from cryptography.hazmat.primitives import hashes, serialization+from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey+from cryptography.hazmat.primitives.kdf.hkdf import HKDF++import protocol++# One home for the port, in the module both apps share byte-for-byte.+PAIRING_PORT = protocol.PAIRING_PORT+BEACON_VERSION = 1+BEACON_INTERVAL_SECONDS = 2.0+# Three missed beacons: long enough to ride out Wi-Fi hiccups, short enough that a PC that+# went to sleep leaves the list before anyone tries it.+BEACON_STALE_SECONDS = 7.0+CODE_LIFETIME_SECONDS = 60.0+CODE_DIGITS = 6+MAX_DATAGRAM_BYTES = 1024+PAIR_REPLY_TIMEOUT_SECONDS = 1.5+PAIR_ATTEMPTS = 3++MSG_BEACON = "beacon"+MSG_PAIR_REQUEST = "pair_request"+MSG_PAIR_REPLY = "pair_reply"++ERROR_NOT_PAIRING = "not_pairing"+ERROR_REFUSED = "refused"++# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing+# pairing and a mixed-version pair for no gain.+TOKEN_INFO = b"beamy-pair-token"+# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing+# pairing and a mixed-version pair for no gain.+CODE_INFO = b"beamy-pair-code"+++class PairingError(Exception):+ pass+++def new_code() -> str:+ return "".join(secrets.choice("0123456789") for _ in range(CODE_DIGITS))+++def _code_key(code: str, pair_id: str) -> bytes:+ # scrypt rather than HKDF on purpose: a recorded proof lets anyone try all million codes+ # offline, and 32MB per guess is what keeps that from finishing inside the code's minute.+ # maxmem is explicit because OpenSSL's default is exactly the 32MiB this needs, and it+ # refuses at the boundary.+ return hashlib.scrypt(+ code.encode("utf-8"), salt=pair_id.encode("utf-8") + CODE_INFO, n=2**15, r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024+ )+++def _proof(key: bytes, role: bytes, pair_id: str, mac_pub: bytes, pc_pub: bytes = b"") -> bytes:+ return hmac.new(key, role + pair_id.encode("utf-8") + mac_pub + pc_pub, hashlib.sha256).digest()+++def _b64(data: bytes) -> str:+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")+++def _unb64(text: str) -> bytes:+ if not isinstance(text, str):+ raise PairingError("expected base64 text")+ try:+ return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))+ except ValueError as exc:+ raise PairingError("bad base64") from exc+++def _public_bytes(key) -> bytes:+ return key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)+++def derive_token(private_key, peer_public: bytes, pair_id: str) -> str:+ shared = private_key.exchange(X25519PublicKey.from_public_bytes(peer_public))+ return _b64(HKDF(algorithm=hashes.SHA256(), length=32, salt=pair_id.encode("utf-8"), info=TOKEN_INFO).derive(shared))+++def encode(message: dict) -> bytes:+ # The "beamy" key is a wire constant, deliberately kept as the pre-rename name: changing it+ # would break an existing pairing and a mixed-version pair for no gain.+ return json.dumps({"beamy": BEACON_VERSION, **message}, separators=(",", ":")).encode("utf-8")+++def decode(data: bytes):+ """The dict a Beamer datagram carries, or None for anything else on the port."""+ if len(data) > MAX_DATAGRAM_BYTES:+ return None+ try:+ message = json.loads(data.decode("utf-8"))+ except (UnicodeDecodeError, ValueError):+ return None+ if not isinstance(message, dict) or message.get("beamy") != BEACON_VERSION:+ return None+ return message+++def beacon_msg(name: str, port: int, pair_id: str = None) -> dict:+ message = {"type": MSG_BEACON, "name": name, "port": int(port)}+ if pair_id:+ message["pair"] = pair_id+ return message+++class PairingHost:+ """The PC's half: holds at most one live code and answers pair requests. Pure -- the+ Announcer owns the socket and the clock is injected for the tests."""++ def __init__(self, clock=time.monotonic):+ self.clock = clock+ self.code = None+ self.pair_id = None+ self.expires_at = 0.0+ self._last = None+ self.paired = None+ # How the last code ended -- "paired", "refused" or "expired" -- for the window to say+ # so; None while a code is live or after a deliberate cancel.+ self.outcome = None++ @property+ def active(self) -> bool:+ if self.code is None:+ return False+ if self.clock() >= self.expires_at:+ self.cancel()+ self.outcome = "expired"+ return False+ return True++ @property+ def seconds_left(self) -> int:+ return max(0, int(self.expires_at - self.clock())) if self.active else 0++ def begin(self) -> str:+ self.code = new_code()+ self.pair_id = secrets.token_hex(4)+ self.expires_at = self.clock() + CODE_LIFETIME_SECONDS+ self._last = None+ self.outcome = None+ return self.code++ def cancel(self) -> None:+ self.code = None+ self.pair_id = None+ self.expires_at = 0.0+ self.outcome = None++ def handle(self, message: dict):+ """The reply to one datagram, or None when it deserves no answer. A successful pairing+ leaves the token in `self.paired` as (token, mac_name); the caller stores it."""+ if message.get("type") != MSG_PAIR_REQUEST:+ return None+ pair_id = message.get("pair")+ if not isinstance(pair_id, str):+ return None+ if self._last is not None and self._last[0] == (pair_id, message.get("pub"), message.get("proof")):+ # A lost reply makes the Mac send the same request again; answer it the same way,+ # so a retransmit is not read as a second attempt.+ return self._last[1]+ if not self.active or pair_id != self.pair_id:+ return {"type": MSG_PAIR_REPLY, "pair": pair_id, "ok": False, "error": ERROR_NOT_PAIRING}+ code, self.code = self.code, None+ try:+ mac_pub = _unb64(message.get("pub"))+ proof = _unb64(message.get("proof"))+ X25519PublicKey.from_public_bytes(mac_pub)+ except (PairingError, ValueError):+ return self._refuse(message, pair_id)+ key = _code_key(code, pair_id)+ if not hmac.compare_digest(proof, _proof(key, b"mac", pair_id, mac_pub)):+ return self._refuse(message, pair_id)+ private_key = X25519PrivateKey.generate()+ pc_pub = _public_bytes(private_key)+ name = message.get("name")+ self.paired = (derive_token(private_key, mac_pub, pair_id), name if isinstance(name, str) else "")+ reply = {+ "type": MSG_PAIR_REPLY,+ "pair": pair_id,+ "ok": True,+ "pub": _b64(pc_pub),+ "proof": _b64(_proof(key, b"pc", pair_id, mac_pub, pc_pub)),+ }+ self._last = ((pair_id, message.get("pub"), message.get("proof")), reply)+ self.cancel()+ self.outcome = "paired"+ return reply++ def _refuse(self, message: dict, pair_id: str) -> dict:+ reply = {"type": MSG_PAIR_REPLY, "pair": pair_id, "ok": False, "error": ERROR_REFUSED}+ self._last = ((pair_id, message.get("pub"), message.get("proof")), reply)+ self.cancel()+ self.outcome = "refused"+ return reply+++class PairingClient:+ """The Mac's half of one attempt: builds the request, checks the reply, yields the token."""++ def __init__(self, pair_id: str, code: str, name: str):+ self.pair_id = pair_id+ self.name = name+ self._private_key = X25519PrivateKey.generate()+ self._pub = _public_bytes(self._private_key)+ self._key = _code_key(code, pair_id)++ def request(self) -> dict:+ return {+ "type": MSG_PAIR_REQUEST,+ "pair": self.pair_id,+ "pub": _b64(self._pub),+ "proof": _b64(_proof(self._key, b"mac", self.pair_id, self._pub)),+ "name": self.name,+ }++ def accept(self, reply: dict) -> str:+ """The agreed token, or PairingError naming why not."""+ if reply.get("type") != MSG_PAIR_REPLY or reply.get("pair") != self.pair_id:+ raise PairingError("not a reply to this attempt")+ if reply.get("ok") is not True:+ raise PairingError(reply.get("error") if reply.get("error") in (ERROR_NOT_PAIRING, ERROR_REFUSED) else ERROR_REFUSED)+ pc_pub = _unb64(reply.get("pub"))+ proof = _unb64(reply.get("proof"))+ if not hmac.compare_digest(proof, _proof(self._key, b"pc", self.pair_id, self._pub, pc_pub)):+ raise PairingError(ERROR_REFUSED)+ return derive_token(self._private_key, pc_pub, self.pair_id)+++def _udp_socket(bind_port: int) -> socket.socket:+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ if hasattr(socket, "SO_REUSEPORT"):+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)+ sock.bind(("", bind_port))+ sock.settimeout(0.5)+ return sock+++def local_address_towards(host: str) -> str:+ """This machine's address on the interface that reaches `host`; nothing is sent."""+ probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ probe.connect((host, 9))+ return probe.getsockname()[0]+ finally:+ probe.close()+++def broadcast_targets(port: int) -> list:+ """Every address worth sending a beacon to, one per local IPv4 interface plus the limited+ broadcast as a backstop.++ ⚠ 255.255.255.255 alone is not enough and this is not theoretical: it leaves by the default+ route only, so a PC with a second interface — a Hyper-V vEthernet switch is the common case,+ and the owner's rig has one — announces on whichever the routing table prefers and may never+ reach the LAN the Mac is on. Measured 10-09-2026: the PC beaconed steadily while no beacon+ reached the Mac at all, and the Mac then paired against a stale id from an older beacon that+ had got through, which is what produced `not_pairing`.++ 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."""+ 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))+ return targets+++def _local_ipv4_addresses() -> list:+ found = []+ try:+ for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):+ address = info[4][0]+ if not address.startswith("127.") and address not in found:+ found.append(address)+ except OSError:+ pass+ return found+++def machine_name() -> str:+ return socket.gethostname().split(".", 1)[0] or "This machine"+++class Announcer:+ """The PC's socket loop: broadcasts the beacon and answers pairing requests on one socket.+ `port_getter` returns the current TCP port, so a changed listen port is announced without a+ restart. `on_paired(token, mac_name, mac_address)` is called on this thread."""++ def __init__(self, port_getter, on_paired, logger=None, bind_port=PAIRING_PORT, announce_to=("255.255.255.255", PAIRING_PORT), name=None):+ self.port_getter = port_getter+ self.on_paired = on_paired+ self.logger = logger or logging.getLogger("Beamer")+ self.bind_port = bind_port+ self.announce_to = announce_to+ self.name = name or machine_name()+ self.host = PairingHost()+ self._lock = threading.Lock()+ self._stop = threading.Event()+ self._thread = None+ self.error = None++ def start(self) -> None:+ if self._thread is not None:+ return+ self._stop.clear()+ self._thread = threading.Thread(target=self._run, name="Beamer-announcer", daemon=True)+ self._thread.start()++ def stop(self) -> None:+ self._stop.set()+ thread = self._thread+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout=2.0)+ self._thread = None++ def begin_pairing(self) -> str:+ with self._lock:+ return self.host.begin()++ def cancel_pairing(self) -> None:+ with self._lock:+ self.host.cancel()++ @property+ def code(self):+ with self._lock:+ return self.host.code if self.host.active else None++ @property+ def seconds_left(self) -> int:+ with self._lock:+ return self.host.seconds_left++ @property+ def outcome(self):+ with self._lock:+ self.host.active+ return self.host.outcome++ def _run(self) -> None:+ try:+ sock = _udp_socket(self.bind_port)+ except OSError as exc:+ self.error = str(exc)+ self.logger.error("pairing beacon could not bind UDP %s: %s", self.bind_port, exc)+ return+ self.error = None+ next_beacon = 0.0+ try:+ while not self._stop.is_set():+ now = time.monotonic()+ if now >= next_beacon:+ next_beacon = now + BEACON_INTERVAL_SECONDS+ with self._lock:+ pair_id = self.host.pair_id if self.host.active else None+ beacon = encode(beacon_msg(self.name, self.port_getter(), pair_id))+ delivered = 0+ # Only a caller asking for the limited broadcast wants the per-interface+ # fan-out; a named address is honoured exactly, which keeps the tests off+ # the real network.+ if self.announce_to[0] == "255.255.255.255":+ targets = broadcast_targets(self.announce_to[1])+ else:+ targets = [self.announce_to]+ for target in targets:+ try:+ sock.sendto(beacon, target)+ delivered += 1+ except OSError:+ continue+ if not delivered:+ self.logger.warning("beacon reached no interface")+ try:+ data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)+ except socket.timeout:+ continue+ except ConnectionResetError:+ # Windows reports an ICMP port-unreachable for a datagram this+ # socket sent as a reset on the next receive. The socket is+ # fine; the peer that was not listening is the Mac's problem.+ continue+ except OSError as exc:+ if self._stop.is_set():+ break+ self.error = str(exc)+ self.logger.error("pairing beacon stopped: %s", exc)+ break+ message = decode(data)+ if message is None:+ continue+ with self._lock:+ reply = self.host.handle(message)+ paired, self.host.paired = self.host.paired, None+ if reply is not None:+ try:+ sock.sendto(encode(reply), address)+ except OSError as exc:+ self.logger.warning("pairing reply not sent: %s", exc)+ if paired is not None:+ self.logger.info("paired with %s at %s", paired[1] or "a Mac", address[0])+ try:+ self.on_paired(paired[0], paired[1], address[0])+ except Exception:+ self.logger.exception("on_paired failed")+ except Exception as exc:+ self.error = str(exc)+ self.logger.exception("pairing beacon stopped")+ finally:+ sock.close()+++class Discovery:+ """The Mac's socket loop: listens for beacons and carries pairing attempts on the same+ socket, so a reply comes back to the port the PC heard from."""++ def __init__(self, logger=None, bind_port=PAIRING_PORT, clock=time.monotonic):+ self.logger = logger or logging.getLogger("Beamer")+ self.bind_port = bind_port+ self.clock = clock+ self._lock = threading.Lock()+ self._seen = {}+ self._replies = queue.Queue()+ self._stop = threading.Event()+ self._thread = None+ self._sock = None+ self.error = None++ def start(self) -> None:+ if self._thread is not None:+ return+ self._stop.clear()+ self._thread = threading.Thread(target=self._run, name="Beamer-discovery", daemon=True)+ self._thread.start()++ def stop(self) -> None:+ self._stop.set()+ thread = self._thread+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout=2.0)+ self._thread = None++ def pcs(self) -> list:+ """Every PC heard from recently: dicts of name, address, port, reply_port, pairing."""+ cutoff = self.clock() - BEACON_STALE_SECONDS+ with self._lock:+ stale = [key for key, entry in self._seen.items() if entry["seen_at"] < cutoff]+ for key in stale:+ del self._seen[key]+ return sorted(+ ({k: v for k, v in entry.items() if k != "seen_at"} for entry in self._seen.values()),+ key=lambda entry: (entry["name"].lower(), entry["address"]),+ )++ def pair(self, pc: dict, code: str, name: str = None) -> str:+ """Runs the exchange with `pc` (an entry from pcs()) and returns the token. Blocks for+ up to PAIR_ATTEMPTS replies' worth; call it off the main thread."""+ sock = self._sock+ if sock is None:+ raise PairingError("discovery is not running")+ client = PairingClient(pc["pair_id"], code, name or machine_name())+ target = (pc["address"], pc["reply_port"])+ while True:+ try:+ self._replies.get_nowait()+ except queue.Empty:+ break+ request = encode(client.request())+ for _attempt in range(PAIR_ATTEMPTS):+ sock.sendto(request, target)+ deadline = self.clock() + PAIR_REPLY_TIMEOUT_SECONDS+ while True:+ remaining = deadline - self.clock()+ if remaining <= 0:+ break+ try:+ reply, address = self._replies.get(timeout=remaining)+ except queue.Empty:+ break+ if address[0] != target[0] or reply.get("pair") != client.pair_id:+ continue+ return client.accept(reply)+ raise PairingError("no_answer")++ def _run(self) -> None:+ try:+ sock = _udp_socket(self.bind_port)+ except OSError as exc:+ self.error = str(exc)+ self.logger.error("discovery could not bind UDP %s: %s", self.bind_port, exc)+ return+ self.error = None+ self._sock = sock+ try:+ while not self._stop.is_set():+ try:+ data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)+ except socket.timeout:+ continue+ except ConnectionResetError:+ continue+ except OSError as exc:+ if self._stop.is_set():+ break+ self.error = str(exc)+ self.logger.error("discovery stopped: %s", exc)+ break+ message = decode(data)+ if message is None:+ continue+ kind = message.get("type")+ if kind == MSG_BEACON:+ self._note_beacon(message, address)+ elif kind == MSG_PAIR_REPLY:+ self._replies.put((message, address))+ except Exception as exc:+ self.error = str(exc)+ self.logger.exception("discovery stopped")+ finally:+ self._sock = None+ sock.close()++ def _note_beacon(self, message: dict, address) -> None:+ name = message.get("name")+ port = message.get("port")+ pair_id = message.get("pair")+ if not isinstance(name, str) or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:+ return+ entry = {+ "name": name[:64] or address[0],+ "address": address[0],+ "port": port,+ "reply_port": address[1],+ "pair_id": pair_id if isinstance(pair_id, str) and pair_id else None,+ "seen_at": self.clock(),+ }+ with self._lock:+ self._seen[address[0]] = entrydiff --git a/win_app/protocol.py b/win_app/protocol.pynew file mode 100644index 0000000..afe05b2--- /dev/null+++ b/win_app/protocol.py@@ -0,0 +1,443 @@+"""Wire protocol shared by mac_app/bridge.py and win_app/receiver.py.++The link is encrypted and authenticated with ChaCha20-Poly1305 under a key both+sides derive from the shared token (HKDF-SHA256); the token itself never crosses+the wire, and a peer that cannot produce a valid tag does not hold it.++A connection opens with one cleartext preamble each way -- WIRE_MAGIC, one+version byte, and that side's 8-byte nonce prefix -- so a version mismatch+produces a readable status instead of undecryptable garbage. Every frame after+that is a 4-byte big-endian length, then a 4-byte big-endian counter, then the+ciphertext with its tag; the length covers the counter and ciphertext. The nonce+is prefix + counter, each side counting its own frames from 1, and the receiver+rejects any counter that is not the next one, so a captured frame cannot be+replayed. A reconnect draws a new prefix, so a counter never repeats under one+key and prefix.+"""++import base64+import binascii+import json+import os+import socket+import struct+import threading+import time++from cryptography.exceptions import InvalidTag+from cryptography.hazmat.primitives import hashes+from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305+from cryptography.hazmat.primitives.kdf.hkdf import HKDF++HEADER_SIZE = 4+COUNTER_SIZE = 4+NONCE_PREFIX_SIZE = 8+MAX_COUNTER = 0xFFFFFFFF+# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing+# pairing and a mixed-version pair for no gain.+WIRE_MAGIC = b"BEAMY"+PREAMBLE_SIZE = len(WIRE_MAGIC) + 1 + NONCE_PREFIX_SIZE+PROTOCOL_VERSION = 4++# Both ports sit below 49152 on purpose. Windows and macOS both hand out 49152-65535 as+# ephemeral ports, and Windows lets WinNAT reserve whole 100-port blocks from that range that+# move on every reboot: one landed on the old 51820 and the receiver could not bind at all,+# while the PC's outward link carried on working, so input went one way only. Nothing is+# handed out below 49152, so the port a user pairs on stays theirs.+DEFAULT_PORT = 24820+PAIRING_PORT = 24821+# What DEFAULT_PORT was until 20-09-2026. A config still carrying it was never chosen by+# anyone, so it is migrated rather than honoured; a port a user picked is left alone.+LEGACY_DEFAULT_PORT = 51820+# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing+# pairing and a mixed-version pair for no gain.+KEY_SALT = b"beamy-key-v1"+# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing+# pairing and a mixed-version pair for no gain.+KEY_INFO = b"beamy-input-channel"+CLIPBOARD_MAX_BYTES = 256 * 1024+# The clipboard goes out ahead of the focus message on every switch, sealed as one frame and+# buffered whole on both sides, so the image cap is a bound on how late the switch lands, not on+# bandwidth. A full-screen grab of a 3456x2234 Retina display measured 2.9MB as PNG (09-09-2026);+# 8MB covers that with room for a busier desktop, and as a base64 frame (~10.7MB) it is about+# 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 * 1024+CLIPBOARD_IMAGE_PNG = "png"+# 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 (18-09-2026).+MAX_FRAME_BYTES = 16 * 1024 * 1024+# The first frame each way is a hello or a welcome of a few dozen bytes. Anything larger before+# authentication is not a Beamer, so it is refused before it is read.+HELLO_MAX_BYTES = 4096+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"++MSG_HELLO = "hello"+MSG_WELCOME = "welcome"+MSG_PING = "ping"+MSG_KEYDOWN = "keydown"+MSG_KEYUP = "keyup"+MSG_MOUSEMOVE = "mousemove"+MSG_MOUSEDOWN = "mousedown"+MSG_MOUSEUP = "mouseup"+MSG_SCROLL = "scroll"+MSG_ACK = "ack"+MSG_CLIPBOARD = "clipboard"+MSG_FOCUS = "focus"+MSG_GESTURE = "gesture"+MSG_SWITCH = "switch"+MSG_ARRANGEMENT = "arrangement"++# System trackpad gestures. The Mac classifies one at the end of the movement and sends a+# single message; the name is the finger motion, not its meaning, so the receiver decides+# what a swipe does and Windows' own touchpad settings apply when it can inject a real one.+GESTURE_SWIPE_UP = "swipe_up"+GESTURE_SWIPE_DOWN = "swipe_down"+GESTURE_SWIPE_LEFT = "swipe_left"+GESTURE_SWIPE_RIGHT = "swipe_right"+GESTURE_SPREAD = "spread"+GESTURE_PINCH = "pinch"+GESTURE_NAMES = frozenset(+ {+ GESTURE_SWIPE_UP,+ GESTURE_SWIPE_DOWN,+ GESTURE_SWIPE_LEFT,+ GESTURE_SWIPE_RIGHT,+ GESTURE_SPREAD,+ GESTURE_PINCH,+ }+)++class ProtocolError(Exception):+ pass+++class ConnectionClosed(Exception):+ pass+++class AuthenticationError(ProtocolError):+ """A frame failed authentication: the peer does not hold the shared token,+ or the stream was tampered with. Deliberately carries nothing else."""++ def __init__(self):+ super().__init__("frame failed authentication")+++class VersionMismatch(ProtocolError):+ """The peer's preamble named another wire version. `peer_version` is None+ when the peer sent no preamble at all -- an older Beamer that opened with a+ length-prefixed cleartext frame instead."""++ def __init__(self, peer_version):+ super().__init__(f"peer speaks wire version {peer_version!r}, expected {PROTOCOL_VERSION}")+ self.peer_version = peer_version+++def derive_key(token: str) -> bytes:+ return HKDF(algorithm=hashes.SHA256(), length=32, salt=KEY_SALT, info=KEY_INFO).derive(+ token.encode("utf-8")+ )+++class SecureSession:+ """One connection's cipher state for both directions. Build a new one per+ connection: it draws a fresh nonce prefix and starts both counters at zero.+ `send_lock` serialises sealing, and send_msg holds it across the write too,+ so counters are never reused and frames reach the wire in counter order;+ `open` is expected to run on a single reader thread per connection."""++ def __init__(self, token: str, prefix: bytes = None):+ self._cipher = ChaCha20Poly1305(derive_key(token))+ self.prefix = os.urandom(NONCE_PREFIX_SIZE) if prefix is None else bytes(prefix)+ if len(self.prefix) != NONCE_PREFIX_SIZE:+ raise ValueError("nonce prefix must be 8 bytes")+ self.send_lock = threading.RLock()+ self._send_counter = 0+ self.peer_prefix = None+ self._recv_counter = 0++ def preamble(self) -> bytes:+ return WIRE_MAGIC + bytes([PROTOCOL_VERSION]) + self.prefix++ def accept_preamble(self, data: bytes) -> None:+ if len(data) != PREAMBLE_SIZE or not data.startswith(WIRE_MAGIC):+ raise VersionMismatch(None)+ version = data[len(WIRE_MAGIC)]+ if version != PROTOCOL_VERSION:+ raise VersionMismatch(version)+ peer_prefix = data[len(WIRE_MAGIC) + 1:]+ # A reflected preamble would let our own frames be played back to us.+ if peer_prefix == self.prefix:+ raise ProtocolError("peer echoed this side's nonce prefix")+ self.peer_prefix = peer_prefix++ def seal(self, msg: dict) -> bytes:+ body = json.dumps(msg).encode("utf-8")+ with self.send_lock:+ if self._send_counter >= MAX_COUNTER:+ raise ProtocolError("frame counter exhausted; reconnect")+ self._send_counter += 1+ counter = struct.pack(">I", self._send_counter)+ ciphertext = self._cipher.encrypt(self.prefix + counter, body, None)+ return struct.pack(">I", COUNTER_SIZE + len(ciphertext)) + counter + ciphertext++ def open(self, body: bytes) -> dict:+ if self.peer_prefix is None:+ raise ProtocolError("frame received before the peer's preamble")+ if len(body) <= COUNTER_SIZE:+ raise ProtocolError("frame too short")+ (counter,) = struct.unpack(">I", body[:COUNTER_SIZE])+ if counter != self._recv_counter + 1:+ raise ProtocolError("frame counter did not advance; replay rejected")+ try:+ plain = self._cipher.decrypt(self.peer_prefix + body[:COUNTER_SIZE], body[COUNTER_SIZE:], None)+ except InvalidTag:+ raise AuthenticationError() from None+ self._recv_counter = counter+ try:+ message = json.loads(plain.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise ProtocolError(f"malformed message body: {exc}") from exc+ if not isinstance(message, dict):+ raise ProtocolError("message body must be a JSON object")+ return message+++def send_msg(sock: socket.socket, session, msg: dict) -> None:+ with session.send_lock:+ sock.sendall(session.seal(msg))+++def legacy_frame(msg: dict) -> bytes:+ """The pre-v4 cleartext framing, kept only so an older peer can be told to+ update in words it understands rather than left waiting on silence."""+ body = json.dumps(msg).encode("utf-8")+ return struct.pack(">I", len(body)) + body+++def _recv_exact(sock: socket.socket, n: int, deadline: 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 one+ byte 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."""+ chunks = []+ remaining = n+ while remaining > 0:+ if deadline is not None:+ left = deadline - time.monotonic()+ if left <= 0:+ raise socket.timeout("deadline passed while reading")+ sock.settimeout(left)+ chunk = sock.recv(remaining)+ if not chunk:+ raise ConnectionClosed("socket closed while reading")+ chunks.append(chunk)+ remaining -= len(chunk)+ return b"".join(chunks)+++def recv_preamble(sock: socket.socket, session, deadline: float = None) -> None:+ session.accept_preamble(_recv_exact(sock, PREAMBLE_SIZE, deadline))+++def recv_msg(sock: socket.socket, session, limit: int = MAX_FRAME_BYTES, deadline: float = None) -> dict:+ """`limit` is the most a frame may claim before it is read. The receiver+ passes HELLO_MAX_BYTES for the first frame: until that frame's tag has+ been checked the peer has proved nothing, so it must not be able to make+ this side buffer a clipboard-sized frame per connection. `deadline`+ bounds the whole read the same way, for the same reason."""+ header = _recv_exact(sock, HEADER_SIZE, deadline)+ (length,) = struct.unpack(">I", header)+ if length < 1 or length > limit:+ raise ProtocolError(f"invalid message length: {length}")+ return session.open(_recv_exact(sock, length, deadline))+++def hello_msg(return_edge: str = None, resistance_px: int = None) -> dict:+ """The first encrypted frame. It carries no token: decrypting it is the+ proof the sender holds the shared secret.++ `return_edge` and `resistance_px` are the same pair a focus message+ carries, sent here as well so the receiver knows the way home before the+ first crossing rather than after it -- which is what lets the receiver's+ own machine push back across that same border unprompted. Both are+ omitted when None and unknown keys are ignored, so this needs no version+ bump."""+ data = {"version": PROTOCOL_VERSION}+ if return_edge is not None:+ data["return_edge"] = return_edge+ if resistance_px is not None:+ data["resistance_px"] = resistance_px+ return {"type": MSG_HELLO, "data": data}+++def welcome_msg(error: str = None) -> dict:+ """Sent by the receiver to confirm authentication and protocol version.+ `error` (e.g. "version_mismatch") is set when the sender's declared version+ is not supported."""+ data = {"version": PROTOCOL_VERSION}+ if error is not None:+ data["error"] = error+ return {"type": MSG_WELCOME, "data": data}+++def ping_msg() -> dict:+ """Sent by the sender while idle so a dead connection is detected quickly.+ Carries no `seq` and must never be recorded as a processed input event."""+ return {"type": MSG_PING, "data": {}}+++def ack_msg(seq: int, locked: bool = False) -> dict:+ """Sent by the receiver to acknowledge processed input up to `seq`.+ The sender increments `seq` once per outbound input event; the receiver+ echoes back the highest `seq` it has processed. Used as a watchdog+ heartbeat — if the sender doesn't see an ACK for ~2s while redirecting,+ it must force-revert to local input.++ `locked` is set only while Windows is clearing its lock screen, during+ which input is being dropped rather than injected. It is omitted when+ false, and unknown keys are ignored on both sides, so this stays+ compatible in both directions and needs no protocol version bump."""+ data = {"seq": seq}+ if locked:+ data["locked"] = True+ return {"type": MSG_ACK, "data": data}+++def scroll_msg(dy, dx=0.0, mode: str = "line") -> dict:+ """Scroll event. `mode` is "pixel" for continuous trackpad deltas (float+ px) or "line" for discrete wheel clicks. `dx` and `mode` are optional on+ receive for backward tolerance: a missing `dx` means 0, a missing `mode`+ means "line"."""+ return {"type": MSG_SCROLL, "data": {"dy": dy, "dx": dx, "mode": mode}}+++def clipboard_msg(text: str = None, image: bytes = None) -> dict:+ """Whatever was on the clipboard at the switch: `text` as before, and an+ optional PNG under `image` (base64) with `image_format` naming it. Each+ key is omitted when absent. A pre-image receiver ignores the two new keys+ and an image-only message (no `text`) the same way it ignores any other+ unknown data, so this needs no protocol version bump: SecureSession.open+ only requires a JSON object, and neither app validates keys it does not+ read."""+ data = {}+ if text is not None:+ data["text"] = text+ if image is not None:+ data["image"] = base64.b64encode(image).decode("ascii")+ data["image_format"] = CLIPBOARD_IMAGE_PNG+ return {"type": MSG_CLIPBOARD, "data": data}+++def clipboard_image(data) -> bytes:+ """The PNG bytes carried by a clipboard message's `data`, or None when+ there is no image or it is not usable: an unknown format, base64 that+ does not decode, bytes that do not start as a PNG, or more than+ CLIPBOARD_IMAGE_MAX_BYTES. Never raises; the clipboard must never break+ a switch, so junk is dropped here rather than surfaced."""+ if not isinstance(data, dict) or data.get("image_format") != CLIPBOARD_IMAGE_PNG:+ return None+ encoded = data.get("image")+ # Length check before decoding, so an oversized payload costs no decode.+ if not isinstance(encoded, str) or len(encoded) > CLIPBOARD_IMAGE_MAX_BYTES * 4 // 3 + 4:+ return None+ try:+ 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 None+ return image+++def focus_msg(+ target: str,+ edge: str = None,+ offset: float = None,+ return_edge: str = None,+ resistance_px: int = None,+) -> dict:+ """Sent by the sender to move input. `edge` is the receiver edge being+ arrived at and `offset` the fraction along it, both absent when the switch+ came from the shortcut rather than a crossing. `return_edge` and+ `resistance_px` are sent on every switch to the receiver: they are how it+ knows the way home, so nothing about crossing is configured on its side.+ `target` names the machine input is moving to, which is the receiver's own+ name on the way out and the sender's on the way back. All four are omitted when None, and unknown keys are ignored,+ so this needs no protocol version bump."""+ data = {"target": target}+ if edge is not None:+ data["edge"] = edge+ if offset is not None:+ data["offset"] = offset+ if return_edge is not None:+ data["return_edge"] = return_edge+ if resistance_px is not None:+ data["resistance_px"] = resistance_px+ return {"type": MSG_FOCUS, "data": data}+++def switch_msg(target: str, edge: str = None, offset: float = None) -> dict:+ """Sent by the receiver to ask the sender to move input, when the pointer+ has been pushed through the receiver's return edge. `target` is the+ sender's machine -- "mac" on the Mac-to-Windows link, "windows" on the+ Windows-to-Mac one. `edge` is the edge to arrive at there and `offset`+ the fraction along it; both are absent for a plain return with no+ position to carry."""+ data = {"target": target}+ if edge is not None:+ data["edge"] = edge+ if offset is not None:+ data["offset"] = offset+ return {"type": MSG_SWITCH, "data": data}+++def arrangement_msg(mac_edge: str, set_at: int) -> dict:+ """Where the two machines are in relation to each other, as one value:+ the edge of the MAC that leads to the PC. Everything else follows from it+ -- the Mac crosses out by that edge, arrives at the opposite edge of the+ PC, and comes home the same way -- so the two ends cannot describe a+ border that does not exist.++ Either machine may change it, and tells the other with this message.+ `set_at` is unix seconds at the machine that made the change: when two+ ends meet holding different arrangements, because one was changed while+ the other was asleep, the newer one wins rather than whichever spoke+ first. Unknown message types are ignored, so an older Beamer keeps+ working with the arrangement it already has."""+ return {"type": MSG_ARRANGEMENT, "data": {"mac_edge": mac_edge, "set_at": int(set_at)}}+++def read_arrangement(data):+ """(mac_edge, set_at) from an arrangement message's data, or None when it+ carries no edge worth acting on. Never raises: a malformed arrangement+ must not take a working link down."""+ if not isinstance(data, dict):+ return None+ edge = data.get("mac_edge")+ if edge not in ("left", "right", "top", "bottom"):+ return None+ set_at = data.get("set_at")+ if isinstance(set_at, bool) or not isinstance(set_at, (int, float)):+ set_at = 0+ return edge, int(set_at)+++def arrangement_wins(theirs: int, mine: int) -> bool:+ """Whether an arrangement the peer sent should replace the one held here.++ Both ends stamp their own change, so the newer stamp stands: without that,+ an arrangement changed at one machine while the other was asleep would be+ silently undone by the sleeper's hello on the next connection. A peer that+ sends no stamp at all (an older Beamer, or a first connection) loses to any+ stamp of ours, and two ends that have never changed it both hold zero and+ agree anyway."""+ return int(theirs or 0) > int(mine or 0)+++def gesture_msg(name: str) -> dict:+ """One completed system gesture (a GESTURE_* name). Unknown message types are+ ignored by the receiver, so this needs no protocol version bump."""+ return {"type": MSG_GESTURE, "data": {"name": name}}diff --git a/win_app/receiver.py b/win_app/receiver.pynew file mode 100644index 0000000..a64691c--- /dev/null+++ b/win_app/receiver.py@@ -0,0 +1,976 @@+"""Threaded TCP receiver and ACK watchdog for the Windows tray app."""++import logging+import math+import socket+import sys+import threading+import time+from enum import Enum+from typing import Callable, Optional++import return_edge as crossing+import protocol+++LOGGER = logging.getLogger(__name__)+# `config` throughout is whichever settings object the app on this side keeps.+# Only `port` and `auth_token` are ever read from it, and the two apps' classes+# are unrelated types, so it is not annotated or imported here -- importing one+# app's config module would stop this file being the other app's as well.+# The longest an idle link goes without an ACK, so the Mac's watchdog keeps+# seeing a heartbeat when nothing is being typed.+ACK_IDLE_SECONDS = 0.4+# How long an ACK waits after input arrives, batching a burst into one reply.+# A per-event ACK at ~100Hz mouse rates would roughly double the packet count;+# 15ms caps it near 66/s while keeping the round trip the Mac reports honest,+# which a 400ms timer did not -- every reading carried up to 400ms of waiting+# that was never network latency.+ACK_COALESCE_SECONDS = 0.015+HELLO_TIMEOUT_SECONDS = 5.0+SESSION_READ_TIMEOUT_SECONDS = 2.5+INJECTION_ERROR_STATUS_INTERVAL_SECONDS = 5.0+# Windows hands the port back only when whatever holds it lets go — WinNAT's+# dynamic reservations move on every reboot and can land on ours — so a bind+# that fails is waited out rather than ending the listener.+BIND_RETRY_SECONDS = 5.0+# Connections still inside the handshake. Each is bounded to HELLO_TIMEOUT_SECONDS as a whole,+# so a stranger holding these slots loses them within seconds, while the real peer's handshake+# takes milliseconds and always finds one free.+MAX_PENDING_CONNECTIONS = 4+++class ServerState(Enum):+ STOPPED = "Stopped"+ WAITING = "Waiting"+ CONNECTED = "Connected"+ ERROR = "Error"+++class ProcessedSequence:+ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._latest = 0+ self._fallback = 0++ def record(self, message: dict) -> int:+ data = message.get("data", {})+ raw_sequence = message.get("seq")+ if raw_sequence is None and isinstance(data, dict):+ raw_sequence = data.get("seq")+ with self._lock:+ if isinstance(raw_sequence, int) and not isinstance(raw_sequence, bool) and raw_sequence >= 0:+ self._latest = max(self._latest, raw_sequence)+ self._fallback = max(self._fallback, self._latest)+ else:+ self._fallback = max(self._fallback, self._latest) + 1+ self._latest = self._fallback+ return self._latest++ def latest(self) -> int:+ with self._lock:+ return self._latest+++def handle_message(message: dict, injector=None) -> bool:+ """Inject one input event. `injector` defaults to the real input_injector+ module, imported lazily here (not at module load) so receiver.py stays+ importable — and its non-injection logic testable — on a machine without+ ctypes.windll. The Mac copy of this file is handed its own injector at+ construction and never reaches that import. Tests can pass a fake+ injector directly."""+ if injector is None:+ import input_injector as injector+ if not isinstance(message, dict):+ raise protocol.ProtocolError("message body must be a JSON object")+ message_type = message.get("type")+ data = message.get("data", {})+ if not isinstance(data, dict):+ raise protocol.ProtocolError("message data must be a JSON object")+ if message_type == protocol.MSG_KEYDOWN:+ injector.inject_key(data["key"], down=True)+ elif message_type == protocol.MSG_KEYUP:+ injector.inject_key(data["key"], down=False)+ elif message_type == protocol.MSG_MOUSEMOVE:+ injector.inject_mouse_move(int(data["dx"]), int(data["dy"]))+ elif message_type == protocol.MSG_MOUSEDOWN:+ injector.inject_mouse_button(data["button"], down=True)+ elif message_type == protocol.MSG_MOUSEUP:+ injector.inject_mouse_button(data["button"], down=False)+ elif message_type == protocol.MSG_SCROLL:+ injector.inject_scroll(data["dy"], data.get("dx", 0), data.get("mode", "line"))+ elif message_type == protocol.MSG_GESTURE:+ injector.inject_gesture(data["name"])+ else:+ LOGGER.warning("Unknown message type ignored: %r", message_type)+ return False+ return True+++class ReceiverServer:+ def __init__(+ self,+ status_callback: Callable[[ServerState, str], None],+ clipboard=None,+ unlock=None,+ desktop=None,+ pressure_callback: Optional[Callable[[str, float, bool], None]] = None,+ injector=None,+ focus_callback: Optional[Callable[[str], None]] = None,+ peer_callback: Optional[Callable[[str, Optional[str], Optional[int]], None]] = None,+ arrangement_callback: Optional[Callable[[str, int], None]] = None,+ self_name: str = "PC",+ peer_name: str = "Mac",+ self_target: str = "windows",+ peer_target: str = "mac",+ ) -> None:+ # One module serves both machines: this file is byte-identical in+ # win_app and mac_app, which test_receiver_parity enforces. Everything+ # platform-shaped is handed in -- the injector, clipboard, desktop+ # geometry and unlock modules, the two names that appear in status+ # text, and the two wire target words -- so nothing below knows which+ # side it is running on. `focus_callback(target)` fires on every focus+ # message, which is how the app that owns this receiver knows input+ # has arrived or gone home -- and once more with the peer's own target+ # when the link that brought input here ends before the peer has+ # taken it back, because the peer fails open on its side and the+ # message saying so never reaches a dead socket.+ self._injector = injector+ self._focus_callback = focus_callback+ self._peer_driving = False+ # `peer_callback(host, return_edge, resistance_px)` fires once per+ # authenticated connection, with the peer's address and the way home+ # its hello carried. It is how the machine on this side learns which+ # border to push out across without anyone configuring it twice --+ # the way home from there is the way out from here.+ self._peer_callback = peer_callback+ # `arrangement_callback(mac_edge, set_at)` fires when the peer says+ # where the two machines are in relation to each other. Either end may+ # change it, so this is how the change arrives at the end that did not+ # make it.+ self._arrangement_callback = arrangement_callback+ self._self_name = self_name+ self._peer_name = peer_name+ self._self_target = self_target+ self._peer_target = peer_target+ self._status_callback = status_callback+ # `desktop` defaults to the real desktop_win module, imported lazily for+ # the same reason as `clipboard` below. `pressure_callback(edge,+ # pressure, crossed)` is called on the session thread as the pointer+ # is pushed against the return edge; the GUI marshals it to the glow.+ self._desktop = desktop+ self._pressure_callback = pressure_callback+ # The way home. Armed by every focus{target:"windows"} the Mac sends,+ # which carries the return edge and resistance, and None until then.+ self._return_edge: Optional[crossing.ReturnEdge] = None+ # `unlock` defaults to the real unlock_win module, imported lazily for+ # the same reason as `clipboard` below.+ self._unlock = unlock+ # Set while a lock-screen unlock is in flight. Input that arrives in+ # that window is dropped rather than queued: an unlock takes several+ # seconds, and replaying seconds of stale mouse moves and keystrokes+ # onto the desktop the moment it appears is worse than losing them.+ self._unlocking = threading.Event()+ # `clipboard` defaults to the real clipboard_win module, imported+ # lazily (not at module load) so receiver.py stays importable -- and+ # its non-clipboard logic testable -- on a machine without+ # ctypes.windll, e.g. this Mac. Tests can pass a fake directly, the+ # same way handle_message's `injector` argument works.+ self._clipboard = clipboard+ self._lock = threading.RLock()+ self._thread: Optional[threading.Thread] = None+ self._stop_event: Optional[threading.Event] = None+ self._listener: Optional[socket.socket] = None+ self._client: Optional[socket.socket] = None+ # The live session per connection, so a message can be sent to the+ # client from outside its own thread -- which is what an arrangement+ # changed in the window needs.+ self._sessions: dict = {}+ self._connections: set = set()+ self._pending = 0+ self._session_generation = 0+ self._requested_running = False++ @property+ def listening(self) -> bool:+ with self._lock:+ return self._requested_running and self._thread is not None and self._thread.is_alive()++ @property+ def return_edge(self) -> Optional[str]:+ """The Windows edge the Mac last named as the way home, or None."""+ model = self._return_edge+ return model.edge if model is not None else None++ @property+ def return_resistance(self) -> Optional[int]:+ """How many pixels of push the Mac last asked for at the return edge, or None."""+ model = self._return_edge+ return model.resistance_px if model is not None else None++ def start(self, config) -> None:+ with self._lock:+ if self._thread is not None and self._thread.is_alive():+ return+ stop_event = threading.Event()+ thread = threading.Thread(+ target=self._server_thread,+ args=(config, stop_event),+ name="Beamer-server",+ daemon=True,+ )+ self._stop_event = stop_event+ self._thread = thread+ self._requested_running = True+ self._set_status(ServerState.WAITING, f"Starting on port {config.port}")+ try:+ thread.start()+ except Exception:+ with self._lock:+ if self._thread is thread:+ self._thread = None+ self._stop_event = None+ self._requested_running = False+ raise++ def stop(self) -> None:+ with self._lock:+ self._requested_running = False+ stop_event = self._stop_event+ listener = self._listener+ connections = set(self._connections)+ thread = self._thread+ if stop_event is not None:+ stop_event.set()+ for connection in connections:+ self._close_socket(connection)+ self._close_socket(listener)+ # start() publishes the thread under the lock and starts it outside, so a+ # stop() landing in that window would join a thread that never started,+ # which raises rather than returning.+ if thread is not None and thread is not threading.current_thread() and thread.ident is not None:+ thread.join(timeout=2.0)+ if thread is not None and thread.is_alive():+ LOGGER.error("Server thread did not stop within two seconds")+ self._set_status(ServerState.ERROR, "Listener did not stop; see log")+ return+ with self._lock:+ if self._thread is thread:+ self._thread = None+ self._stop_event = None+ self._listener = None+ self._client = None+ self._hand_back("Listening stopped")+ self._set_status(ServerState.STOPPED, "Listening stopped")++ def _server_thread(self, config, stop_event: threading.Event) -> None:+ failed = False+ try:+ self._serve(config, stop_event)+ except Exception as exc:+ if not stop_event.is_set():+ failed = True+ LOGGER.exception("Server thread failed")+ self._set_status(ServerState.ERROR, f"Listener failed: {exc}")+ finally:+ with self._lock:+ listener = self._listener+ connections = set(self._connections)+ self._listener = None+ self._client = None+ if self._thread is threading.current_thread():+ self._thread = None+ self._stop_event = None+ if failed:+ self._requested_running = False+ for connection in connections:+ self._close_socket(connection)+ self._close_socket(listener)+ if stop_event.is_set():+ self._set_status(ServerState.STOPPED, "Listening stopped")++ def _bind(self, config, stop_event: threading.Event):+ """Bind the listening socket, waiting for the port if something holds it."""+ reported = ""+ while not stop_event.is_set():+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ # On the Mac this is what lets the port be taken back straight+ # after a restart, while the last session's connections sit in+ # TIME_WAIT. On Windows the same option means something else: a+ # second bind on a port another listener holds succeeds, and the+ # two split the Mac's connections between them, so the held-port+ # wait below never fired for a zombie Beamer (rig, 22-09-2026).+ # Windows does not need it for TIME_WAIT, so it does without.+ if sys.platform != "win32":+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ try:+ listener.bind(("0.0.0.0", config.port))+ except OSError as exc:+ self._close_socket(listener)+ # Said the way a user can act on it: the log carries the error, the+ # status carries the one thing they can change.+ detail = f"Another program is using port {config.port} — change the port on the Connection page"+ # Only on a change: a retry every few seconds otherwise repeats+ # the same line and the same status for as long as the port is held.+ if detail != reported:+ LOGGER.error("Cannot listen on port %s: %s", config.port, exc)+ reported = detail+ self._set_status(ServerState.ERROR, detail)+ stop_event.wait(BIND_RETRY_SECONDS)+ continue+ return listener+ return None++ def _serve(self, config, stop_event: threading.Event) -> None:+ listener = self._bind(config, stop_event)+ if listener is None:+ return+ # A stale, not-yet-torn-down session must never block a reconnect: a+ # backlog of 2 lets a fresh Mac connection queue up while the previous+ # session's thread is still winding down, instead of the OS refusing+ # it outright.+ listener.listen(2)+ listener.settimeout(0.5)+ with self._lock:+ self._listener = listener+ LOGGER.info("Listening on 0.0.0.0:%s", config.port)+ self._set_status(ServerState.WAITING, f"Waiting on port {config.port}")+ while not stop_event.is_set():+ try:+ connection, address = listener.accept()+ except socket.timeout:+ continue+ except OSError:+ if stop_event.is_set():+ break+ raise+ # Hand the connection to its own thread immediately and go back+ # to accept(): a slow or stuck peer must never stall the listener,+ # which is what used to make a stale session block a reconnect.+ # Bounded, because accept() happens before any proof of the token.+ # Only handshakes count: an authenticated peer never blocks the+ # next one, and a stranger's slot frees itself within seconds.+ with self._lock:+ crowded = self._pending >= MAX_PENDING_CONNECTIONS+ if not crowded:+ self._pending += 1+ if crowded:+ LOGGER.warning("Refusing %s:%s: %d handshakes already in progress", address[0], address[1], MAX_PENDING_CONNECTIONS)+ self._close_socket(connection)+ continue+ thread = threading.Thread(+ target=self._session_thread,+ args=(connection, address, config, stop_event),+ name="Beamer-session",+ daemon=True,+ )+ thread.start()++ def _session_thread(+ self,+ connection: socket.socket,+ address,+ config,+ server_stop: threading.Event,+ ) -> None:+ with self._lock:+ self._connections.add(connection)+ try:+ self._handle_client(connection, address, config, server_stop)+ finally:+ with self._lock:+ self._connections.discard(connection)+ self._close_socket(connection)++ def _handle_client(+ self,+ connection: socket.socket,+ address,+ config,+ server_stop: threading.Event,+ ) -> None:+ peer = f"{address[0]}:{address[1]}"+ LOGGER.info("Connection from %s", peer)+ try:+ handshake = self._handshake(connection, peer, config, server_stop)+ finally:+ with self._lock:+ self._pending -= 1+ if handshake is None:+ return+ session, version, hello = handshake++ if version != protocol.PROTOCOL_VERSION:+ LOGGER.warning(+ "Rejecting %s: unsupported protocol version %r (expected %s)",+ peer,+ version,+ protocol.PROTOCOL_VERSION,+ )+ self._send_message(connection, session, protocol.welcome_msg(error="version_mismatch"))+ self._note_version_mismatch(f"{self._peer_name} app is an older Beamer version — update both apps")+ return++ # The Mac now pings at least once a second while idle, so a read+ # timeout here means the peer is gone, not merely quiet.+ connection.settimeout(SESSION_READ_TIMEOUT_SECONDS)+ connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)+ sequence = ProcessedSequence()+ if not self._send_message(connection, session, protocol.welcome_msg()):+ return++ with self._lock:+ previous_client = self._client+ self._client = connection+ self._sessions[connection] = session+ self._session_generation += 1+ my_generation = self._session_generation+ if previous_client is not None and previous_client is not connection:+ # Preempt: a reconnecting Mac instantly replaces a stale session+ # instead of queueing behind it. Closing it here unblocks that+ # thread's blocked recv so it can exit.+ LOGGER.info("Superseding the previous session for %s", peer)+ self._close_socket(previous_client)++ LOGGER.info("Authenticated %s (protocol v%s)", peer, version)+ # A peer that has just connected has its input at home, whatever the+ # session it replaced was in the middle of.+ self._hand_back(f"{self._peer_name} reconnected")+ self._notify_peer(address[0], hello)+ self._set_status(ServerState.CONNECTED, f"Connected to {address[0]}")++ client_stop = threading.Event()+ ack_due = threading.Event()+ ack_thread = threading.Thread(+ target=self._ack_thread,+ args=(connection, session, sequence, client_stop, server_stop, ack_due),+ name="Beamer-ack",+ daemon=True,+ )+ ack_thread.start()++ last_injection_status_at = 0.0+ try:+ while not server_stop.is_set() and not client_stop.is_set():+ try:+ message = protocol.recv_msg(connection, session)+ except socket.timeout:+ if self._is_current_session(my_generation):+ LOGGER.warning("%s went quiet; treating the connection as dead", peer)+ break+ except protocol.ConnectionClosed:+ if self._is_current_session(my_generation):+ LOGGER.info("%s disconnected", peer)+ break+ except protocol.ProtocolError as exc:+ if self._is_current_session(my_generation):+ LOGGER.warning("Protocol error from %s: %s", peer, exc)+ break+ except OSError as exc:+ if (+ not server_stop.is_set()+ and not client_stop.is_set()+ and self._is_current_session(my_generation)+ ):+ LOGGER.warning("Receive failed for %s: %s", peer, exc)+ break+ message_type = message.get("type") if isinstance(message, dict) else None+ if message_type == protocol.MSG_PING:+ # Liveness only; never recorded or acked as an input event.+ continue+ if message_type == protocol.MSG_FOCUS:+ # Never recorded or acked as an input event, like ping.+ self._handle_focus(message, connection, session, peer, address[0])+ continue+ if message_type == protocol.MSG_CLIPBOARD:+ # Never recorded or acked as an input event, like ping.+ self._handle_inbound_clipboard(message, peer)+ continue+ if message_type == protocol.MSG_ARRANGEMENT:+ # Never recorded or acked as an input event, like ping.+ self._handle_arrangement(message)+ continue+ if self._unlocking.is_set():+ # Dropped, not queued: see _begin_unlock. Still recorded so+ # the ACK sequence stays continuous and the Mac's watchdog+ # does not read the unlock as a dead link.+ sequence.record(message)+ continue+ if message_type == protocol.MSG_MOUSEMOVE and self._return_trip(message, connection, session):+ # Held at the edge or crossed: not injected, but still an+ # input event for the ACK sequence.+ sequence.record(message)+ continue+ try:+ processed = handle_message(message, self._injector)+ except Exception:+ LOGGER.exception("Input event from %s could not be injected", peer)+ now = time.monotonic()+ if now - last_injection_status_at >= INJECTION_ERROR_STATUS_INTERVAL_SECONDS:+ last_injection_status_at = now+ self._set_status(ServerState.CONNECTED, f"Input error from {address[0]}; see log")+ continue+ if not processed:+ continue+ sequence.record(message)+ ack_due.set()+ finally:+ client_stop.set()+ ack_thread.join(timeout=1.0)+ if ack_thread.is_alive():+ LOGGER.error("ACK thread did not stop within one second")+ self._set_status(ServerState.ERROR, "ACK worker did not stop; see log")+ with self._lock:+ self._sessions.pop(connection, None)+ is_current = self._session_generation == my_generation+ if is_current:+ self._client = None+ if is_current:+ self._hand_back(f"{self._peer_name} went away")+ # A preempted (superseded) session must exit silently: only the+ # current-generation session may flip status to WAITING.+ if is_current and not server_stop.is_set():+ self._set_status(ServerState.WAITING, f"Waiting on port {config.port}")++ def _is_current_session(self, generation: int) -> bool:+ with self._lock:+ return self._session_generation == generation++ def _handshake(self, connection: socket.socket, peer: str, config, server_stop: threading.Event):+ """Read the Mac's preamble, answer with ours, then open its hello.+ Returns (session, declared version) or None once the failure has been+ logged. The preamble is read before ours is sent so an older Mac, which+ opens with a cleartext frame instead, gets a cleartext version_mismatch+ it can display rather than bytes it reads as a bogus length."""+ connection.settimeout(HELLO_TIMEOUT_SECONDS)+ # One deadline for the whole handshake, not a timeout per read: a peer+ # trickling a byte at a time would otherwise hold its slot for ever.+ deadline = time.monotonic() + HELLO_TIMEOUT_SECONDS+ session = protocol.SecureSession(config.auth_token)+ try:+ try:+ protocol.recv_preamble(connection, session, deadline=deadline)+ except protocol.VersionMismatch as exc:+ if exc.peer_version is None:+ LOGGER.warning("%s opened with the pre-v4 cleartext protocol", peer)+ connection.sendall(protocol.legacy_frame(protocol.welcome_msg(error="version_mismatch")))+ self._note_version_mismatch(f"{self._peer_name} app is an older Beamer version — update both apps")+ else:+ LOGGER.warning("%s speaks wire version %r, expected %s", peer, exc.peer_version, protocol.PROTOCOL_VERSION)+ connection.sendall(session.preamble())+ self._note_version_mismatch(+ f"{self._peer_name} app is Beamer protocol v{exc.peer_version}, this {self._self_name} is v{protocol.PROTOCOL_VERSION} — update both apps"+ )+ return None+ connection.sendall(session.preamble())+ first = protocol.recv_msg(connection, session, limit=protocol.HELLO_MAX_BYTES, deadline=deadline)+ except socket.timeout:+ LOGGER.warning("Authentication timed out for %s", peer)+ return None+ except protocol.ConnectionClosed:+ LOGGER.info("%s disconnected before authentication", peer)+ return None+ except protocol.AuthenticationError:+ # The one signal that the Mac does not hold the shared token. Nothing is sent back:+ # a reply would tell a guesser it had reached a Beamer.+ LOGGER.warning("Authentication failed for %s: frame failed authentication", peer)+ return None+ except protocol.ProtocolError as exc:+ LOGGER.warning("Protocol error during authentication from %s: %s", peer, exc)+ return None+ except OSError as exc:+ if not server_stop.is_set():+ LOGGER.warning("Authentication receive failed for %s: %s", peer, exc)+ return None+ if first.get("type") != protocol.MSG_HELLO:+ LOGGER.warning("%s authenticated but did not say hello first", peer)+ return None+ data = first.get("data")+ return session, self._hello_version(first), data if isinstance(data, dict) else {}++ def _note_version_mismatch(self, detail: str) -> None:+ with self._lock:+ has_active_client = self._client is not None+ if not has_active_client:+ self._set_status(ServerState.ERROR, detail)++ def _ack_thread(+ self,+ connection: socket.socket,+ session: protocol.SecureSession,+ sequence: ProcessedSequence,+ client_stop: threading.Event,+ server_stop: threading.Event,+ ack_due: threading.Event,+ ) -> None:+ try:+ while not server_stop.is_set():+ woken = ack_due.wait(ACK_IDLE_SECONDS)+ if client_stop.is_set():+ return+ if woken:+ ack_due.clear()+ # Coalesce on client_stop, not sleep, so a disconnect during+ # the batching window still exits promptly.+ if client_stop.wait(ACK_COALESCE_SECONDS):+ return+ ack = protocol.ack_msg(sequence.latest(), locked=self._unlocking.is_set())+ if not self._send_message(connection, session, ack):+ client_stop.set()+ self._close_socket(connection)+ return+ except Exception as exc:+ LOGGER.exception("ACK thread failed")+ self._set_status(ServerState.ERROR, f"ACK worker failed: {exc}")+ client_stop.set()+ self._close_socket(connection)++ def _clipboard_module(self):+ if self._clipboard is not None:+ return self._clipboard+ import clipboard_win+ return clipboard_win++ def _unlock_module(self):+ if self._unlock is not None:+ return self._unlock+ import unlock_win+ return unlock_win++ def _desktop_module(self):+ if self._desktop is not None:+ return self._desktop+ import desktop_win+ return desktop_win++ def _return_trip(self, message: dict, connection: socket.socket, session: protocol.SecureSession) -> bool:+ """The return path. Feeds every mouse move to the pressure model while+ a return edge is armed; True means the move was consumed — the pointer+ was held at the edge, or it broke through and the Mac has been asked+ to take input back — and must not be injected."""+ model = self._return_edge+ if model is None or not model.armed:+ return False+ data = message.get("data")+ if not isinstance(data, dict):+ return False+ try:+ desktop = self._desktop_module()+ outcome = model.feed(desktop.monitors(), desktop.cursor_position(), float(data["dx"]), float(data["dy"]))+ if outcome.action == crossing.HOLD:+ desktop.set_cursor_position(*outcome.position)+ elif outcome.action == crossing.CROSS:+ LOGGER.info("Pointer pushed through the %s edge; returning input to the %s", model.edge, self._peer_name)+ self._send_message(connection, session, protocol.switch_msg(self._peer_target, outcome.edge, outcome.offset))+ except Exception:+ # Logged once, not at 100Hz: the return edge is dropped until the+ # Mac's next switch re-arms it, and input keeps flowing normally.+ LOGGER.exception("Return edge failed; crossing back is off until the next switch")+ self._return_edge = None+ return False+ if outcome.action == crossing.PASS:+ return False+ self._notify_pressure(model.edge, outcome.pressure, outcome.action == crossing.CROSS)+ return True++ def send_arrangement(self, mac_edge: str, set_at: int) -> bool:+ """Tell the peer where the machines are, over the connection it opened+ to this one. Used when the change was made at this end: the outward+ link may be down, or may not exist on this machine at all, and this+ one is up by definition whenever there is anyone to tell."""+ with self._lock:+ connection = self._client+ session = self._session_for(connection)+ if connection is None or session is None:+ return False+ return self._send_message(connection, session, protocol.arrangement_msg(mac_edge, set_at))++ def send_home(self) -> bool:+ """Send the peer's input back to it from this end, as its own return+ edge would. The escape that does not depend on that edge: the owner+ calls it when someone here asks to switch while the peer is driving,+ which was refused outright until the 23-09-2026 afternoon a push+ through the edge never fired and the PC's mouse stayed on the Mac.+ The send runs on its own thread, because the callers are a hook and+ an event tap that must never block on a socket."""+ with self._lock:+ connection = self._client+ session = self._session_for(connection)+ if not self._peer_driving or connection is None or session is None:+ return False+ self._return_edge = None+ LOGGER.info("Switch asked for here; sending input home to the %s", self._peer_name)+ threading.Thread(+ target=self._send_message,+ args=(connection, session, protocol.switch_msg(self._peer_target)),+ name="Beamer-send-home",+ daemon=True,+ ).start()+ return True++ def _session_for(self, connection):+ return self._sessions.get(connection) if connection is not None else None++ def _handle_arrangement(self, message: dict) -> None:+ read = protocol.read_arrangement(message.get("data"))+ if read is None or self._arrangement_callback is None:+ return+ try:+ self._arrangement_callback(*read)+ except Exception:+ LOGGER.exception("Arrangement callback failed")++ def _notify_peer(self, host: str, hello: dict) -> None:+ if self._peer_callback is None:+ return+ edge = hello.get("return_edge")+ if edge not in crossing.EDGES:+ edge = None+ resistance = hello.get("resistance_px")+ if isinstance(resistance, bool) or not isinstance(resistance, (int, float)):+ resistance = None+ try:+ self._peer_callback(host, edge, None if resistance is None else int(resistance))+ except Exception:+ LOGGER.exception("Peer callback failed")++ def _notify_focus(self, target) -> None:+ if self._focus_callback is None or not isinstance(target, str):+ return+ if target == self._self_target:+ self._peer_driving = True+ elif target == self._peer_target:+ self._peer_driving = False+ try:+ self._focus_callback(target)+ except Exception:+ LOGGER.exception("Focus callback failed")++ def _hand_back(self, why: str) -> None:+ """The peer's input was on this machine and the link that carried it+ is over. The peer has already failed open on its own side; the focus+ that would have said so died with the socket, so it is raised here.+ Otherwise the owner of this receiver keeps treating the peer as+ driving, and its own edge and shortcut stay dead until the peer next+ crosses in and back."""+ if not self._peer_driving:+ return+ self._return_edge = None+ LOGGER.info("%s while its input was here; input returned to this %s", why, self._self_name)+ self._release_peer_keys()+ self._notify_focus(self._peer_target)++ def _release_peer_keys(self) -> None:+ """Let go of whatever the peer was holding here. A modifier or button+ injected for the peer and never released -- a chord in flight when+ input went home or the link died -- would otherwise stay down on this+ machine, turning every later local keystroke into a shortcut."""+ injector = self._injector+ if injector is None:+ try:+ import input_injector as injector+ except Exception:+ LOGGER.exception("Injector unavailable; keys the peer held may still be down")+ return+ release = getattr(injector, "release_all", None)+ if release is None:+ return+ try:+ release()+ except Exception:+ LOGGER.exception("Could not release the keys the %s was holding", self._peer_name)++ def _notify_pressure(self, edge: str, pressure: float, crossed: bool) -> None:+ if self._pressure_callback is None:+ return+ try:+ self._pressure_callback(edge, pressure, crossed)+ except Exception:+ LOGGER.exception("Pressure callback failed")++ def _arm_return(self, data: dict) -> None:+ """Every switch to Windows says which edge leads home and how hard to+ push; an older Mac that says neither gets no return edge, so nothing+ it does not expect can fire."""+ edge = data.get("return_edge")+ if edge not in crossing.EDGES:+ self._return_edge = None+ return+ resistance = data.get("resistance_px", crossing.DEFAULT_RESISTANCE_PX)+ # json.loads accepts Infinity and NaN, and int() of either raises, which+ # nothing above this catches: a bad number gets the default instead.+ if isinstance(resistance, bool) or not isinstance(resistance, (int, float)) or not math.isfinite(resistance):+ resistance = crossing.DEFAULT_RESISTANCE_PX+ self._return_edge = crossing.ReturnEdge(edge, int(resistance))++ def _place_pointer(self, data: dict) -> None:+ edge = data.get("edge")+ offset = data.get("offset")+ if edge not in crossing.EDGES or isinstance(offset, bool) or not isinstance(offset, (int, float)):+ return+ try:+ desktop = self._desktop_module()+ desktop.set_cursor_position(*crossing.arrival_position(desktop.monitors(), edge, offset))+ except Exception:+ LOGGER.exception("Could not place the pointer at the %s edge on arrival", edge)++ def _begin_unlock(self, peer: str, host: str) -> None:+ """Take the console off the lock screen, if it is on one, so the input+ about to arrive has somewhere to land. Beamer cannot type on the secure+ desktop at all -- see unlock_win -- so without this, switching to a+ locked PC silently injects into nothing.++ The lock test is a cheap in-process snapshot, so the common case (an+ unlocked PC) stays inline and costs nothing. Only a real unlock goes to+ a thread, because it takes seconds and this runs on the message loop+ that has to keep draining pings."""+ try:+ unlock = self._unlock_module()+ except Exception:+ LOGGER.exception("Unlock support unavailable")+ return+ if unlock.is_locked() is not True:+ return+ if self._unlocking.is_set():+ return+ self._unlocking.set()+ LOGGER.info("%s switched to a locked PC; asking the provider to unlock", peer)+ self._set_status(ServerState.CONNECTED, "Unlocking Windows…")+ with self._lock:+ generation = self._session_generation+ threading.Thread(+ target=self._unlock_worker,+ args=(unlock, peer, host, generation),+ name="Beamer-unlock",+ daemon=True,+ ).start()++ def _unlock_worker(self, unlock, peer: str, host: str, generation: int) -> None:+ try:+ unlocked = unlock.ensure_unlocked()+ except Exception:+ LOGGER.exception("Unlock failed for %s", peer)+ unlocked = False+ finally:+ self._unlocking.clear()+ # An unlock takes seconds, so the Mac may have gone in the meantime and+ # the session's own exit already have set WAITING. Only the session+ # that asked for this unlock may report its outcome.+ if not self._is_current_session(generation):+ return+ if unlocked:+ self._set_status(ServerState.CONNECTED, f"Connected to {host}")+ else:+ self._set_status(+ ServerState.CONNECTED, "Windows is locked — unlock it at the PC"+ )++ def _handle_focus(+ self,+ message: dict,+ connection: socket.socket,+ session: protocol.SecureSession,+ peer: str,+ host: str,+ ) -> None:+ """`focus{target:"mac"}` means the Mac just switched input back to+ itself: reply with this Windows clipboard's text so the Mac's+ pasteboard picks up whatever was last copied here.+ `target:"windows"` means input is coming here: learn the way home+ from it, land the pointer where a crossing says, and clear the lock+ screen out of its way."""+ data = message.get("data")+ target = data.get("target") if isinstance(data, dict) else None+ if target == self._peer_target:+ # Released before the owner hears input is home: the Mac's tap+ # comes back on at that notice, and a modifier still down would+ # chord with the first local keystroke.+ self._return_edge = None+ self._release_peer_keys()+ self._notify_focus(target)+ if target == self._self_target:+ self._arm_return(data)+ self._place_pointer(data)+ self._begin_unlock(peer, host)+ return+ if target != self._peer_target:+ return+ clipboard = self._clipboard_module()+ try:+ text, image = clipboard.get_contents()+ except Exception:+ LOGGER.exception("Failed to read the local clipboard for %s", peer)+ return+ if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:+ LOGGER.warning("Local clipboard text too large; skipping the text for %s", peer)+ text = None+ if image is not None and len(image) > protocol.CLIPBOARD_IMAGE_MAX_BYTES:+ LOGGER.warning(+ "Local clipboard image is %d bytes, over the %d cap; skipping the image for %s",+ len(image),+ protocol.CLIPBOARD_IMAGE_MAX_BYTES,+ peer,+ )+ image = None+ if not text and image is None:+ return+ self._send_message(connection, session, protocol.clipboard_msg(text or None, image))++ def _handle_inbound_clipboard(self, message: dict, peer: str) -> None:+ data = message.get("data")+ text = data.get("text") if isinstance(data, dict) else None+ if not isinstance(text, str) or not text:+ text = None+ elif len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:+ LOGGER.warning("Ignoring oversized inbound clipboard text from %s", peer)+ text = None+ image = protocol.clipboard_image(data)+ if text is None and image is None:+ return+ clipboard = self._clipboard_module()+ try:+ if not clipboard.set_contents(text, image):+ LOGGER.warning("Failed to set the local clipboard for %s", peer)+ except Exception:+ LOGGER.exception("Failed to set the local clipboard for %s", peer)++ @staticmethod+ def _hello_version(message: dict):+ data = message.get("data", {})+ if not isinstance(data, dict):+ return None+ return data.get("version")++ @staticmethod+ def _send_message(+ connection: socket.socket,+ session: protocol.SecureSession,+ message: dict,+ ) -> bool:+ """The session's own lock serialises the seal and the write together,+ so frames reach the wire in counter order from every thread."""+ try:+ protocol.send_msg(connection, session, message)+ return True+ except (OSError, protocol.ProtocolError) as exc:+ LOGGER.warning("Send failed: %s", exc)+ return False++ def _set_status(self, state: ServerState, detail: str) -> None:+ try:+ self._status_callback(state, detail)+ except Exception:+ LOGGER.exception("Status callback failed")++ @staticmethod+ def _close_socket(sock: Optional[socket.socket]) -> None:+ if sock is None:+ return+ try:+ sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+ try:+ sock.close()+ except OSError:+ passdiff --git a/win_app/requirements-win.txt b/win_app/requirements-win.txtnew file mode 100644index 0000000..75c91de--- /dev/null+++ b/win_app/requirements-win.txt@@ -0,0 +1,4 @@+PySide6-Essentials>=6.11.1+pyinstaller>=6.0+pyinstaller-hooks-contrib>=2024.1+cryptography>=42diff --git a/win_app/return_edge.py b/win_app/return_edge.pynew file mode 100644index 0000000..d565fdb--- /dev/null+++ b/win_app/return_edge.py@@ -0,0 +1,227 @@+"""Return-edge geometry and the pressure model for crossing back to the Mac.++Pure: no ctypes, no Qt, no Windows. The receiver feeds it the monitor+rectangles, the pointer position, each incoming movement delta and a clock, and it+answers with what to do — inject the delta, hold the pointer at the edge, or+cross. The model mirrors the Mac's so the two boundaries feel like one:+outward travel at the edge accumulates as pressure, inward travel subtracts,+time decays it to nothing over DECAY_SECONDS, and at `resistance_px` of net+outward travel the edge gives.+"""++import time+from dataclasses import dataclass+from typing import Callable, Iterable, List, Optional, Tuple++EDGES = ("left", "right", "top", "bottom")+OPPOSITE = {"left": "right", "right": "left", "top": "bottom", "bottom": "top"}+DEFAULT_RESISTANCE_PX = 120+DECAY_SECONDS = 0.4+# How near a corner counts as being in it. The Mac's own engine uses the same+# 8 pixels, and the two boundaries are meant to feel like one.+CORNER_PX = 8+CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")++PASS = "pass"+HOLD = "hold"+CROSS = "cross"+++@dataclass(frozen=True)+class Rect:+ """A monitor or the virtual desktop, in virtual-desktop pixels. `x`/`y` may+ be negative: the primary monitor is at the origin, not the bounding box."""++ x: int+ y: int+ width: int+ height: int++ @property+ def right(self) -> int:+ return self.x + self.width - 1++ @property+ def bottom(self) -> int:+ return self.y + self.height - 1+++def union(monitors: Iterable[Rect]) -> Rect:+ rects = list(monitors)+ x = min(r.x for r in rects)+ y = min(r.y for r in rects)+ return Rect(x, y, max(r.right for r in rects) - x + 1, max(r.bottom for r in rects) - y + 1)+++@dataclass(frozen=True)+class Outcome:+ action: str+ pressure: float = 0.0+ position: Optional[Tuple[int, int]] = None+ edge: Optional[str] = None+ offset: Optional[float] = None+++def _clamp(value, low, high):+ return max(low, min(high, value))+++def _contains(rect: Rect, point: Tuple[int, int]) -> bool:+ return rect.x <= point[0] <= rect.right and rect.y <= point[1] <= rect.bottom+++def edge_offset(bounds: Rect, edge: str, pointer: Tuple[int, int]) -> float:+ """Fraction along `edge`, top to bottom or left to right, against the+ bounding box — the convention the Mac measures its own departures in."""+ if edge in ("left", "right"):+ return _clamp((pointer[1] - bounds.y) / max(bounds.height, 1), 0.0, 1.0)+ return _clamp((pointer[0] - bounds.x) / max(bounds.width, 1), 0.0, 1.0)+++def owning_monitor(monitors: List[Rect], edge: str) -> Rect:+ """The monitor that reaches the bounding box on `edge`; ties go to the+ first enumerated, which on Windows is the primary."""+ if edge == "left":+ return min(monitors, key=lambda r: r.x)+ if edge == "right":+ return max(monitors, key=lambda r: r.right)+ if edge == "top":+ return min(monitors, key=lambda r: r.y)+ return max(monitors, key=lambda r: r.bottom)+++def arrival_position(monitors: List[Rect], edge: str, offset: float) -> Tuple[int, int]:+ """Where a pointer arriving at `edge`, `offset` of the way along it, lands.+ The fraction is applied against the whole bounding box, then clamped into+ the owning monitor so a staggered arrangement never lands it in a gap."""+ bounds = union(monitors)+ owner = owning_monitor(monitors, edge)+ offset = _clamp(float(offset), 0.0, 1.0)+ if edge in ("left", "right"):+ x = owner.x if edge == "left" else owner.right+ y = _clamp(int(round(bounds.y + offset * bounds.height)), owner.y, owner.bottom)+ else:+ y = owner.y if edge == "top" else owner.bottom+ x = _clamp(int(round(bounds.x + offset * bounds.width)), owner.x, owner.right)+ return x, y+++class ReturnEdge:+ """Pressure against one edge of the Windows virtual desktop. Armed by the+ Mac on every switch (it sends `return_edge` and `resistance_px`), and+ disarmed once a crossing has been sent, so a burst of deltas still in+ flight after breakthrough cannot send a second one."""++ def __init__(self, edge: str, resistance_px: int = DEFAULT_RESISTANCE_PX, clock: Callable[[], float] = time.monotonic) -> None:+ if edge not in EDGES:+ raise ValueError(f"unknown edge {edge!r}")+ self.edge = edge+ self.resistance_px = max(0, int(resistance_px))+ self._clock = clock+ self._travel = 0.0+ self._last_at = clock()+ self.armed = True++ @property+ def pressure(self) -> float:+ if self.resistance_px == 0:+ return 1.0 if self._travel > 0 else 0.0+ return _clamp(self._travel / self.resistance_px, 0.0, 1.0)++ def reset(self) -> None:+ self._travel = 0.0+ self._last_at = self._clock()++ def _outward(self, dx: float, dy: float) -> float:+ if self.edge == "left":+ return -dx+ if self.edge == "right":+ return dx+ if self.edge == "top":+ return -dy+ return dy++ def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:+ """On a monitor, with no monitor one pixel beyond it: the pointer is+ against a wall. Testing the bounding box instead made the edge of a+ shorter monitor in a staggered arrangement unreachable — on the rig,+ pushing down on the LG, whose bottom stops 204px above the ultrawide's,+ never went home."""+ x, y = pointer+ step_x, step_y = {"left": (-1, 0), "right": (1, 0), "top": (0, -1), "bottom": (0, 1)}[self.edge]+ beyond = (x + step_x, y + step_y)+ return any(_contains(m, pointer) for m in monitors) and not any(_contains(m, beyond) for m in monitors)++ def feed(self, monitors: List[Rect], pointer: Tuple[int, int], dx: float, dy: float) -> Outcome:+ bounds = union(monitors)+ now = self._clock()+ elapsed = max(0.0, now - self._last_at)+ self._last_at = now+ # Decay runs against the wall clock between deltas, pushing or not. A+ # brisk push outruns it; a slow lean on the edge to reach a menu never+ # accumulates, which is the whole point of the resistance.+ self._travel = max(0.0, self._travel - self.resistance_px * elapsed / DECAY_SECONDS)+ if not self.armed:+ return Outcome(PASS, self.pressure)+ outward = self._outward(dx, dy)+ if outward <= 0 or not self._at_edge(monitors, pointer):+ if outward < 0:+ self._travel = max(0.0, self._travel + outward)+ return Outcome(PASS, self.pressure)+ self._travel += outward+ if self._travel >= self.resistance_px:+ self.armed = False+ offset = edge_offset(bounds, self.edge, pointer)+ self._travel = 0.0+ return Outcome(CROSS, 1.0, edge=OPPOSITE[self.edge], offset=offset)+ x, y = pointer+ if self.edge in ("left", "right"):+ position = (x, _clamp(int(y + dy), bounds.y, bounds.bottom))+ else:+ position = (_clamp(int(x + dx), bounds.x, bounds.right), y)+ return Outcome(HOLD, self.pressure, position=position)+++class CornerPush(ReturnEdge):+ """The same pressure model gated to one corner, for a machine whose whole+ edge is busy with something else. The push has to be diagonal: travel that+ leaves by only one of the corner's two sides is not a corner push and+ counts for nothing, which is what stops a slide along an edge triggering+ the corner it ends at.++ `edge` is still the side that leads to the other machine, so a corner+ crossing arrives where an edge crossing would, at the end of that edge the+ corner sits at."""++ def __init__(self, corner: str, edge: str, resistance_px: int = DEFAULT_RESISTANCE_PX, clock=time.monotonic) -> None:+ if corner not in CORNERS:+ raise ValueError(f"unknown corner {corner!r}")+ super().__init__(edge, resistance_px, clock)+ self.corner = corner+ self.vertical, self.horizontal = corner.split("_")++ def _outward(self, dx: float, dy: float) -> float:+ out_x = -dx if self.horizontal == "left" else dx+ out_y = -dy if self.vertical == "top" else dy+ if out_x > 0 and out_y > 0:+ return (out_x * out_x + out_y * out_y) ** 0.5+ inward = (min(0.0, out_x) ** 2 + min(0.0, out_y) ** 2) ** 0.5+ return -inward++ def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:+ """In the corner's own box, and against at least one of its two walls.+ The box is measured on the monitor the pointer is on, for the same+ reason the edge test is: on a staggered arrangement the bounding box+ has corners no display reaches."""+ x, y = pointer+ home = next((m for m in monitors if _contains(m, pointer)), None)+ if home is None:+ return False+ near_x = x <= home.x + CORNER_PX if self.horizontal == "left" else x >= home.right - CORNER_PX+ near_y = y <= home.y + CORNER_PX if self.vertical == "top" else y >= home.bottom - CORNER_PX+ if not (near_x and near_y):+ return False+ return any(+ not any(_contains(m, beyond) for m in monitors)+ for beyond in ((x + (-1 if self.horizontal == "left" else 1), y), (x, y + (-1 if self.vertical == "top" else 1)))+ )diff --git a/win_app/sender.py b/win_app/sender.pynew file mode 100644index 0000000..843f59f--- /dev/null+++ b/win_app/sender.py@@ -0,0 +1,881 @@+"""Sending this PC's own keyboard and mouse to the Mac: the mirror of+mac_app/bridge.py's link half, talking to the same receiver.py the Mac's+sender talks to, over a second connection this PC opens outwards.++Two links, not one bidirectional socket. The existing Mac-to-Windows link is+the one Toby uses every day, and its sequence, acknowledgement and watchdog+bookkeeping is all sender-shaped; threading a second ownership state through+it would put that link at risk for nothing. This one is opened by this PC, to+the Mac's own listener on the same port number, so it needs no inbound+firewall rule here.++Nothing about the crossing is configured on this side. The Mac names the way+home on its own link -- the Windows edge input comes back through -- and that+is the same physical border this PC pushes out across, so the edge, its+resistance and the Mac's address are all learned rather than typed.++Which way input is flowing is one state across both links: the outbound edge+is armed only while the Mac is not driving this PC, so a pointer the Mac is+moving cannot push itself back out through the border it just came in by.+"""++import ipaddress+import logging+import queue+import socket+import struct+import threading+import time+from typing import Callable, Optional++import protocol+import return_edge++LOGGER = logging.getLogger(__name__)++ACK_TIMEOUT_SECONDS = 2.0+CONNECT_TIMEOUT_SECONDS = 1.0+AUTH_TIMEOUT_SECONDS = 2.0+SOCKET_IO_TIMEOUT_SECONDS = 0.5+PING_INTERVAL_SECONDS = 1.0+OUTBOUND_QUEUE_SIZE = 2048+MONITORS_MAX_AGE_SECONDS = 1.0++CONTROL_MESSAGE_TYPES = frozenset({protocol.MSG_FOCUS, protocol.MSG_CLIPBOARD})+_LOCAL_CLIPBOARD_SENTINEL_TYPE = "_local_clipboard"+_GATE_EXEMPT_TYPES = CONTROL_MESSAGE_TYPES | {_LOCAL_CLIPBOARD_SENTINEL_TYPE}+# A key-up owed to the Mac for a key that went down there, queued as input+# comes home. Local to the queue: _process_outbound rebuilds the message from+# its type and data, so the mark never reaches the wire.+_RELEASE_MARK = "_release"++OLD_RECEIVER_STATUS = "The Mac did not answer the handshake — it is probably running an older Beamer; update it"+AUTH_FAILED_STATUS = "The Mac could not be authenticated — check the shared token matches on both sides"+++class HandshakeError(protocol.ProtocolError):+ def __init__(self, status):+ super().__init__(status)+ self.status = status+++class FrameDecoder:+ """Reassembles and opens frames from the raw chunks the reader thread+ receives. One per connection, like the session it opens frames with."""++ def __init__(self, session):+ self.session = session+ self.buffer = bytearray()++ def feed(self, chunk):+ self.buffer.extend(chunk)+ messages = []+ while len(self.buffer) >= protocol.HEADER_SIZE:+ length = struct.unpack_from(">I", self.buffer)[0]+ if length < 1 or length > protocol.MAX_FRAME_BYTES:+ raise protocol.ProtocolError(f"invalid message length: {length}")+ frame_length = protocol.HEADER_SIZE + length+ if len(self.buffer) < frame_length:+ break+ body = bytes(self.buffer[protocol.HEADER_SIZE:frame_length])+ del self.buffer[:frame_length]+ messages.append(self.session.open(body))+ return messages+++def is_this_machine(host: str, local_addresses=None, address_towards=None) -> bool:+ """Whether `host` is this PC rather than the Mac. Worth a guard of its+ own: the Mac's address is learned from the peer address of its own link,+ and when the Mac connects through the macOS 27 SSH tunnel that address is+ 127.0.0.1 -- this PC's. Connecting there would reach this PC's own+ receiver, authenticate with the shared token, and the receiver's preempt+ rule would close the real Mac's session. The daily link would drop and+ reconnect for as long as both were running.++ Two answers are consulted, because the first one fails silently: the+ hostname-based address list is empty on a PC whose name does not+ resolve, and an empty list would have said "not this machine" for this+ machine's own address. The route probe asks the stack which local+ address would reach `host`; for this PC's own address that is the+ address itself."""+ if not host:+ return True+ try:+ address = ipaddress.ip_address(host)+ except ValueError:+ return False+ if address.is_loopback or address.is_unspecified:+ return True+ import pairing++ if local_addresses is None:+ local_addresses = pairing._local_ipv4_addresses()+ if host in local_addresses:+ return True+ if address_towards is None:+ address_towards = pairing.local_address_towards+ try:+ return address_towards(host) == host+ except OSError:+ return False+++def _default_socket_factory(address, timeout):+ return socket.create_connection(address, timeout=timeout)+++class MacSender:+ """One link to the Mac, plus the decision -- taken on the hook thread --+ of whether each local input event belongs to this PC or to the Mac.++ `status_callback(connected, detail)` and `redirect_callback(redirecting)`+ are called from worker threads; a GUI marshals them. `desktop` and+ `clipboard` default to the real Win32 modules and are handed in by tests.+ """++ def __init__(+ self,+ status_callback: Callable[[bool, str], None] = None,+ redirect_callback: Callable[[bool], None] = None,+ pressure_callback: Callable[[str, float, bool], None] = None,+ arrangement_callback: Callable[[str, int], None] = None,+ desktop=None,+ clipboard=None,+ socket_factory=_default_socket_factory,+ is_local=is_this_machine,+ clock=time.monotonic,+ ) -> None:+ self._status_callback = status_callback+ self._redirect_callback = redirect_callback+ self._pressure_callback = pressure_callback+ self._arrangement_callback = arrangement_callback+ self._desktop = desktop+ self._clipboard = clipboard+ self._socket_factory = socket_factory+ self._is_local = is_local+ self._clock = clock++ self._config = None+ self._config_lock = threading.RLock()+ self._socket_lock = threading.RLock()+ self._sequence_lock = threading.RLock()+ self._sock: Optional[socket.socket] = None+ self._session: Optional[protocol.SecureSession] = None+ self._outbound: "queue.Queue[dict]" = queue.Queue(maxsize=OUTBOUND_QUEUE_SIZE)+ self._stop_event = threading.Event()+ self._threads = []++ self._status = "Not connected to the Mac"+ # Keys whose down-stroke went to the Mac and whose release has not: a+ # dict, not a set, only so the hook thread's pop() stays one operation.+ self._keys_down: dict = {}+ self._last_sent_seq = 0+ self._last_ack_seq = -1+ self._last_ack_at = 0.0+ self._connected_at = 0.0+ self._last_send_at = 0.0++ self.redirecting = False+ # Where the pointer was pinned while the Mac has input, and where it+ # last was while this PC has it. Two names for two states: conflating+ # them made a push against the edge measure its delta from the pin.+ self._pin_point = None+ self._last_point = None+ self._edge = None+ # Two ways the pointer leaves, either or both armed: the whole edge+ # that leads to the Mac, and the corner sitting at one end of it. The+ # corner is tried first, because its box is inside the edge's strip.+ self._edge_model: Optional[return_edge.ReturnEdge] = None+ self._corner_model: Optional[return_edge.CornerPush] = None+ self._monitors = None+ self._monitors_at = 0.0+ # Set by the app while the Mac is driving this PC: the outbound edge+ # stays disarmed for as long as it is, so input that arrived over the+ # other link cannot push itself straight back out.+ self._receiving = False+ # The receiver's way of sending the Mac's input home, handed in by the+ # app that owns both halves.+ self.send_peer_home = None++ # -- state the GUI reads ------------------------------------------------++ @property+ def connected(self) -> bool:+ with self._socket_lock:+ return self._sock is not None++ @property+ def status(self) -> str:+ return self._status++ @property+ def edge(self) -> Optional[str]:+ return self._edge++ def set_receiving(self, receiving: bool) -> None:+ """Called when the Mac takes input on this PC, and again when it gives+ it back. While it is True nothing here arms, sends or crosses."""+ receiving = bool(receiving)+ if receiving == self._receiving:+ return+ self._receiving = receiving+ if receiving and self.redirecting:+ self.set_redirecting(False)+ self._last_point = None+ self._rearm_edge()++ # -- lifecycle ----------------------------------------------------------++ def start(self, config) -> None:+ self.update_config(config)+ if self._threads:+ return+ self._stop_event.clear()+ for name, target in (+ ("Beamer-mac-link", self._connection_worker),+ ("Beamer-mac-out", self._outbound_worker),+ ("Beamer-mac-in", self._reader_worker),+ ("Beamer-mac-watchdog", self._watchdog_worker),+ ):+ thread = threading.Thread(target=target, name=name, daemon=True)+ thread.start()+ self._threads.append(thread)++ def stop(self) -> None:+ self._stop_event.set()+ self.set_redirecting(False)+ self._drop_connection()+ for thread in self._threads:+ thread.join(timeout=2.0)+ self._threads = []++ def update_config(self, config) -> None:+ with self._config_lock:+ previous = self._config+ self._config = config+ edge = getattr(config, "mac_return_edge", "") or None+ self._edge = edge if edge in return_edge.EDGES else None+ self._rearm_edge()+ if previous is not None and self._address(previous) != self._address(config):+ self._drop_connection()++ @staticmethod+ def _address(config):+ return (getattr(config, "mac_host", "") or "", int(getattr(config, "port", 0) or 0))++ def _ready_config(self):+ with self._config_lock:+ config = self._config+ if config is None or not getattr(config, "send_to_mac", True):+ return None+ host, port = self._address(config)+ if not host or not port or not config.auth_token:+ return None+ if self._is_local(host):+ return None+ return config++ # -- the hooks' two decisions -------------------------------------------++ def _link_live(self) -> bool:+ """Whether input may still be taken from this PC. Deliberately cheap+ and lock-light: it is read on the hook thread for every keystroke and+ every mouse move, and a hook that cannot answer promptly is a hook+ Windows removes -- with Toby's keyboard inside it."""+ if self._sock is None:+ return False+ last = max(self._last_ack_at, self._connected_at)+ return (self._clock() - last) <= ACK_TIMEOUT_SECONDS++ def on_key(self, name: str, down: bool) -> bool:+ if not self.redirecting:+ # A key that went down on the Mac and is still held after input+ # came home: the Mac was sent its release when input left, and+ # Windows never saw it go down, so it must see neither its+ # autorepeats nor its release. The entry goes on the release.+ if name not in self._keys_down:+ return False+ if not down:+ self._keys_down.pop(name, None)+ return True+ if not self._link_live():+ self._force_local("the link to the Mac went quiet")+ return False+ if down:+ self._keys_down[name] = True+ self._enqueue({"type": protocol.MSG_KEYDOWN, "data": {"key": name}})+ else:+ self._keys_down.pop(name, None)+ # Marked, so a release still queued when input comes home is sent+ # rather than dropped by the gate: the Mac has the key-down.+ self._enqueue({"type": protocol.MSG_KEYUP, "data": {"key": name}, _RELEASE_MARK: True})+ return True++ def on_mouse(self, message: int, x: int, y: int, mouse_data: int) -> bool:+ """Buttons and the wheel, and swallowing a move -- never the distance+ it covered, which comes from on_motion. Returns True when the event+ belongs to the Mac and Windows must not see it."""+ import capture_win++ if not self.redirecting:+ return False+ if not self._link_live():+ self._force_local("the link to the Mac went quiet")+ return False+ if message == capture_win.WM_MOUSEMOVE:+ # Swallowed, and the pointer put back where it was: a hook that+ # returns 1 stops the message, but the cursor has already been+ # moved by the time it runs.+ self._warp_to_pin()+ return True+ return self._send_mouse(capture_win, message, mouse_data)++ def on_motion(self, dx: int, dy: int) -> None:+ """One raw mouse movement, in the mouse's own counts. Consumes+ nothing: raw input cannot block an event, so the hook above is what+ keeps the movement off this PC."""+ if self.redirecting:+ if not self._link_live():+ self._force_local("the link to the Mac went quiet")+ return+ self._enqueue({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": int(dx), "dy": int(dy)}})+ return+ self._press_edge(int(dx), int(dy))++ def _send_mouse(self, capture_win, message, mouse_data) -> bool:+ button = capture_win.BUTTON_MESSAGES.get(message)+ if button is not None:+ name, down = button+ self._enqueue(+ {"type": protocol.MSG_MOUSEDOWN if down else protocol.MSG_MOUSEUP, "data": {"button": name}}+ )+ return True+ if message == capture_win.WM_MOUSEWHEEL:+ self._enqueue(protocol.scroll_msg(capture_win.wheel_notches(mouse_data), 0.0, "line"))+ return True+ if message == capture_win.WM_MOUSEHWHEEL:+ self._enqueue(protocol.scroll_msg(0.0, capture_win.wheel_notches(mouse_data), "line"))+ return True+ # An X button, or anything else the Mac has no name for: left to+ # Windows rather than dropped, so a thumb button still works here.+ return False++ def _press_edge(self, dx, dy) -> None:+ """One raw movement while input is still this PC's. Feeds the same+ return-edge model the Mac's receiver uses, so the border behaves+ identically whichever side of it the pointer starts on.++ Nothing is held here, unlike the receiver's side of the same model:+ Windows has already stopped the cursor at the edge of the desktop, so+ the hold is the screen's own. Only the pressure is ours to measure,+ and only a breakthrough acts."""+ if self._receiving or not self.connected:+ return+ try:+ desktop = self._desktop_module()+ monitors = self._cached_monitors()+ pointer = desktop.cursor_position()+ outcome = model = None+ for candidate in (self._corner_model, self._edge_model):+ if candidate is None:+ continue+ result = candidate.feed(monitors, pointer, float(dx), float(dy))+ if result.action != return_edge.PASS:+ outcome, model = result, candidate+ break+ if outcome is None:+ return+ except Exception:+ LOGGER.exception("The way out to the Mac failed; crossing out is off until the next reconnect")+ self._edge_model = self._corner_model = None+ return+ self._notify_pressure(model.edge, outcome.pressure, outcome.action == return_edge.CROSS)+ if outcome.action == return_edge.CROSS:+ # The model names the edge on the far side, not the one just left:+ # it is the same border, read from the other end.+ self.set_redirecting(True, arrival_edge=outcome.edge, offset=outcome.offset)++ # -- switching ----------------------------------------------------------++ def set_redirecting(self, value, arrival_edge=None, offset=None) -> bool:+ """`arrival_edge` is the Mac edge the pointer arrives at and `offset`+ the fraction along it -- the same fraction it left this PC at, which+ is what makes one border out of two screens. Both are absent when the+ shortcut moved input rather than a crossing."""+ value = bool(value)+ if value == self.redirecting:+ return False+ if value:+ if not self.connected:+ LOGGER.warning("cannot redirect: the Mac is not connected")+ return False+ if self._receiving:+ # The Mac is driving this PC over the other link, so switching+ # to the Mac means sending its input home, the way back that+ # does not depend on the Mac's own return edge.+ send_home = self.send_peer_home+ if send_home is not None and send_home():+ return True+ LOGGER.warning("cannot redirect: the Mac is driving this PC and cannot be reached")+ return False+ self.redirecting = True+ self._pin_point = self._desktop_module().cursor_position()+ arrival = arrival_edge if arrival_edge in return_edge.EDGES else None+ self._enqueue_control({"type": _LOCAL_CLIPBOARD_SENTINEL_TYPE, "data": {}})+ self._enqueue_control(+ protocol.focus_msg(+ "mac",+ edge=arrival,+ offset=offset,+ return_edge=arrival or self._mac_arrival_edge(),+ resistance_px=int(self._resistance()),+ )+ )+ LOGGER.info("redirecting input to the Mac")+ else:+ # The flag first, so the hook thread stops adding keys; then+ # whatever is still down on the Mac is released there before the+ # focus goes home, marked to pass the gate that has just closed.+ # The entries stay, so the physical releases here are swallowed.+ self.redirecting = False+ for name in list(self._keys_down):+ self._enqueue_control({"type": protocol.MSG_KEYUP, "data": {"key": name}, _RELEASE_MARK: True})+ self._pin_point = None+ self._last_point = None+ # A fresh model, not a reset one: the old one disarmed itself at+ # breakthrough so a burst of deltas still in flight could not+ # cross twice, and nothing else re-arms it.+ self._rearm_edge()+ self._enqueue_control(protocol.focus_msg("windows"))+ LOGGER.info("input returned to this PC")+ if self._redirect_callback is not None:+ try:+ self._redirect_callback(value)+ except Exception:+ LOGGER.exception("Redirect callback failed")+ return True++ def toggle(self) -> None:+ """The shortcut's way across and back, for when the pointer is not at+ an edge -- or the edge is off."""+ self.set_redirecting(not self.redirecting)++ def _handle_switch(self, data) -> None:+ """The Mac pushed the pointer back through its return edge. Stop+ sending, then land the pointer on the edge of this PC it comes back+ to."""+ if not isinstance(data, dict) or data.get("target") != "windows":+ return+ self.set_redirecting(False)+ edge = data.get("edge")+ offset = data.get("offset")+ if edge in return_edge.EDGES and isinstance(offset, (int, float)) and not isinstance(offset, bool):+ try:+ desktop = self._desktop_module()+ desktop.set_cursor_position(*return_edge.arrival_position(self._cached_monitors(), edge, offset))+ except Exception:+ LOGGER.exception("Could not place the pointer at the %s edge on arrival", edge)++ # -- the link -----------------------------------------------------------++ def _connection_worker(self) -> None:+ while not self._stop_event.is_set():+ config = self._ready_config()+ if config is None or self.connected:+ self._stop_event.wait(0.5)+ continue+ if not self._connect_once(config):+ self._stop_event.wait(max(0.5, float(getattr(config, "reconnect_interval_s", 2.0))))++ def _connect_once(self, config) -> bool:+ host, port = self._address(config)+ sock = None+ self._set_status(f"Connecting to the Mac at {host}:{port}")+ try:+ sock = self._socket_factory((host, port), CONNECT_TIMEOUT_SECONDS)+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)+ session = protocol.SecureSession(config.auth_token)+ sock.sendall(session.preamble())+ sock.settimeout(AUTH_TIMEOUT_SECONDS)+ try:+ protocol.recv_preamble(sock, session)+ except socket.timeout:+ raise HandshakeError(OLD_RECEIVER_STATUS) from None+ except protocol.VersionMismatch as exc:+ raise HandshakeError(+ f"The Mac speaks Beamer protocol v{exc.peer_version}, this PC v{protocol.PROTOCOL_VERSION} — update both apps"+ ) from None+ protocol.send_msg(+ sock,+ session,+ protocol.hello_msg(+ return_edge=self._mac_arrival_edge(), resistance_px=int(self._resistance())+ ),+ )+ try:+ reply = protocol.recv_msg(sock, session)+ except (protocol.ConnectionClosed, protocol.AuthenticationError):+ # The receiver closes without a word when a frame fails to authenticate.+ raise HandshakeError(AUTH_FAILED_STATUS) from None+ if reply.get("type") != protocol.MSG_WELCOME:+ raise protocol.ProtocolError("the Mac did not confirm authentication")+ data = reply.get("data")+ if not isinstance(data, dict):+ raise protocol.ProtocolError("welcome message missing data")+ if data.get("error") or data.get("version") != protocol.PROTOCOL_VERSION:+ raise HandshakeError(OLD_RECEIVER_STATUS)+ sock.settimeout(SOCKET_IO_TIMEOUT_SECONDS)+ except HandshakeError as exc:+ self._close(sock)+ self._set_status(exc.status)+ LOGGER.warning("connection to the Mac failed: %s", exc.status)+ return False+ except (OSError, protocol.ProtocolError) as exc:+ self._close(sock)+ self._set_status(f"The Mac is not reachable on {host}:{port}")+ LOGGER.debug("connection to the Mac failed: %s", exc)+ return False+ with self._socket_lock:+ if self._stop_event.is_set() or self._sock is not None:+ self._close(sock)+ return False+ self._sock = sock+ self._session = session+ now = self._clock()+ with self._sequence_lock:+ self._last_sent_seq = 0+ self._last_ack_seq = -1+ self._last_ack_at = now+ self._connected_at = now+ self._last_send_at = now+ self._set_status(f"Connected to the Mac at {host}")+ LOGGER.info("connected to the Mac at %s:%s", host, port)+ return True++ def _outbound_worker(self) -> None:+ while not self._stop_event.is_set():+ try:+ message = self._outbound.get(timeout=0.2)+ except queue.Empty:+ continue+ try:+ self._process_outbound(message)+ except Exception:+ # One bad message must not end the only thread that drains+ # this queue: nothing restarts it, and the hooks would keep+ # swallowing input into a queue nobody reads.+ LOGGER.exception("outbound worker recovered")+ self._force_local(f"outbound message {message.get('type')!r} failed")+ finally:+ self._outbound.task_done()++ def _process_outbound(self, message) -> None:+ message_type = message.get("type")+ if message_type not in _GATE_EXEMPT_TYPES and not self.redirecting and not message.get(_RELEASE_MARK):+ return+ if message_type == _LOCAL_CLIPBOARD_SENTINEL_TYPE:+ self._send_local_clipboard()+ return+ if message_type in CONTROL_MESSAGE_TYPES:+ self._send_raw(message)+ return+ with self._sequence_lock:+ self._last_sent_seq += 1+ seq = self._last_sent_seq+ data = dict(message.get("data", {}))+ data["seq"] = seq+ self._send_raw({"type": message_type, "data": data})++ def send_arrangement(self, mac_edge: str, set_at: int) -> bool:+ """Tell the Mac where the machines are, when the change was made here."""+ return self._send_raw(protocol.arrangement_msg(mac_edge, set_at))++ def _send_local_clipboard(self) -> None:+ try:+ text, image = self._clipboard_module().get_contents()+ except Exception:+ LOGGER.exception("Failed to read the local clipboard for the Mac")+ return+ if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:+ LOGGER.warning("Local clipboard text too large; skipping the text")+ text = None+ if image is not None and len(image) > protocol.CLIPBOARD_IMAGE_MAX_BYTES:+ LOGGER.warning("Local clipboard image over the cap; skipping the image")+ image = None+ if not text and image is None:+ return+ self._send_raw(protocol.clipboard_msg(text or None, image))++ def _send_raw(self, message) -> bool:+ with self._socket_lock:+ sock, session = self._sock, self._session+ if sock is None:+ return False+ try:+ protocol.send_msg(sock, session, message)+ self._last_send_at = self._clock()+ return True+ except (OSError, protocol.ProtocolError) as exc:+ self._connection_failed(f"Sending to the Mac failed: {exc}", expected_socket=sock)+ return False++ def _reader_worker(self) -> None:+ active_socket = None+ decoder = None+ while not self._stop_event.is_set():+ with self._socket_lock:+ sock, session = self._sock, self._session+ if sock is None:+ active_socket = None+ self._stop_event.wait(0.1)+ continue+ if sock is not active_socket:+ active_socket = sock+ decoder = FrameDecoder(session)+ try:+ chunk = sock.recv(4096)+ except socket.timeout:+ continue+ except OSError as exc:+ self._connection_failed(f"Receiving from the Mac failed: {exc}", expected_socket=sock)+ active_socket = None+ continue+ if not chunk:+ self._connection_failed("The Mac closed the connection", expected_socket=sock)+ active_socket = None+ continue+ try:+ for message in decoder.feed(chunk):+ self._handle_inbound(message)+ except protocol.AuthenticationError:+ self._connection_failed(AUTH_FAILED_STATUS, expected_socket=sock)+ active_socket = None+ except protocol.ProtocolError as exc:+ self._connection_failed(f"Invalid stream from the Mac: {exc}", expected_socket=sock)+ active_socket = None+ except Exception as exc:+ # The same outcome as a malformed frame: this connection goes,+ # the thread stays, and the next connection gets a reader.+ LOGGER.exception("inbound handling failed")+ self._connection_failed(f"Inbound message from the Mac failed: {exc}", expected_socket=sock)+ active_socket = None++ def _handle_inbound(self, message) -> None:+ message_type = message.get("type")+ if not isinstance(message_type, str) or not message_type:+ raise protocol.ProtocolError(f"malformed inbound message: {message!r}")+ with self._sequence_lock:+ self._last_ack_at = self._clock()+ if message_type == protocol.MSG_ACK:+ self._record_ack(message)+ return+ if message_type == protocol.MSG_CLIPBOARD:+ self._apply_inbound_clipboard(message.get("data", {}))+ return+ if message_type == protocol.MSG_SWITCH:+ self._handle_switch(message.get("data", {}))+ return+ if message_type == protocol.MSG_ARRANGEMENT:+ read = protocol.read_arrangement(message.get("data"))+ if read is not None and self._arrangement_callback is not None:+ try:+ self._arrangement_callback(*read)+ except Exception:+ LOGGER.exception("Arrangement callback failed")+ return++ def _record_ack(self, message) -> None:+ data = message.get("data")+ if not isinstance(data, dict):+ raise protocol.ProtocolError("ACK data must be a JSON object")+ seq = data.get("seq")+ if isinstance(seq, bool) or not isinstance(seq, int) or seq < 0:+ raise protocol.ProtocolError("ACK seq must be a non-negative integer")+ with self._sequence_lock:+ if seq < self._last_ack_seq:+ raise protocol.ProtocolError("ACK seq moved backwards")+ if seq > self._last_sent_seq:+ raise protocol.ProtocolError("ACK seq is ahead of the sender")+ self._last_ack_seq = seq++ def _apply_inbound_clipboard(self, data) -> None:+ if not isinstance(data, dict):+ return+ text = data.get("text")+ if not isinstance(text, str) or not text:+ text = None+ elif len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:+ LOGGER.warning("Ignoring oversized inbound clipboard text from the Mac")+ text = None+ image = protocol.clipboard_image(data)+ if text is None and image is None:+ return+ try:+ self._clipboard_module().set_contents(text, image)+ except Exception:+ LOGGER.exception("Failed to set the local clipboard from the Mac")++ def _watchdog_worker(self) -> None:+ while not self._stop_event.wait(0.1):+ self._watchdog_tick()++ def _watchdog_tick(self) -> bool:+ if not self.connected:+ return False+ now = self._clock()+ with self._sequence_lock:+ last_heartbeat = max(self._last_ack_at, self._connected_at)+ if now - last_heartbeat > ACK_TIMEOUT_SECONDS:+ self._connection_failed("The Mac stopped responding")+ return True+ if now - self._last_send_at >= PING_INTERVAL_SECONDS:+ self._send_raw(protocol.ping_msg())+ return False++ # -- plumbing -----------------------------------------------------------++ def _enqueue(self, message) -> None:+ try:+ self._outbound.put_nowait(message)+ except queue.Full:+ self._force_local("the outbound queue to the Mac filled up")++ def _enqueue_control(self, message) -> None:+ try:+ self._outbound.put_nowait(message)+ except queue.Full:+ LOGGER.error("outbound queue full; dropped control message %r", message.get("type"))++ def _force_local(self, reason) -> None:+ if self.redirecting:+ LOGGER.error("%s; input forced back to this PC", reason)+ self.redirecting = False+ self._pin_point = None+ if self._redirect_callback is not None:+ try:+ self._redirect_callback(False)+ except Exception:+ LOGGER.exception("Redirect callback failed")++ def _connection_failed(self, reason, expected_socket=None) -> None:+ self._force_local(reason)+ self._set_status(reason)+ self._drop_connection(expected_socket)++ def _drop_connection(self, expected_socket=None) -> None:+ with self._socket_lock:+ if expected_socket is not None and self._sock is not expected_socket:+ return+ sock = self._sock+ self._sock = None+ self._session = None+ self._close(sock)++ @staticmethod+ def _close(sock) -> None:+ if sock is None:+ return+ try:+ sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+ try:+ sock.close()+ except OSError:+ pass++ def _mac_arrival_edge(self) -> Optional[str]:+ """The Mac edge input arrives at, which is also the Mac's way home:+ the far side of this PC's own outward edge. Sent in the hello as well+ as on every switch, so the Mac is armed to push back before it has+ ever been pushed into."""+ return return_edge.OPPOSITE.get(self._edge) if self._edge else None++ def _rearm_edge(self) -> None:+ """A fresh pair of models. Not a reset: a model disarms itself at+ breakthrough so a burst of deltas still in flight cannot cross twice,+ and nothing else re-arms it."""+ methods = self._methods()+ resistance = int(self._resistance())+ if self._edge is None:+ self._edge_model = self._corner_model = None+ return+ self._edge_model = return_edge.ReturnEdge(self._edge, resistance) if "edge" in methods else None+ corner = self._setting("crossing_corner", "top_left")+ if "corner" in methods and corner in return_edge.CORNERS:+ self._corner_model = return_edge.CornerPush(corner, self._edge, resistance)+ else:+ self._corner_model = None++ def _methods(self):+ return set(self._setting("crossing_methods", ("edge", "shortcut")) or ())++ @property+ def shortcut_armed(self) -> bool:+ """Whether the double-tap may move input. The app asks before acting on+ the trigger, so turning the shortcut off here turns it off everywhere."""+ return "shortcut" in self._methods()++ def _setting(self, name, fallback):+ with self._config_lock:+ config = self._config+ if config is None:+ return fallback+ value = getattr(config, name, fallback)+ return fallback if value is None else value++ def _resistance(self) -> int:+ """How hard this PC's own way out pushes back, which is this PC's+ setting -- and also what the Mac is asked to use at its return edge, so+ one number governs the whole round trip in this direction."""+ return int(self._setting("crossing_resistance_px", return_edge.DEFAULT_RESISTANCE_PX))++ def _warp_to_pin(self) -> None:+ """Put the pointer back where it was when input left. Measured on the+ rig, 17-09-2026: SetCursorPos produces no raw input at all -- a+ deliberate 137-pixel warp in a quiet window produced no WM_INPUT -- so+ the pin cannot feed itself back to the Mac as movement nobody made."""+ pin = self._pin_point+ if pin is None:+ return+ try:+ self._desktop_module().set_cursor_position(*pin)+ except Exception:+ LOGGER.exception("Could not hold the pointer while the Mac has input")++ def _cached_monitors(self):+ now = self._clock()+ if self._monitors is None or now - self._monitors_at > MONITORS_MAX_AGE_SECONDS:+ self._monitors = self._desktop_module().monitors()+ self._monitors_at = now+ return self._monitors++ def _desktop_module(self):+ if self._desktop is not None:+ return self._desktop+ import desktop_win+ return desktop_win++ def _clipboard_module(self):+ if self._clipboard is not None:+ return self._clipboard+ import clipboard_win+ return clipboard_win++ def _notify_pressure(self, edge, pressure, crossed) -> None:+ if self._pressure_callback is None:+ return+ try:+ self._pressure_callback(edge, pressure, crossed)+ except Exception:+ LOGGER.exception("Pressure callback failed")++ def _set_status(self, detail: str) -> None:+ self._status = detail+ if self._status_callback is None:+ return+ try:+ self._status_callback(self.connected, detail)+ except Exception:+ LOGGER.exception("Status callback failed")diff --git a/win_app/tests/fakes.py b/win_app/tests/fakes.pynew file mode 100644index 0000000..a03533f--- /dev/null+++ b/win_app/tests/fakes.py@@ -0,0 +1,145 @@+"""Shared test doubles and helpers for the Windows receiver test suite.++receiver.py normally injects real input via input_injector, which only works+on Windows. These helpers let the receiver's connection-handling logic (auth,+versioning, preemption, timeouts, message dispatch) be exercised on any+platform, including this Mac, without touching a real desktop.+"""++import socket+import time+from typing import List, Optional, Tuple++import protocol+++class FakeInjector:+ """A drop-in replacement for input_injector, passed to+ receiver.handle_message(message, injector=...) so tests never need a real+ Windows desktop (or even ctypes.windll) to run. Records every call so+ tests can assert on what would have been injected."""++ def __init__(self):+ self.calls: List[Tuple[str, tuple]] = []++ def inject_key(self, key, down):+ self.calls.append(("key", (key, down)))++ def inject_mouse_move(self, dx, dy):+ self.calls.append(("mouse_move", (dx, dy)))++ def inject_mouse_button(self, button, down):+ self.calls.append(("mouse_button", (button, down)))++ def inject_scroll(self, dy, dx=0.0, mode="line"):+ self.calls.append(("scroll", (dy, dx, mode)))++ def inject_gesture(self, name):+ self.calls.append(("gesture", (name,)))+++class FakeClipboard:+ """A drop-in replacement for clipboard_win, passed to+ ReceiverServer(status_callback, clipboard=...) so tests never need a real+ Windows desktop (or even ctypes.windll) to run."""++ def __init__(self, text=None, image=None):+ self.text = text+ self.image = image+ self.set_calls: List[Tuple[Optional[str], Optional[bytes]]] = []++ def get_contents(self):+ return self.text, self.image++ def set_contents(self, text, image):+ self.set_calls.append((text, image))+ return True+++class FakeDesktop:+ """A drop-in replacement for desktop_win, passed to+ ReceiverServer(status_callback, desktop=...). Monitors are crossing.Rect+ values in virtual-desktop pixels, so a negative-origin arrangement is one+ list away."""++ def __init__(self, monitors, cursor=(0, 0)):+ self._monitors = list(monitors)+ self.cursor = cursor+ self.set_calls: List[Tuple[int, int]] = []++ def monitors(self):+ return list(self._monitors)++ def cursor_position(self):+ return self.cursor++ def set_cursor_position(self, x, y):+ self.cursor = (x, y)+ self.set_calls.append((x, y))+++class SecureClient:+ """The Mac's half of a v4 connection, driven from a test over a real+ socket: sends its preamble at once and reads the receiver's on first use,+ so it can be built before the session thread that answers it has started.+ Frames are sealed and opened with the real cipher, never mocked away."""++ def __init__(self, sock, token="shared-token"):+ self.sock = sock+ self.session = protocol.SecureSession(token)+ sock.sendall(self.session.preamble())++ def send(self, message):+ protocol.send_msg(self.sock, self.session, message)++ def recv(self):+ if self.session.peer_prefix is None:+ protocol.recv_preamble(self.sock, self.session)+ return protocol.recv_msg(self.sock, self.session)++ def settimeout(self, value):+ self.sock.settimeout(value)++ def close(self):+ self.sock.close()+++def connected_socket_pair(token="shared-token"):+ """Return (client, server_socket, client_address) for a loopback TCP+ connection, mirroring what ReceiverServer._serve would hand to a session+ thread after accept(). `client` is a SecureClient holding `token`; its raw+ socket is `client.sock` for tests that need to misbehave on purpose."""+ listener = socket.socket()+ listener.bind(("127.0.0.1", 0))+ listener.listen(1)+ client = socket.create_connection(listener.getsockname())+ server, address = listener.accept()+ listener.close()+ return SecureClient(client, token), server, address+++def wait_for_status(statuses, state, timeout=1.0):+ """Poll a (state, detail) list appended to by a status callback until an+ entry matching `state` shows up. Status callbacks fire from a background+ session thread, so tests must not assume they've landed the instant a+ socket operation on the other end of the connection completes."""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ for entry in list(statuses):+ if entry[0] == state:+ return entry+ time.sleep(0.01)+ raise AssertionError(f"status {state!r} not observed within {timeout}s; got {statuses!r}")+++def wait_for_calls(calls, minimum=1, timeout=1.0):+ """Poll a list a background session thread appends to (e.g.+ FakeClipboard.set_calls) until it has at least `minimum` entries. Needed+ for effects with no reply on the wire to synchronize on, unlike+ wait_for_status which polls status-callback entries instead."""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if len(calls) >= minimum:+ return+ time.sleep(0.01)+ raise AssertionError(f"expected at least {minimum} call(s) within {timeout}s; got {calls!r}")diff --git a/win_app/tests/test_app_config.py b/win_app/tests/test_app_config.pynew file mode 100644index 0000000..86fdd6f--- /dev/null+++ b/win_app/tests/test_app_config.py@@ -0,0 +1,148 @@+import json+import tempfile+import unittest+from pathlib import Path+from unittest import mock++import app_config+import protocol+from dataclasses import replace++from app_config import ConfigError, config_from_dict, config_to_dict, default_config, migrate_legacy_config+++BASE = {"host": "192.168.1.3", "port": 51820, "auth_token": "shared-token"}+++class EdgeGlowConfigTests(unittest.TestCase):+ def test_defaults_on_and_round_trips(self):+ self.assertTrue(config_from_dict(dict(BASE)).edge_glow)+ config = config_from_dict({**BASE, "edge_glow": False})+ self.assertFalse(config.edge_glow)+ self.assertIs(config_to_dict(config)["edge_glow"], False)++ def test_rejects_a_non_boolean(self):+ with self.assertRaises(ConfigError):+ config_from_dict({**BASE, "edge_glow": "yes"})++ def test_style_and_colour_default_to_the_original_look_and_round_trip(self):+ config = config_from_dict(dict(BASE))+ self.assertEqual((config.glow_style, config.glow_colour), ("glow", "signal"))+ config = config_from_dict({**BASE, "glow_style": "beam", "glow_colour": "sunset"})+ saved = config_to_dict(config)+ self.assertEqual((saved["glow_style"], saved["glow_colour"]), ("beam", "sunset"))++ def test_colour_choices_are_the_shared_palettes(self):+ import tokens++ self.assertEqual(app_config.GLOW_COLOURS, tuple(tokens.PALETTES))++ def test_rejects_an_unknown_style_or_colour(self):+ for key, value in (("glow_style", "sparkle"), ("glow_colour", "tartan")):+ with self.subTest(key=key), self.assertRaises(ConfigError) as caught:+ config_from_dict({**BASE, key: value})+ self.assertIn(key, str(caught.exception))+++class MigrateLegacyConfigTests(unittest.TestCase):+ def test_copies_without_touching_the_old_file(self):+ with tempfile.TemporaryDirectory() as directory:+ old_path = Path(directory) / "OpenKB" / "config.json"+ old_path.parent.mkdir()+ old_path.write_text(json.dumps(BASE), encoding="utf-8")+ new_path = Path(directory) / "Beamer" / "config.json"+ with mock.patch.object(app_config, "default_config_path", return_value=new_path), \+ mock.patch.object(app_config, "legacy_config_path", return_value=old_path):+ self.assertTrue(migrate_legacy_config())+ self.assertTrue(old_path.exists())+ self.assertEqual(+ json.loads(new_path.read_text(encoding="utf-8")),+ json.loads(old_path.read_text(encoding="utf-8")),+ )+ # A second run must not overwrite the now-existing new config.+ new_path.write_text(json.dumps({"changed": True}), encoding="utf-8")+ self.assertFalse(migrate_legacy_config())+ self.assertEqual(json.loads(new_path.read_text(encoding="utf-8")), {"changed": True})++ def test_is_a_noop_with_no_legacy_file(self):+ with tempfile.TemporaryDirectory() as directory:+ old_path = Path(directory) / "OpenKB" / "config.json"+ new_path = Path(directory) / "Beamer" / "config.json"+ with mock.patch.object(app_config, "default_config_path", return_value=new_path), \+ mock.patch.object(app_config, "legacy_config_path", return_value=old_path):+ self.assertFalse(migrate_legacy_config())+ self.assertFalse(new_path.parent.exists())+++if __name__ == "__main__":+ unittest.main()+++class ArrangementTests(unittest.TestCase):+ """Which end's arrangement stands when the two disagree."""++ def test_the_newer_stamp_wins(self):+ self.assertTrue(protocol.arrangement_wins(200, 100))+ self.assertFalse(protocol.arrangement_wins(100, 200))++ def test_an_equal_stamp_changes_nothing(self):+ self.assertFalse(protocol.arrangement_wins(100, 100))++ def test_a_peer_with_no_stamp_never_beats_a_change_made_here(self):+ self.assertFalse(protocol.arrangement_wins(0, 100))+ self.assertFalse(protocol.arrangement_wins(None, 100))++ def test_two_ends_that_never_changed_it_agree(self):+ self.assertFalse(protocol.arrangement_wins(0, 0))+++class LegacyTriggerTests(unittest.TestCase):+ def test_right_alt_is_a_choice_and_is_kept(self):+ # "alt_r" was once rewritten to "cmd_r" as a dead default, but it is a live entry in+ # TRIGGER_KEYS that the window offers, so a person who picked it lost it on every load.+ config = config_from_dict(+ {"host": "192.168.1.3", "port": 51820, "auth_token": "t", "trigger_key": "alt_r"}+ )+ self.assertEqual(config.trigger_key, "alt_r")++ def test_a_fresh_install_has_no_address_and_still_saves(self):+ config = default_config()+ self.assertEqual(config.host, "")+ config_to_dict(replace(config, auth_token="t"))++ def test_a_key_someone_chose_is_left_alone(self):+ config = config_from_dict(+ {"host": "192.168.1.3", "port": 51820, "auth_token": "t", "trigger_key": "shift_r"}+ )+ self.assertEqual(config.trigger_key, "shift_r")+++class LegacyPortTests(unittest.TestCase):+ def test_the_old_default_port_is_moved_out_of_the_ephemeral_range(self):+ config = config_from_dict(+ {"host": "192.168.1.3", "port": protocol.LEGACY_DEFAULT_PORT, "auth_token": "t"}+ )+ self.assertEqual(config.port, protocol.DEFAULT_PORT)+ self.assertLess(protocol.DEFAULT_PORT, 49152)+ self.assertLess(protocol.PAIRING_PORT, 49152)++ def test_a_port_someone_chose_is_left_alone(self):+ config = config_from_dict({"host": "192.168.1.3", "port": 9000, "auth_token": "t"})+ self.assertEqual(config.port, 9000)++ def test_a_new_config_starts_on_the_new_port(self):+ self.assertEqual(default_config().port, protocol.DEFAULT_PORT)++ def test_loading_a_config_on_the_old_port_writes_the_move_down(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "config.json"+ path.write_text(+ json.dumps(+ {"host": "192.168.1.3", "port": protocol.LEGACY_DEFAULT_PORT, "auth_token": "t"}+ ),+ encoding="utf-8",+ )+ self.assertEqual(app_config.load_config(path).port, protocol.DEFAULT_PORT)+ on_disk = json.loads(path.read_text(encoding="utf-8"))+ self.assertEqual(on_disk["port"], protocol.DEFAULT_PORT)+diff --git a/win_app/tests/test_autostart_win.py b/win_app/tests/test_autostart_win.pynew file mode 100644index 0000000..12b6e53--- /dev/null+++ b/win_app/tests/test_autostart_win.py@@ -0,0 +1,66 @@+import subprocess+import unittest+import xml.etree.ElementTree as ET++import autostart_win++NS = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"}+EXE = r"C:\Users\alex\AppData\Local\Beamer\Beamer.exe"+++class FakeSchtasks:+ def __init__(self, exists=False, fail=None):+ self.exists = exists+ self.fail = fail+ self.calls = []+ self.xml = None++ def __call__(self, args):+ self.calls.append(args[1])+ if args[1] == "/create" and self.fail is None:+ with open(args[args.index("/xml") + 1], encoding="utf-16") as handle:+ self.xml = handle.read()+ self.exists = True+ if args[1] == "/delete" and self.fail is None:+ self.exists = False+ if args[1] == "/query":+ return subprocess.CompletedProcess(args, 0 if self.exists else 1, "", "")+ return subprocess.CompletedProcess(args, 1 if self.fail else 0, "", self.fail or "")+++class TaskXmlTests(unittest.TestCase):+ def test_starts_hidden_elevated_and_never_times_out(self):+ root = ET.fromstring(autostart_win.task_xml(EXE, r"STUDIO-PC\alex").replace('encoding="UTF-16"', ""))+ self.assertEqual(root.find("t:Actions/t:Exec/t:Command", NS).text, EXE)+ self.assertEqual(root.find("t:Actions/t:Exec/t:Arguments", NS).text, "--hidden")+ self.assertEqual(root.find("t:Principals/t:Principal/t:RunLevel", NS).text, "HighestAvailable")+ self.assertEqual(root.find("t:Settings/t:ExecutionTimeLimit", NS).text, "PT0S")+ self.assertEqual(root.find("t:Triggers/t:LogonTrigger/t:UserId", NS).text, r"STUDIO-PC\alex")++ def test_escapes_the_path(self):+ ET.fromstring(autostart_win.task_xml(r"C:\A & B\Beamer.exe", "u").replace('encoding="UTF-16"', ""))+++class SwitchTests(unittest.TestCase):+ def test_on_then_off(self):+ fake = FakeSchtasks()+ autostart_win.set_enabled(True, EXE, user="u", run=fake)+ self.assertIn("--hidden", fake.xml)+ self.assertTrue(autostart_win.is_enabled(fake))+ autostart_win.set_enabled(False, EXE, run=fake)+ self.assertFalse(autostart_win.is_enabled(fake))++ def test_off_when_absent_touches_nothing(self):+ fake = FakeSchtasks()+ autostart_win.set_enabled(False, EXE, run=fake)+ self.assertEqual(fake.calls, ["/query"])++ def test_refusal_is_raised(self):+ fake = FakeSchtasks(fail="ERROR: Access is denied.")+ with self.assertRaises(OSError) as caught:+ autostart_win.set_enabled(True, EXE, user="u", run=fake)+ self.assertIn("Access is denied", str(caught.exception))+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_capture_win.py b/win_app/tests/test_capture_win.pynew file mode 100644index 0000000..b6133a4--- /dev/null+++ b/win_app/tests/test_capture_win.py@@ -0,0 +1,134 @@+"""What this PC's keys become on the wire. The translation runs against the+real keyboard layout through ToUnicodeEx, which reads a keyboard state handed+to it rather than the live one, so nothing here touches what is actually being+typed."""++import sys+import unittest++import capture_win+from capture_win import REDIRECT, RETURN, TOGGLE, KeyboardState, Trigger, key_name, wheel_notches+from input_injector import INJECTED_MARK++VK_A = 0x41+VK_1 = 0x31+VK_NUMPAD5 = 0x65+++def names_only(vk, scan, state):+ """A translate function for the tests that never touch Windows."""+ return {VK_A: "a"}.get(vk)+++class NameTests(unittest.TestCase):+ def test_ctrl_leaves_this_pc_as_command(self):+ # The semantic swap happens here and nowhere else: the Mac injects+ # exactly the name it is given.+ state = KeyboardState()+ self.assertEqual(key_name(0xA2, 0, state, names_only), "cmd")+ self.assertEqual(key_name(0xA3, 0, state, names_only), "cmd_r")++ def test_the_windows_key_leaves_as_control(self):+ state = KeyboardState()+ self.assertEqual(key_name(0x5B, 0, state, names_only), "ctrl")++ def test_alt_stays_alt(self):+ state = KeyboardState()+ self.assertEqual(key_name(0xA4, 0, state, names_only), "alt")++ def test_a_key_with_no_character_sends_nothing(self):+ state = KeyboardState()+ self.assertIsNone(key_name(0xFF, 0, state, names_only))++[email protected](sys.platform == "win32", "ToUnicodeEx needs Windows")+class LayoutTests(unittest.TestCase):+ """Against the real layout. The state passed in is the one the hook keeps,+ not the live keyboard, so these translate a key without pressing it."""++ def translate(self, vk, shift=False, caps=False):+ state = KeyboardState()+ state.shift_down = shift+ state.caps_lock = caps+ return key_name(vk, 0, state, capture_win._to_unicode)++ def test_a_letter_comes_back_as_itself(self):+ self.assertEqual(self.translate(VK_A), "a")++ def test_shift_is_applied(self):+ self.assertEqual(self.translate(VK_A, shift=True), "A")++ def test_caps_lock_is_applied(self):+ self.assertEqual(self.translate(VK_A, caps=True), "A")++ def test_a_shifted_digit_gives_the_symbol_the_layout_prints(self):+ self.assertEqual(self.translate(VK_1), "1")+ self.assertEqual(self.translate(VK_1, shift=True), "!")++ def test_the_numpad_types_its_digit(self):+ self.assertEqual(self.translate(VK_NUMPAD5), "5")+++class WheelTests(unittest.TestCase):+ def test_one_notch_each_way(self):+ self.assertEqual(wheel_notches(120 << 16), 1.0)+ self.assertEqual(wheel_notches((0x10000 - 120) << 16), -1.0)+++class TriggerTests(unittest.TestCase):+ def test_two_taps_inside_the_window_fire_once(self):+ trigger = Trigger("cmd_r", "double_tap", 300)+ self.assertIsNone(trigger.feed("cmd_r", True, 1.00))+ self.assertEqual(trigger.feed("cmd_r", True, 1.20), TOGGLE)+ # The pair is spent: a third tap starts a new one rather than firing.+ self.assertIsNone(trigger.feed("cmd_r", True, 1.30))++ def test_a_slow_second_tap_does_not_fire(self):+ trigger = Trigger("cmd_r", "double_tap", 300)+ trigger.feed("cmd_r", True, 1.0)+ self.assertIsNone(trigger.feed("cmd_r", True, 2.0))++ def test_another_key_is_not_the_trigger(self):+ trigger = Trigger("cmd_r", "double_tap", 300)+ trigger.feed("cmd_r", True, 1.0)+ self.assertIsNone(trigger.feed("a", True, 1.1))++ def test_holding_sends_input_over_and_releasing_brings_it_back(self):+ trigger = Trigger("alt_r", "hold", 300)+ self.assertEqual(trigger.feed("alt_r", True, 1.0), REDIRECT)+ # Key repeat while held changes nothing, and is still swallowed.+ self.assertIsNone(trigger.feed("alt_r", True, 1.1))+ self.assertEqual(trigger.feed("alt_r", False, 1.4), RETURN)++ def test_the_key_and_the_style_can_be_changed(self):+ trigger = Trigger("cmd_r", "double_tap", 300)+ trigger.configure("alt_r", "hold", 300)+ self.assertIsNone(trigger.feed("cmd_r", True, 1.0))+ self.assertEqual(trigger.feed("alt_r", True, 1.0), REDIRECT)+++class HandMotionTests(unittest.TestCase):+ """What the WM_INPUT reader keeps. Raw Input reports a SendInput move+ exactly as it reports the mouse, so the injector's stamp is the only+ thing keeping the Mac's pointer out of this PC's own edge."""++ def test_the_hands_counts_pass(self):+ self.assertEqual(capture_win.hand_motion(0, -20, 3, 0), (-20, 3))++ def test_a_move_beamer_injected_is_not_the_hands(self):+ self.assertIsNone(capture_win.hand_motion(0, -20, 3, INJECTED_MARK))++ def test_another_devices_own_signature_still_passes(self):+ # A pen stamps its own signature into the same field; only Beamer's+ # mark is Beamer's.+ self.assertEqual(capture_win.hand_motion(0, -20, 3, 0xFF515700), (-20, 3))++ def test_an_absolute_reading_is_not_measured(self):+ self.assertIsNone(capture_win.hand_motion(capture_win.MOUSE_MOVE_ABSOLUTE, 500, 500, 0))++ def test_no_movement_is_nothing(self):+ self.assertIsNone(capture_win.hand_motion(0, 0, 0, 0))+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_clipboard_win.py b/win_app/tests/test_clipboard_win.pynew file mode 100644index 0000000..b620bb8--- /dev/null+++ b/win_app/tests/test_clipboard_win.py@@ -0,0 +1,288 @@+"""The clipboard image path that runs on any platform: the pure DIB codec,+the clipboard message's image payload, and the read/write orchestration+over fake user32/kernel32 backed by real ctypes buffers. The Qt PNG codec is+replaced with a marker encoding so nothing here needs PySide6 or Windows."""++import ctypes+import struct+import sys+import unittest+from unittest import mock++import clipboard_win+import protocol+from clipboard_win import BI_BITFIELDS, BI_RGB, CF_DIB, CF_UNICODETEXT, bgra_to_dib, dib_to_bgra+++def header(width, height, bpp, compression=BI_RGB, size=40):+ fields = struct.pack("<IiiHHIIiiII", size, width, height, 1, bpp, compression, 0, 0, 0, 0, 0)+ return fields + b"\x00" * (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+++class DibCodecTests(unittest.TestCase):+ def test_32_bit_round_trip(self):+ dib = bgra_to_dib(2, 2, BGRA)+ self.assertEqual(len(dib), 40 + 16)+ self.assertEqual(dib_to_bgra(dib), (2, 2, BGRA))++ def test_written_dib_is_bottom_up(self):+ dib = bgra_to_dib(2, 2, BGRA)+ self.assertEqual(dib[40:48], BGRA[8:16])++ def test_24_bit_rows_are_padded_and_alpha_is_opaque(self):+ # Width 3 at 24 bits is 9 bytes a row, padded to 12; one row, so+ # bottom-up and top-down coincide.+ row = bytes([1, 2, 3, 4, 5, 6, 7, 8, 9]) + b"\x00\x00\x00"+ self.assertEqual(+ dib_to_bgra(header(3, 1, 24) + row),+ (3, 1, bytes([1, 2, 3, 255, 4, 5, 6, 255, 7, 8, 9, 255])),+ )++ def test_negative_height_is_top_down(self):+ self.assertEqual(dib_to_bgra(header(2, -2, 32) + BGRA), (2, 2, BGRA))++ def test_bi_rgb_all_zero_alpha_reads_as_opaque(self):+ pixels = bytes([10, 20, 30, 0] * 4)+ self.assertEqual(dib_to_bgra(header(2, -2, 32) + pixels)[2], bytes([10, 20, 30, 255] * 4))++ def test_bi_rgb_real_alpha_is_kept(self):+ pixels = bytes([10, 20, 30, 0, 10, 20, 30, 200] * 2)+ self.assertEqual(dib_to_bgra(header(2, -2, 32) + pixels)[2], pixels)++ def test_bitfields_with_v5_alpha_mask_keeps_zero_alpha(self):+ masks = struct.pack("<IIII", 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000)+ head = header(2, -2, 32, BI_BITFIELDS, size=124)+ head = head[:40] + masks + head[56:]+ pixels = bytes([10, 20, 30, 0] * 4)+ self.assertEqual(dib_to_bgra(head + pixels)[2], pixels)++ def test_bitfields_with_40_byte_header_reads_masks_after_it(self):+ masks = struct.pack("<III", 0x00FF0000, 0x0000FF00, 0x000000FF)+ self.assertEqual(dib_to_bgra(header(2, -2, 32, BI_BITFIELDS) + masks + BGRA), (2, 2, BGRA))++ def test_v2_header_mask_overread_does_not_produce_transparent_output(self):+ # clipboard-injection-2: a 52-byte BITMAPV2INFOHEADER carries only 3+ # BI_BITFIELDS masks (ending at offset 52), but dib_to_bgra always+ # unpacks 4 (through offset 56) whenever size > BITMAPINFOHEADER_SIZE,+ # so masks[3] is actually the DIB's first 4 pixel bytes. The only way+ # those bytes can equal _ALPHA_MASK (0xFF000000, i.e. le bytes+ # 00 00 00 FF) is for that same pixel's own real alpha byte to be+ # 0xFF -- which makes it impossible for every real alpha byte in the+ # image to be zero, so the all-zero-alpha-means-opaque fallback this+ # would otherwise suppress was never going to fire anyway. The+ # over-read is real but inert: this pixel, and the whole 1-3px+ # sweep in the verifier's notes, decode identically to a version that+ # reads the correct 3 masks for a size-52 header.+ masks = struct.pack("<III", 0x00FF0000, 0x0000FF00, 0x000000FF)+ head = header(1, -1, 32, BI_BITFIELDS, size=52)+ head = head[:40] + masks+ pixel = bytes([0x00, 0x00, 0x00, 0xFF]) # B, G, R, A=0xFF+ self.assertEqual(dib_to_bgra(head + pixel), (1, 1, pixel))++ def test_unusual_masks_are_refused(self):+ masks = struct.pack("<III", 0x000000FF, 0x0000FF00, 0x00FF0000)+ self.assertIsNone(dib_to_bgra(header(2, -2, 32, BI_BITFIELDS) + masks + BGRA))++ def test_junk_is_refused_without_raising(self):+ for junk in (+ b"",+ b"short",+ header(2, 2, 8) + b"\x00" * 64,+ header(2, 2, 32, compression=1) + BGRA,+ header(2, 2, 32) + BGRA[:-1],+ header(0, 2, 32) + BGRA,+ header(2, 0, 32) + BGRA,+ header(2, 2, 32, size=48) + BGRA,+ header(1 << 30, 1 << 30, 32) + BGRA,+ ):+ with self.subTest(junk=junk[:48]):+ self.assertIsNone(dib_to_bgra(junk))+++class ClipboardMessageTests(unittest.TestCase):+ def test_text_only_message_is_unchanged(self):+ self.assertEqual(protocol.clipboard_msg("hello"), {"type": "clipboard", "data": {"text": "hello"}})+ self.assertIsNone(protocol.clipboard_image(protocol.clipboard_msg("hello")["data"]))++ def test_image_round_trips_through_the_sealed_wire(self):+ sender = protocol.SecureSession("shared-token")+ receiver = protocol.SecureSession("shared-token")+ receiver.accept_preamble(sender.preamble())+ frame = sender.seal(protocol.clipboard_msg("shot.png", PNG))+ message = receiver.open(frame[protocol.HEADER_SIZE:])+ self.assertEqual(message["data"]["text"], "shot.png")+ self.assertEqual(message["data"]["image_format"], "png")+ self.assertEqual(protocol.clipboard_image(message["data"]), PNG)++ def test_image_only_message_carries_no_text_key(self):+ self.assertNotIn("text", protocol.clipboard_msg(None, PNG)["data"])++ def test_oversized_image_is_refused(self):+ big = protocol.PNG_SIGNATURE + b"\x00" * protocol.CLIPBOARD_IMAGE_MAX_BYTES+ self.assertIsNone(protocol.clipboard_image(protocol.clipboard_msg(None, big)["data"]))++ def test_malformed_payloads_are_refused_without_raising(self):+ good = protocol.clipboard_msg(None, PNG)["data"]+ for data in (+ None,+ {},+ {"image": good["image"]},+ {"image": good["image"], "image_format": "jpeg"},+ {"image": "not base64!", "image_format": "png"},+ {"image": 42, "image_format": "png"},+ {"image": "", "image_format": "png"},+ {"image": protocol.clipboard_msg(None, b"GIF89a junk")["data"]["image"], "image_format": "png"},+ ):+ with self.subTest(data=data):+ self.assertIsNone(protocol.clipboard_image(data))+++class FakeMem32:+ """kernel32 stand-in whose handles are real ctypes buffers, so the+ string_at/memmove in clipboard_win run for real on this Mac."""++ def __init__(self):+ self.buffers = {}+ self.freed = []++ def handle_for(self, payload):+ # A str becomes a wchar_t buffer, since wstring_at reads wchar_t and+ # that is four bytes here and two on Windows.+ if isinstance(payload, str):+ buffer = ctypes.create_unicode_buffer(payload)+ else:+ buffer = ctypes.create_string_buffer(payload, len(payload))+ handle = ctypes.addressof(buffer)+ self.buffers[handle] = buffer+ return handle++ def GlobalAlloc(self, flags, size):+ return self.handle_for(b"\x00" * size)++ def GlobalSize(self, handle):+ return ctypes.sizeof(self.buffers[handle])++ def GlobalLock(self, handle):+ return handle++ def GlobalUnlock(self, handle):+ return 1++ def GlobalFree(self, handle):+ self.freed.append(handle)++ def contents(self, handle):+ return self.buffers[handle].raw+++class FakeWin32:+ def __init__(self, mem32, formats=None):+ self.mem32 = mem32+ self.formats = dict(formats or {})+ self.emptied = 0++ def OpenClipboard(self, owner):+ return 1++ def CloseClipboard(self):+ return 1++ def EmptyClipboard(self):+ self.emptied += 1+ self.formats.clear()+ return 1++ def GetClipboardData(self, clipboard_format):+ return self.formats.get(clipboard_format, 0)++ def SetClipboardData(self, clipboard_format, handle):+ self.formats[clipboard_format] = handle+ return handle+++def fake_png_to_bgra(png):+ if not png.startswith(b"FAKEPNG"):+ return None+ width, height = struct.unpack("<II", png[7:15])+ return width, height, png[15:]+++def fake_bgra_to_png(width, height, bgra):+ return b"FAKEPNG" + struct.pack("<II", width, height) + bgra+++class ClipboardOrchestrationTests(unittest.TestCase):+ def setUp(self):+ patches = [+ mock.patch.object(clipboard_win, "_png_to_bgra", fake_png_to_bgra),+ mock.patch.object(clipboard_win, "_bgra_to_png", fake_bgra_to_png),+ ]+ for patch in patches:+ patch.start()+ self.addCleanup(patch.stop)+ self.mem32 = FakeMem32()++ def test_get_contents_reads_text_and_converts_the_dib(self):+ win32 = FakeWin32(+ self.mem32,+ {+ CF_UNICODETEXT: self.mem32.handle_for("hi"),+ CF_DIB: self.mem32.handle_for(bgra_to_dib(2, 2, BGRA)),+ },+ )+ self.assertEqual(clipboard_win._get_contents(win32, self.mem32), ("hi", fake_bgra_to_png(2, 2, BGRA)))++ def test_get_contents_with_an_undecodable_dib_still_returns_the_text(self):+ win32 = FakeWin32(+ self.mem32,+ {+ CF_UNICODETEXT: self.mem32.handle_for("hi"),+ CF_DIB: self.mem32.handle_for(b"garbage" * 10),+ },+ )+ self.assertEqual(clipboard_win._get_contents(win32, self.mem32), ("hi", None))++ def test_set_contents_writes_text_and_dib_after_one_empty(self):+ win32 = FakeWin32(self.mem32)+ self.assertTrue(clipboard_win._set_contents(win32, self.mem32, "hi", fake_bgra_to_png(2, 2, BGRA)))+ self.assertEqual(win32.emptied, 1)+ self.assertEqual(self.mem32.contents(win32.formats[CF_UNICODETEXT]), "hi".encode("utf-16-le") + b"\x00\x00")+ self.assertEqual(self.mem32.contents(win32.formats[CF_DIB]), bgra_to_dib(2, 2, BGRA))+ self.assertEqual(self.mem32.freed, [])++ def test_set_contents_writes_windows_line_endings(self):+ win32 = FakeWin32(self.mem32)+ self.assertTrue(clipboard_win._set_contents(win32, self.mem32, "one\ntwo\r\nthree", None))+ self.assertEqual(+ self.mem32.contents(win32.formats[CF_UNICODETEXT]),+ "one\r\ntwo\r\nthree".encode("utf-16-le") + b"\x00\x00",+ )++ def test_set_contents_with_an_undecodable_png_sets_the_text_only(self):+ win32 = FakeWin32(self.mem32)+ self.assertTrue(clipboard_win._set_contents(win32, self.mem32, "hi", b"\x89PNG but not really"))+ self.assertEqual(sorted(win32.formats), [CF_UNICODETEXT])++ def test_set_contents_with_only_an_undecodable_png_leaves_the_clipboard_alone(self):+ win32 = FakeWin32(self.mem32, {CF_UNICODETEXT: self.mem32.handle_for(b"k\x00\x00\x00")})+ self.assertFalse(clipboard_win._set_contents(win32, self.mem32, None, b"junk"))+ self.assertEqual(win32.emptied, 0)++ @unittest.skipIf(sys.platform == "win32", "the real clipboard answers on Windows")+ def test_get_contents_never_raises_off_windows(self):+ # The public entry points are the ones the app calls on both platforms, so they must+ # return empty rather than raise where there is no Windows clipboard. On Windows they+ # really do write, which is why this is skipped there rather than asserted the other+ # way -- it would then be a live-clipboard test, and the build must not clobber+ # whatever the person running it had copied.+ self.assertEqual(clipboard_win.get_contents(), (None, None))+ self.assertFalse(clipboard_win.set_contents("x", PNG))+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_edge_glow.py b/win_app/tests/test_edge_glow.pynew file mode 100644index 0000000..094c77f--- /dev/null+++ b/win_app/tests/test_edge_glow.py@@ -0,0 +1,25 @@+import unittest++try:+ import edge_glow+except ImportError: # PySide6 is only in the Windows build venv+ edge_glow = None++[email protected](edge_glow is None, "PySide6 is not installed")+class BeamMathsTests(unittest.TestCase):+ def test_comet_travels_faster_as_pressure_builds(self):+ self.assertEqual(edge_glow.traverse_seconds(0.0), edge_glow.SLOW_TRAVERSE_S)+ self.assertAlmostEqual(edge_glow.traverse_seconds(1.0), edge_glow.FAST_TRAVERSE_S)+ self.assertLess(edge_glow.traverse_seconds(0.7), edge_glow.traverse_seconds(0.2))++ def test_edge_is_brightest_at_the_comet_and_dim_away_from_it(self):+ self.assertEqual(edge_glow.comet_alpha(0.5, 0.5, 0.0), 1.0)+ self.assertEqual(edge_glow.comet_alpha(0.0, 0.5, 0.0), edge_glow.BEAM_BASE)++ def test_breakthrough_lights_the_whole_edge(self):+ self.assertEqual(edge_glow.comet_alpha(0.0, 0.5, 1.0), 1.0)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_firewall_win.py b/win_app/tests/test_firewall_win.pynew file mode 100644index 0000000..78e3fd1--- /dev/null+++ b/win_app/tests/test_firewall_win.py@@ -0,0 +1,216 @@+"""Firewall interpretation and the advice it turns into, exercised on any platform.++firewall_win's PowerShell stays untouched here: every test hands interpret() the JSON shape+the status script emits, so the decisions run on the Mac with no Windows at all.+"""++import unittest++import firewall_win+from firewall_win import advise, interpret++EXE = r"C:\Users\alex\AppData\Local\Beamer\Beamer.exe"+PORT = 51820+++def rule(action="Allow", profile="Private", program=EXE, port="51820", protocol="TCP", enabled="True", direction="Inbound"):+ return {+ "name": "{x}", "display": "Beamer Receiver (TCP-In)", "enabled": enabled, "action": action,+ "direction": direction, "profile": profile, "program": program, "protocol": protocol,+ "localPort": [port] if port is not None else ["Any"],+ }+++def pairing_rule(action="Allow", profile="Private", program=EXE, enabled="True"):+ """The UDP beacon rule repair() and the installer write beside the TCP one."""+ return {+ "name": "{y}", "display": "Beamer Pairing (UDP-In)", "enabled": enabled, "action": action,+ "direction": "Inbound", "profile": profile, "program": program, "protocol": "UDP",+ "localPort": [str(firewall_win.PAIRING_PORT)],+ }+++def network(category="Private", alias="Wi-Fi", index=5, ipv4="Internet", ipv6="NoTraffic"):+ return {"alias": alias, "index": index, "category": category, "ipv4": ipv4, "ipv6": ipv6}+++def payload(rules=(), networks=(network(),)):+ return {"rules": list(rules), "networks": list(networks)}+++class InterpretTests(unittest.TestCase):+ def test_no_rule_at_all(self):+ status = interpret(payload(), EXE, PORT)+ self.assertFalse(status.allowed)+ self.assertFalse(status.blocked)+ self.assertFalse(status.covered)+ self.assertEqual(status.active_profiles, ("Private",))+ self.assertEqual(advise(status).action, "repair")++ def test_correct_rule_on_private_lan(self):+ status = interpret(payload([rule(), pairing_rule()]), EXE, PORT)+ self.assertTrue(status.allowed)+ self.assertTrue(status.covered)+ self.assertTrue(status.pairing_allowed)+ self.assertFalse(status.blocked)+ self.assertEqual(status.public_interfaces, ())+ advice = advise(status)+ self.assertEqual(advice.action, "check")+ self.assertIn("lets your Mac reach Beamer", advice.sentence)++ def test_rule_scoped_to_a_profile_the_lan_is_not_on(self):+ # The installer's Private-only rule, but the LAN has been reclassified Public.+ status = interpret(payload([rule()], [network("Public", alias="Ethernet", index=9)]), EXE, PORT)+ self.assertTrue(status.allowed)+ self.assertFalse(status.covered)+ self.assertEqual(status.public_interfaces, ((9, "Ethernet"),))+ advice = advise(status)+ self.assertEqual(advice.action, "trust")+ self.assertIn("Ethernet", advice.sentence)+ self.assertEqual(advice.button, "Trust this network")++ def test_public_only_rule_on_private_lan_is_rewritten_not_trusted(self):+ status = interpret(payload([rule(profile="Public")]), EXE, PORT)+ self.assertTrue(status.allowed)+ self.assertFalse(status.covered)+ self.assertEqual(status.public_interfaces, ())+ self.assertEqual(advise(status).action, "repair")++ def test_block_rule_beats_allow_rule(self):+ # What Windows writes when Cancel is pressed on its own prompt: a block, any port, per profile.+ rules = [rule(), rule(action="Block", profile="Private, Public", port="Any"), rule(action="Block", profile="Private, Public", port="Any", protocol="UDP")]+ status = interpret(payload(rules), EXE, PORT)+ self.assertTrue(status.allowed)+ self.assertTrue(status.blocked)+ advice = advise(status)+ self.assertEqual(advice.action, "repair")+ self.assertIn("blocking", advice.sentence)++ def test_block_rule_on_an_inactive_profile_is_harmless(self):+ status = interpret(payload([rule(), pairing_rule(), rule(action="Block", profile="Public", port="Any")]), EXE, PORT)+ self.assertFalse(status.blocked)+ self.assertEqual(advise(status).action, "check")++ def test_disabled_block_rule_is_ignored(self):+ status = interpret(payload([rule(), rule(action="Block", port="Any", enabled="False")]), EXE, PORT)+ self.assertFalse(status.blocked)++ def test_executable_path_not_matching_the_rule(self):+ status = interpret(payload([rule(program=r"C:\Users\alex\code\Beamer\dist\Beamer.exe")]), EXE, PORT)+ self.assertFalse(status.allowed)+ self.assertEqual(advise(status).action, "repair")++ def test_path_match_ignores_case_and_slashes(self):+ status = interpret(payload([rule(program=EXE.lower().replace("\\", "/"))]), EXE, PORT)+ self.assertTrue(status.allowed)++ def test_port_must_cover_the_listen_port(self):+ self.assertFalse(interpret(payload([rule(port="51821")]), EXE, PORT).allowed)+ self.assertTrue(interpret(payload([rule(port="51000-52000")]), EXE, PORT).allowed)+ self.assertTrue(interpret(payload([rule(port="Any")]), EXE, PORT).allowed)+ self.assertFalse(interpret(payload([rule(protocol="UDP")]), EXE, PORT).allowed)+ self.assertFalse(interpret(payload([rule(direction="Outbound")]), EXE, PORT).allowed)++ def test_any_profile_rule_covers_everything(self):+ status = interpret(payload([rule(profile="Any"), pairing_rule(profile="Any")], [network("Public")]), EXE, PORT)+ self.assertTrue(status.covered)+ self.assertEqual(status.public_interfaces, ((5, "Wi-Fi"),))+ self.assertEqual(advise(status).action, "check")++ def test_bitmask_profile_is_understood(self):+ self.assertTrue(interpret(payload([rule(profile=2)]), EXE, PORT).covered)+ self.assertFalse(interpret(payload([rule(profile=4)]), EXE, PORT).covered)++ def test_public_hyper_v_switch_beside_private_wifi_is_not_the_lan(self):+ # The owner's machine today: Wi-Fi Private with Internet, a vEthernet switch Public with none.+ networks = [network(), network("Public", alias="vEthernet (AI-Hub-Switch)", index=31, ipv4="NoTraffic")]+ status = interpret(payload([rule(), pairing_rule()], networks), EXE, PORT)+ self.assertEqual(status.active_profiles, ("Private", "Public"))+ self.assertEqual(status.lan_profiles, ("Private",))+ self.assertTrue(status.covered)+ self.assertEqual(advise(status).action, "check")++ def test_domain_lan_widens_the_rule_to_domain_never_public(self):+ status = interpret(payload([rule()], [network("DomainAuthenticated", alias="Ethernet")]), EXE, PORT)+ advice = advise(status)+ self.assertEqual(advice.action, "repair")+ self.assertEqual(advice.rule_profiles, ("Private", "Domain"))++ def test_not_elevated_explains_instead_of_offering(self):+ status = interpret(payload(), EXE, PORT, elevated=False)+ advice = advise(status)+ self.assertIsNone(advice.action)+ self.assertIn("not running as administrator", advice.sentence)++ def test_error_offers_a_recheck(self):+ status = firewall_win.FirewallStatus(PORT, False, False, (), (), False, (), True, error="Access is denied")+ advice = advise(status)+ self.assertEqual(advice.action, "check")+ self.assertIn("Access is denied", advice.sentence)++ def test_status_off_windows_reports_an_error_not_a_crash(self):+ if firewall_win._IS_WINDOWS:+ self.skipTest("the Windows path shells out")+ status = firewall_win.status(EXE, PORT)+ self.assertTrue(status.error)+ self.assertFalse(status.allowed)+++class RepairScriptTests(unittest.TestCase):+ def test_repair_never_opens_the_port_on_public(self):+ rendered = firewall_win._REPAIR_SCRIPT.format(+ exe=firewall_win._quote(EXE), filters=firewall_win._RULES_FOR_LEAF,+ name=firewall_win._quote(firewall_win.RULE_NAME), port=PORT,+ pairing_name=firewall_win._quote(firewall_win.PAIRING_RULE_NAME), pairing_port=firewall_win.PAIRING_PORT,+ profiles="Private",+ )+ self.assertIn("-Profile Private ", rendered)+ self.assertNotIn("Public", rendered)+ self.assertIn(f"-Protocol TCP -LocalPort {PORT} ", rendered)+ self.assertIn(f"-Protocol UDP -LocalPort {firewall_win.PAIRING_PORT} ", rendered)+ self.assertEqual(rendered.count("-Profile Private "), 2)+ # A bare Remove-NetFirewallRule deletes every rule on the machine.+ self.assertNotIn("\nRemove-NetFirewallRule", rendered)+ self.assertIn("if ($stale.Count -gt 0)", rendered)++ def test_quote_doubles_single_quotes(self):+ self.assertEqual(firewall_win._quote("it's"), "'it''s'")+++if __name__ == "__main__":+ unittest.main()+++class PairingRuleTests(unittest.TestCase):+ """An install made before pairing existed has the TCP rule and not the UDP one. Reporting+ only the TCP rule told that user everything was fine while no Mac could ever discover them."""++ def test_tcp_rule_without_the_pairing_rule_is_reported_and_repairable(self):+ status = interpret(payload([rule()]), EXE, PORT)+ self.assertTrue(status.allowed)+ self.assertFalse(status.pairing_allowed)+ advice = advise(status)+ self.assertEqual(advice.action, "repair")+ self.assertIn("pairing beacon", advice.sentence)++ def test_both_rules_present_is_all_clear(self):+ status = interpret(payload([rule(), pairing_rule()]), EXE, PORT)+ self.assertTrue(status.pairing_allowed)+ advice = advise(status)+ self.assertEqual(advice.action, "check")+ self.assertIn("discover this PC", advice.sentence)++ def test_a_disabled_pairing_rule_does_not_count(self):+ status = interpret(payload([rule(), pairing_rule(enabled="False")]), EXE, PORT)+ self.assertFalse(status.pairing_allowed)++ def test_a_tcp_rule_on_the_pairing_port_is_not_the_pairing_rule(self):+ wrong = rule(port=str(firewall_win.PAIRING_PORT))+ status = interpret(payload([rule(), wrong]), EXE, PORT)+ self.assertFalse(status.pairing_allowed)++ def test_a_missing_tcp_rule_is_reported_before_the_pairing_rule(self):+ # Input not arriving at all is the bigger problem; one button fixes both.+ status = interpret(payload([pairing_rule()]), EXE, PORT)+ self.assertFalse(status.allowed)+ self.assertIn("no rule letting your Mac reach", advise(status).sentence)diff --git a/win_app/tests/test_hook_key_repeat.py b/win_app/tests/test_hook_key_repeat.pynew file mode 100644index 0000000..24266e2--- /dev/null+++ b/win_app/tests/test_hook_key_repeat.py@@ -0,0 +1,109 @@+"""kvm_bridge_win.py:1056-1071 (`_on_hook_key`) cannot be imported here (it+needs PySide6, Windows-only), so this drives its exact dispatch by hand+against the two pure-Python pieces it calls: `capture_win.Trigger.feed` and+`sender.MacSender.on_key`. The dispatch replicated below is copied verbatim+from `_on_hook_key`'s body."""++import time+import unittest++import capture_win+import protocol+import sender+from capture_win import Trigger+from fakes import FakeDesktop+from sender import MacSender+++def dispatch(trigger, mac_sender, name, down):+ """`WindowsApplication._on_hook_key`, verbatim."""+ action = trigger.feed(name, down, time.monotonic())+ if action is not None:+ if action == capture_win.TOGGLE:+ mac_sender.toggle()+ else:+ mac_sender.set_redirecting(action == capture_win.REDIRECT)+ return True+ if trigger.claims(name, down, mac_sender.redirecting):+ return True+ return mac_sender.on_key(name, down)+++class HeldTriggerRepeatTests(unittest.TestCase):+ def setUp(self):+ self.trigger = Trigger("alt_r", "hold", 300)+ self.mac_sender = MacSender(desktop=FakeDesktop([]))+ # Make the link look live without a real socket or connection+ # thread, exactly as `_link_live`/`connected` require.+ self.mac_sender._sock = object()+ self.mac_sender._connected_at = time.monotonic()++ def test_held_trigger_key_repeat_is_not_forwarded_to_mac(self):+ # Physical press: the trigger claims it, redirecting turns on.+ self.assertTrue(dispatch(self.trigger, self.mac_sender, "alt_r", True))+ self.assertTrue(self.mac_sender.redirecting)++ # Windows autorepeats WM_KEYDOWN for as long as the key stays down.+ # The trigger's own comment says a repeat "never reaches an app";+ # it must not be forwarded to the Mac as a live keystroke.+ dispatch(self.trigger, self.mac_sender, "alt_r", True)++ forwarded = [+ message+ for message in list(self.mac_sender._outbound.queue)+ if message.get("type") == protocol.MSG_KEYDOWN+ and message.get("data", {}).get("key") == "alt_r"+ ]+ self.assertEqual(+ forwarded,+ [],+ "an autorepeat of the held trigger key was forwarded to the Mac "+ "as MSG_KEYDOWN",+ )++ def test_a_lone_tap_at_home_under_double_tap_is_an_ordinary_key(self):+ trigger = Trigger("cmd_r", "double_tap", 300)+ self.assertFalse(dispatch(trigger, self.mac_sender, "cmd_r", True))+ self.assertFalse(dispatch(trigger, self.mac_sender, "cmd_r", False))++ def test_the_trigger_is_swallowed_while_input_is_away_under_double_tap(self):+ trigger = Trigger("cmd_r", "double_tap", 300)+ self.mac_sender.set_redirecting(True)+ self.assertTrue(dispatch(trigger, self.mac_sender, "cmd_r", True))+ self.assertTrue(dispatch(trigger, self.mac_sender, "cmd_r", False))+ forwarded = [m for m in list(self.mac_sender._outbound.queue) if m.get("data", {}).get("key") == "cmd_r"]+ self.assertEqual(forwarded, [])++ def test_the_second_taps_release_is_swallowed_after_coming_home(self):+ # Two taps while away toggle input home on the second down; that+ # tap's release must not reach Windows as a key-up with no key-down.+ trigger = Trigger("cmd_r", "double_tap", 300)+ self.mac_sender.set_redirecting(True)+ self.assertTrue(dispatch(trigger, self.mac_sender, "cmd_r", True))+ self.assertTrue(dispatch(trigger, self.mac_sender, "cmd_r", False))+ self.assertTrue(dispatch(trigger, self.mac_sender, "cmd_r", True))+ self.assertFalse(self.mac_sender.redirecting)+ self.assertTrue(dispatch(trigger, self.mac_sender, "cmd_r", False))+ # A later lone tap at home is an ordinary key again.+ self.assertFalse(dispatch(trigger, self.mac_sender, "cmd_r", True))+ self.assertFalse(dispatch(trigger, self.mac_sender, "cmd_r", False))++ def test_physical_release_never_reaches_on_key_so_no_keyup_is_sent(self):+ dispatch(self.trigger, self.mac_sender, "alt_r", True)+ dispatch(self.trigger, self.mac_sender, "alt_r", True) # the repeat+ dispatch(self.trigger, self.mac_sender, "alt_r", False) # real release++ keyups = [+ message+ for message in list(self.mac_sender._outbound.queue)+ if message.get("type") == protocol.MSG_KEYUP+ and message.get("data", {}).get("key") == "alt_r"+ ]+ # RETURN swallows the release before sender.on_key ever sees it, so+ # a key-down that did leak (proven above) is never balanced by a+ # key-up -- the Mac is left with a phantom held key.+ self.assertEqual(keyups, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_input_injector.py b/win_app/tests/test_input_injector.pynew file mode 100644index 0000000..2a0605c--- /dev/null+++ b/win_app/tests/test_input_injector.py@@ -0,0 +1,448 @@+import ctypes+import unittest+from unittest import mock++import input_injector+from input_injector import (+ KEYEVENTF_EXTENDEDKEY,+ KEYEVENTF_KEYUP,+ KEYEVENTF_UNICODE,+ MOUSEEVENTF_HWHEEL,+ MOUSEEVENTF_WHEEL,+ WHEEL_UNITS_PER_PIXEL,+ plan_key_inputs,+ plan_scroll_units,+)+++# Fake VkKeyScanW: maps a character to a 16-bit (shift_state << 8) | vk value,+# or -1 if the character can't be produced by the "layout" at all.+FAKE_VK_SCAN = {+ "c": 0x0043, # plain, no shift needed+ "e": 0x0045, # plain+ "C": 0x0143, # shift + VK_C (upper-case via shift)+ "k": 0x004B, # plain, no shift needed+ "K": 0x014B, # shift + VK_K (upper-case via shift)+ "@": 0x0602, # requires ctrl+alt (AltGr) bits -> unsupported combo+}++# Fake MapVirtualKeyW: vk -> hardware scan code.+FAKE_SCAN_CODES = {+ 0x43: 0x2E, # 'C' key+ 0x45: 0x12, # 'E' key+ 0x4B: 0x25, # 'K' key+ 0x0D: 0x1C, # enter+ 0x26: 0x48, # up arrow+ 0xA3: 0x1D, # ctrl_r+ 0x5B: 0x5B, # cmd (left win)+ 0x08: 0x0E, # backspace+ 0x2E: 0x53, # delete+}+++def fake_vk_lookup(ch: str) -> int:+ return FAKE_VK_SCAN.get(ch, -1)+++def fake_scan_lookup(vk: int) -> int:+ return FAKE_SCAN_CODES.get(vk, 0)+++class BackspaceTests(unittest.TestCase):+ """Backspace is an ordinary named key under every modifier. It used to be+ remapped to Delete under Ctrl+Alt to stand in for Ctrl+Alt+Del; that went+ with the SAS feature, so Ctrl+Alt+Backspace now reaches Windows as the+ plain chord it is."""++ def plan(self, down, mods_down, char_vk_down):+ return plan_key_inputs(+ "backspace", down, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup+ )++ def test_plain_backspace_stays_backspace(self):+ char_vk_down = {}+ self.assertEqual(self.plan(True, set(), char_vk_down), [(0x08, 0x0E, 0)])+ self.assertEqual(+ self.plan(False, set(), char_vk_down), [(0x08, 0x0E, KEYEVENTF_KEYUP)]+ )++ def test_ctrl_only_backspace_stays_backspace(self):+ self.assertEqual(self.plan(True, {"ctrl"}, {}), [(0x08, 0x0E, 0)])++ def test_ctrl_alt_backspace_is_an_ordinary_chord(self):+ char_vk_down = {}+ for mods in ({"ctrl", "alt"}, {"ctrl_r", "alt_r"}):+ self.assertEqual(self.plan(True, mods, char_vk_down), [(0x08, 0x0E, 0)])+ self.assertEqual(+ self.plan(False, mods, char_vk_down), [(0x08, 0x0E, KEYEVENTF_KEYUP)]+ )+ self.assertEqual(char_vk_down, {})+++class PlanKeyInputsChordTests(unittest.TestCase):+ def setUp(self):+ input_injector._warned_chars.clear()++ def test_ctrl_held_char_uses_vk_keystroke_and_mirrors_on_keyup(self):+ mods_down = {"ctrl"}+ char_vk_down = {}++ down_plan = plan_key_inputs("c", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(down_plan, [(0x43, 0x2E, 0)])+ self.assertEqual(char_vk_down, {"c": 0x43})++ up_plan = plan_key_inputs("c", False, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(up_plan, [(0x43, 0x2E, KEYEVENTF_KEYUP)])+ self.assertEqual(char_vk_down, {})++ def test_win_held_char_uses_vk_path(self):+ mods_down = {"cmd"}+ char_vk_down = {}++ down_plan = plan_key_inputs("e", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(down_plan, [(0x45, 0x12, 0)])+ self.assertEqual(char_vk_down, {"e": 0x45})++ def test_keyup_mirrors_vk_even_if_modifier_released_first(self):+ mods_down = {"ctrl"}+ char_vk_down = {}++ plan_key_inputs("c", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(char_vk_down, {"c": 0x43})++ # Modifier released before the char keyup arrives.+ plan_key_inputs("ctrl", False, mods_down, {}, fake_vk_lookup, fake_scan_lookup)+ self.assertNotIn("ctrl", mods_down)++ up_plan = plan_key_inputs("c", False, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(up_plan, [(0x43, 0x2E, KEYEVENTF_KEYUP)])+ self.assertEqual(char_vk_down, {})++ def test_no_modifier_and_unresolvable_char_uses_unicode_path(self):+ # 'a' has no entry in FAKE_VK_SCAN, standing in for a character this+ # "layout" can't resolve at all -- vk_lookup is still consulted (no+ # longer gated on a chord modifier being held), but comes back -1,+ # so this falls back to Unicode exactly like before.+ mods_down = set()+ char_vk_down = {}++ with self.assertLogs("input_injector", level="WARNING"):+ down_plan = plan_key_inputs("a", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(down_plan, [(0, ord("a"), KEYEVENTF_UNICODE)])++ up_plan = plan_key_inputs("a", False, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(up_plan, [(0, ord("a"), KEYEVENTF_UNICODE | KEYEVENTF_KEYUP)])+ self.assertEqual(char_vk_down, {})++ def test_altgr_char_falls_back_to_unicode(self):+ mods_down = {"ctrl"}+ char_vk_down = {}++ with self.assertLogs("input_injector", level="WARNING"):+ down_plan = plan_key_inputs("@", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)++ self.assertEqual(down_plan, [(0, ord("@"), KEYEVENTF_UNICODE)])+ self.assertEqual(char_vk_down, {})++ def test_unresolvable_char_falls_back_to_unicode(self):+ mods_down = {"alt"}+ char_vk_down = {}++ with self.assertLogs("input_injector", level="WARNING"):+ down_plan = plan_key_inputs("$", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)++ self.assertEqual(down_plan, [(0, ord("$"), KEYEVENTF_UNICODE)])+ self.assertEqual(char_vk_down, {})++ def test_shift_only_vk_scan_result_adds_no_synthetic_shift(self):+ # Ctrl+Shift+C: the chord modifier alone doesn't satisfy a+ # shift-only VkKeyScanW result -- shift must actually be held too+ # (it is here), and when it is, no extra synthetic shift keydown is+ # injected on top of the real VK+scan keystroke.+ mods_down = {"ctrl", "shift"}+ char_vk_down = {}++ down_plan = plan_key_inputs("C", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(down_plan, [(0x43, 0x2E, 0)])+ self.assertEqual(char_vk_down, {"C": 0x43})++ def test_shift_only_result_without_shift_held_falls_back_even_with_a_chord(self):+ # A chord modifier being held is not enough on its own: Ctrl+C+ # where "C" only resolves via a shift bit that isn't actually down+ # (e.g. caps-lock) must not be sent as the plain 'c' VK -- that+ # would silently turn Ctrl+Shift+C into Ctrl+C on Windows.+ mods_down = {"ctrl"}+ char_vk_down = {}++ down_plan = plan_key_inputs("C", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(down_plan, [(0, ord("C"), KEYEVENTF_UNICODE)])+ self.assertEqual(char_vk_down, {})+++class PlanKeyInputsBareCharacterTests(unittest.TestCase):+ """Bug: a bare character (no chord modifier held) used to always go out+ as KEYEVENTF_UNICODE, which delivers text (WM_CHAR-style) but no usable+ keyCode -- apps and web pages listening for a real keydown (e.g.+ YouTube's 'k' to pause) never saw it, even though typing into a text+ field worked fine. The VK path is now preferred for any character the+ layout can resolve, chord or not; Unicode is only the fallback."""++ def setUp(self):+ input_injector._warned_chars.clear()++ def test_bare_character_uses_vk_path_with_scan_code(self):+ mods_down = set()+ char_vk_down = {}+ down_plan = plan_key_inputs("k", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(down_plan, [(0x4B, 0x25, 0)])+ self.assertEqual(char_vk_down, {"k": 0x4B})++ def test_bare_character_keyup_mirrors_the_recorded_vk(self):+ mods_down = set()+ char_vk_down = {}+ plan_key_inputs("k", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ up_plan = plan_key_inputs("k", False, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(up_plan, [(0x4B, 0x25, KEYEVENTF_KEYUP)])+ self.assertEqual(char_vk_down, {})++ def test_shift_required_and_held_uses_vk_path_with_no_synthetic_shift(self):+ mods_down = {"shift"}+ char_vk_down = {}+ down_plan = plan_key_inputs("K", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ # A single tuple only: the Mac is already forwarding shift as its+ # own physical keydown, so nothing synthetic is added here.+ self.assertEqual(down_plan, [(0x4B, 0x25, 0)])+ self.assertEqual(char_vk_down, {"K": 0x4B})++ def test_shift_r_also_satisfies_the_shift_only_requirement(self):+ mods_down = {"shift_r"}+ char_vk_down = {}+ down_plan = plan_key_inputs("K", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(down_plan, [(0x4B, 0x25, 0)])++ def test_shift_required_but_not_held_falls_back_to_unicode(self):+ # Caps-lock case: VkKeyScanW says shift is needed to produce 'K',+ # but no physical shift is currently down. Trusting the VK here+ # would desync from the real keyboard state, so this must stay+ # Unicode -- and silently, since it isn't a broken layout.+ mods_down = set()+ char_vk_down = {}+ down_plan = plan_key_inputs("K", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(down_plan, [(0, ord("K"), KEYEVENTF_UNICODE)])+ self.assertEqual(char_vk_down, {})++ def test_altgr_character_without_any_chord_falls_back_to_unicode(self):+ mods_down = set()+ char_vk_down = {}+ with self.assertLogs("input_injector", level="WARNING"):+ down_plan = plan_key_inputs("@", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(down_plan, [(0, ord("@"), KEYEVENTF_UNICODE)])+ self.assertEqual(char_vk_down, {})++ def test_unresolvable_character_without_any_chord_falls_back_to_unicode(self):+ mods_down = set()+ char_vk_down = {}+ with self.assertLogs("input_injector", level="WARNING"):+ down_plan = plan_key_inputs("$", True, mods_down, char_vk_down, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(down_plan, [(0, ord("$"), KEYEVENTF_UNICODE)])+ self.assertEqual(char_vk_down, {})+++class PlanKeyInputsNamedKeyTests(unittest.TestCase):+ def test_named_keys_use_scan_lookup(self):+ plan = plan_key_inputs("enter", True, set(), {}, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(plan, [(0x0D, 0x1C, 0)])++ def test_extended_keys_carry_extended_flag(self):+ for name, vk in (("up", 0x26), ("ctrl_r", 0xA3), ("cmd", 0x5B)):+ with self.subTest(name=name):+ plan = plan_key_inputs(name, True, set(), {}, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(len(plan), 1)+ _, _, flags = plan[0]+ self.assertTrue(flags & KEYEVENTF_EXTENDEDKEY)++ def test_non_extended_named_key_has_no_extended_flag(self):+ plan = plan_key_inputs("ctrl", True, set(), {}, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(len(plan), 1)+ _, _, flags = plan[0]+ self.assertFalse(flags & KEYEVENTF_EXTENDEDKEY)++ def test_named_modifier_key_updates_mods_down(self):+ mods_down = set()+ plan_key_inputs("ctrl", True, mods_down, {}, fake_vk_lookup, fake_scan_lookup)+ self.assertIn("ctrl", mods_down)+ plan_key_inputs("ctrl", False, mods_down, {}, fake_vk_lookup, fake_scan_lookup)+ self.assertNotIn("ctrl", mods_down)++ def test_unknown_key_name_is_dropped(self):+ plan = plan_key_inputs("not_a_real_key", True, set(), {}, fake_vk_lookup, fake_scan_lookup)+ self.assertEqual(plan, [])+++class PlanScrollUnitsLineModeTests(unittest.TestCase):+ def test_line_mode_scales_by_120_and_never_carries_a_remainder(self):+ accum = [0.0, 0.0]+ self.assertEqual(plan_scroll_units(1, 0, "line", accum), (120, 0))+ self.assertEqual(accum, [0.0, 0.0])+ self.assertEqual(plan_scroll_units(-2, 3, "line", accum), (-240, 360))+ self.assertEqual(accum, [0.0, 0.0])++ def test_line_mode_defaults_to_no_horizontal_movement(self):+ accum = [0.0, 0.0]+ self.assertEqual(plan_scroll_units(1, 0, "line", accum), (120, 0))+++class PlanScrollUnitsPixelModeTests(unittest.TestCase):+ def test_pixel_mode_small_delta_does_not_flush_immediately(self):+ # WHEEL_UNITS_PER_PIXEL is 3.0 by default: 0.1px is 0.3 wheel units,+ # under a whole unit, so a single small delta must not flush yet.+ accum = [0.0, 0.0]+ self.assertEqual(plan_scroll_units(0.1, 0.0, "pixel", accum), (0, 0))+ self.assertAlmostEqual(accum[0], 0.3, places=6)++ def test_pixel_mode_flushes_once_enough_small_deltas_accumulate(self):+ accum = [0.0, 0.0]+ for _ in range(3):+ plan_scroll_units(0.1, 0.0, "pixel", accum)+ # 0.3 units/call * 4 calls = 1.2 -> flush 1, carry 0.2.+ whole_y, whole_x = plan_scroll_units(0.1, 0.0, "pixel", accum)+ self.assertEqual((whole_y, whole_x), (1, 0))+ self.assertAlmostEqual(accum[0], 0.2, places=6)++ def test_pixel_mode_carries_residue_across_multiple_small_deltas(self):+ accum = [0.0, 0.0]+ # 0.4px * 3.0 units/px = 1.2 units per call.+ self.assertEqual(plan_scroll_units(0.4, 0.0, "pixel", accum), (1, 0))+ self.assertAlmostEqual(accum[0], 0.2, places=6)+ # 0.2 + 1.2 = 1.4 -> flush 1, carry 0.4.+ self.assertEqual(plan_scroll_units(0.4, 0.0, "pixel", accum), (1, 0))+ self.assertAlmostEqual(accum[0], 0.4, places=6)++ def test_pixel_mode_tracks_horizontal_axis_independently(self):+ accum = [0.0, 0.0]+ whole_y, whole_x = plan_scroll_units(0.0, 0.4, "pixel", accum)+ self.assertEqual((whole_y, whole_x), (0, 1))+ self.assertAlmostEqual(accum[0], 0.0)+ self.assertAlmostEqual(accum[1], 0.2, places=6)++ def test_pixel_mode_negative_deltas_carry_a_negative_remainder(self):+ accum = [0.0, 0.0]+ whole_y, _ = plan_scroll_units(-0.1, 0.0, "pixel", accum)+ self.assertEqual(whole_y, 0)+ self.assertAlmostEqual(accum[0], -0.1 * WHEEL_UNITS_PER_PIXEL, places=6)+++class InjectScrollDispatchTests(unittest.TestCase):+ """inject_scroll's real _send_input call requires Win32 SendInput, which+ only exists on Windows. These tests fake that boundary (patch+ _send_input) so the dispatch logic -- which flags to use, whether an+ axis with nothing to flush is skipped -- can be verified on any+ platform, matching how plan_key_inputs/inject_key are already split for+ testability.+ """++ def setUp(self):+ # inject_scroll accumulates in module-level state; reset it so tests+ # don't leak residue into each other.+ input_injector._scroll_accum[:] = [0.0, 0.0]++ def test_line_mode_sends_wheel_and_hwheel_with_expected_flags(self):+ with mock.patch.object(input_injector, "_send_input") as fake_send:+ input_injector.inject_scroll(1, -2, "line")+ calls = [call.args[0] for call in fake_send.call_args_list]+ self.assertEqual(len(calls), 2)+ self.assertEqual(calls[0].union.mi.mouseData, 120)+ self.assertEqual(calls[0].union.mi.dwFlags, MOUSEEVENTF_WHEEL)+ self.assertEqual(calls[1].union.mi.mouseData, ctypes.c_ulong(-240).value)+ self.assertEqual(calls[1].union.mi.dwFlags, MOUSEEVENTF_HWHEEL)++ def test_zero_delta_axis_sends_nothing(self):+ with mock.patch.object(input_injector, "_send_input") as fake_send:+ input_injector.inject_scroll(1, 0, "line")+ calls = [call.args[0] for call in fake_send.call_args_list]+ self.assertEqual(len(calls), 1)+ self.assertEqual(calls[0].union.mi.dwFlags, MOUSEEVENTF_WHEEL)++ def test_pixel_mode_small_delta_flushes_nothing_yet(self):+ with mock.patch.object(input_injector, "_send_input") as fake_send:+ input_injector.inject_scroll(0.1, 0.0, "pixel")+ fake_send.assert_not_called()+ self.assertAlmostEqual(input_injector._scroll_accum[0], 0.1 * WHEEL_UNITS_PER_PIXEL, places=6)+++if __name__ == "__main__":+ unittest.main()+++class InjectGestureTests(unittest.TestCase):+ def setUp(self):+ self.pressed = []+ patcher = mock.patch.object(+ input_injector, "inject_key", side_effect=lambda key, down: self.pressed.append((key, down))+ )+ patcher.start()+ self.addCleanup(patcher.stop)++ def test_touchpad_swipe_is_preferred_and_ends_the_gesture(self):+ swipes = []+ input_injector.inject_gesture("swipe_up", swipe=lambda fingers, direction: swipes.append((fingers, direction)) or True)+ self.assertEqual(swipes, [(3, "up")])+ self.assertEqual(self.pressed, [])++ def test_refused_swipe_falls_back_to_the_shortcut_chord(self):+ input_injector.inject_gesture("swipe_left", swipe=lambda fingers, direction: False)+ self.assertEqual(+ self.pressed,+ [("cmd", True), ("ctrl", True), ("right", True), ("right", False), ("ctrl", False), ("cmd", False)],+ )++ def test_spread_and_swipe_down_both_show_the_desktop(self):+ for name in ("spread", "swipe_down"):+ swipes = []+ input_injector.inject_gesture(name, swipe=lambda fingers, direction: swipes.append((fingers, direction)) or True)+ self.assertEqual(swipes, [(3, "down")], name)++ def test_pinch_has_no_touchpad_gesture_and_opens_start(self):+ input_injector.inject_gesture("pinch", swipe=lambda fingers, direction: self.fail("no swipe expected"))+ self.assertEqual(self.pressed, [("cmd", True), ("cmd", False)])++ def test_unknown_gesture_does_nothing(self):+ input_injector.inject_gesture("wiggle", swipe=lambda fingers, direction: self.fail("no swipe expected"))+ self.assertEqual(self.pressed, [])+++class TouchpadContactFramesTests(unittest.TestCase):+ def test_fingers_move_together_by_the_axis_distance_and_stay_on_the_pad(self):+ import touchpad_injector++ frames = touchpad_injector.contact_frames(3, "up")+ self.assertEqual(len(frames), touchpad_injector.SWIPE_STEPS + 1)+ first, last = frames[0], frames[-1]+ for (x0, y0), (x1, y1) in zip(first, last):+ self.assertEqual(x1, x0)+ self.assertEqual(y0 - y1, 3000)+ for frame in frames:+ for x, y in frame:+ self.assertTrue(0 <= x <= touchpad_injector.PAD_WIDTH)+ self.assertTrue(0 <= y <= touchpad_injector.PAD_HEIGHT)++ def test_four_fingers_sideways_keep_their_spacing(self):+ import touchpad_injector++ frames = touchpad_injector.contact_frames(4, "left")+ xs = [x for x, _ in frames[-1]]+ self.assertEqual([b - a for a, b in zip(xs, xs[1:])], [touchpad_injector.FINGER_SPACING] * 3)+++class InjectedMarkTests(unittest.TestCase):+ """Every INPUT carries the mark. The raw-input reader in capture_win+ reads it back out of ulExtraInformation to tell the Mac's pointer from+ the hand; nothing else in Windows does."""++ def test_a_mouse_input_is_stamped(self):+ item = input_injector._mouse_input(5, 0, 0, input_injector.MOUSEEVENTF_MOVE)+ self.assertEqual(item.union.mi.dwExtraInfo, input_injector.INJECTED_MARK)++ def test_a_key_input_is_stamped(self):+ item = input_injector._keybd_input(0x41, 0x1E, 0)+ self.assertEqual(item.union.ki.dwExtraInfo, input_injector.INJECTED_MARK)diff --git a/win_app/tests/test_key_up_after_switch_back.py b/win_app/tests/test_key_up_after_switch_back.pynew file mode 100644index 0000000..bd6f9e7--- /dev/null+++ b/win_app/tests/test_key_up_after_switch_back.py@@ -0,0 +1,105 @@+"""Reproduces win-sender-3: a key held down while redirecting, released after+switching back to Windows, never reaches the Mac as a key-up -- because+on_key's gate reads the live `redirecting` flag rather than whether the+key-down was actually forwarded."""++import time+import unittest++import protocol+import sender+from fakes import FakeClipboard, FakeDesktop+from return_edge import Rect++MONITORS = [Rect(0, 0, 1920, 1080)]+++def make_config(**overrides):+ from app_config import Config++ values = dict(+ host="127.0.0.1",+ port=0,+ auth_token="shared-token",+ mac_host="127.0.0.1",+ mac_return_edge="left",+ mac_resistance_px=40,+ crossing_resistance_px=40,+ )+ values.update(overrides)+ return Config(**values)+++class KeyUpAfterSwitchBackTest(unittest.TestCase):+ def setUp(self):+ self.desktop = FakeDesktop(MONITORS, cursor=(0, 500))+ self.sender = sender.MacSender(desktop=self.desktop, clipboard=FakeClipboard(), is_local=lambda host: False)+ self.sender.update_config(make_config())+ self.sender._sock = object()+ self.sender._connected_at = time.monotonic()+ self.sender._last_ack_at = time.monotonic()++ def tearDown(self):+ self.sender._sock = None++ def _drain_keys(self):+ keys = []+ while not self.sender._outbound.empty():+ message = self.sender._outbound.get_nowait()+ if message.get("type") in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP):+ keys.append(message)+ return keys++ def test_key_released_after_switch_back_is_dropped(self):+ self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)++ sent_down = self.sender.on_key("a", True)+ self.assertTrue(sent_down, "the key-down while redirecting should have been forwarded")++ self.sender.set_redirecting(False)++ sent_up = self.sender.on_key("a", False)++ keys = self._drain_keys()+ self.assertEqual(+ [k["type"] for k in keys],+ [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP],+ "a key-down forwarded to the Mac owes it the matching key-up, "+ "even after redirecting has already been switched back off",+ )+ self.assertTrue(+ sent_up,+ "on_key must swallow the key-up locally, since Windows never saw the key go down",+ )++ def test_a_held_keys_autorepeat_at_home_is_swallowed_until_its_release(self):+ self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)+ self.sender.on_key("a", True)+ self.sender.set_redirecting(False)+ self.assertTrue(self.sender.on_key("a", True), "an autorepeat of a key the Mac holds")+ self.assertTrue(self.sender.on_key("a", False), "the release Windows never saw the down for")+ self.assertFalse(self.sender.on_key("a", True), "a fresh press is Windows' own again")++ def test_a_release_still_queued_when_input_comes_home_is_sent(self):+ sent = []+ self.sender._send_raw = lambda message: sent.append(message) or True++ def drain():+ while not self.sender._outbound.empty():+ self.sender._process_outbound(self.sender._outbound.get_nowait())++ self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)+ self.sender.on_key("a", True)+ drain()+ # The release is queued but not yet sent when input comes home.+ self.sender.on_key("a", False)+ self.sender.set_redirecting(False)+ drain()+ self.assertEqual(+ [m["type"] for m in sent if m["type"] in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP)],+ [protocol.MSG_KEYDOWN, protocol.MSG_KEYUP],+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_pages_win.py b/win_app/tests/test_pages_win.pynew file mode 100644index 0000000..1322268--- /dev/null+++ b/win_app/tests/test_pages_win.py@@ -0,0 +1,40 @@+import unittest++import pages_win+++class PagesWinTest(unittest.TestCase):+ def test_keys_match_pages_in_order(self):+ self.assertEqual(pages_win.KEYS, tuple(page[0] for page in pages_win.PAGES))++ def test_every_page_has_a_name_and_purpose(self):+ for key, name, purpose in pages_win.PAGES:+ self.assertTrue(name)+ self.assertTrue(purpose)+ self.assertEqual(key, key.lower())++ def test_no_dots_when_all_clear(self):+ self.assertEqual(pages_win.dots(False, None), {})++ def test_no_dot_for_the_healthy_firewall_tone(self):+ # "note" is Firewall's own healthy end-state -- its button just offers a manual+ # re-check, so it must not earn a dot the way an amber or fault tone does.+ self.assertEqual(pages_win.dots(False, "note"), {})++ def test_config_error_marks_connection(self):+ self.assertEqual(pages_win.dots(True, None), {"connection": "fault"})++ def test_firewall_amber_marks_firewall(self):+ self.assertEqual(pages_win.dots(False, "note-amber"), {"firewall": "amber"})++ def test_firewall_fault_marks_firewall(self):+ self.assertEqual(pages_win.dots(False, "note-fault"), {"firewall": "fault"})++ def test_both_problems_mark_both_pages(self):+ self.assertEqual(+ pages_win.dots(True, "note-amber"), {"connection": "fault", "firewall": "amber"}+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_pairing.py b/win_app/tests/test_pairing.pynew file mode 100644index 0000000..0321263--- /dev/null+++ b/win_app/tests/test_pairing.py@@ -0,0 +1,143 @@+import json+import unittest++import pairing+from pairing import PairingClient, PairingHost, beacon_msg, decode, encode+++class FakeClock:+ def __init__(self, value=1000.0):+ self.value = value++ def __call__(self):+ return self.value++ def advance(self, seconds):+ self.value += seconds+++def exchange(host, code, pair_id=None):+ client = PairingClient(pair_id or host.pair_id, code, "Test Mac")+ request = client.request()+ return client, request, host.handle(request)+++class BeaconTests(unittest.TestCase):+ def test_beacon_carries_only_name_port_and_pairing_id(self):+ host = PairingHost(FakeClock())+ code = host.begin()+ raw = encode(beacon_msg("TEST-PC", 51820, host.pair_id))+ message = json.loads(raw)+ self.assertEqual(set(message), {"beamy", "type", "name", "port", "pair"})+ self.assertEqual(message["pair"], host.pair_id)+ self.assertNotIn(code.encode(), raw)+ self.assertEqual(decode(raw), message)++ def test_beacon_without_a_code_has_no_pairing_id(self):+ self.assertNotIn("pair", beacon_msg("TEST-PC", 51820, None))++ def test_decode_ignores_foreign_datagrams(self):+ self.assertIsNone(decode(b"\xff\x00not json"))+ self.assertIsNone(decode(b'{"beamy": 99, "type": "beacon"}'))+ self.assertIsNone(decode(b"[]"))+ self.assertIsNone(decode(b"x" * (pairing.MAX_DATAGRAM_BYTES + 1)))+++class PairingHostTests(unittest.TestCase):+ def setUp(self):+ self.clock = FakeClock()+ self.host = PairingHost(self.clock)++ def test_right_code_agrees_one_token_on_both_sides_without_sending_it(self):+ code = self.host.begin()+ client, request, reply = exchange(self.host, code)+ self.assertTrue(reply["ok"])+ token = client.accept(reply)+ self.assertEqual(self.host.paired[0], token)+ self.assertEqual(self.host.paired[1], "Test Mac")+ self.assertGreaterEqual(len(token), 40)+ wire = encode(request) + encode(reply)+ self.assertNotIn(token.encode(), wire)+ self.assertNotIn(code.encode(), wire)+ self.assertFalse(self.host.active)++ def test_wrong_code_is_refused_and_burns_the_code(self):+ code = self.host.begin()+ wrong = str((int(code) + 1) % 10**6).zfill(6)+ client, _request, reply = exchange(self.host, wrong)+ self.assertEqual(reply, {"type": "pair_reply", "pair": client.pair_id, "ok": False, "error": "refused"})+ with self.assertRaises(pairing.PairingError):+ client.accept(reply)+ self.assertIsNone(self.host.paired)+ self.assertFalse(self.host.active)+ # The right code, one second later, is no longer accepted either.+ _client, _request, retry = exchange(self.host, code, client.pair_id)+ self.assertFalse(retry["ok"])+ self.assertEqual(retry["error"], "not_pairing")++ def test_expired_code_is_refused(self):+ code = self.host.begin()+ pair_id = self.host.pair_id+ self.clock.advance(pairing.CODE_LIFETIME_SECONDS)+ _client, _request, reply = exchange(self.host, code, pair_id)+ self.assertFalse(reply["ok"])+ self.assertEqual(reply["error"], "not_pairing")+ self.assertIsNone(self.host.paired)++ def test_unknown_pairing_id_does_not_burn_the_code(self):+ code = self.host.begin()+ _client, _request, reply = exchange(self.host, code, "deadbeef")+ self.assertEqual(reply["error"], "not_pairing")+ self.assertTrue(self.host.active)+ _client, _request, reply = exchange(self.host, code)+ self.assertTrue(reply["ok"])++ def test_retransmitted_request_gets_the_same_reply(self):+ code = self.host.begin()+ client, request, reply = exchange(self.host, code)+ self.assertEqual(self.host.handle(request), reply)+ self.assertEqual(client.accept(reply), client.accept(self.host.handle(request)))++ def test_malformed_request_burns_the_code(self):+ self.host.begin()+ reply = self.host.handle({"type": "pair_request", "pair": self.host.pair_id, "pub": "!!", "proof": "??"})+ self.assertEqual(reply["error"], "refused")+ self.assertFalse(self.host.active)++ def test_seconds_left_counts_down_to_zero(self):+ self.host.begin()+ self.assertEqual(self.host.seconds_left, int(pairing.CODE_LIFETIME_SECONDS))+ self.clock.advance(10)+ self.assertEqual(self.host.seconds_left, int(pairing.CODE_LIFETIME_SECONDS) - 10)+ self.clock.advance(100)+ self.assertEqual(self.host.seconds_left, 0)+ self.assertIsNone(self.host.code)+++class PairingClientTests(unittest.TestCase):+ def test_pc_that_does_not_know_the_code_is_rejected(self):+ host = PairingHost(FakeClock())+ code = host.begin()+ client = PairingClient(host.pair_id, code, "Test Mac")+ client.request()+ # A different host, holding a different code, answers in the real one's place.+ impostor = PairingHost(FakeClock())+ impostor.begin()+ impostor.pair_id = host.pair_id+ reply = impostor.handle(client.request())+ self.assertFalse(reply["ok"])+ with self.assertRaises(pairing.PairingError):+ client.accept(reply)++ def test_tampered_reply_is_rejected(self):+ host = PairingHost(FakeClock())+ code = host.begin()+ client, _request, reply = exchange(host, code)+ other = pairing.X25519PrivateKey.generate()+ reply["pub"] = pairing._b64(pairing._public_bytes(other))+ with self.assertRaises(pairing.PairingError):+ client.accept(reply)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_receiver.py b/win_app/tests/test_receiver.pynew file mode 100644index 0000000..80c39f1--- /dev/null+++ b/win_app/tests/test_receiver.py@@ -0,0 +1,985 @@+import socket+import threading+import time+import unittest+from unittest import mock++import input_injector+import protocol+import receiver+from app_config import Config+from receiver import ReceiverServer, ServerState, handle_message++from return_edge import Rect+from fakes import FakeClipboard, FakeDesktop, FakeInjector, connected_socket_pair, wait_for_calls, wait_for_status+++FAKE_PNG = protocol.PNG_SIGNATURE + b"\x00" * 64+++def make_config(port=0, token="shared-token"):+ return Config(host="127.0.0.1", port=port, auth_token=token)+++class ReceiverHandshakeTests(unittest.TestCase):+ def _serve(self, client_token="shared-token"):+ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))+ client, connection, address = connected_socket_pair(token=client_token)+ stop_event = threading.Event()+ # _session_thread, not _handle_client: it closes the socket when the+ # handler returns, which is what a rejected client actually sees.+ thread = threading.Thread(+ target=server._session_thread,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ self.addCleanup(connection.close)+ self.addCleanup(thread.join, 1)+ self.addCleanup(stop_event.set)+ self.addCleanup(client.close)+ return statuses, client, thread++ def test_hello_receives_welcome_and_reports_connected(self):+ statuses, client, thread = self._serve()+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ # The welcome is sent before the status callback fires on the+ # session thread, so poll rather than assert immediately.+ _, detail = wait_for_status(statuses, ServerState.CONNECTED)+ self.assertEqual(detail, "Connected to 127.0.0.1")++ def test_wrong_token_is_closed_without_a_reply(self):+ statuses, client, thread = self._serve(client_token="not-the-token")+ client.send(protocol.hello_msg())+ client.settimeout(2.0)+ with self.assertRaises(protocol.ConnectionClosed):+ client.recv()+ thread.join(timeout=1)+ self.assertFalse(thread.is_alive())+ self.assertNotIn(ServerState.CONNECTED, [state for state, _ in statuses])++ def test_replayed_frame_drops_the_connection(self):+ statuses, client, thread = self._serve()+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ frame = client.session.seal(protocol.ping_msg())+ client.sock.sendall(frame)+ client.sock.sendall(frame)+ client.settimeout(2.0)+ with self.assertRaises(protocol.ConnectionClosed):+ while True:+ client.recv()+ thread.join(timeout=1)+ self.assertFalse(thread.is_alive())++ def test_hello_without_version_is_rejected_with_welcome_error(self):+ statuses, client, thread = self._serve()+ client.send({"type": protocol.MSG_HELLO, "data": {}})+ reply = client.recv()+ self.assertEqual(reply["type"], protocol.MSG_WELCOME)+ self.assertEqual(reply["data"].get("error"), "version_mismatch")+ thread.join(timeout=1)+ self.assertFalse(thread.is_alive())+ self.assertNotIn(ServerState.CONNECTED, [state for state, _ in statuses])+ self.assertIn(+ (ServerState.ERROR, "Mac app is an older Beamer version — update both apps"),+ statuses,+ )++ def test_unsupported_version_is_rejected_with_welcome_error(self):+ statuses, client, thread = self._serve()+ client.send({"type": protocol.MSG_HELLO, "data": {"version": 1}})+ self.assertEqual(client.recv(), protocol.welcome_msg(error="version_mismatch"))+ self.assertNotIn(ServerState.CONNECTED, [state for state, _ in statuses])++ def test_pre_v4_client_gets_a_cleartext_version_mismatch(self):+ # A v3 Mac opens with a length-prefixed cleartext hello, no preamble.+ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))+ listener = socket.socket()+ listener.bind(("127.0.0.1", 0))+ listener.listen(1)+ raw = socket.create_connection(listener.getsockname())+ connection, address = listener.accept()+ listener.close()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ raw.sendall(protocol.legacy_frame({"type": protocol.MSG_HELLO, "data": {"token": "shared-token", "version": 3}}))+ raw.settimeout(2.0)+ expected = protocol.legacy_frame(protocol.welcome_msg(error="version_mismatch"))+ got = b""+ while len(got) < len(expected):+ chunk = raw.recv(4096)+ if not chunk:+ break+ got += chunk+ self.assertEqual(got, expected)+ thread.join(timeout=1)+ self.assertFalse(thread.is_alive())+ self.assertIn(+ (ServerState.ERROR, "Mac app is an older Beamer version — update both apps"),+ statuses,+ )+ finally:+ raw.close()+ stop_event.set()+ thread.join(timeout=1)+ connection.close()++ def test_other_wire_version_is_answered_with_our_preamble_and_closed(self):+ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))+ listener = socket.socket()+ listener.bind(("127.0.0.1", 0))+ listener.listen(1)+ raw = socket.create_connection(listener.getsockname())+ connection, address = listener.accept()+ listener.close()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._session_thread,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ raw.sendall(protocol.WIRE_MAGIC + bytes([protocol.PROTOCOL_VERSION + 1]) + b"\x01" * protocol.NONCE_PREFIX_SIZE)+ raw.settimeout(2.0)+ got = raw.recv(protocol.PREAMBLE_SIZE)+ self.assertEqual(got[: len(protocol.WIRE_MAGIC) + 1], protocol.WIRE_MAGIC + bytes([protocol.PROTOCOL_VERSION]))+ self.assertEqual(raw.recv(4096), b"")+ thread.join(timeout=1)+ self.assertFalse(thread.is_alive())+ self.assertIn(+ (ServerState.ERROR, f"Mac app is Beamer protocol v{protocol.PROTOCOL_VERSION + 1}, this PC is v{protocol.PROTOCOL_VERSION} — update both apps"),+ statuses,+ )+ finally:+ raw.close()+ stop_event.set()+ thread.join(timeout=1)+ connection.close()+++class ReceiverPreemptionTests(unittest.TestCase):+ # This test used to shorten SESSION_READ_TIMEOUT_SECONDS to 0.3s for the+ # whole test, on the theory that a short read timeout is the+ # deterministic backstop bounding how long a preempted session can take+ # to notice it was superseded. Two separate timing problems made that+ # ~1-in-8 flaky, both now fixed below:+ #+ # 1. That backstop starts counting down from the moment A authenticates,+ # independent of anything B does. On a slow/loaded run, A's *own*+ # silence could trip the shortened timeout before B ever finished+ # connecting, making the server legitimately (but spuriously, for this+ # test's purposes) report WAITING before the handover even started.+ # Fixed by resetting A's idle clock at a point the test controls,+ # immediately before connecting B: a `ping` is a real message, so+ # receiving it makes thread_a's blocked recv() return and loop back+ # into a fresh recv() call with a fresh timeout window, decoupling the+ # deadline from whatever setup work (A's own authentication,+ # wait_for_status, ...) came before it.+ #+ # 2. Closing a socket from a different thread than the one blocked in+ # recv() on it doesn't reliably interrupt that recv() on macOS --+ # confirmed empirically (a throwaway probe: ~20-40% of trials left the+ # blocked thread stuck until its full configured read timeout+ # elapsed, unmoved by another thread's shutdown()+close() of the same+ # fd). So thread_a's own recv() may not notice the server's+ # preemption-driven close of connection_a promptly, and nothing the+ # test can do from the client side afterwards wakes a recv() already+ # blocked on an fd the server has *already fully closed* -- there is+ # no live socket left to deliver anything to. thread_a's own+ # (shortened) read timeout is the only way it reliably exits in that+ # unlucky case, which means the test's own wait for thread_a to join+ # can itself take up to that same short timeout. B's *own* idle+ # detection must not have a chance to fire for real during that wait+ # -- it would legitimately (B really has gone quiet) but spuriously+ # (for this test) report WAITING too. Fixed by giving B, once+ # connected, a read timeout far larger than anything this test could+ # take: B's own liveness detection isn't what's under test here, only+ # that its status doesn't flap while A is being torn down.+ _READ_TIMEOUT_SECONDS = 0.4+ _B_READ_TIMEOUT_SECONDS = 30.0++ def test_new_authenticated_client_preempts_the_previous_one_without_flapping_status(self):+ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))+ config = make_config()+ stop_event = threading.Event()++ with mock.patch.object(receiver, "SESSION_READ_TIMEOUT_SECONDS", self._READ_TIMEOUT_SECONDS):+ client_a, connection_a, address_a = connected_socket_pair()+ thread_a = threading.Thread(+ target=server._handle_client,+ args=(connection_a, address_a, config, stop_event),+ )+ thread_a.start()+ client_a.send(protocol.hello_msg())+ self.assertEqual(client_a.recv(), protocol.welcome_msg())+ wait_for_status(statuses, ServerState.CONNECTED)++ client_b = connection_b = thread_b = None+ try:+ # Reset A's idle clock right here, at a moment the test controls,+ # so its (still short, unpatched-again-below) read timeout races+ # only the setup immediately following (fast, local, and+ # bounded) rather than everything before it.+ with mock.patch.object(receiver, "SESSION_READ_TIMEOUT_SECONDS", self._READ_TIMEOUT_SECONDS):+ client_a.send(protocol.ping_msg())++ # B gets a generously long read timeout (see the class docstring)+ # so its own idle detection can't fire for real while the test+ # waits out thread_a's worst case below. Kept in effect for the+ # rest of the test, since thread_b reads this constant once, the+ # first time it calls connection.settimeout(...).+ with mock.patch.object(receiver, "SESSION_READ_TIMEOUT_SECONDS", self._B_READ_TIMEOUT_SECONDS):+ client_b, connection_b, address_b = connected_socket_pair()+ thread_b = threading.Thread(+ target=server._handle_client,+ args=(connection_b, address_b, config, stop_event),+ )+ thread_b.start()+ client_b.send(protocol.hello_msg())+ self.assertEqual(client_b.recv(), protocol.welcome_msg())++ # A must be severed once B takes over. This is a real,+ # server-initiated shutdown()+close() of connection_a, which+ # reliably delivers a FIN to client_a's end of an actual TCP+ # connection -- unlike interrupting thread_a's own blocked+ # recv() from another thread (see the class docstring above),+ # a peer-visible EOF over an actual socket is a genuine+ # incoming network event, not a same-process fd-close+ # notification, so it isn't subject to that race.+ client_a.settimeout(2.0)+ self.assertEqual(client_a.sock.recv(4096), b"")++ # thread_a must actually exit. Sized with headroom over the+ # patched read timeout: the common case is a prompt close,+ # but the worst case is thread_a's own recv() falling back to+ # the (freshly-reset, still short) timeout above.+ thread_a.join(timeout=self._READ_TIMEOUT_SECONDS + 2.0)+ self.assertFalse(thread_a.is_alive())++ # ...and B must be reported CONNECTED without status ever+ # having dropped to WAITING in between (a stale session must+ # not be able to flap the UI while a reconnect takes over).+ wait_for_status(statuses, ServerState.CONNECTED)+ self.assertNotIn(ServerState.WAITING, [state for state, _ in statuses])+ finally:+ # Close the test's own client sockets first: that's a real+ # network-level close, so the peer's blocked recv() unblocks+ # promptly. Only close the server-side sockets afterwards,+ # once their handler threads have already joined -- closing+ # them earlier would race the same thread that's blocked in+ # recv() on them.+ client_a.close()+ if client_b is not None:+ client_b.close()+ stop_event.set()+ thread_a.join(timeout=1.0)+ if thread_b is not None:+ thread_b.join(timeout=1.0)+ connection_a.close()+ if connection_b is not None:+ connection_b.close()+++class ReceiverReadTimeoutTests(unittest.TestCase):+ def test_silent_authenticated_client_is_declared_dead_after_the_read_timeout(self):+ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ with mock.patch.object(receiver, "SESSION_READ_TIMEOUT_SECONDS", 0.2):+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ wait_for_status(statuses, ServerState.CONNECTED)+ # Say nothing further. A dead/half-open peer must be detected+ # from the (now short) read timeout alone -- no TCP-level+ # close required.+ wait_for_status(statuses, ServerState.WAITING, timeout=2.0)+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()+ self.assertFalse(thread.is_alive())+++class ReceiverPingTests(unittest.TestCase):+ def test_ping_is_never_recorded_or_specially_acked(self):+ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ client.send(protocol.ping_msg())+ client.send(protocol.ping_msg())+ # A ping never bumps the processed sequence, so every ack the+ # client observes afterwards -- whether the periodic heartbeat or+ # one for a genuine event -- must still read seq 0.+ client.settimeout(1.0)+ self.assertEqual(client.recv(), protocol.ack_msg(0))+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()+++class HandleMessageInjectorTests(unittest.TestCase):+ def test_keydown_is_routed_to_the_injector(self):+ injector = FakeInjector()+ processed = handle_message(+ {"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}}, injector=injector+ )+ self.assertTrue(processed)+ self.assertEqual(injector.calls, [("key", ("a", True))])++ def test_gesture_is_routed_to_the_injector_by_name(self):+ injector = FakeInjector()+ processed = handle_message(protocol.gesture_msg("swipe_up"), injector=injector)+ self.assertTrue(processed)+ self.assertEqual(injector.calls, [("gesture", ("swipe_up",))])++ def test_unknown_type_is_ignored(self):+ injector = FakeInjector()+ processed = handle_message({"type": "bogus", "data": {}}, injector=injector)+ self.assertFalse(processed)+ self.assertEqual(injector.calls, [])++ def test_scroll_passes_dx_and_mode_through_to_the_injector(self):+ injector = FakeInjector()+ processed = handle_message(+ {"type": protocol.MSG_SCROLL, "data": {"dy": 12.5, "dx": -3.25, "mode": "pixel"}},+ injector=injector,+ )+ self.assertTrue(processed)+ self.assertEqual(injector.calls, [("scroll", (12.5, -3.25, "pixel"))])++ def test_scroll_defaults_dx_and_mode_when_omitted(self):+ # Backward tolerance: an older sender (or a plain line-mode wheel+ # click) may omit dx/mode entirely.+ injector = FakeInjector()+ processed = handle_message(+ {"type": protocol.MSG_SCROLL, "data": {"dy": 1}}, injector=injector+ )+ self.assertTrue(processed)+ self.assertEqual(injector.calls, [("scroll", (1, 0, "line"))])+++class ReceiverAckTests(unittest.TestCase):+ def test_a_burst_of_events_is_acked_once_promptly(self):+ # Input is acked as soon as it lands, batched by ACK_COALESCE_SECONDS:+ # a per-event ACK would roughly double packet count at ~100Hz mouse+ # rates, but the old fixed 400ms timer put up to 400ms of pure waiting+ # into the round trip the Mac measures and reports.+ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(+ receiver, "ACK_COALESCE_SECONDS", 0.2+ ), mock.patch.object(input_injector, "inject_mouse_move"):+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ for _ in range(3):+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 1, "dy": 1}}+ )+ # Well inside the parked idle heartbeat, so an ACK arriving at+ # all proves the burst itself woke the thread.+ client.settimeout(1.0)+ ack = client.recv()+ self.assertEqual(ack["type"], protocol.MSG_ACK)+ # seq 3 in the FIRST ACK is the coalescing: all three events+ # were covered by one reply rather than one ACK each. Asserting+ # on a second ACK not arriving would be a test of thread+ # scheduling, so it is deliberately not asserted here.+ self.assertEqual(ack["data"]["seq"], 3)+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()++ def test_an_idle_link_still_gets_a_heartbeat_ack(self):+ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 0.05):+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ client.settimeout(1.0)+ ack = client.recv()+ self.assertEqual(ack["type"], protocol.MSG_ACK)+ self.assertEqual(ack["data"]["seq"], 0)+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()+++class ReceiverClipboardTests(unittest.TestCase):+ def test_focus_mac_replies_with_the_local_clipboard_text(self):+ statuses = []+ clipboard = FakeClipboard(text="hello from windows")+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ client.send(protocol.focus_msg("mac"))+ client.settimeout(1.0)+ self.assertEqual(client.recv(), protocol.clipboard_msg("hello from windows"))+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()++ def test_focus_windows_is_a_reserved_noop(self):+ statuses = []+ clipboard = FakeClipboard(text="must not be sent")+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0):+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ client.send(protocol.focus_msg("windows"))+ client.settimeout(0.3)+ with self.assertRaises((socket.timeout, TimeoutError)):+ client.recv()+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()++ def test_focus_mac_with_empty_clipboard_sends_no_reply(self):+ statuses = []+ clipboard = FakeClipboard(text="")+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0):+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ client.send(protocol.focus_msg("mac"))+ client.settimeout(0.3)+ with self.assertRaises((socket.timeout, TimeoutError)):+ client.recv()+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()++ def test_focus_mac_with_oversized_clipboard_sends_no_reply(self):+ statuses = []+ clipboard = FakeClipboard(text="z" * (protocol.CLIPBOARD_MAX_BYTES + 1))+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0):+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ client.send(protocol.focus_msg("mac"))+ client.settimeout(0.3)+ with self.assertRaises((socket.timeout, TimeoutError)):+ client.recv()+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()++ def test_inbound_clipboard_sets_the_windows_clipboard(self):+ statuses = []+ clipboard = FakeClipboard()+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ client.send(protocol.clipboard_msg("copied on the Mac"))+ wait_for_calls(clipboard.set_calls, minimum=1)+ self.assertEqual(clipboard.set_calls, [("copied on the Mac", None)])+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()++ def test_inbound_clipboard_ignores_oversized_payload(self):+ statuses = []+ clipboard = FakeClipboard()+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ oversized = "y" * (protocol.CLIPBOARD_MAX_BYTES + 1)+ client.send(protocol.clipboard_msg(oversized))+ # Follow up with a normal clipboard message and wait for that one+ # instead of sleeping blind: if the oversized one had been+ # applied, set_calls would already be non-empty by this point.+ client.send(protocol.clipboard_msg("ok"))+ wait_for_calls(clipboard.set_calls, minimum=1)+ self.assertEqual(clipboard.set_calls, [("ok", None)])+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()++ def test_focus_mac_replies_with_text_and_image(self):+ statuses = []+ clipboard = FakeClipboard(text="shot.png", image=FAKE_PNG)+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ client.send(protocol.focus_msg("mac"))+ client.settimeout(1.0)+ self.assertEqual(client.recv(), protocol.clipboard_msg("shot.png", FAKE_PNG))+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()++ def test_focus_mac_drops_an_oversized_image_but_sends_the_text(self):+ statuses = []+ big = protocol.PNG_SIGNATURE + b"\x00" * protocol.CLIPBOARD_IMAGE_MAX_BYTES+ clipboard = FakeClipboard(text="shot.png", image=big)+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ client.send(protocol.focus_msg("mac"))+ client.settimeout(1.0)+ self.assertEqual(client.recv(), protocol.clipboard_msg("shot.png"))+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()++ def test_inbound_clipboard_sets_text_and_image_and_ignores_a_malformed_image(self):+ statuses = []+ clipboard = FakeClipboard()+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ client.send({"type": protocol.MSG_CLIPBOARD, "data": {"text": "bad", "image": "not base64!", "image_format": "png"}})+ client.send(protocol.clipboard_msg("shot.png", FAKE_PNG))+ wait_for_calls(clipboard.set_calls, minimum=2)+ self.assertEqual(clipboard.set_calls, [("bad", None), ("shot.png", FAKE_PNG)])+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()++ def test_focus_and_clipboard_do_not_bump_the_processed_sequence(self):+ # Mirrors ReceiverPingTests.test_ping_is_never_recorded_or_specially_acked:+ # control messages must not be recorded, and must not trigger their+ # own immediate ack -- only the periodic ack timer's seq 0 shows up.+ statuses = []+ clipboard = FakeClipboard(text="")+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), clipboard=clipboard)+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ try:+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ client.send(protocol.focus_msg("windows"))+ client.send(protocol.clipboard_msg("from the mac"))+ client.settimeout(1.0)+ self.assertEqual(client.recv(), protocol.ack_msg(0))+ finally:+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()+++class ReceiverCrossingTests(unittest.TestCase):+ """The way home, end to end on the wire: a focus that names the return+ edge arms it and places the pointer; pushing through it sends switch."""++ MONITORS = [Rect(0, 0, 2560, 1440), Rect(-1920, 200, 1920, 1080)]++ def _session(self, desktop, pressures=None):+ statuses = []+ server = ReceiverServer(+ lambda state, detail: statuses.append((state, detail)),+ clipboard=FakeClipboard(text=""),+ desktop=desktop,+ pressure_callback=None if pressures is None else (lambda *args: pressures.append(args)),+ )+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ return server, client, connection, stop_event, thread++ @staticmethod+ def _teardown(client, connection, stop_event, thread):+ client.close()+ stop_event.set()+ thread.join(timeout=1.0)+ connection.close()++ @staticmethod+ def _focus_windows(**extra):+ return {"type": protocol.MSG_FOCUS, "data": {"target": "windows", **extra}}++ def test_arrival_places_the_pointer_and_arms_the_return_edge(self):+ desktop = FakeDesktop(self.MONITORS, cursor=(500, 500))+ server, client, connection, stop_event, thread = self._session(desktop)+ try:+ client.send(self._focus_windows(edge="left", offset=0.5, return_edge="left", resistance_px=100))+ wait_for_calls(desktop.set_calls, minimum=1)+ self.assertEqual(desktop.set_calls, [(-1920, 720)])+ self.assertEqual(server.return_edge, "left")+ finally:+ self._teardown(client, connection, stop_event, thread)++ def test_shortcut_switch_arms_without_moving_the_pointer(self):+ desktop = FakeDesktop(self.MONITORS, cursor=(500, 500))+ server, client, connection, stop_event, thread = self._session(desktop)+ try:+ client.send(self._focus_windows(return_edge="top", resistance_px=120))+ client.send(protocol.ping_msg())+ client.settimeout(1.0)+ self.assertEqual(client.recv(), protocol.ack_msg(0))+ self.assertEqual(desktop.set_calls, [])+ self.assertEqual(server.return_edge, "top")+ finally:+ self._teardown(client, connection, stop_event, thread)++ def test_pushing_through_the_return_edge_sends_switch_to_the_mac(self):+ desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 720))+ pressures = []+ with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(+ input_injector, "inject_mouse_move"+ ) as inject:+ server, client, connection, stop_event, thread = self._session(desktop, pressures)+ try:+ client.send(self._focus_windows(return_edge="left", resistance_px=100))+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 3}})+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})+ client.settimeout(1.0)+ self.assertEqual(client.recv(), protocol.switch_msg("mac", "right", 723 / 1440))+ # Held at the edge first (clamped, lateral movement kept), then+ # crossed; neither move reached SendInput.+ self.assertEqual(desktop.set_calls, [(-1920, 723)])+ inject.assert_not_called()+ # The receiver sends the switch before it reports the breakthrough pressure, so+ # the second entry can land after recv() returns: 2 in 15 runs failed on the rig.+ wait_for_calls(pressures, minimum=2)+ self.assertEqual([edge for edge, _, _ in pressures], ["left", "left"])+ self.assertAlmostEqual(pressures[0][1], 0.6)+ self.assertEqual(pressures[1][1:], (1.0, True))+ # Disarmed after the crossing: the next move injects normally.+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})+ wait_for_calls(inject.call_args_list, minimum=1)+ inject.assert_called_once_with(-60, 0)+ finally:+ self._teardown(client, connection, stop_event, thread)++ def test_moves_inject_normally_when_no_return_edge_is_armed(self):+ desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 720))+ with mock.patch.object(input_injector, "inject_mouse_move") as inject:+ server, client, connection, stop_event, thread = self._session(desktop)+ try:+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})+ wait_for_calls(inject.call_args_list, minimum=1)+ self.assertEqual(desktop.set_calls, [])+ finally:+ self._teardown(client, connection, stop_event, thread)+++class ReceiverHandBackTests(unittest.TestCase):+ """The peer's input is here and the link that brought it ends. The peer+ fails open on its own side, but the focus saying so dies with the socket,+ so the receiver raises it: otherwise the owner keeps treating the peer as+ driving and its own edge and shortcut stay dead."""++ def _session(self, focuses):+ server = ReceiverServer(+ lambda state, detail: None,+ clipboard=FakeClipboard(text=""),+ desktop=FakeDesktop([Rect(0, 0, 1920, 1080)], cursor=(500, 500)),+ focus_callback=focuses.append,+ )+ client, connection, address = connected_socket_pair()+ stop_event = threading.Event()+ thread = threading.Thread(+ target=server._handle_client,+ args=(connection, address, make_config(), stop_event),+ )+ thread.start()+ client.send(protocol.hello_msg())+ self.assertEqual(client.recv(), protocol.welcome_msg())+ return server, client, connection, thread++ @staticmethod+ def _focus(target, **extra):+ return {"type": protocol.MSG_FOCUS, "data": {"target": target, **extra}}++ def test_a_peer_that_drops_while_driving_hands_input_back(self):+ focuses = []+ server, client, connection, thread = self._session(focuses)+ try:+ client.send(self._focus("windows", return_edge="left", resistance_px=100))+ wait_for_calls(focuses, minimum=1)+ self.assertEqual(server.return_edge, "left")+ client.close()+ thread.join(timeout=2.0)+ self.assertEqual(focuses, ["windows", "mac"])+ self.assertIsNone(server.return_edge)+ finally:+ connection.close()++ def test_send_home_while_driving_sends_the_peer_its_input(self):+ # The escape that does not depend on the return edge: 23-09-2026, the+ # PC's mouse stayed on the Mac after a push through the edge never fired.+ focuses = []+ server, client, connection, thread = self._session(focuses)+ try:+ client.send(self._focus("windows", return_edge="left", resistance_px=100))+ wait_for_calls(focuses, minimum=1)+ self.assertTrue(server.send_home())+ client.settimeout(1.0)+ self.assertEqual(client.recv(), protocol.switch_msg("mac"))+ self.assertIsNone(server.return_edge)+ finally:+ client.close()+ thread.join(timeout=2.0)+ connection.close()++ def test_send_home_with_input_already_home_does_nothing(self):+ focuses = []+ server, client, connection, thread = self._session(focuses)+ try:+ self.assertFalse(server.send_home())+ finally:+ client.close()+ thread.join(timeout=2.0)+ connection.close()++ def test_a_peer_that_drops_with_input_at_home_says_nothing_more(self):+ focuses = []+ server, client, connection, thread = self._session(focuses)+ try:+ client.send(self._focus("windows"))+ client.send(self._focus("mac"))+ wait_for_calls(focuses, minimum=2)+ client.close()+ thread.join(timeout=2.0)+ self.assertEqual(focuses, ["windows", "mac"])+ finally:+ connection.close()++ def test_stopping_the_listener_while_driving_hands_input_back(self):+ focuses = []+ server, client, connection, thread = self._session(focuses)+ try:+ client.send(self._focus("windows", return_edge="left", resistance_px=100))+ wait_for_calls(focuses, minimum=1)+ server.stop()+ self.assertEqual(focuses, ["windows", "mac"])+ self.assertIsNone(server.return_edge)+ client.close()+ thread.join(timeout=2.0)+ # The session's own end finds nothing left to hand back.+ self.assertEqual(focuses, ["windows", "mac"])+ finally:+ connection.close()++ def test_a_peer_that_reconnects_while_driving_starts_with_input_at_home(self):+ focuses = []+ server, client, connection, thread = self._session(focuses)+ try:+ client.send(self._focus("windows"))+ wait_for_calls(focuses, minimum=1)+ # A second session authenticates before the first has noticed+ # anything: the preempt closes the first, and either way the+ # peer's input is at home the moment it is back.+ second_client, second_connection, second_address = connected_socket_pair()+ second_thread = threading.Thread(+ target=server._handle_client,+ args=(second_connection, second_address, make_config(), threading.Event()),+ )+ second_thread.start()+ second_client.send(protocol.hello_msg())+ self.assertEqual(second_client.recv(), protocol.welcome_msg())+ wait_for_calls(focuses, minimum=2)+ self.assertEqual(focuses, ["windows", "mac"])+ second_client.close()+ second_thread.join(timeout=2.0)+ self.assertEqual(focuses, ["windows", "mac"])+ second_connection.close()+ client.close()+ thread.join(timeout=2.0)+ finally:+ connection.close()+++class ReceiverBindTests(unittest.TestCase):+ def test_a_held_port_is_waited_out_rather_than_ending_the_listener(self):+ # WinNAT's dynamic reservations move on every reboot and have landed on+ # Beamer's port, which used to kill the server thread for the whole run.+ holder = socket.socket()+ # The receiver listens on 0.0.0.0, and SO_REUSEADDR only collides with+ # a holder on the same address, so 127.0.0.1 here would bind happily.+ holder.bind(("0.0.0.0", 0))+ holder.listen(1)+ port = holder.getsockname()[1]+ self.addCleanup(holder.close)++ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))+ self.addCleanup(server.stop)+ with mock.patch.object(receiver, "BIND_RETRY_SECONDS", 0.05):+ server.start(make_config(port=port))+ _, detail = wait_for_status(statuses, ServerState.ERROR, timeout=2.0)+ self.assertIn(f"port {port}", detail)+ self.assertIn("Connection page", detail)+ holder.close()+ deadline = time.monotonic() + 3.0+ waiting = (ServerState.WAITING, f"Waiting on port {port}")+ while waiting not in statuses and time.monotonic() < deadline:+ time.sleep(0.01)+ self.assertIn(waiting, statuses)++ def test_a_reuseaddr_zombie_still_blocks_the_new_bind(self):+ # A held port is normally a third-party program (the test above) or a+ # WinNAT reservation, but it can also be a zombie copy of Beamer+ # itself, whose listener was opened by this same _bind() and so also+ # carries SO_REUSEADDR. If Windows' SO_REUSEADDR let a second+ # SO_REUSEADDR socket steal a listening one, this is the scenario+ # where it would happen — the "held port" detection would never fire+ # and the two zombies would silently split inbound connections.+ holder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ holder.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ holder.bind(("0.0.0.0", 0))+ holder.listen(1)+ port = holder.getsockname()[1]+ self.addCleanup(holder.close)++ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)))+ self.addCleanup(server.stop)+ with mock.patch.object(receiver, "BIND_RETRY_SECONDS", 0.05):+ server.start(make_config(port=port))+ _, detail = wait_for_status(statuses, ServerState.ERROR, timeout=2.0)+ self.assertIn(f"port {port}", detail)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_return_edge.py b/win_app/tests/test_return_edge.pynew file mode 100644index 0000000..aab26e5--- /dev/null+++ b/win_app/tests/test_return_edge.py@@ -0,0 +1,124 @@+import unittest++from return_edge import CROSS, HOLD, PASS, Rect, ReturnEdge, arrival_position, edge_offset, union+++class FakeClock:+ def __init__(self, now=0.0):+ self.now = now++ def __call__(self):+ return self.now++ def advance(self, seconds):+ self.now += seconds+++# A 1080p monitor hanging off the left of a 1440p primary, so the bounding box+# starts at x=-1920 and the primary is not its origin.+LEFT = Rect(-1920, 200, 1920, 1080)+PRIMARY = Rect(0, 0, 2560, 1440)+ARRANGEMENT = [PRIMARY, LEFT]+BOUNDS = union(ARRANGEMENT)+++class GeometryTests(unittest.TestCase):+ def test_union_spans_a_negative_origin(self):+ self.assertEqual(BOUNDS, Rect(-1920, 0, 4480, 1440))+ self.assertEqual(BOUNDS.right, 2559)+ self.assertEqual(BOUNDS.bottom, 1439)++ def test_offset_is_measured_along_the_edge_against_the_bounding_box(self):+ self.assertAlmostEqual(edge_offset(BOUNDS, "left", (-1920, 720)), 0.5)+ self.assertAlmostEqual(edge_offset(BOUNDS, "top", (-1920 + 1120, 0)), 0.25)+ self.assertEqual(edge_offset(BOUNDS, "right", (2559, 99999)), 1.0)++ def test_arrival_lands_on_the_monitor_owning_each_edge(self):+ # left: the monitor with the smallest x, offset against the whole box+ # then clamped into that monitor's own span.+ self.assertEqual(arrival_position(ARRANGEMENT, "left", 0.5), (-1920, 720))+ self.assertEqual(arrival_position(ARRANGEMENT, "left", 0.0), (-1920, 200))+ # right: the primary, at its last pixel column.+ self.assertEqual(arrival_position(ARRANGEMENT, "right", 0.5), (2559, 720))+ # top: the primary is the only monitor reaching y=0; 10% of 4480 from+ # x=-1920 is in the left monitor's column range, so it clamps to x=0.+ self.assertEqual(arrival_position(ARRANGEMENT, "top", 0.1), (0, 0))+ self.assertEqual(arrival_position(ARRANGEMENT, "top", 0.75), (1440, 0))+ # bottom: the primary reaches y=1439; the left monitor stops at 1279.+ self.assertEqual(arrival_position(ARRANGEMENT, "bottom", 1.0), (2559, 1439))+++class PressureTests(unittest.TestCase):+ def setUp(self):+ self.clock = FakeClock()+ self.edge = ReturnEdge("left", resistance_px=120, clock=self.clock)++ def feed(self, pointer, dx, dy=0, after=0.0):+ self.clock.advance(after)+ return self.edge.feed(ARRANGEMENT, pointer, dx, dy)++ def test_movement_away_from_the_edge_passes_through(self):+ self.assertEqual(self.feed((-1000, 500), -40).action, PASS)+ self.assertEqual(self.feed((-1920, 500), 5).action, PASS)+ self.assertEqual(self.edge.pressure, 0.0)++ def test_outward_push_at_the_edge_holds_and_accumulates(self):+ outcome = self.feed((-1920, 500), -30, 4)+ self.assertEqual(outcome.action, HOLD)+ self.assertAlmostEqual(outcome.pressure, 0.25)+ # Pinned to the edge; the lateral component still slides along it.+ self.assertEqual(outcome.position, (-1920, 504))+ outcome = self.feed((-1920, 504), -30)+ self.assertAlmostEqual(outcome.pressure, 0.5)++ def test_inward_movement_subtracts(self):+ self.feed((-1920, 500), -60)+ outcome = self.feed((-1920, 500), 24)+ self.assertEqual(outcome.action, PASS)+ self.assertAlmostEqual(self.edge.pressure, 0.3)++ def test_pressure_decays_to_nothing_over_400ms(self):+ self.feed((-1920, 500), -60)+ self.assertAlmostEqual(self.feed((-1920, 500), 0, after=0.2).pressure, 0.0)+ self.feed((-1920, 500), -60)+ self.assertAlmostEqual(self.feed((-1920, 500), 0, after=0.1).pressure, 0.25)++ def test_breakthrough_sends_the_opposite_edge_and_the_offset(self):+ self.feed((-1920, 720), -100)+ outcome = self.feed((-1920, 720), -20)+ self.assertEqual(outcome.action, CROSS)+ self.assertEqual(outcome.edge, "right")+ self.assertAlmostEqual(outcome.offset, 0.5)+ self.assertEqual(outcome.pressure, 1.0)+ # Disarmed until the Mac's next switch: deltas still in flight pass.+ self.assertFalse(self.edge.armed)+ self.assertEqual(self.feed((-1920, 720), -200).action, PASS)++ def test_zero_resistance_crosses_on_contact(self):+ edge = ReturnEdge("bottom", resistance_px=0, clock=self.clock)+ outcome = edge.feed(ARRANGEMENT, (100, 1439), 0, 1)+ self.assertEqual(outcome.action, CROSS)+ self.assertEqual(outcome.edge, "top")++ def test_a_shorter_monitors_outer_edge_counts(self):+ # The left monitor stops at y=1279, well short of the box's 1439, with+ # nothing below it: the pointer is stopped there, so it is a way home.+ edge = ReturnEdge("bottom", resistance_px=120, clock=self.clock)+ self.assertEqual(edge.feed(ARRANGEMENT, (-1000, 1279), 0, 50).action, HOLD)+ self.assertEqual(edge.feed(ARRANGEMENT, (1000, 1439), 0, 50).action, HOLD)+ top = ReturnEdge("top", resistance_px=120, clock=self.clock)+ self.assertEqual(top.feed(ARRANGEMENT, (-1000, 200), 0, -50).action, HOLD)++ def test_an_edge_shared_with_another_monitor_does_not_count(self):+ # x=0 on the primary meets the left monitor between y=200 and 1279.+ edge = ReturnEdge("left", resistance_px=120, clock=self.clock)+ self.assertEqual(edge.feed(ARRANGEMENT, (0, 500), -50, 0).action, PASS)+ self.assertEqual(edge.feed(ARRANGEMENT, (0, 100), -50, 0).action, HOLD)++ def test_rejects_an_unknown_edge(self):+ with self.assertRaises(ValueError):+ ReturnEdge("sideways")+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_sender.py b/win_app/tests/test_sender.pynew file mode 100644index 0000000..6a6c47f--- /dev/null+++ b/win_app/tests/test_sender.py@@ -0,0 +1,297 @@+"""The Windows-to-Mac direction, driven over a real loopback socket against+the same receiver.py the Mac runs, so the two halves are proved against each+other rather than against a mock of each other."""++import socket+import threading+import time+import unittest++import capture_win+import protocol+import receiver+import sender+from app_config import Config+from fakes import FakeClipboard, FakeDesktop, FakeInjector, wait_for_calls+from return_edge import Rect++MONITORS = [Rect(0, 0, 1920, 1080)]+++def make_config(**overrides):+ values = dict(+ host="127.0.0.1",+ port=0,+ auth_token="shared-token",+ mac_host="127.0.0.1",+ mac_return_edge="left",+ mac_resistance_px=40,+ crossing_resistance_px=40,+ )+ values.update(overrides)+ return Config(**values)+++class EdgeTests(unittest.TestCase):+ """The outward crossing, with no link in the way: the model, the gate and+ the pin, which is everything the hook thread does per mouse move."""++ def setUp(self):+ self.desktop = FakeDesktop(MONITORS, cursor=(0, 500))+ self.link = MacSenderWithLink(desktop=self.desktop)++ def tearDown(self):+ self.link.close()++ def push(self, times, dx=-20):+ """The hand still moving left with the cursor already stopped at the+ left edge: the position never changes, which is exactly why the+ movement has to come from raw input rather than from the hook."""+ for _ in range(times):+ self.link.sender.on_motion(dx, 0)++ def test_a_push_against_the_edge_crosses(self):+ self.push(4)+ self.assertTrue(self.link.sender.redirecting, "a sustained push against the left edge never crossed")++ def test_the_edge_is_dead_while_the_mac_is_driving(self):+ self.link.sender.set_receiving(True)+ self.push(10)+ self.assertFalse(self.link.sender.redirecting)++ def test_the_shortcut_while_the_mac_is_driving_sends_its_input_home(self):+ sent_home = []+ self.link.sender.send_peer_home = lambda: sent_home.append(True) or True+ self.link.sender.set_receiving(True)+ self.assertTrue(self.link.sender.set_redirecting(True))+ self.assertEqual(sent_home, [True])+ self.assertFalse(self.link.sender.redirecting)++ def test_a_push_away_from_the_edge_never_crosses(self):+ self.push(10, dx=20)+ self.assertFalse(self.link.sender.redirecting)++ def test_a_pointer_off_the_edge_never_crosses(self):+ self.desktop.cursor = (900, 500)+ self.push(10)+ self.assertFalse(self.link.sender.redirecting)++ def test_the_edge_can_be_turned_off(self):+ self.link.sender.update_config(make_config(crossing_methods=["shortcut"]))+ self.push(10)+ self.assertFalse(self.link.sender.redirecting)+ self.assertTrue(self.link.sender.shortcut_armed)++ def test_the_shortcut_can_be_turned_off_on_its_own(self):+ self.link.sender.update_config(make_config(crossing_methods=["edge"]))+ self.assertFalse(self.link.sender.shortcut_armed)+ self.push(4)+ self.assertTrue(self.link.sender.redirecting)+++class CornerTests(unittest.TestCase):+ """The corner is for a machine whose whole edge is busy: it wants a+ diagonal push in an 8-pixel box, and nothing else."""++ def setUp(self):+ self.desktop = FakeDesktop(MONITORS, cursor=(0, 0))+ self.link = MacSenderWithLink(desktop=self.desktop)+ self.link.sender.update_config(+ make_config(crossing_methods=["corner"], crossing_corner="top_left")+ )++ def tearDown(self):+ self.link.close()++ def test_a_diagonal_push_in_the_corner_crosses(self):+ for _ in range(4):+ self.link.sender.on_motion(-20, -20)+ self.assertTrue(self.link.sender.redirecting)++ def test_a_straight_push_along_the_edge_does_not(self):+ for _ in range(10):+ self.link.sender.on_motion(-20, 0)+ self.assertFalse(self.link.sender.redirecting)++ def test_the_same_diagonal_away_from_the_corner_does_not(self):+ self.desktop.cursor = (900, 500)+ for _ in range(10):+ self.link.sender.on_motion(-20, -20)+ self.assertFalse(self.link.sender.redirecting)+++class SelfConnectionTests(unittest.TestCase):+ """The one way this PC could take its own daily link down: learning its+ own address as the Mac's, connecting to its own receiver with the shared+ token, and having the preempt rule close the real Mac's session."""++ def test_loopback_and_this_pcs_own_addresses_are_refused(self):+ self.assertTrue(sender.is_this_machine("127.0.0.1"))+ self.assertTrue(sender.is_this_machine("0.0.0.0"))+ self.assertTrue(sender.is_this_machine(""))+ self.assertTrue(sender.is_this_machine("192.168.1.3", ["192.168.1.3"]))++ def test_the_macs_address_is_not(self):+ self.assertFalse(sender.is_this_machine("192.168.1.5", ["192.168.1.3"], address_towards=lambda host: "192.168.1.3"))++ def test_this_pcs_own_real_address_is_not_missed_when_enumeration_fails(self):+ # local_addresses=[] is what pairing._local_ipv4_addresses() returns+ # when the hostname does not resolve; the route probe then answers,+ # and for this PC's own address it answers with that address.+ self.assertTrue(sender.is_this_machine("192.168.1.3", [], address_towards=lambda host: host))+ self.assertFalse(sender.is_this_machine("192.168.1.5", [], address_towards=lambda host: "192.168.1.3"))++ def test_a_route_probe_that_fails_does_not_stop_the_link(self):+ def refuse(host):+ raise OSError("network is unreachable")++ self.assertFalse(sender.is_this_machine("192.168.1.5", [], address_towards=refuse))++ def test_a_sender_pointed_at_this_pc_never_opens_a_link(self):+ attempts = []++ def refuse(address, timeout):+ attempts.append(address)+ raise AssertionError("the sender tried to connect to this PC")++ link = sender.MacSender(socket_factory=refuse, desktop=FakeDesktop(MONITORS))+ link.update_config(make_config(mac_host="127.0.0.1", port=51820))+ self.assertIsNone(link._ready_config())+ self.assertEqual(attempts, [])+++class LinkTests(unittest.TestCase):+ def setUp(self):+ self.injector = FakeInjector()+ self.clipboard = FakeClipboard()+ self.mac_desktop = FakeDesktop(MONITORS, cursor=(900, 500))+ self.statuses = []+ self.arrangements = []+ self.server = receiver.ReceiverServer(+ status_callback=lambda state, detail: self.statuses.append((state, detail)),+ arrangement_callback=lambda edge, set_at: self.arrangements.append((edge, set_at)),+ clipboard=self.clipboard,+ unlock=NoUnlock(),+ desktop=self.mac_desktop,+ injector=self.injector,+ self_name="Mac",+ peer_name="PC",+ self_target="mac",+ peer_target="windows",+ )+ self.port = free_port()+ self.server.start(Config(host="127.0.0.1", port=self.port, auth_token="shared-token"))+ self.desktop = FakeDesktop(MONITORS, cursor=(0, 500))+ # The loopback address is this PC's own, which the real guard refuses+ # to connect to; here it is the Mac at the other end of the test.+ self.sender = sender.MacSender(+ desktop=self.desktop, clipboard=FakeClipboard("copied"), is_local=lambda host: False+ )+ self.sender.start(make_config(port=self.port))+ self.assertTrue(wait_for(lambda: self.sender.connected), f"never connected: {self.sender.status}")++ def tearDown(self):+ self.sender.stop()+ self.server.stop()++ def test_keys_reach_the_mac_injector(self):+ self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)+ self.sender.on_key("cmd", True)+ self.sender.on_key("c", True)+ self.sender.on_key("c", False)+ self.sender.on_key("cmd", False)+ wait_for_calls(self.injector.calls, 4)+ self.assertEqual(+ self.injector.calls,+ [+ ("key", ("cmd", True)),+ ("key", ("c", True)),+ ("key", ("c", False)),+ ("key", ("cmd", False)),+ ],+ )++ def test_the_switch_places_the_mac_pointer_and_arms_its_way_home(self):+ self.sender.set_redirecting(True, arrival_edge="right", offset=0.25)+ self.assertTrue(wait_for(lambda: self.server.return_edge == "right"))+ self.assertEqual(self.mac_desktop.cursor[0], MONITORS[0].right)++ def test_nothing_is_sent_while_input_is_this_pcs(self):+ self.sender.on_key("a", True)+ time.sleep(0.2)+ self.assertEqual(self.injector.calls, [])++ def test_the_mac_pushing_home_takes_input_back(self):+ self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)+ self.assertTrue(wait_for(lambda: self.server.return_edge == "right"))+ # The Mac's own pointer, pushed off its right edge: the receiver+ # answers with a switch, which must stop this PC sending.+ self.mac_desktop.cursor = (MONITORS[0].right, 500)+ for _ in range(20):+ self.sender.on_motion(40, 0)+ self.mac_desktop.cursor = (MONITORS[0].right, 500)+ if not self.sender.redirecting:+ break+ self.assertTrue(wait_for(lambda: not self.sender.redirecting), "the Mac's push home was ignored")++ def test_the_arrangement_travels_to_the_mac(self):+ self.sender.send_arrangement("right", 1758100000)+ wait_for_calls(self.arrangements, 1)+ self.assertEqual(self.arrangements[0], ("right", 1758100000))++ def test_the_arrangement_travels_back_from_the_mac(self):+ heard = []+ self.sender._arrangement_callback = lambda edge, set_at: heard.append((edge, set_at))+ self.assertTrue(self.server.send_arrangement("top", 1758100001))+ wait_for_calls(heard, 1)+ self.assertEqual(heard[0], ("top", 1758100001))++ def test_a_malformed_arrangement_does_not_take_the_link_down(self):+ self.sender._send_raw({"type": protocol.MSG_ARRANGEMENT, "data": {"mac_edge": "sideways"}})+ time.sleep(0.2)+ self.assertEqual(self.arrangements, [])+ self.assertTrue(self.sender.connected)++ def test_the_clipboard_travels_with_the_switch(self):+ self.sender.set_redirecting(True, arrival_edge="right", offset=0.5)+ wait_for_calls(self.clipboard.set_calls, 1)+ self.assertEqual(self.clipboard.set_calls[0][0], "copied")+++class NoUnlock:+ def is_locked(self):+ return None+++class MacSenderWithLink:+ """A sender with no socket at all, for the edge tests: `connected` is+ forced true so the gate opens, and nothing is ever sent."""++ def __init__(self, desktop):+ self.sender = sender.MacSender(desktop=desktop, clipboard=FakeClipboard(), is_local=lambda host: False)+ self.sender.update_config(make_config())+ self.sender._sock = object()+ self.sender._connected_at = time.monotonic()+ self.sender._last_ack_at = time.monotonic()++ def close(self):+ self.sender._sock = None+++def free_port():+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ return probe.getsockname()[1]+++def wait_for(predicate, timeout=5.0):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return True+ time.sleep(0.02)+ return False+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_shared_copies.py b/win_app/tests/test_shared_copies.pynew file mode 100644index 0000000..70d23eb--- /dev/null+++ b/win_app/tests/test_shared_copies.py@@ -0,0 +1,61 @@+"""The files both apps share are kept byte-identical, not merely similar.++`protocol.py`, `receiver.py` and `return_edge.py` each exist once in mac_app+and once in win_app because neither app can import across the other's+directory -- both are packaged as self-contained bundles. Everything+platform-shaped in them is injected at construction instead, so there is no+legitimate reason for the two copies to differ by a byte, and a diff is+always drift. This test is byte-for-byte on purpose: a structural comparison+would pass while the two sides' return-edge arithmetic or status wording+quietly diverged.++This file is itself one of those copies, and checks itself.+"""++import hashlib+import os+import unittest++_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))+_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))++SHARED_MODULES = ("protocol.py", "receiver.py", "return_edge.py")+SHARED_TESTS = ("test_shared_copies.py",)+++def _digest(path):+ with open(path, "rb") as handle:+ return hashlib.sha256(handle.read()).hexdigest()+++class SharedCopyTests(unittest.TestCase):+ def _assert_identical(self, mac_path, win_path, name):+ if not os.path.isfile(mac_path) or not os.path.isfile(win_path):+ self.skipTest(f"{name} is missing from one side; nothing to compare")+ self.assertEqual(+ _digest(mac_path),+ _digest(win_path),+ f"mac_app and win_app copies of {name} have drifted apart",+ )++ def test_shared_modules_are_identical(self):+ for name in SHARED_MODULES:+ with self.subTest(module=name):+ self._assert_identical(+ os.path.join(_REPO_ROOT, "mac_app", name),+ os.path.join(_REPO_ROOT, "win_app", name),+ name,+ )++ def test_shared_tests_are_identical(self):+ for name in SHARED_TESTS:+ with self.subTest(module=name):+ self._assert_identical(+ os.path.join(_REPO_ROOT, "mac_app", "tests", name),+ os.path.join(_REPO_ROOT, "win_app", "tests", name),+ name,+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_stuck_modifier_on_drop.py b/win_app/tests/test_stuck_modifier_on_drop.pynew file mode 100644index 0000000..620a145--- /dev/null+++ b/win_app/tests/test_stuck_modifier_on_drop.py@@ -0,0 +1,68 @@+import sys+import unittest++import input_injector+import receiver+++class FakeInjector:+ def __init__(self):+ self.calls = []++ def inject_key(self, name, down):+ self.calls.append((name, down))++ def release_all(self):+ self.calls.append(("release_all",))+++class PeerKeysReleasedTests(unittest.TestCase):+ """Invariant 3: anything injected for the peer is released when input+ comes home or the link dies, on this PC exactly as on the Mac."""++ def _server(self, injector):+ server = receiver.ReceiverServer(+ status_callback=lambda *a: None,+ injector=injector,+ focus_callback=lambda target: None,+ )+ server._peer_driving = True+ return server++ def test_hand_back_releases_what_the_peer_held(self):+ injector = FakeInjector()+ server = self._server(injector)+ receiver.handle_message({"type": "keydown", "data": {"key": "ctrl"}}, injector=injector)+ server._hand_back("peer went away")+ self.assertIn(("release_all",), injector.calls)++ def test_input_going_home_releases_what_the_peer_held(self):+ injector = FakeInjector()+ server = self._server(injector)+ server._clipboard = type("C", (), {"get_contents": staticmethod(lambda: (None, None))})+ server._handle_focus({"type": "focus", "data": {"target": "mac"}}, None, None, "peer", "192.168.1.5")+ self.assertIn(("release_all",), injector.calls)++ @unittest.skipUnless(sys.platform == "win32", "the scan-code lookup needs user32")+ def test_the_windows_injector_releases_keys_and_buttons(self):+ sent = []+ original_send = input_injector._send_input+ input_injector._send_input = lambda *inputs: sent.extend(inputs)+ try:+ input_injector._mods_down.update({"ctrl", "shift"})+ input_injector._char_vk_down["a"] = 0x41+ input_injector._buttons_down.add("left")+ input_injector.release_all()+ finally:+ input_injector._send_input = original_send+ self.assertEqual(input_injector._mods_down, set())+ self.assertEqual(input_injector._char_vk_down, {})+ self.assertEqual(input_injector._buttons_down, set())+ keyups = [i for i in sent if i.type == input_injector.INPUT_KEYBOARD and i.union.ki.dwFlags & input_injector.KEYEVENTF_KEYUP]+ buttonups = [i for i in sent if i.type == input_injector.INPUT_MOUSE and i.union.mi.dwFlags == input_injector.MOUSEEVENTF_LEFTUP]+ self.assertEqual(len(keyups), 3)+ self.assertEqual(len(buttonups), 1)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_tokens.py b/win_app/tests/test_tokens.pynew file mode 100644index 0000000..f366c1e--- /dev/null+++ b/win_app/tests/test_tokens.py@@ -0,0 +1,19 @@+from pathlib import Path+import unittest++WIN_APP = Path(__file__).resolve().parent.parent+ROOT_TOKENS = WIN_APP.parent / "tokens.py"+++class TokensCopyTest(unittest.TestCase):+ @unittest.skipUnless(ROOT_TOKENS.exists(), "no repo root beside win_app, as in an installed layout")+ def test_win_app_copy_is_byte_identical_to_the_root(self):+ self.assertEqual(+ (WIN_APP / "tokens.py").read_bytes(),+ ROOT_TOKENS.read_bytes(),+ "win_app/tokens.py has drifted from tokens.py; copy the root file across",+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_tray_icon.py b/win_app/tests/test_tray_icon.pynew file mode 100644index 0000000..d1d7bb6--- /dev/null+++ b/win_app/tests/test_tray_icon.py@@ -0,0 +1,38 @@+import os+from pathlib import Path+import subprocess+import sys+import unittest++# The scale factor only takes effect before a QApplication exists, and another test may already+# have made one, so the render runs in its own process.+PROBE = """+from PySide6.QtWidgets import QApplication+app = QApplication([])+import kvm_bridge_win as k+pixmap = k.status_icon(k.ServerState.CONNECTED)+print(pixmap.width(), pixmap.toImage().pixelColor(32, 32).name())+"""+++class TrayIconTest(unittest.TestCase):+ def test_mark_survives_a_scaled_display(self):+ # At 150% the tray once showed only the state dot on a taskbar-coloured square.+ env = dict(os.environ, QT_SCALE_FACTOR="1.5", QT_QPA_PLATFORM="offscreen")+ out = subprocess.run(+ [sys.executable, "-c", PROBE],+ cwd=Path(__file__).resolve().parent.parent,+ env=env,+ capture_output=True,+ text=True,+ timeout=60,+ )+ self.assertEqual(out.returncode, 0, out.stderr)+ width, centre = out.stdout.split()+ self.assertEqual(width, "64")+ # The centre of the mark is the cursor's off-white, not the fallback panel fill.+ self.assertEqual(centre, "#efeee6")+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/tests/test_unlock_win.py b/win_app/tests/test_unlock_win.pynew file mode 100644index 0000000..9461653--- /dev/null+++ b/win_app/tests/test_unlock_win.py@@ -0,0 +1,189 @@+"""Unlock orchestration, exercised on any platform.++unlock_win talks to kernel32, so every test here passes a fake `mem32` in its+place -- the same dependency-injection trick clipboard_win.py and+handle_message use, so this suite runs on the Mac.+"""++import unittest++import protocol+import receiver+import unlock_win+from receiver import ReceiverServer, ServerState+++class FakeKernel32:+ """Stands in for kernel32. `locked_sequence` is consumed one entry per+ is_locked() call so a test can script the console unlocking part-way+ through the poll loop."""++ def __init__(self, locked_sequence, event_opens=True):+ self.locked_sequence = list(locked_sequence)+ self.event_opens = event_opens+ self.opened_names = []+ self.set_events = 0+ self.closed = 0++ # is_locked() reaches the process list through this pair.+ def CreateToolhelp32Snapshot(self, flags, pid):+ return 1234++ def Process32FirstW(self, snapshot, entry):+ locked = self.locked_sequence.pop(0) if self.locked_sequence else False+ # The production call passes ctypes.byref(entry); a CArgObject exposes+ # the structure it wraps as _obj.+ entry._obj.szExeFile = "logonui.exe" if locked else "explorer.exe"+ return 1++ def Process32NextW(self, snapshot, entry):+ return 0++ def WTSGetActiveConsoleSessionId(self):+ return 1++ def OpenEventW(self, access, inherit, name):+ self.opened_names.append(name)+ return 99 if self.event_opens else None++ def SetEvent(self, handle):+ self.set_events += 1+ return 1++ def CloseHandle(self, handle):+ self.closed += 1+ return 1+++class IsLockedTests(unittest.TestCase):+ def test_logonui_running_means_locked(self):+ self.assertIs(unlock_win.is_locked(FakeKernel32([True])), True)++ def test_no_logonui_means_unlocked(self):+ self.assertIs(unlock_win.is_locked(FakeKernel32([False])), False)++ def test_failed_snapshot_is_unknown_not_unlocked(self):+ """None, never False: reporting an unknown state as unlocked would+ silently skip an unlock the machine actually needed."""+ fake = FakeKernel32([False])+ fake.CreateToolhelp32Snapshot = lambda flags, pid: None+ self.assertIsNone(unlock_win.is_locked(fake))+++class SignalUnlockTests(unittest.TestCase):+ def test_signals_the_event_for_the_console_session(self):+ fake = FakeKernel32([True])+ self.assertTrue(unlock_win.signal_unlock(fake))+ self.assertEqual(fake.opened_names, ["Global\\RoomDeckUnlock.1"])+ self.assertEqual(fake.set_events, 1)+ self.assertEqual(fake.closed, 1)++ def test_missing_provider_fails_cleanly(self):+ fake = FakeKernel32([True], event_opens=False)+ self.assertFalse(unlock_win.signal_unlock(fake))+ self.assertEqual(fake.set_events, 0)+++class EnsureUnlockedTests(unittest.TestCase):+ def test_already_unlocked_never_signals(self):+ fake = FakeKernel32([False])+ self.assertTrue(unlock_win.ensure_unlocked(fake, sleep=lambda _: None))+ self.assertEqual(fake.set_events, 0)++ def test_unknown_state_is_treated_as_unlocked(self):+ fake = FakeKernel32([False])+ fake.CreateToolhelp32Snapshot = lambda flags, pid: None+ self.assertTrue(unlock_win.ensure_unlocked(fake, sleep=lambda _: None))+ self.assertEqual(fake.set_events, 0)++ def test_locked_console_is_signalled_and_polled_until_it_clears(self):+ # Locked on the initial test and the first poll, unlocked on the next.+ fake = FakeKernel32([True, True, False])+ self.assertTrue(unlock_win.ensure_unlocked(fake, sleep=lambda _: None))+ self.assertEqual(fake.set_events, 1)++ def test_console_that_never_unlocks_reports_failure(self):+ fake = FakeKernel32([True] * 100)+ self.assertFalse(+ unlock_win.ensure_unlocked(fake, timeout=1.0, poll=0.5, sleep=lambda _: None)+ )++ def test_missing_provider_reports_failure_without_polling(self):+ fake = FakeKernel32([True], event_opens=False)+ self.assertFalse(unlock_win.ensure_unlocked(fake, sleep=lambda _: None))+++class FakeUnlockModule:+ def __init__(self, locked, unlocks=True):+ self.locked = locked+ self.unlocks = unlocks+ self.ensure_calls = 0++ def is_locked(self):+ return self.locked++ def ensure_unlocked(self):+ self.ensure_calls += 1+ return self.unlocks+++class ReceiverUnlockTests(unittest.TestCase):+ """focus{target:"windows"} is the moment input starts arriving here, so it+ is where the lock screen has to be cleared out of its way."""++ def _server(self, unlock):+ statuses = []+ server = ReceiverServer(lambda state, detail: statuses.append((state, detail)), unlock=unlock)+ return server, statuses++ def test_unlocked_pc_does_no_work_on_focus(self):+ unlock = FakeUnlockModule(locked=False)+ server, _ = self._server(unlock)+ server._begin_unlock("192.168.1.5:1", "192.168.1.5")+ self.assertEqual(unlock.ensure_calls, 0)+ self.assertFalse(server._unlocking.is_set())++ def test_locked_pc_unlocks_and_restores_the_connected_status(self):+ unlock = FakeUnlockModule(locked=True)+ server, statuses = self._server(unlock)+ server._begin_unlock("192.168.1.5:1", "192.168.1.5")+ for _ in range(200):+ if not server._unlocking.is_set():+ break+ import time+ time.sleep(0.01)+ self.assertEqual(unlock.ensure_calls, 1)+ self.assertIn((ServerState.CONNECTED, "Unlocking Windows…"), statuses)+ self.assertEqual(statuses[-1], (ServerState.CONNECTED, "Connected to 192.168.1.5"))++ def test_failed_unlock_says_so_rather_than_claiming_a_connection(self):+ unlock = FakeUnlockModule(locked=True, unlocks=False)+ server, statuses = self._server(unlock)+ server._begin_unlock("192.168.1.5:1", "192.168.1.5")+ for _ in range(200):+ if not server._unlocking.is_set():+ break+ import time+ time.sleep(0.01)+ self.assertEqual(+ statuses[-1],+ (ServerState.CONNECTED, "Windows is locked — unlock it at the PC"),+ )++ def test_a_session_that_ended_mid_unlock_does_not_report_a_connection(self):+ """An unlock outlives a Mac that disconnects during it; the session's+ own exit has already set WAITING and must not be overwritten."""+ unlock = FakeUnlockModule(locked=True)+ server, statuses = self._server(unlock)+ server._unlock_worker(unlock, "192.168.1.5:1", "192.168.1.5", generation=-1)+ self.assertEqual(statuses, [])++ def test_ack_advertises_the_unlock_only_while_it_is_running(self):+ """The Mac reads this to explain the pause; it must not linger, or the+ Mac shows 'Unlocking Windows…' forever."""+ self.assertNotIn("locked", protocol.ack_msg(7)["data"])+ self.assertIs(protocol.ack_msg(7, locked=True)["data"]["locked"], True)+++if __name__ == "__main__":+ unittest.main()diff --git a/win_app/theme.py b/win_app/theme.pynew file mode 100644index 0000000..4583f01--- /dev/null+++ b/win_app/theme.py@@ -0,0 +1,265 @@+"""Vernier theming for the Windows receiver, built from tokens.py.++Widgets opt into a component with a `vernier` property set before the stylesheet is applied, or+re-polished with `repolish(widget)` after it changes. QSS cannot express letter spacing, so the+tracked labels and the big numerals take a QFont. The base face is the application font, never a+QWidget rule: a stylesheet font-size beats every QFont set on a widget beneath it.+"""++from __future__ import annotations++import os+import sys++import titlebar+import tokens++P = tokens.PALETTE+TYPE = tokens.TYPE+RADIUS = tokens.RADIUS++_sans = "Segoe UI"+_mono = "Consolas"++# Derived here because tokens.py has no value for them: the heading size inside a module (the+# mock sets the Windows status word at 22px, between body and status_word_narrow), and the+# countdown numeral (30px in the mock).+HEADING = 22.0+COUNT = 30.0++# The sidebar's fixed width. Windows does not reflow it with the window the way the Mac's+# does; a fixed width leaves 640 - SIDEBAR_WIDTH - 1 of content, which every page's grid is+# laid out to fit.+SIDEBAR_WIDTH = 168++# The pairing code sits beside the countdown and the Pair button now, in a page narrower than+# the window used to be with no sidebar -- tokens.TYPE["code"] (92px, shared with the Mac's own+# pairing card) does not fit that row at 640 wide, so this page uses its own smaller size.+PAIRING_CODE = 48.0++# One tone per receiver state, shared by the LED, the tray dot and the heading.+STATE_TONE = {+ "connected": "signal",+ "waiting": "amber",+ "stopped": "off",+ "error": "fault",+}+++def assets_dir() -> str:+ if getattr(sys, "frozen", False):+ base = getattr(sys, "_MEIPASS", os.path.dirname(sys.executable))+ return os.path.join(base, "assets")+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")+++def init_fonts() -> None:+ """Loads the bundled faces. A face that will not load leaves Segoe UI or Consolas in its+ place rather than stopping the window opening."""+ global _sans, _mono+ from PySide6.QtGui import QFontDatabase++ loaded: set[str] = set()+ for name in tokens.FONT_FILES:+ path = os.path.join(assets_dir(), name)+ handle = QFontDatabase.addApplicationFont(path) if os.path.exists(path) else -1+ if handle != -1:+ loaded.update(QFontDatabase.applicationFontFamilies(handle))+ _sans = tokens.UI_FAMILY if tokens.UI_FAMILY in loaded else "Segoe UI"+ _mono = tokens.MONO_FAMILY if tokens.MONO_FAMILY in loaded else "Consolas"+++def sans() -> str:+ return _sans+++def mono() -> str:+ return _mono+++def colour(name: str) -> str:+ return P[name]+++def state_tone(state: str) -> str:+ return STATE_TONE.get(state, "off")+++def state_colour(state: str) -> str:+ return P[state_tone(state)]+++def font(size: float, weight: int = 400):+ from PySide6.QtGui import QFont++ face = QFont(_sans)+ face.setPixelSize(round(size))+ face.setWeight(QFont.Weight(weight))+ return face+++def mono_font(size: float, weight: int = 400):+ from PySide6.QtGui import QFont++ face = QFont(_mono)+ face.setStyleHint(QFont.StyleHint.Monospace)+ face.setPixelSize(round(size))+ face.setWeight(QFont.Weight(weight))+ return face+++def eyebrow_font(key: str = "eyebrow"):+ from PySide6.QtGui import QFont++ face = font(TYPE[key], 700)+ face.setCapitalization(QFont.Capitalization.AllUppercase)+ face.setLetterSpacing(QFont.SpacingType.AbsoluteSpacing, TYPE[key] * tokens.TRACKING[key])+ return face+++def repolish(widget) -> None:+ style = widget.style()+ style.unpolish(widget)+ style.polish(widget)+ widget.update()+++def stylesheet() -> str:+ values = dict(P)+ values.update(+ sans=_sans,+ mono=_mono,+ body=round(TYPE["body"]),+ note=round(TYPE["note"]),+ small=round(TYPE["small"]),+ field_mono=round(TYPE["field_mono"]),+ button=round(TYPE["button"]),+ r_field=round(RADIUS["field"]),+ r_button=round(RADIUS["button"]),+ )+ return _TEMPLATE.format(**values)+++_TEMPLATE = """+QWidget {{+ background: {ground};+ color: {ink};+}}+QWidget[vernier="rack"] {{ background: {rule}; }}+QFrame[vernier="module"] {{ background: {panel}; border: 0; }}+QFrame[vernier="commit"] {{ background: {ground}; border: 0; border-top: 1px solid {rule}; }}+QWidget[vernier="plain"] {{ background: transparent; }}+QWidget[vernier="rule"] {{ background: {rule}; }}+QWidget[vernier="sidebar"] {{ background: {panel}; }}++QLabel {{ background: transparent; color: {ink_2}; }}+QLabel[vernier="eyebrow"] {{ color: {ink_3}; }}+QLabel[vernier="heading"] {{ color: {ink}; }}+QLabel[vernier="heading-amber"] {{ color: {amber}; }}+QLabel[vernier="heading-fault"] {{ color: {fault}; }}+QLabel[vernier="note"] {{ color: {ink_2}; font-size: {note}px; }}+QLabel[vernier="note-amber"] {{ color: {amber}; font-size: {note}px; }}+QLabel[vernier="note-fault"] {{ color: {fault}; font-size: {note}px; }}+QLabel[vernier="note-live"] {{ color: {signal}; font-size: {note}px; }}+QLabel[vernier="key"] {{ color: {ink_2}; font-size: {note}px; }}+QLabel[vernier="mono"] {{ color: {ink_2}; font-family: "{mono}"; font-size: {note}px; }}+QLabel[vernier="readout"] {{ color: {ink}; font-family: "{mono}"; font-size: {note}px; font-weight: 700; }}+QLabel[vernier="code"] {{ color: {ink}; }}+QLabel[vernier="code-idle"] {{ color: {ink_3}; }}+QLabel[vernier="count"] {{ color: {ink}; }}+QLabel[vernier="count-idle"] {{ color: {ink_3}; }}+QLabel[vernier="sidebar-link"] {{ color: {ink}; font-size: {body}px; font-weight: 700; }}++QPushButton {{+ background: {well};+ border: 1px solid {edge};+ border-radius: {r_button}px;+ color: {ink};+ font-size: {button}px;+ font-weight: 600;+ padding: 7px 12px;+}}+QPushButton:hover {{ border-color: {ink_3}; }}+QPushButton:focus {{ border: 2px solid {signal}; padding: 6px 11px; }}+QPushButton:disabled {{ color: {ink_3}; border-color: {rule}; background: {panel}; }}+QPushButton[vernier="primary"] {{ background: {ink}; border-color: {ink}; color: {ground}; }}+QPushButton[vernier="primary"]:hover {{ background: {ink_2}; border-color: {ink_2}; }}+QPushButton[vernier="primary"]:focus {{ border: 2px solid {signal}; }}+QPushButton[vernier="primary"]:disabled {{ background: {well}; border-color: {rule}; color: {ink_3}; }}+QPushButton[vernier="live"] {{ background: {signal}; border-color: {signal}; color: {ground}; }}+QPushButton[vernier="live"]:focus {{ border: 2px solid {ink}; }}+QPushButton[vernier="small"] {{ font-size: {small}px; padding: 4px 10px; }}+QPushButton[vernier="small"]:focus {{ padding: 3px 9px; }}+QPushButton[vernier="choice"] {{ color: {ink_2}; font-size: {small}px; font-weight: 400; padding: 4px 8px; }}+QPushButton[vernier="choice"]:checked {{ background: {ink}; border-color: {ink}; color: {ground}; font-weight: 600; }}+QPushButton[vernier="choice"]:focus {{ padding: 3px 7px; }}+QPushButton[vernier="choice"]:disabled {{ color: {ink_3}; border-color: {rule}; background: {panel}; }}+QPushButton[vernier="choice"]:checked:disabled {{ background: {well}; border-color: {rule}; color: {ink_2}; }}++QPushButton[vernier="page"] {{+ background: transparent;+ border: 0;+ border-radius: {r_button}px;+ color: {ink_2};+ font-size: {body}px;+ font-weight: 500;+ padding: 8px 12px;+ text-align: left;+}}+QPushButton[vernier="page"]:hover {{ background: {well}; color: {ink}; }}+QPushButton[vernier="page"]:checked {{ background: {well}; color: {ink}; font-weight: 700; }}+QPushButton[vernier="page"]:focus {{ border: 1px solid {signal}; padding: 7px 11px; }}++QCheckBox {{ background: transparent; color: {ink}; font-size: {body}px; spacing: 8px; }}+QCheckBox::indicator {{ width: 16px; height: 16px; border: 1px solid {edge}; border-radius: 3px; background: {well}; }}+QCheckBox::indicator:hover {{ border-color: {ink_3}; }}+QCheckBox::indicator:checked {{ background: {signal}; border-color: {signal}; }}++QSlider::groove:horizontal {{ height: 4px; background: {well}; border-radius: 2px; }}+QSlider::sub-page:horizontal {{ background: {signal}; border-radius: 2px; }}+QSlider::add-page:horizontal {{ background: {well}; border-radius: 2px; }}+QSlider::handle:horizontal {{ width: 14px; height: 14px; margin: -6px 0; border-radius: 7px; background: {ink}; border: 1px solid {ink}; }}+QSlider::handle:horizontal:hover {{ background: {signal}; border-color: {signal}; }}+QSlider::handle:horizontal:disabled {{ background: {ink_3}; border-color: {ink_3}; }}+QSlider::groove:horizontal:disabled {{ background: {panel}; }}++QLineEdit {{+ background: {ground};+ border: 1px solid {edge};+ border-radius: {r_field}px;+ color: {ink};+ font-family: "{mono}";+ font-size: {field_mono}px;+ padding: 6px 8px;+ selection-background-color: {signal_dim};+ selection-color: {ink};+ lineedit-password-character: 8226;+}}+QLineEdit:focus {{ border: 2px solid {signal}; padding: 5px 7px; }}++QScrollArea {{ background: {ground}; border: 0; }}+QScrollBar:vertical {{ background: {ground}; width: 10px; margin: 0; }}+QScrollBar::handle:vertical {{ background: {edge}; border-radius: 3px; min-height: 32px; margin: 2px; }}+QScrollBar::handle:vertical:hover {{ background: {ink_3}; }}+QScrollBar:horizontal {{ height: 0; }}+QScrollBar::add-line, QScrollBar::sub-line {{ height: 0; width: 0; }}+QScrollBar::add-page, QScrollBar::sub-page {{ background: transparent; }}++QToolTip {{+ background: {well};+ border: 1px solid {edge};+ color: {ink};+ padding: 5px 8px;+}}+QMenu {{ background: {panel}; border: 1px solid {edge}; color: {ink}; padding: 4px; }}+QMenu::item {{ padding: 6px 22px 6px 12px; border-radius: {r_field}px; }}+QMenu::item:selected {{ background: {well}; color: {ink}; }}+QMenu::item:disabled {{ color: {ink_3}; }}+QMenu::separator {{ height: 1px; background: {rule}; margin: 4px 6px; }}+"""+++def apply_titlebar(hwnd: int) -> None:+ """Paints the native title bar at hwnd in the Vernier ground, so it stops following the+ user's accent colour."""+ titlebar.apply_caption(hwnd, P)diff --git a/win_app/titlebar.py b/win_app/titlebar.pynew file mode 100644index 0000000..365512f--- /dev/null+++ b/win_app/titlebar.py@@ -0,0 +1,51 @@+"""Beamer's native title-bar colouring on Windows 11.++Windows paints the ACTIVE window's native caption in the user's accent colour when "Show accent+colour on title bars and window borders" is on (HKCU\\Software\\Microsoft\\Windows\\DWM+ColorPrevalence). DWMWA_USE_IMMERSIVE_DARK_MODE only toggles which of the two system caption themes+is used — it does not opt out of that accent paint, so a window can look right unfocused and turn+accent-coloured the moment it gains focus. DWMWA_CAPTION_COLOR and its neighbours (Windows 11+22H2+) are the documented opt-out.+"""++from __future__ import annotations++import sys++DWMWA_BORDER_COLOR = 34+DWMWA_CAPTION_COLOR = 35+DWMWA_TEXT_COLOR = 36+DWMWA_USE_IMMERSIVE_DARK_MODE = 20+DWMWA_COLOR_NONE = 0xFFFFFFFE+++def _colorref(hex_colour: str) -> int:+ """"#RRGGBB" -> COLORREF (0x00BBGGRR), the byte order DWM's colour attributes expect."""+ value = hex_colour.lstrip("#")+ r, g, b = (int(value[i : i + 2], 16) for i in (0, 2, 4))+ return (b << 16) | (g << 8) | r+++def apply_caption(hwnd: int, palette: dict) -> None:+ """Paints hwnd's native title bar with Vernier's ground, ink and rule from `palette`+ (tokens.PALETTE), replacing the Windows accent colour. Vernier is dark only, so this pins the+ native caption to dark mode too. Cosmetic only: any failure (older Windows, missing dwmapi, a+ bad hwnd) is swallowed so the caller's window still opens."""+ if sys.platform != "win32":+ return+ try:+ import ctypes++ dwmapi = ctypes.windll.dwmapi+ dark = ctypes.c_int(1)+ for attribute in (DWMWA_USE_IMMERSIVE_DARK_MODE, 19): # 19 is the pre-20H1 alias+ if dwmapi.DwmSetWindowAttribute(hwnd, attribute, ctypes.byref(dark), ctypes.sizeof(dark)) == 0:+ break+ caption = ctypes.c_int(_colorref(palette["ground"]))+ dwmapi.DwmSetWindowAttribute(hwnd, DWMWA_CAPTION_COLOR, ctypes.byref(caption), ctypes.sizeof(caption))+ text = ctypes.c_int(_colorref(palette["ink_2"]))+ dwmapi.DwmSetWindowAttribute(hwnd, DWMWA_TEXT_COLOR, ctypes.byref(text), ctypes.sizeof(text))+ border = ctypes.c_int(_colorref(palette["rule"]))+ dwmapi.DwmSetWindowAttribute(hwnd, DWMWA_BORDER_COLOR, ctypes.byref(border), ctypes.sizeof(border))+ except Exception:+ passdiff --git a/win_app/tokens.py b/win_app/tokens.pynew file mode 100644index 0000000..83c7627--- /dev/null+++ b/win_app/tokens.py@@ -0,0 +1,109 @@+"""Beamer's design tokens: the Vernier direction, chosen 10-09-2026.++The mock is docs/designs/claude-2-vernier.html and its reasoning docs/designs/claude-2-vernier-notes.md.+This file is the one home for every colour, size, face and spring both apps draw with. The Mac app+reads it through the root theme.py; win_app/tokens.py is a byte-identical copy because PyInstaller+only bundles what sits under the app, and win_app's tests fail if the two drift. Edit this one, then+copy it across.++Dark only. `signal` is the one colour that means something is happening: the link is up, input is on+Windows, pressure is building, a permission is granted. The mock used lime; it was swapped for+cockpit cyan at build time because lime on near-black is the stock developer-tool look, and B612+Mono is a cockpit face. Reverting is this one value and `signal_dim`.+"""++PALETTE = {+ "ground": "#0e0f0d",+ "panel": "#161714",+ "well": "#1f201c",+ "rule": "#2a2b26",+ "edge": "#6e6f66",+ "ink": "#efeee6",+ "ink_2": "#b3b2a7",+ "ink_3": "#8f8e84",+ "signal": "#5fd4f4",+ "signal_dim": "#1f4a55",+ "amber": "#f2b544",+ "fault": "#ff7a66",+ "off": "#4a4b44",+}++# Measured WCAG ratios, for whoever changes a value: ink on panel 15.5, ink_2 on panel 8.4, ink_3 on+# panel 5.5, edge on panel 3.5 (control boundaries), signal on panel 10.4, ground on signal 11.1,+# amber on panel 9.8, fault on panel 7.1.++UI_FAMILY = "Hanken Grotesk"+MONO_FAMILY = "B612 Mono"+FONT_FILES = (+ "HankenGrotesk-Variable.ttf",+ "B612Mono-Regular.ttf",+ "B612Mono-Bold.ttf",+)++# Points on the Mac, logical pixels on Windows. The `_narrow` sizes apply at the 640 minimum width.+TYPE = {+ "eyebrow": 10.5,+ "readout_key": 9.5,+ "small": 11.5,+ "note": 12.5,+ "body": 13.0,+ "button": 13.0,+ "status_word": 38.0,+ "status_word_narrow": 30.0,+ "readout": 34.0,+ "readout_narrow": 26.0,+ "numeral": 52.0,+ "numeral_narrow": 42.0,+ "keycap": 20.0,+ "field_mono": 13.0,+ "code": 92.0,+}++# Colour choices for the crossing feedback on both machines: `crossing.glow_colour` on the Mac and+# `glow_colour` on Windows. `signal` is the Vernier colour; the rest are Border Beam's palettes+# (libraries.dev/beam), each in the order its colours sit round a border.+PALETTES = {+ "signal": (PALETTE["signal"],),+ "colourful": ("#ff3264", "#ff7828", "#f032b4", "#b428f0", "#6446ff", "#288cff", "#1eb9aa", "#32c850"),+ "ocean": ("#288cff", "#6446ff", "#1eb9aa", "#3c6eff"),+ "sunset": ("#ff7828", "#ff3264", "#ffb43c", "#f03278"),+ "mono": ("#ebebeb", "#969696", "#ebebeb"),+}++# Letter spacing as a fraction of the font size, for the uppercase tracked labels.+TRACKING = {+ "eyebrow": 0.14,+ "readout_key": 0.14,+ "selector": 0.12,+}++RADIUS = {+ "field": 4.0,+ "button": 5.0,+ "segment": 5.0,+ "keycap": 6.0,+}++MODULE_PADDING = (14.0, 16.0)+RACK_GAP = 1.0+MIN_WINDOW = {"mac": (640, 540), "windows": (640, 600)}++# Mass-spring parameters (mass 1) for everything that moves. The notch island integrates two of+# these, width and depth; a trackpad tick adds `tick_velocity` points per second to the width.+SPRING = {+ "island": {"stiffness": 300.0, "damping": 20.0},+ "breakthrough": {"stiffness": 600.0, "damping": 28.0, "seconds": 0.32},+ "tick_velocity": 260.0,+ "flash_seconds": 0.14,+}++ISLAND = {+ "grow_width": 40.0,+ "grow_depth": 26.0,+ "meter_segments": 4,+ "meter_after_depth": 14.0,+}+++def tokens() -> dict:+ return dict(PALETTE)diff --git a/win_app/touchpad_injector.py b/win_app/touchpad_injector.pynew file mode 100644index 0000000..54f1dad--- /dev/null+++ b/win_app/touchpad_injector.py@@ -0,0 +1,220 @@+"""Replays a finger swipe through a synthetic Precision Touchpad so Windows'+own gesture engine recognises it and the user's Settings > Touchpad choices+decide what it does -- Task View for three fingers up, desktop switching for+four fingers sideways, with the same animation real fingers get.++Uses CreateSyntheticPointerDevice2 / InjectSyntheticPointerInput with+PT_TOUCHPAD (Windows 11; documented 28-03-2026 with a pre-release banner,+present on build 26200). Every entry point returns False rather than+raising when the API is missing or refuses, so the caller can fall back to+a keyboard shortcut. Importable on macOS for the tests: nothing touches+user32 until a swipe is asked for.+"""++import ctypes+import logging+import time++LOGGER = logging.getLogger("Beamer")++PT_TOUCHPAD = 5+POINTER_FEEDBACK_NONE = 3+SDCO_PHYSICAL_SIZE = 0x1+SDCO_TOUCHPAD_GESTURE_ONLY = 0x2+POINTER_FLAG_INRANGE = 0x2+POINTER_FLAG_INCONTACT = 0x4+POINTER_FLAG_CONFIDENCE = 0x4000+MAX_CONTACTS = 5++# A 100mm x 60mm pad in himetric (1/100 mm). Only the proportions matter:+# the gesture engine judges a swipe by distance across the pad.+PAD_WIDTH = 10000+PAD_HEIGHT = 6000+FINGER_SPACING = 1500+SWIPE_STEPS = 12+STEP_MS = 10++_DISTANCE = {+ "up": (0, -3000),+ "down": (0, 3000),+ "left": (-4000, 0),+ "right": (4000, 0),+}+++class _POINT(ctypes.Structure):+ _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]+++class _RECT(ctypes.Structure):+ _fields_ = [("left", ctypes.c_long), ("top", ctypes.c_long), ("right", ctypes.c_long), ("bottom", ctypes.c_long)]+++class POINTER_INFO(ctypes.Structure):+ _fields_ = [+ ("pointerType", ctypes.c_uint32),+ ("pointerId", ctypes.c_uint32),+ ("frameId", ctypes.c_uint32),+ ("pointerFlags", ctypes.c_uint32),+ ("sourceDevice", ctypes.c_void_p),+ ("hwndTarget", ctypes.c_void_p),+ ("ptPixelLocation", _POINT),+ ("ptHimetricLocation", _POINT),+ ("ptPixelLocationRaw", _POINT),+ ("ptHimetricLocationRaw", _POINT),+ ("dwTime", ctypes.c_uint32),+ ("historyCount", ctypes.c_uint32),+ ("InputData", ctypes.c_int32),+ ("dwKeyStates", ctypes.c_uint32),+ ("PerformanceCount", ctypes.c_uint64),+ ("ButtonChangeType", ctypes.c_int32),+ ]+++class POINTER_TOUCH_INFO(ctypes.Structure):+ _fields_ = [+ ("pointerInfo", POINTER_INFO),+ ("touchFlags", ctypes.c_uint32),+ ("touchMask", ctypes.c_uint32),+ ("rcContact", _RECT),+ ("rcContactRaw", _RECT),+ ("orientation", ctypes.c_uint32),+ ("pressure", ctypes.c_uint32),+ ]+++class POINTER_PEN_INFO(ctypes.Structure):+ _fields_ = [+ ("pointerInfo", POINTER_INFO),+ ("penFlags", ctypes.c_uint32),+ ("penMask", ctypes.c_uint32),+ ("pressure", ctypes.c_uint32),+ ("rotation", ctypes.c_uint32),+ ("tiltX", ctypes.c_int32),+ ("tiltY", ctypes.c_int32),+ ]+++class _POINTER_TYPE_UNION(ctypes.Union):+ _fields_ = [("touchInfo", POINTER_TOUCH_INFO), ("penInfo", POINTER_PEN_INFO)]+++class POINTER_TYPE_INFO(ctypes.Structure):+ _anonymous_ = ("u",)+ _fields_ = [("type", ctypes.c_uint32), ("u", _POINTER_TYPE_UNION)]+++class SYNTHETIC_DEVICE_CREATION_PARAMS(ctypes.Structure):+ _fields_ = [+ ("pointerType", ctypes.c_uint32),+ ("maxCount", ctypes.c_uint32),+ ("feedbackMode", ctypes.c_uint32),+ ("hMonitor", ctypes.c_void_p),+ ("deviceWidth", ctypes.c_uint32),+ ("deviceHeight", ctypes.c_uint32),+ ("options", ctypes.c_uint32),+ ]+++_user32 = None+_device = None+_unavailable = False+++def _load():+ global _user32+ if _user32 is not None:+ return _user32+ user32 = ctypes.WinDLL("user32", use_last_error=True)+ user32.CreateSyntheticPointerDevice2.restype = ctypes.c_void_p+ user32.CreateSyntheticPointerDevice2.argtypes = [ctypes.POINTER(SYNTHETIC_DEVICE_CREATION_PARAMS)]+ user32.InjectSyntheticPointerInput.argtypes = [+ ctypes.c_void_p,+ ctypes.POINTER(POINTER_TYPE_INFO),+ ctypes.c_uint32,+ ]+ user32.InjectSyntheticPointerInput.restype = ctypes.c_int+ _user32 = user32+ return user32+++def _get_device():+ """The gesture-only device, created once. Gesture-only means its input+ can never be read as a click or a cursor move, only as a gesture."""+ global _device, _unavailable+ if _device is not None or _unavailable:+ return _device+ try:+ user32 = _load()+ params = SYNTHETIC_DEVICE_CREATION_PARAMS(+ PT_TOUCHPAD,+ MAX_CONTACTS,+ POINTER_FEEDBACK_NONE,+ None,+ PAD_WIDTH,+ PAD_HEIGHT,+ SDCO_PHYSICAL_SIZE | SDCO_TOUCHPAD_GESTURE_ONLY,+ )+ _device = user32.CreateSyntheticPointerDevice2(ctypes.byref(params))+ if not _device:+ raise OSError(ctypes.get_last_error(), "CreateSyntheticPointerDevice2 returned NULL")+ except (AttributeError, OSError) as exc:+ _unavailable = True+ LOGGER.warning("Synthetic touchpad unavailable; gestures fall back to shortcuts: %s", exc)+ return _device+++def contact_frames(fingers, direction, steps=SWIPE_STEPS):+ """Pure planning: the himetric positions of each finger at each step,+ as a list of frames, each a list of (x, y). The fingers sit in a row+ across the middle of the pad and move together by the axis distance."""+ dx, dy = _DISTANCE[direction]+ row_width = FINGER_SPACING * (fingers - 1)+ start = [+ ((PAD_WIDTH - row_width) // 2 + i * FINGER_SPACING - dx // 2, PAD_HEIGHT // 2 - dy // 2)+ for i in range(fingers)+ ]+ return [+ [(x + dx * step // steps, y + dy * step // steps) for (x, y) in start]+ for step in range(steps + 1)+ ]+++def swipe(fingers, direction):+ """Replay one swipe. Blocks for about SWIPE_STEPS * STEP_MS ms. Returns+ False when the device or an injection call is refused."""+ if fingers < 1 or fingers > MAX_CONTACTS or direction not in _DISTANCE:+ return False+ device = _get_device()+ if not device:+ return False+ user32 = _load()+ frames = contact_frames(fingers, direction)+ contacts = (POINTER_TYPE_INFO * fingers)()+ down_flags = POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT | POINTER_FLAG_CONFIDENCE++ def send(frame, elapsed_ms, flags):+ for index, (x, y) in enumerate(frame):+ contacts[index].type = PT_TOUCHPAD+ info = contacts[index].touchInfo.pointerInfo+ info.pointerType = PT_TOUCHPAD+ info.pointerId = index+ info.pointerFlags = flags+ info.ptHimetricLocation.x = x+ info.ptHimetricLocation.y = y+ # Every frame must carry a later time than the last, the lift included.+ info.dwTime = 1 + elapsed_ms+ if not user32.InjectSyntheticPointerInput(device, contacts, fingers):+ raise OSError(ctypes.get_last_error(), "InjectSyntheticPointerInput failed")++ try:+ for step, frame in enumerate(frames):+ if step:+ time.sleep(STEP_MS / 1000.0)+ send(frame, step * STEP_MS, down_flags)+ time.sleep(STEP_MS / 1000.0)+ send(frames[-1], (len(frames)) * STEP_MS, POINTER_FLAG_CONFIDENCE)+ except OSError as exc:+ LOGGER.warning("Touchpad swipe injection failed: %s", exc)+ return False+ return Truediff --git a/win_app/unlock_win.py b/win_app/unlock_win.pynew file mode 100644index 0000000..4c28899--- /dev/null+++ b/win_app/unlock_win.py@@ -0,0 +1,188 @@+"""Unlock a locked Windows console so injected input has somewhere to land.++Beamer cannot type on the lock screen and never will: that is the Winlogon+secure desktop, whose security descriptor admits only SYSTEM, and SendInput+only reaches the desktop its calling thread is attached to. Running elevated+clears UIPI, not desktop access -- which is why an admin Beamer still cannot+touch a locked machine.++So this module does not inject into the lock screen. It asks Room Deck's+credential provider to take the machine *off* the lock screen, after which+the console is back on the Default desktop and the ordinary+input_injector.py path works unchanged.++The provider (Room-Deck/room-deck-agent/provider) is a COM DLL that LogonUI+loads as SYSTEM. It waits on an auto-reset event and, when signalled,+submits the password stored in a machine-DPAPI blob. Its event's DACL grants+Authenticated Users EVENT_MODIFY_STATE, so an unelevated Beamer can signal it+and no Beamer process ever holds a password.++Room Deck owns the provider; Beamer only knocks. Shipping a second provider+would put two waiters on one auto-reset event, and losing that race is the+exact bug that cost Room Deck a day (see its 28-08-2026 doc). If the+provider is not installed, every call here fails cleanly and Beamer behaves+as it did before.++Guarded like clipboard_win.py and input_injector.py so it stays importable,+and its orchestration testable, on a machine without ctypes.windll.+"""++import ctypes+import logging+import sys+import time+from typing import Optional+++LOGGER = logging.getLogger(__name__)++_IS_WINDOWS = sys.platform == "win32"++kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) if _IS_WINDOWS else None++# Named by the provider as Global\RoomDeckUnlock.<its own session id>. Global+# rather than Local because an RDP round trip leaves the agent and the console+# in different sessions; the session suffix restores the per-session isolation+# that stops a stale lock screen elsewhere swallowing the auto-reset signal.+UNLOCK_EVENT_PREFIX = "Global\\RoomDeckUnlock."++EVENT_MODIFY_STATE = 0x0002+TH32CS_SNAPPROCESS = 0x00000002+INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value+MAX_PATH = 260++# LogonUI.exe is the lock screen: it exists while the console is locked and+# not otherwise. The session table cannot answer this -- locking does not+# disconnect the console session, which stays Active throughout.+LOCK_SCREEN_PROCESS = "logonui.exe"++UNLOCK_TIMEOUT_SECONDS = 10.0+UNLOCK_POLL_SECONDS = 0.5+++class PROCESSENTRY32W(ctypes.Structure):+ _fields_ = [+ ("dwSize", ctypes.c_ulong),+ ("cntUsage", ctypes.c_ulong),+ ("th32ProcessID", ctypes.c_ulong),+ ("th32DefaultHeapID", ctypes.c_size_t),+ ("th32ModuleID", ctypes.c_ulong),+ ("cntThreads", ctypes.c_ulong),+ ("th32ParentProcessID", ctypes.c_ulong),+ ("pcPriClassBase", ctypes.c_long),+ ("dwFlags", ctypes.c_ulong),+ ("szExeFile", ctypes.c_wchar * MAX_PATH),+ ]+++if _IS_WINDOWS:+ kernel32.OpenEventW.restype = ctypes.c_void_p+ kernel32.OpenEventW.argtypes = [ctypes.c_ulong, ctypes.c_int, ctypes.c_wchar_p]+ kernel32.SetEvent.restype = ctypes.c_int+ kernel32.SetEvent.argtypes = [ctypes.c_void_p]+ kernel32.CloseHandle.restype = ctypes.c_int+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]+ kernel32.WTSGetActiveConsoleSessionId.restype = ctypes.c_ulong+ kernel32.WTSGetActiveConsoleSessionId.argtypes = []+ kernel32.CreateToolhelp32Snapshot.restype = ctypes.c_void_p+ kernel32.CreateToolhelp32Snapshot.argtypes = [ctypes.c_ulong, ctypes.c_ulong]+ kernel32.Process32FirstW.restype = ctypes.c_int+ kernel32.Process32FirstW.argtypes = [ctypes.c_void_p, ctypes.POINTER(PROCESSENTRY32W)]+ kernel32.Process32NextW.restype = ctypes.c_int+ kernel32.Process32NextW.argtypes = [ctypes.c_void_p, ctypes.POINTER(PROCESSENTRY32W)]+++def _running_process_names(mem32) -> Optional[set]:+ """Every running process's image name, lowercased, or None if the+ snapshot could not be taken. Enumeration only reads names and PIDs, so it+ needs no privilege over the processes it lists -- LogonUI runs as SYSTEM+ and still shows up."""+ snapshot = mem32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)+ if not snapshot or snapshot == INVALID_HANDLE_VALUE:+ return None+ try:+ entry = PROCESSENTRY32W()+ entry.dwSize = ctypes.sizeof(PROCESSENTRY32W)+ if not mem32.Process32FirstW(snapshot, ctypes.byref(entry)):+ return None+ names = set()+ while True:+ names.add(entry.szExeFile.lower())+ if not mem32.Process32NextW(snapshot, ctypes.byref(entry)):+ break+ return names+ finally:+ mem32.CloseHandle(snapshot)+++def is_locked(mem32=None) -> Optional[bool]:+ """True if the console is sitting on the lock screen, False if it is not,+ None if that could not be determined. None is deliberately distinct from+ False: an unknown state must not be reported as unlocked, or the caller+ silently skips an unlock the machine actually needed."""+ mem32 = mem32 if mem32 is not None else kernel32+ if mem32 is None:+ return None+ try:+ names = _running_process_names(mem32)+ except Exception:+ LOGGER.exception("Could not enumerate processes to test for the lock screen")+ return None+ if names is None:+ return None+ return LOCK_SCREEN_PROCESS in names+++def signal_unlock(mem32=None) -> bool:+ """Signal the provider's trigger event for the active console session.+ False means the event could not be opened, which normally means the+ provider is not registered on this machine."""+ mem32 = mem32 if mem32 is not None else kernel32+ if mem32 is None:+ return False+ name = f"{UNLOCK_EVENT_PREFIX}{mem32.WTSGetActiveConsoleSessionId()}"+ handle = mem32.OpenEventW(EVENT_MODIFY_STATE, False, name)+ if not handle:+ LOGGER.warning(+ "Could not open %s -- is the Room Deck unlock provider registered?", name+ )+ return False+ try:+ return bool(mem32.SetEvent(handle))+ finally:+ mem32.CloseHandle(handle)+++def ensure_unlocked(+ mem32=None,+ timeout: float = UNLOCK_TIMEOUT_SECONDS,+ poll: float = UNLOCK_POLL_SECONDS,+ sleep=time.sleep,+) -> bool:+ """Get the console off the lock screen so injected input can land.++ True means input has somewhere to go -- either the machine was already+ unlocked, or the provider unlocked it in time. False means it is still+ locked, so the caller should tell the user rather than inject into+ nothing.++ An unknown lock state is treated as unlocked: Beamer's existing behaviour+ is to inject and let it fail visibly, which is better than refusing to+ send input on a machine that was never locked."""+ locked = is_locked(mem32)+ if locked is not True:+ return True+ if not signal_unlock(mem32):+ return False+ deadline = timeout+ while deadline > 0:+ sleep(poll)+ deadline -= poll+ if is_locked(mem32) is False:+ LOGGER.info("Console unlocked after %.1fs", timeout - deadline)+ return True+ LOGGER.error(+ "Console still locked after %.0fs -- see C:\\ProgramData\\RoomDeck\\provider.log",+ timeout,+ )+ return Falsediff --git a/win_app/widgets.py b/win_app/widgets.pynew file mode 100644index 0000000..ccb4fc1--- /dev/null+++ b/win_app/widgets.py@@ -0,0 +1,277 @@+"""The Vernier components the receiver window draws that a stylesheet cannot: module, eyebrow,+LED, the 60-segment countdown and the switch."""++from __future__ import annotations++from PySide6.QtCore import QRectF, QSize, Qt+from PySide6.QtGui import QColor, QPainter+from PySide6.QtWidgets import (+ QCheckBox,+ QFrame,+ QGridLayout,+ QHBoxLayout,+ QLabel,+ QPushButton,+ QSizePolicy,+ QVBoxLayout,+ QWidget,+)++import theme+import tokens+++def label(text: str, role: str, wrap: bool = False) -> QLabel:+ item = QLabel(text)+ item.setProperty("vernier", role)+ item.setWordWrap(wrap)+ return item+++def set_role(widget: QWidget, role: str) -> None:+ if widget.property("vernier") != role:+ widget.setProperty("vernier", role)+ theme.repolish(widget)+++class Eyebrow(QLabel):+ def __init__(self, text: str, parent: QWidget | None = None) -> None:+ super().__init__(text, parent)+ self.setProperty("vernier", "eyebrow")+ self.setFont(theme.eyebrow_font())+++class Module(QFrame):+ """One `panel` cell in the rack, eyebrow first."""++ def __init__(self, title: str, parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self.setProperty("vernier", "module")+ self.body = QVBoxLayout(self)+ vertical, horizontal = (round(v) for v in tokens.MODULE_PADDING)+ self.body.setContentsMargins(horizontal, vertical, horizontal, horizontal)+ self.body.setSpacing(12)+ self.eyebrow = Eyebrow(title)+ self.body.addWidget(self.eyebrow)+ self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Preferred)+++class Led(QWidget):+ def __init__(self, tone: str = "off", parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self.tone = tone+ self.setFixedSize(QSize(8, 8))++ def set_tone(self, tone: str) -> None:+ if tone != self.tone:+ self.tone = tone+ self.update()++ def paintEvent(self, _event) -> None:+ painter = QPainter(self)+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)+ painter.setPen(Qt.PenStyle.NoPen)+ painter.setBrush(QColor(theme.colour(self.tone)))+ painter.drawEllipse(0, 0, 8, 8)+++class Drain(QWidget):+ """Sixty segments, one per second of the code's life, emptying left to right in `rule`."""++ SEGMENTS = 60++ def __init__(self, parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self.remaining = 0+ self.setFixedHeight(12)+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)++ def set_remaining(self, seconds: int) -> None:+ seconds = max(0, min(self.SEGMENTS, int(seconds)))+ if seconds != self.remaining:+ self.remaining = seconds+ self.update()++ def paintEvent(self, _event) -> None:+ painter = QPainter(self)+ gap = 1.0+ width = (self.width() - gap * (self.SEGMENTS - 1)) / self.SEGMENTS+ lit, spent = QColor(theme.colour("signal")), QColor(theme.colour("rule"))+ for index in range(self.SEGMENTS):+ painter.fillRect(+ QRectF(index * (width + gap), 0, width, self.height()),+ lit if index < self.remaining else spent,+ )+++def rule(vertical: bool = True) -> QWidget:+ """A one-pixel divider in `rule`, the sidebar/content seam or a horizontal seam under it."""+ widget = QWidget()+ widget.setProperty("vernier", "rule")+ if vertical:+ widget.setFixedWidth(1)+ else:+ widget.setFixedHeight(1)+ return widget+++class Choice:+ """A row of exclusive Vernier choice buttons, `columns` wide. Pick a divisor of+ `len(items)` so a wrap never orphans one. `on_change(value)` fires only on a real+ click -- never on `set_value`, so refreshing from an incoming setting cannot loop back."""++ def __init__(self, items, columns: int, current: str, on_change=None, parent: QWidget | None = None) -> None:+ self.view = QWidget(parent)+ self.view.setProperty("vernier", "plain")+ grid = QGridLayout(self.view)+ grid.setContentsMargins(0, 0, 0, 0)+ grid.setSpacing(4)+ self._buttons: dict = {}+ for index, (value, text) in enumerate(items):+ button = QPushButton(text)+ button.setProperty("vernier", "choice")+ button.setCheckable(True)+ button.setAutoExclusive(True)+ button.setCursor(Qt.CursorShape.PointingHandCursor)+ button.setChecked(value == current)+ if on_change is not None:+ button.clicked.connect(lambda _checked=False, v=value: on_change(v))+ grid.addWidget(button, index // columns, index % columns)+ self._buttons[value] = button++ @property+ def value(self):+ return next((value for value, button in self._buttons.items() if button.isChecked()), None)++ def set_value(self, value) -> None:+ button = self._buttons.get(value)+ if button is not None and not button.isChecked():+ button.setChecked(True)++ def set_enabled(self, enabled: bool) -> None:+ for button in self._buttons.values():+ button.setEnabled(enabled)+++class PageButton(QPushButton):+ """One entry in the sidebar's page list, with an optional tone dot for a page that+ needs attention."""++ def __init__(self, text: str, parent: QWidget | None = None) -> None:+ super().__init__(text, parent)+ self.setProperty("vernier", "page")+ self.setCheckable(True)+ self.setAutoExclusive(True)+ self.setCursor(Qt.CursorShape.PointingHandCursor)+ self._dot = None++ def set_dot(self, tone: str | None) -> None:+ if tone != self._dot:+ self._dot = tone+ self.update()++ def paintEvent(self, event) -> None:+ super().paintEvent(event)+ if self._dot is None:+ return+ painter = QPainter(self)+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)+ painter.setPen(Qt.PenStyle.NoPen)+ painter.setBrush(QColor(theme.colour(self._dot)))+ size = 6+ painter.drawEllipse(QRectF(self.width() - size - 10, (self.height() - size) / 2, size, size))+++class Sidebar(QWidget):+ """The page list, with the link state pinned above it. `on_select(key)` fires on a+ click; the window drives `select`/`set_link`/`set_dots` the rest of the time."""++ def __init__(self, pages, on_select, parent: QWidget | None = None) -> None:+ super().__init__(parent)+ self.setProperty("vernier", "sidebar")+ outer = QVBoxLayout(self)+ outer.setContentsMargins(0, 0, 0, 0)+ outer.setSpacing(0)++ link = QWidget()+ link.setProperty("vernier", "plain")+ link_layout = QHBoxLayout(link)+ link_layout.setContentsMargins(16, 16, 16, 16)+ link_layout.setSpacing(8)+ self.link_led = Led()+ link_layout.addWidget(self.link_led, 0, Qt.AlignmentFlag.AlignVCenter)+ self.link_word = label("", "sidebar-link")+ link_layout.addWidget(self.link_word, 1)+ outer.addWidget(link)+ outer.addWidget(rule(vertical=False))++ list_layout = QVBoxLayout()+ list_layout.setContentsMargins(8, 8, 8, 8)+ list_layout.setSpacing(2)+ self._buttons: dict = {}+ for key, name, _purpose in pages:+ button = PageButton(name)+ button.clicked.connect(lambda _checked=False, k=key: on_select(k))+ list_layout.addWidget(button)+ self._buttons[key] = button+ list_layout.addStretch(1)+ outer.addLayout(list_layout)++ def select(self, key: str) -> None:+ button = self._buttons.get(key)+ if button is not None and not button.isChecked():+ button.setChecked(True)++ def set_link(self, tone: str, word: str) -> None:+ self.link_led.set_tone(tone)+ if self.link_word.text() != word:+ self.link_word.setText(word)++ def set_dots(self, marks: dict) -> None:+ for key, button in self._buttons.items():+ button.set_dot(marks.get(key))+++class Switch(QCheckBox):+ """A QCheckBox drawn as Vernier's switch: label left, track right."""++ TRACK = QSize(34, 18)++ def __init__(self, text: str, parent: QWidget | None = None) -> None:+ super().__init__(text, parent)+ self.setCursor(Qt.CursorShape.PointingHandCursor)+ self.setMinimumHeight(24)++ def sizeHint(self) -> QSize:+ text = self.fontMetrics().horizontalAdvance(self.text())+ return QSize(text + 12 + self.TRACK.width() + 4, max(24, self.TRACK.height() + 6))++ def hitButton(self, pos) -> bool:+ return self.rect().contains(pos)++ def paintEvent(self, _event) -> None:+ painter = QPainter(self)+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)+ on = self.isChecked()+ track = QRectF(+ self.width() - self.TRACK.width() - 2.5,+ (self.height() - self.TRACK.height()) / 2 + 0.5,+ self.TRACK.width(),+ self.TRACK.height() - 1,+ )+ if self.hasFocus():+ painter.setPen(QColor(theme.colour("signal")))+ painter.setBrush(Qt.BrushStyle.NoBrush)+ painter.drawRoundedRect(track.adjusted(-2, -2, 2, 2), 11, 11)+ painter.setPen(QColor(theme.colour("signal" if on else "edge")))+ painter.setBrush(QColor(theme.colour("well")))+ painter.drawRoundedRect(track, track.height() / 2, track.height() / 2)+ painter.setPen(Qt.PenStyle.NoPen)+ painter.setBrush(QColor(theme.colour("signal" if on else "ink_3")))+ knob = 12.0+ x = track.right() - knob - 2.5 if on else track.left() + 2.5+ painter.drawEllipse(QRectF(x, track.center().y() - knob / 2, knob, knob))+ painter.setPen(QColor(theme.colour("ink")))+ painter.setFont(self.font())+ text_rect = QRectF(0, 0, track.left() - 12, self.height())+ painter.drawText(text_rect, Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, self.text())