Skip to content

One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.

Beamer 1.3.0

Toby Kalkman094603afbffb
diff --git a/README.md b/README.md
index cc02b47..c695f3f 100644
--- a/README.md
+++ b/README.md
@@ -1,154 +1,331 @@
-# 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.
+<p align="center"><img src="Beamer.svg" width="96" height="96" alt=""></p>
+<h1 align="center">Beamer</h1>
+<p align="center">One keyboard and one mouse or trackpad for a Mac and a Windows PC on the same network, in either direction.</p>
+<p align="center">
+ <a href="https://github.com/kalkman-code/beamer/releases/latest"><img src="https://img.shields.io/github/v/release/kalkman-code/beamer" alt="Latest release"></a>
+ <a href="LICENSE"><img src="https://img.shields.io/github/license/kalkman-code/beamer" alt="Licence"></a>
+ <img src="https://img.shields.io/badge/platforms-macOS%20%7C%20Windows-lightgrey" alt="Platforms: macOS and Windows">
+ <a href="https://github.com/kalkman-code/beamer/releases"><img src="https://img.shields.io/github/downloads/kalkman-code/beamer/total" alt="Downloads"></a>
+</p>
+
+![The pointer is pushed against the right-hand edge of a Mac's screen, the edge lights up as the push builds, and the pointer carries on onto the Windows PC beside it at the same height](assets/beamer-crossing.gif)
+
+Push the pointer off the edge of the screen and it carries on onto the other machine, the way it
+would onto a second monitor. Or double-tap a key. The clipboard comes with you, your shortcuts
+still work, and nothing leaves your network.
## 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 licensed under the GNU General Public License v3.0; see `LICENSE`. Releases up to and including 1.2.0 were MIT.
-
-## 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:
+Free, with no account. Every installer is on the [releases page](https://github.com/kalkman-code/beamer/releases/latest).
+
+| Platform | Get it | Notes |
+|---|---|---|
+| macOS 13 or later | `Beamer-<version>.dmg` | Signed and notarised by Apple |
+| Windows 10 and 11 | `Beamer-Setup-<version>.exe` | Not code-signed; see step 1 below |
+| Windows, through winget | `winget install KalkmanCode.Beamer` | The same installer, without the warning |
+
+## Quick start
+
+1. **Install on both machines.** On the Mac, drag Beamer to Applications, open it, and press the
+ two Grant buttons on the Permissions page (Accessibility, then Input Monitoring). On Windows,
+ run the installer. It is not code-signed, because a certificate costs money and Beamer is free,
+ so Windows says "Windows protected your PC" the first time: choose More info, then Run anyway.
+ winget does not show that warning. Beamer on Windows runs as administrator, so expect one UAC
+ prompt when you open it.
+2. **Pair them.** On the PC, press Pair a Mac; a six-digit code appears. On the Mac, open the
+ Pairing page, choose the PC from the list and type the code. It lasts a minute and works once.
+3. **Cross.** Push the Mac's pointer off the right-hand edge of its screen, or double-tap Right
+ Option, and the Mac's keyboard and trackpad are on the PC. Push back through the PC's left edge,
+ or double-tap again, to come home. The PC's own keyboard and mouse go the other way: push
+ through the same edge, or double-tap Right Ctrl.
+
+That is all most people need. The edge, the keys and everything else can be changed in each
+machine's settings.
+
+## Screenshots
+
+| Mac | Windows |
+|---|---|
+| <img src="assets/mac-overview.png" width="400" alt="Beamer's Overview page on the Mac: where input is, whether the link is up, and the two everyday controls"> | <img src="assets/windows-overview.png" width="400" alt="Beamer's Overview page on Windows: where input is, and a switch for each direction"> |
+| <img src="assets/mac-design.png" width="400" alt="Beamer's Design page on the Mac: the notch and edge styles with live previews, and the colour schemes"> | <img src="assets/windows-design.png" width="400" alt="Beamer's Design page on Windows: the glow switch, Glow and Beam with live previews, and the colour schemes"> |
+
+## What it does
+
+- **Push through the edge.** Off the edge that faces the other machine, through a corner, or up
+ through the MacBook's notch. The pointer arrives at the same point along the border. The edge
+ lights up as you push, and the trackpad ticks at every quarter of the way through.
+- **Or press a key.** Double-tap or hold a trigger key to switch without moving the pointer. Right
+ Option on the Mac and Right Ctrl on the PC to start with; on the Mac it can be any key you like.
+- **Either way round.** The Mac drives the PC and the PC drives the Mac. Each machine has a switch
+ per direction, so you can turn one way off and keep the other.
+- **The clipboard comes with you.** Text and images, both ways, at the moment you switch. Files
+ stay where they are.
+- **Your shortcuts still work.** Cmd becomes Ctrl and Option becomes Alt on Windows, so Cmd+C
+ copies there too. The PC gets the reverse: its Ctrl+C arrives on the Mac as Cmd+C.
+- **Media keys follow you.** Play, pause, skip, mute and volume act on whichever machine you are
+ driving. Brightness stays with the Mac.
+- **Keys and buttons that stay put.** Each machine keeps a list of keys and mouse buttons that keep
+ working where they were pressed while its input is on the other one: a mouse's back button for
+ this machine's browser, a volume key for its speakers. Add one by pressing it. The back and
+ forward side buttons cross in both directions otherwise.
+- **Mac gestures on Windows.** Three or four fingers up for Task View, down for the desktop, left
+ and right to change virtual desktop, all from the Mac's trackpad.
+- **Make it yours.** The edge as a glow or a beam, five colour schemes, the notch as a beam or an
+ island with a meter, and how hard you push before it crosses.
+- **Out of the way when it should be.** A full-screen app holds the edges, so a game or a film never
+ loses the pointer; the trigger key still works. Switch to a PC that is asleep and Beamer wakes it.
+- **Your network, nobody else's.** No server in the middle. The two machines talk to each other
+ directly, encrypted, and you pair them once with a six-digit code. More in [SECURITY.md](SECURITY.md).
+- **Free and open source.** No account, no subscription, GPL-3.0.
+
+## Settings
+
+Each machine has its own settings window and makes its own choices about how input leaves it.
+Both sidebars end with the version and a link to kalkmancode.co.uk/beamer, and both menus have
+About Beamer.
+
+| Page | Mac | Windows |
+|---|---|---|
+| Overview | Where input is, the link, the everyday controls, start at login | Where input is, a switch per direction, start at sign-in |
+| Crossing | Ways in (edge, corner, notch, shortcut), which edge, resistance | Ways in (edge, corner, shortcut), the arrangement with the Mac, resistance |
+| Design | Notch style, edge glow or beam, colour scheme, haptics, with live previews | Glow on or off, Glow or Beam, colour scheme, with live previews |
+| Keyboard | Trigger key (recorded), double-tap or hold, modifier style, what stays on this Mac | Trigger key, double-tap or hold, what stays on this PC |
+| Pairing | Choose a PC and type its code | Pair a Mac shows the code |
+| Connection | The PC's address, port and token | This PC's address, port and token |
+| Permissions / Firewall | Accessibility and Input Monitoring | Whether Windows Firewall lets the Mac in, with a one-button fix |
+
+Which edge of the Mac leads to the PC is one setting either machine can change; the two keep it in
+step, so the border is always the same one seen from both ends.
+
+## Known limits
+
+- **The Windows secure desktop cannot be driven.** UAC prompts, Ctrl+Alt+Del and the lock screen
+ refuse input from any app by design, and Ctrl+Alt+Del cannot be sent at all. Use the PC's own
+ keyboard there.
+- **Files do not cross**, only text and images, up to 256KB of text and an 8MB image.
+- **AltGr is out of reach from the Mac.**
+- **The Windows installer is unsigned.** SmartScreen warns until it has a download history; winget
+ avoids it.
+- **macOS 27 beta 4 could block a signed app's local-network access** even when Terminal could
+ reach the PC. The DMG includes `Beamer Tunnel.command` for that case: open it, leave its window
+ running, then open Beamer, which uses the tunnel only when its direct connection is blocked.
+
+## In detail
+
+<details>
+<summary><strong>Connection states</strong></summary>
+
+Written from the Mac, which connects to the PC. The PC's link to the Mac reports the mirror of
+them, naming the Mac.
+
+| Status | Meaning |
+|---|---|
+| `Connected to <address>:<port>` | The encrypted link is up: the PC decrypted the Mac's first frame, so both hold the same token, and the protocol versions match. Reads `Connected to Windows via secure macOS 27 fallback` when the tunnel is carrying it. |
+| `Windows is reachable, but Beamer is not listening on this port.` | The PC answered but nothing accepted the TCP port. |
+| `Windows could not be authenticated — check the shared token matches on both sides` | The two derived different keys. The tokens differ. |
+| `Windows is unreachable from this Mac` | Nothing got as far as Beamer or the firewall. Check Wi-Fi client isolation, the PC's network, and that the Mac can resolve its address. |
+| `Windows did not answer the handshake — it is probably running an older Beamer; update it` | A PC that has never completed a handshake this run is silent, as a Beamer from before encryption is. |
+| `Windows receiver speaks Beamer protocol vN, this Mac vM — update both apps` | The wire versions differ. The version travels in cleartext at the start of the connection, so a mismatch says so rather than hanging. |
+| `Windows stopped responding` | No ping or acknowledgement for about two seconds. |
+
+Both ends notice a dead link within a few seconds. The PC enforces a 2.5-second read timeout and
+the Mac pings at least once a second while idle, so the PC is back to waiting for the Mac within
+about three seconds; the Mac notices in about two and takes its input back.
+
+The Mac always fails open. A dropped connection, a missing acknowledgement, a crashed capture
+worker or a full event queue returns input to the Mac at once. A watchdog runs for as long as a
+socket exists, so a half-open connection is caught and the Mac reconnects even if you never
+switched. Trying to switch while the link is down beeps and posts a notification.
+
+</details>
+
+<details>
+<summary><strong>Crossing</strong></summary>
+
+Push the pointer at the outer edge and it does not move: the push builds as pressure, the edge
+lights up, the trackpad ticks at each quarter, and once you have pushed far enough the boundary
+gives. The resistance is the point. An edge that switches the instant you touch it does so every
+time you overshoot a close button. The default is 120 points; zero switches on contact.
+
+| Way in | Where it triggers | Mac | PC |
+|---|---|---|---|
+| Shortcut | Double-tap the trigger key, or hold it | Yes | Yes |
+| Edge | The whole of one outer edge of the desktop | Yes | Yes |
+| Corner | An 8pt box in one corner, needing a diagonal push | Yes | Yes |
+| Notch | The top edge, only within the notch's width | Yes | No |
+
+Any combination can be on. On the Mac, shortcut and the right-hand edge are on to start with.
+
+- The notch has no pixels to light, so a push there draws on the notch itself. Beam, the default,
+ runs a comet of light round a small tab under the notch that brightens and speeds up with the
+ push. Island springs a black island out of the notch with a four-segment meter; with Reduce
+ Motion on it stays one size and fades with the push.
+- Only the outer boundary of the whole desktop counts, so an edge between two displays on the same
+ machine behaves as the system intends.
+- The pointer arrives where it left: 42% of the way down the Mac's right edge is 42% of the way
+ down the PC's left edge, on whichever monitor owns it.
+- Crossing never fires while a mouse button is held, because a drag that reaches the edge is a drag.
+- It suspends itself while a full-screen app has focus. Pause crossing in the Mac's menu bar puts it
+ away until you resume it or restart Beamer.
+- Only one machine's input is on the other at a time. While the Mac drives the PC, pushing the PC's
+ own mouse through the edge sends the Mac's input home and takes the PC's mouse across behind it.
+- Either machine's own switch, the menu item or the trigger key, sends the other's input home, so a
+ way back never depends on the edge alone.
+- Switching to a PC that is asleep sends wake-on-LAN. The PC's hardware address is read from the
+ Mac's ARP table after a successful connection, never typed.
+
+Each machine's menu has one tick per direction: This Mac drives Windows and Windows drives this
+Mac on the Mac, Mac drives this PC and This PC drives the Mac in the Windows tray. Turning one off
+stops that direction only.
+
+</details>
+
+<details>
+<summary><strong>Keys, buttons and media keys</strong></summary>
+
+Mac modifiers map to Windows by meaning, so the shortcuts your fingers know keep working. The
+Mac's Keyboard page can switch this to positional, where Cmd sends the Windows key.
| 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.
+So Cmd+C, Cmd+V, Cmd+Z and Cmd+T are copy, paste, undo and new tab, Ctrl+E opens Explorer and Ctrl
+on its own opens Start. The PC's keys arrive on the Mac the reverse way. Chords with Ctrl, Alt or
+Windows held are sent as real virtual-key presses, so they land on the right key for the active
+Windows keyboard layout. The `key_map` object in each app's config JSON can still override single
+keys.
-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.
+The trigger key is never forwarded. On the Mac it is recorded by pressing it, Right Option to start
+with; on the PC it is one of eight modifier and Menu keys, Right Ctrl to start with. Either can
+double-tap or hold.
-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.
+The stays-here list is per machine, because a Mac keycode and a Windows virtual key are different
+numbers for the same key. It takes keys, the right, middle, back and forward mouse buttons, and on
+the Mac its media keys. A listed press stays on the machine it was pressed on while input is away;
+its release goes wherever its press went, so nothing is ever left held down on the far side. The
+trigger key cannot be added.
-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.
+The F7–F12 media row and the volume keys forward as play/pause, next, previous, mute and volume.
+On the Mac they arrive as system events rather than key events and are captured separately
+(`mac_app/media_keys.py`). Brightness and keyboard-backlight keys stay with macOS, since Windows has
+no equivalent.
-## Crossing
+Ctrl+Alt+Del is the Secure Attention Sequence, trapped by the kernel before any app sees it.
+`SendInput` cannot produce it, and `SendSAS()` needs a Windows service or a signed `uiAccess` app
+installed under Program Files, which Beamer is not.
-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.
+</details>
-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.
+<details>
+<summary><strong>Gestures</strong></summary>
-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.
+Trackpad scrolling is smooth and horizontal scrolling works on Windows. While input is on the PC,
+the Mac's system gestures do the equivalent thing there and nothing on the Mac:
-There are four ways in and any combination can be on at once:
+| 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 |
+| Two-finger pinch | Zoom (Ctrl+scroll) |
+| Two-finger swipe between pages | Back and forward (Alt+Left/Right) |
-| 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 |
+The Mac classifies a system gesture when it ends and sends one message. The PC replays it as a real
+swipe through a synthetic Precision Touchpad, so Windows' own touchpad settings apply and Task View
+animates as it would under fingers. Where Windows refuses that device, it presses the shortcut with
+the same default meaning instead (Win+Tab, Win+D, Win+Ctrl+Left/Right, Win). Direction comes from
+private macOS event fields, keyed by macOS major version in `mac_app/gestures.py`, because the
+horizontal sign has flipped between releases.
-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.
+</details>
-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.
+<details>
+<summary><strong>Clipboard</strong></summary>
-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.
+The clipboard moves at the moment of a switch, ahead of the switch itself: switching from the Mac
+carries the Mac's clipboard to the PC, and switching back carries the PC's to the Mac. Where it
+holds both an image and text, both cross and the pasting app picks. The caps keep the switch
+prompt: 256KB of text and an 8MB image as PNG. Over a cap, that half is left alone rather than
+truncated. The PC converts to and from the Windows clipboard's DIB format itself, using the Qt it
+already ships.
-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.
+</details>
-## Media keys
+<details>
+<summary><strong>Latency</strong></summary>
-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.
+If both machines are on Wi-Fi, every event crosses the air twice, Mac to access point to PC.
+Ethernet on either machine removes a hop. Where Wi-Fi is unavoidable, 5GHz or 6GHz and turning off
+power saving on the PC's adapter both help.
-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.
+Beamer sends every event at once (TCP_NODELAY). Acknowledgements are coalesced over 15ms so a
+100Hz stream of moves cannot double the packet count, with an idle heartbeat every 400ms. The Mac's
+settings show the measured round trip while input is on the PC.
-## Clipboard
+</details>
-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.
+<details>
+<summary><strong>Security</strong></summary>
-## Gestures
+Both apps derive a key from the shared token with HKDF-SHA256 and seal every frame with
+ChaCha20-Poly1305. The token is never sent. Pairing agrees a token over X25519, with each side
+proving it knows the six-digit code. What that does and does not protect against is in
+[SECURITY.md](SECURITY.md).
-Trackpad scrolling is smooth and supports horizontal motion on Windows, always.
+</details>
-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:
+<details>
+<summary><strong>Windows specifics</strong></summary>
-| 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 |
+The installer puts Beamer in `%LOCALAPPDATA%\Beamer` for the current user with a Start menu
+shortcut. Quit Beamer from the tray before installing a newer version over it; only one instance
+runs at a time.
+
+Beamer runs elevated (its exe carries a `requireAdministrator` manifest), because Windows silently
+drops input from a non-elevated app aimed at an elevated window such as an admin PowerShell. Start
+Beamer when you sign in, on Overview, writes and removes an elevated `Beamer` logon task; nothing
+else touches autostart.
+
+Beamer needs two inbound rules on Private networks: TCP 24820 for input and UDP 24821 for pairing,
+both below the range Windows and macOS hand out for themselves. The app adds them on its first
+elevated start. The Firewall page says in one sentence whether the Mac can get in and offers one
+button for whichever of three things usually stops it: the rule is missing (it adds it), Cancel was
+pressed on Windows' own "allow this app" prompt, which writes a block rule that beats any allow rule
+(it removes the block and adds the rule), or the network is classed as public (it marks the network
+private rather than opening the port on every public network).
-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.
+**The lock screen.** No elevation lets an app type there: it is the Winlogon secure desktop, which
+admits only SYSTEM. On a PC with the author's separate unlock credential provider installed (not
+part of this repository), switching to a locked PC signals that provider, which unlocks it in about
+four seconds; input sent meanwhile is dropped. Beamer only signals the provider and never holds a
+password. Without it, the Mac reports `Windows is locked — unlock it at the PC`.
-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.
+</details>
-## Latency
+<details>
+<summary><strong>Building from source</strong></summary>
-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.
+On the Mac, double-click `mac_app/Install-Beamer-Mac.command`. It builds a self-contained app,
+installs it at `/Applications/Beamer.app`, and leaves it closed so the permission prompts do not
+appear unexpectedly.
-## Switching a direction off
+On Windows, run `win_app\Install-Beamer.ps1` from an admin PowerShell. It builds and installs
+`%LOCALAPPDATA%\Beamer\Beamer.exe`, adds a Start menu shortcut and the two firewall rules. From a
+non-admin PowerShell it still installs but skips the rules, which the app adds on its first
+elevated start.
-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.
+Pairing is the easy path, not the only one: each Connection page still takes an address, port and
+shared token typed by hand, and they must match on both machines.
-## Development checks
+</details>
+
+<details>
+<summary><strong>Development checks</strong></summary>
From `mac_app`:
@@ -164,19 +341,36 @@ 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.
+A local Mac build is signed with the release's Developer ID identity when the login keychain can
+reach it, so privacy grants carry between local builds and releases, and ad-hoc otherwise (over
+SSH), under the hardened runtime either way. It is not notarised.
+
+Files shared by both apps (`receiver.py`, `return_edge.py`, `pairing.py`, `ignored.py`, `tokens.py`
+and others) are byte-identical copies, because each app bundles only what sits under it; a test
+fails if a pair drifts. `Beamer.svg` is the master of the mark, and `Beamer.ico`, `Beamer.png` and
+`Beamer.icns` are rendered from it.
+
+</details>
-## Release builds
+<details>
+<summary><strong>Release builds</strong></summary>
-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.
+The version lives once, in `VERSION` at the repository root; the Mac build number is the commit
+count. Change `VERSION`, commit, then build each platform from that commit. Both commands refuse
+uncommitted changes outside `docs/`, upload nothing except the Mac's notary submissions, and 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):
+On the Mac, from `mac_app`, in a desktop 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.
+It signs every nested binary with Developer ID under the hardened runtime with a secure timestamp,
+checks the bundle still runs, notarises and staples the app, then the DMG, and checks both with
+`stapler validate` and `spctl`. Notarisation uses the App Store Connect API key named in
+`~/.appstoreconnect/key_id`.
On Windows, from `win_app`:
@@ -184,6 +378,15 @@ On Windows, from `win_app`:
.\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.
+It runs the tests, builds `Beamer.exe` and compiles `Beamer-Setup.iss` with Inno Setup 6 into
+`Beamer-Setup-<version>.exe`. The installer adds no firewall rules and leaves autostart off.
+
+</details>
+
+## Licence and support
+
+GPL-3.0; see [LICENSE](LICENSE). Releases up to and including 1.2.0 were MIT.
-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.
+Beamer is free and made by one person. Issues are welcome and read, but there is no guarantee of a
+reply. Report security problems privately, as [SECURITY.md](SECURITY.md) describes. Home page:
+[kalkmancode.co.uk/beamer](https://kalkmancode.co.uk/beamer).
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..f1aa133
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,53 @@
+# Security
+
+Beamer sends your keystrokes, pointer and clipboard between two machines, so the link between
+them matters. This is what it protects, what it does not, and how to report a problem.
+
+## What the link protects
+
+- **Every frame is encrypted and authenticated.** Both apps derive a key from the shared token with
+ HKDF-SHA256 and seal every frame with ChaCha20-Poly1305. A peer that cannot decrypt the first
+ frame does not hold the token, and the connection goes no further.
+- **The token is never sent.** Not when connecting, and not when pairing.
+- **Captured frames cannot be replayed.** Each frame carries a counter the receiver requires to
+ advance by one, and every connection starts from a fresh random nonce prefix.
+- **Pairing is a six-digit code that lasts a minute and works once.** The two machines agree a
+ token over X25519, and each proves it knows the code with an HMAC keyed from it (scrypt, salted
+ per code). The code itself never crosses the network. The PC uses up its code on the first
+ answer it receives, right or wrong, so each code allows one guess, and a new code needs someone
+ at the PC to press Pair a Mac again.
+- **Traffic stays on your network.** The two machines talk to each other directly. There is no
+ server, no account and no telemetry. On Windows, the firewall rules Beamer adds apply to Private
+ networks only.
+- **Strangers cannot tie it up cheaply.** A connection must authenticate within a deadline and
+ within 4KB, and only a handful of unauthenticated connections are held at once.
+
+## What it does not protect against
+
+- **Anyone on your network can see that Beamer is running.** The PC broadcasts a small beacon every
+ two seconds with its name and Beamer's port, and both machines listen on TCP 24820. Anyone can
+ send to the pairing port on UDP 24821 while a code is on screen.
+- **Someone on your network while you pair can interfere.** A junk answer uses up the code and
+ stops that pairing. An attacker who answers the Mac in the PC's place during that minute receives
+ a proof they can try all million codes against offline, and with enough hardware could pair as
+ the other machine. The scheme trusts your network for the minute a code is on screen. Pair on a
+ network you trust.
+- **A machine that holds the token is trusted completely.** It can type and click anything on the
+ other machine. On Windows that includes admin windows, because Beamer runs elevated so it can
+ reach them. Treat the token like a password.
+- **The token is stored in each app's settings file**, in the user's own profile: under
+ `~/Library/Application Support/Beamer` on the Mac, readable only by that user, and under
+ `%LOCALAPPDATA%\Beamer` on Windows. Anyone who can read that file can act as the paired machine.
+ Pairing again replaces it.
+- **Malware on either machine.** Anything that can read your keyboard or the settings file on one
+ machine already has what Beamer would protect.
+- **Traffic analysis.** Encryption hides what you type, not when. Someone watching the network can
+ see that the two machines are talking and the size and timing of frames. The protocol version
+ byte at the start of each connection is sent in the clear.
+
+## Reporting a vulnerability
+
+Please report privately, not in a public issue. On
+[github.com/kalkman-code/beamer](https://github.com/kalkman-code/beamer), open the Security tab and
+choose Report a vulnerability. Say what you found, how to reproduce it, and which version and
+platform. Beamer is made by one person, so there is no fixed response time.
diff --git a/VERSION b/VERSION
index 26aaba0..f0bb29e 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.2.0
+1.3.0
diff --git a/assets/beamer-crossing.gif b/assets/beamer-crossing.gif
new file mode 100644
index 0000000..9b58abb
Binary files /dev/null and b/assets/beamer-crossing.gif differ
diff --git a/assets/mac-design.png b/assets/mac-design.png
new file mode 100644
index 0000000..ae7f652
Binary files /dev/null and b/assets/mac-design.png differ
diff --git a/assets/mac-overview.png b/assets/mac-overview.png
new file mode 100644
index 0000000..9612252
Binary files /dev/null and b/assets/mac-overview.png differ
diff --git a/assets/windows-design.png b/assets/windows-design.png
new file mode 100644
index 0000000..48ca1ea
Binary files /dev/null and b/assets/windows-design.png differ
diff --git a/assets/windows-overview.png b/assets/windows-overview.png
new file mode 100644
index 0000000..b4ed4db
Binary files /dev/null and b/assets/windows-overview.png differ
diff --git a/mac_app/bridge.py b/mac_app/bridge.py
index b9d695a..4ea3170 100644
--- a/mac_app/bridge.py
+++ b/mac_app/bridge.py
@@ -17,6 +17,7 @@ import clipboard_mac
import crossing
from input_injector_mac import INJECTED_MARK
import gestures
+import ignored
import media_keys
import protocol
from key_codes import (
@@ -131,6 +132,10 @@ NX_DEVICE_MODIFIER_BITS = {
# excluded on purpose -- see _unicode_character.
CHORD_MODIFIER_KEY_CODES = frozenset({0x36, 0x37, 0x3A, 0x3B, 0x3D, 0x3E})
+# CoreGraphics numbers the other buttons from 2; 3 and 4 are a mouse's back and forward side
+# buttons, which Windows calls XBUTTON1 and XBUTTON2.
+WIRE_OTHER_BUTTONS = {2: "middle", 3: "back", 4: "forward"}
+
_ALL_NX_DEVICE_MODIFIER_BITS = 0
for _bit in NX_DEVICE_MODIFIER_BITS.values():
_ALL_NX_DEVICE_MODIFIER_BITS |= _bit
@@ -241,17 +246,11 @@ class QuartzEventTranslator:
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:
+ name, is_down = self.button_of(event_type, event)
+ if name not in WIRE_OTHER_BUTTONS.values():
return []
- message_type = (
- protocol.MSG_MOUSEDOWN
- if event_type == quartz.kCGEventOtherMouseDown
- else protocol.MSG_MOUSEUP
- )
- return [{"type": message_type, "data": {"button": "middle"}}]
+ message_type = protocol.MSG_MOUSEDOWN if is_down else protocol.MSG_MOUSEUP
+ return [{"type": message_type, "data": {"button": name}}]
if event_type == quartz.kCGEventScrollWheel:
is_continuous = bool(
quartz.CGEventGetIntegerValueField(event, quartz.kCGScrollWheelEventIsContinuous)
@@ -281,6 +280,24 @@ class QuartzEventTranslator:
return [{"type": protocol.MSG_SCROLL, "data": {"dy": dy, "dx": dx, "mode": "line"}}]
return []
+ def button_of(self, event_type, event):
+ """(name, is_down) for a button event, else None. Left, right and the other buttons by
+ name where the wire has one -- middle, back, forward -- and by their 1-based number
+ where it does not, so a sixth button can still be kept on this Mac."""
+ quartz = self.quartz
+ fixed = {
+ quartz.kCGEventLeftMouseDown: ("left", True),
+ quartz.kCGEventLeftMouseUp: ("left", False),
+ quartz.kCGEventRightMouseDown: ("right", True),
+ quartz.kCGEventRightMouseUp: ("right", False),
+ }
+ if event_type in fixed:
+ return fixed[event_type]
+ if event_type not in (quartz.kCGEventOtherMouseDown, quartz.kCGEventOtherMouseUp):
+ return None
+ number = int(quartz.CGEventGetIntegerValueField(event, quartz.kCGMouseEventButtonNumber))
+ return WIRE_OTHER_BUTTONS.get(number, str(number + 1)), event_type == quartz.kCGEventOtherMouseDown
+
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
@@ -491,6 +508,11 @@ class KVMController:
self.capture_thread = None
self.input_error = None
self.connection_status = "Waiting to connect"
+ # The host, port and token that last completed a handshake. Silence after the preamble
+ # from a PC that has answered this run is a PC too busy to answer (Windows stalls every
+ # app for half a minute while it reconfigures its displays), not an older Beamer. The
+ # token is part of it so a re-pair, even to another PC at the same address, starts clean.
+ self.answered = None
# Set while Windows reports it is clearing its lock screen. Beamer
# cannot type on the secure desktop, so Windows unlocks first and
# drops input meanwhile; without this the switch just looks dead for
@@ -506,6 +528,7 @@ class KVMController:
self.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]
self.last_trigger_down = 0.0
self.trigger_suppressed = False
+ self.ignore_gate = ignored.Gate(cfg.ignored_inputs)
# Crossing: the engine is pure and runs on the event-tap thread; the
# desktop bounds come from CoreGraphics (already in the top-left
# global space CGEventGetLocation uses, so nothing is flipped) and are
@@ -634,6 +657,7 @@ class KVMController:
self.translator.modifier_down.clear()
self.translator.printable_down.clear()
self.translator.reset_mouse_accumulators()
+ self.ignore_gate.configure(cfg.ignored_inputs)
self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)
self._crossing_failed = False
self._drop_connection()
@@ -655,6 +679,7 @@ class KVMController:
# changes rather than waiting for the next reconnect.
self.send_arrangement(edge, cfg.crossing.get("arrangement_set_at", 0))
self.trigger_code = KEY_NAME_TO_CODE[cfg.trigger_key]
+ self.ignore_gate.configure(cfg.ignored_inputs)
self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)
self._crossing_failed = False
@@ -726,6 +751,7 @@ class KVMController:
self._set_cursor_follows_mouse(True)
self.cursor_pin_point = None
self.translator.reset_mouse_accumulators()
+ self.ignore_gate.reset()
self.crossing.reset()
self._forget_round_trips()
if was_redirecting:
@@ -956,10 +982,17 @@ class KVMController:
)
if result.is_trigger:
return self._handle_trigger(result, event)
+ if self.redirecting:
+ keycode = self.quartz.CGEventGetIntegerValueField(event, self.quartz.kCGKeyboardEventKeycode)
+ if self.ignore_gate.keeps(ignored.key(keycode), result.is_down):
+ return event
messages = result.messages
else:
if not self.redirecting:
return self._handle_local_mouse(event_type, event)
+ button = self.translator.button_of(event_type, event)
+ if button is not None and self.ignore_gate.keeps(ignored.button(button[0]), button[1]):
+ return event
messages = self.translator.mouse_messages(event_type, event)
if not self.redirecting:
return event
@@ -1114,8 +1147,8 @@ class KVMController:
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."""
+ share NSSystemDefined -- passes through to macOS untouched, as does a
+ media key kept on this Mac and everything when not redirecting."""
if not self.redirecting:
return event
try:
@@ -1129,6 +1162,8 @@ class KVMController:
if media is None:
return event
name, is_down, _is_repeat = media
+ if self.ignore_gate.keeps(ignored.media(name), is_down):
+ return event
message_type = protocol.MSG_KEYDOWN if is_down else protocol.MSG_KEYUP
wire_name = self.cfg.key_map.get(name, name)
try:
@@ -1274,6 +1309,8 @@ class KVMController:
def _connect_once(self):
sock = None
fallback = False
+ # Read once: update_config can replace self.cfg from the AppKit thread mid-handshake.
+ endpoint = (self.cfg.host, self.cfg.port, self.cfg.auth_token)
self.connection_status = f"Connecting to {self.cfg.host}:{self.cfg.port}"
try:
try:
@@ -1294,6 +1331,8 @@ class KVMController:
try:
protocol.recv_preamble(sock, session)
except socket.timeout:
+ if self.answered == endpoint:
+ raise _HandshakeError("Windows stopped responding") from None
raise _HandshakeError(OLD_RECEIVER_STATUS) from None
except protocol.VersionMismatch as exc:
raise _HandshakeError(
@@ -1377,6 +1416,7 @@ class KVMController:
self.last_ack_at = now
self.connected_at = now
self.last_send_at = now
+ self.answered = endpoint
if fallback:
self.connection_status = "Connected to Windows via secure macOS 27 fallback"
self.logger.info("connected to Windows through the SSH fallback")
diff --git a/mac_app/config.py b/mac_app/config.py
index 80c7a02..05670e6 100644
--- a/mac_app/config.py
+++ b/mac_app/config.py
@@ -64,6 +64,8 @@ class Config:
# 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
+ # Keys and buttons that stay on this Mac while its input is on Windows; see ignored.py.
+ ignored_inputs: list = field(default_factory=list)
def key_map_style(key_map):
@@ -130,4 +132,5 @@ def load_config(path: str = None) -> Config:
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,
+ ignored_inputs=raw.get("ignored_inputs", []),
)
diff --git a/mac_app/ignored.py b/mac_app/ignored.py
new file mode 100644
index 0000000..5bc01a5
--- /dev/null
+++ b/mac_app/ignored.py
@@ -0,0 +1,85 @@
+"""Keys and buttons that stay on the machine they were pressed on while its input is on the other
+one: a mouse's back and forward buttons kept for this machine's browser, a volume key kept for its
+speakers. A per-machine setting, so each app records its own keyboard's codes -- a Mac keycode and
+a Windows virtual key are different numbers for the same key, and neither end ever reads the
+other's list.
+
+Each entry is a string: `key:<code>` for a key in the platform's own numbering, `button:<name>`
+for a mouse button, and `media:<name>` for a Mac media key, which arrives as a system event rather
+than a key. Byte-identical in both apps.
+"""
+
+import re
+import threading
+
+MAX_ENTRIES = 64
+_ENTRY = re.compile(r"^(key:[0-9]{1,5}|button:[a-z0-9_]{1,24}|media:[a-z_]{1,24})$")
+
+
+def key(code):
+ return f"key:{int(code)}"
+
+
+def button(name):
+ return f"button:{name}"
+
+
+def media(name):
+ return f"media:{name}"
+
+
+def validate(entries):
+ """The list as saved, or ValueError naming what is wrong with it."""
+ if not isinstance(entries, list):
+ raise ValueError("ignored_inputs must be a list")
+ if len(entries) > MAX_ENTRIES:
+ raise ValueError(f"ignored_inputs holds at most {MAX_ENTRIES} entries")
+ for entry in entries:
+ if not isinstance(entry, str) or not _ENTRY.match(entry):
+ raise ValueError(f"ignored_inputs has an entry Beamer cannot read: {entry!r}")
+ return list(entries)
+
+
+class Gate:
+ """Decides, while input is on the other machine, which presses stay here.
+
+ A press stays when it is on the list. Its release goes wherever its press went, whatever the
+ list says by then: a key sent across and put on the list while still held would otherwise have
+ its release kept here and stay down on the far side, and one kept here and taken off the list
+ would stay down here. `keeps` runs on the one thread that reads input on each platform; `reset`
+ is for when input comes home, since the far side lets go of everything it was holding then, and
+ is called from other threads, hence the lock."""
+
+ def __init__(self, entries=()):
+ self.entries = frozenset(entries)
+ self._sent = set()
+ self._kept = set()
+ self._lock = threading.Lock()
+
+ def configure(self, entries):
+ self.entries = frozenset(entries)
+
+ def keeps(self, entry, down):
+ with self._lock:
+ if entry in self._sent:
+ if not down:
+ self._sent.discard(entry)
+ return False
+ if entry in self._kept:
+ if not down:
+ self._kept.discard(entry)
+ return True
+ if entry in self.entries:
+ if down:
+ self._kept.add(entry)
+ return True
+ if down:
+ self._sent.add(entry)
+ return False
+
+ def reset(self):
+ with self._lock:
+ self._sent.clear()
+ # A release that arrives once input is home is never asked about, so what was kept
+ # here is forgotten too.
+ self._kept.clear()
diff --git a/mac_app/ignored_titles.py b/mac_app/ignored_titles.py
new file mode 100644
index 0000000..859c586
--- /dev/null
+++ b/mac_app/ignored_titles.py
@@ -0,0 +1,65 @@
+"""Display names for ignored_inputs entries, and the pure decision behind recording one -- factored
+out of the AppKit recorder in widgets.py so both are testable without it.
+"""
+
+import ignored
+import media_keys
+from bridge import WIRE_OTHER_BUTTONS
+from key_codes import PRINTABLE_KEY_FALLBACKS, SPECIAL_KEY_NAMES, key_title
+
+BUTTON_TITLES = {
+ "right": "Right button",
+ "middle": "Middle button",
+ "back": "Back button",
+ "forward": "Forward button",
+}
+
+MEDIA_TITLES = {
+ "volume_up": "Volume Up",
+ "volume_down": "Volume Down",
+ "volume_mute": "Mute",
+ "media_play_pause": "Play/Pause",
+ "media_next": "Next Track",
+ "media_prev": "Previous Track",
+}
+
+
+def entry_title(entry):
+ """The name Beamer shows for one entry in ignored_inputs."""
+ kind, _, value = entry.partition(":")
+ if kind == "key":
+ code = int(value)
+ name = SPECIAL_KEY_NAMES.get(code)
+ if name is not None:
+ return key_title(name)
+ fallback = PRINTABLE_KEY_FALLBACKS.get(code)
+ return fallback.upper() if fallback is not None else f"Key {code}"
+ if kind == "button":
+ return BUTTON_TITLES.get(value, f"Button {value}")
+ if kind == "media":
+ return MEDIA_TITLES.get(value, value)
+ return entry
+
+
+def recorded_entry(kind, value, trigger_code):
+ """The ignored_inputs entry one captured press becomes, or None. `kind` is "key" (a keycode
+ from a KeyDown or FlagsChanged event), "right" (the right mouse button, `value` unused),
+ "other" (another mouse button, `value` its CoreGraphics button number) or "media" (a
+ NX_SUBTYPE_AUX_CONTROL_BUTTONS system-defined event, `value` its data1). None means: the
+ trigger key, which always stays with Beamer, or a media event that is not a recognised
+ key-down, which the recorder keeps listening past rather than finishing on."""
+ if kind == "key":
+ code = int(value)
+ return None if code == trigger_code else ignored.key(code)
+ if kind == "right":
+ return ignored.button("right")
+ if kind == "other":
+ number = int(value)
+ return ignored.button(WIRE_OTHER_BUTTONS.get(number, str(number + 1)))
+ if kind == "media":
+ decoded = media_keys.decode(media_keys.NX_SUBTYPE_AUX_CONTROL_BUTTONS, int(value))
+ if decoded is None:
+ return None
+ name, is_down, _is_repeat = decoded
+ return ignored.media(name) if is_down else None
+ return None
diff --git a/mac_app/input_injector_mac.py b/mac_app/input_injector_mac.py
index ddb9402..efb02e1 100644
--- a/mac_app/input_injector_mac.py
+++ b/mac_app/input_injector_mac.py
@@ -59,7 +59,7 @@ MODIFIER_FLAG_NAMES = {
# 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")
+BUTTONS = ("left", "right", "middle", "back", "forward")
# 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.
@@ -199,11 +199,16 @@ MOVE_EVENTS = {
"left": "kCGEventLeftMouseDragged",
"right": "kCGEventRightMouseDragged",
"middle": "kCGEventOtherMouseDragged",
+ "back": "kCGEventOtherMouseDragged",
+ "forward": "kCGEventOtherMouseDragged",
}
BUTTON_EVENTS = {
"left": ("kCGEventLeftMouseDown", "kCGEventLeftMouseUp", "kCGMouseButtonLeft"),
"right": ("kCGEventRightMouseDown", "kCGEventRightMouseUp", "kCGMouseButtonRight"),
"middle": ("kCGEventOtherMouseDown", "kCGEventOtherMouseUp", "kCGMouseButtonCenter"),
+ # The side buttons have no CoreGraphics constant; they are other buttons 3 and 4.
+ "back": ("kCGEventOtherMouseDown", "kCGEventOtherMouseUp", 3),
+ "forward": ("kCGEventOtherMouseDown", "kCGEventOtherMouseUp", 4),
}
@@ -222,7 +227,12 @@ def _post(event) -> None:
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)
+ if button_name is None:
+ button = 0
+ elif isinstance(button_name, int):
+ button = button_name
+ else:
+ button = getattr(quartz, button_name)
event = quartz.CGEventCreateMouseEvent(
None, getattr(quartz, event_name), quartz.CGPointMake(float(x), float(y)), button
)
diff --git a/mac_app/key_codes.py b/mac_app/key_codes.py
index 7647a44..313beb0 100644
--- a/mac_app/key_codes.py
+++ b/mac_app/key_codes.py
@@ -111,3 +111,25 @@ PRINTABLE_KEY_FALLBACKS = {
0x2F: ".",
0x32: "`",
}
+
+# What the settings window calls a key. Names the wire and config keep as they are. AppKit-free,
+# so widgets.py re-exports key_title rather than defining it, and anything that only needs a
+# display name can import it without pulling AppKit in.
+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())
diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.py
index 22e7d95..e9b6bbf 100644
--- a/mac_app/kvm_bridge_app.py
+++ b/mac_app/kvm_bridge_app.py
@@ -23,11 +23,13 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import config as config_module
import crossing
import gestures
+import ignored_titles
import notch_beam
import previews
from notch_beam import NotchBeam
from notch_island import NotchIsland
from bridge import _GestureEventView
+from key_codes import KEY_NAME_TO_CODE
import link_state
import login_item
import pages
@@ -650,6 +652,27 @@ class EdgeGlow:
self.visible = False
+BEAMER_SITE_URL = "https://kalkmancode.co.uk/beamer"
+
+
+def show_about_panel():
+ """The standard About panel, with a centred credits line linking to the project's page. The
+ version shown is Info.plist's own CFBundleShortVersionString, already the VERSION file's
+ contents (see setup.py) -- nothing to pass here for that. Activates the app first: without it,
+ a panel asked for from the menu-bar item alone can open behind everything else."""
+ AppKit.NSApp.activateIgnoringOtherApps_(True)
+ paragraph = AppKit.NSMutableParagraphStyle.alloc().init()
+ paragraph.setAlignment_(AppKit.NSTextAlignmentCenter)
+ credits = AppKit.NSAttributedString.alloc().initWithString_attributes_(
+ "kalkmancode.co.uk/beamer",
+ {
+ AppKit.NSLinkAttributeName: AppKit.NSURL.URLWithString_(BEAMER_SITE_URL),
+ AppKit.NSParagraphStyleAttributeName: paragraph,
+ },
+ )
+ AppKit.NSApp.orderFrontStandardAboutPanelWithOptions_({AppKit.NSAboutPanelOptionCredits: credits})
+
+
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
@@ -667,6 +690,8 @@ def install_main_menu(control_window):
application_item = main_menu.addItemWithTitle_action_keyEquivalent_("Beamer", None, "")
application_menu = AppKit.NSMenu.alloc().initWithTitle_("Beamer")
+ item(application_menu, "About Beamer", "showAbout:", "", target=control_window)
+ application_menu.addItem_(AppKit.NSMenuItem.separatorItem())
item(application_menu, "Hide Beamer", "hide:", "h")
item(
application_menu,
@@ -777,7 +802,14 @@ class ControlWindow(AppKit.NSObject):
content.layer().setBackgroundColor_(theme.colour("ground").CGColor())
top = widgets.hairline()
- self.sidebar = widgets.Sidebar(pages.PAGES, self._select_page)
+ self.sidebar = widgets.Sidebar(
+ pages.PAGES,
+ self._select_page,
+ # Two lines: one, at the sidebar's narrowest, cuts the address off.
+ footer_text=f"Beamer {VERSION}\nkalkmancode.co.uk/beamer",
+ footer_label="Open kalkmancode.co.uk/beamer",
+ on_footer=self._open_beamer_site,
+ )
divider = widgets.box("rule")
pane = widgets.stack(spacing=0)
for view in (top, self.sidebar.view, divider, pane):
@@ -888,8 +920,17 @@ class ControlWindow(AppKit.NSObject):
for name, scroll in self.pages.items():
scroll.setHidden_(name != key)
self.sidebar.select(key)
+ if key != "keyboard":
+ # Both recorders listen application-wide; left armed, they would take the first key
+ # typed on another page.
+ self.key_recorder.cancel()
+ self.ignored_recorder.cancel()
self._run_previews()
+ @objc.python_method
+ def _open_beamer_site(self):
+ AppKit.NSWorkspace.sharedWorkspace().openURL_(AppKit.NSURL.URLWithString_(BEAMER_SITE_URL))
+
@objc.python_method
def _run_previews(self):
"""The previews play only while someone can see them: the Design page open in a visible
@@ -913,6 +954,8 @@ class ControlWindow(AppKit.NSObject):
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.ignored_entries = list(raw["ignored_inputs"])
+ self._render_ignored()
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"]))
@@ -968,6 +1011,7 @@ class ControlWindow(AppKit.NSObject):
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))
+ self.ignored_recorder.set_trigger_code(KEY_NAME_TO_CODE.get(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)
@@ -1064,6 +1108,7 @@ class ControlWindow(AppKit.NSObject):
def windowWillClose_(self, _notification):
self.key_recorder.cancel()
+ self.ignored_recorder.cancel()
if self.previews is not None:
self.previews.stop()
@@ -1181,6 +1226,7 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _keyboard_page(self, body):
widgets.add(body, self._shortcut_module().view)
+ widgets.add(body, self._ignored_module().view)
widgets.add(body, self._modifier_module().view)
@objc.python_method
@@ -1320,6 +1366,72 @@ class ControlWindow(AppKit.NSObject):
module.add(self.style_hint.view)
return module
+ @objc.python_method
+ def _ignored_module(self):
+ module = widgets.Module()
+ module.add(widgets.eyebrow("Stays on this Mac"))
+ module.add(widgets.note(
+ "These keys and buttons keep working on this Mac while its input is on Windows: a "
+ "mouse's back button for this Mac's browser, say, or a volume key for its speakers."
+ ).view)
+ self.ignored_entries = []
+ self.ignored_list = widgets.stack(spacing=6)
+ module.add(self.ignored_list)
+ self.ignored_empty = widgets.note("Nothing yet. Every key and button goes to Windows while it has input.")
+ module.add(self.ignored_empty.view)
+ self.ignored_recorder = widgets.IgnoredRecorder(
+ KEY_NAME_TO_CODE.get(self.key_recorder.value), on_recorded=self._add_ignored
+ )
+ module.add(self.ignored_recorder.view)
+ self.ignored_status = widgets.note()
+ module.add(self.ignored_status.view)
+ self._render_ignored()
+ return module
+
+ @objc.python_method
+ def _render_ignored(self):
+ for view in list(self.ignored_list.arrangedSubviews()):
+ self.ignored_list.removeArrangedSubview_(view)
+ view.removeFromSuperview()
+ for entry in self.ignored_entries:
+ # One quiet row per entry, as on Windows: the name, and a small Remove that does not
+ # outweigh it.
+ title = ignored_titles.entry_title(entry)
+ chip = widgets.box("well", "rule", theme.RADIUS["field"])
+ name = widgets.Label(title, theme.TYPE["small"], 600, mono=True)
+ remove = widgets.pressable(lambda entry=entry: self._remove_ignored(entry), radius=theme.RADIUS["field"])
+ remove.setAccessibilityLabel_(f"Remove {title}")
+ remove_word = widgets.Label("Remove", theme.TYPE["small"], ink="ink_3")
+ remove.addSubview_(remove_word.view)
+ widgets.pin(remove_word.view, remove, (4, 8, 4, 8))
+ line = widgets.stack(vertical=False, spacing=10)
+ line.addArrangedSubview_(name.view)
+ line.addArrangedSubview_(remove)
+ widgets.hug(name.view, AppKit.NSLayoutPriorityDefaultLow)
+ chip.addSubview_(line)
+ widgets.pin(line, chip, (5, 12, 5, 4))
+ widgets.add(self.ignored_list, chip)
+ self.ignored_empty.view.setHidden_(bool(self.ignored_entries))
+
+ @objc.python_method
+ def _add_ignored(self, entry):
+ if entry is None:
+ self.ignored_status.set("That key is the shortcut; it always stays with Beamer.")
+ return
+ if entry in self.ignored_entries:
+ return
+ self.ignored_entries.append(entry)
+ self.ignored_status.set("")
+ self._render_ignored()
+ self._changed()
+
+ @objc.python_method
+ def _remove_ignored(self, entry):
+ self.ignored_entries.remove(entry)
+ self.ignored_status.set("")
+ self._render_ignored()
+ self._changed()
+
@objc.python_method
def _on_screen_module(self):
module = widgets.Module(spacing=8)
@@ -1623,6 +1735,7 @@ class ControlWindow(AppKit.NSObject):
raw = config_to_raw(self.controller.cfg)
try:
raw["trigger_key"] = self.key_recorder.value
+ raw["ignored_inputs"] = list(self.ignored_entries)
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:
@@ -1691,6 +1804,9 @@ class ControlWindow(AppKit.NSObject):
def quitApp_(self, _sender):
self.quit_handler()
+ def showAbout_(self, _sender):
+ show_about_panel()
+
def requestAccessibility_(self, _sender):
ApplicationServices.AXIsProcessTrustedWithOptions(
{ApplicationServices.kAXTrustedCheckOptionPrompt: True}
@@ -2090,6 +2206,7 @@ class TrayApp(rumps.App):
rumps.MenuItem("Settings…", callback=self.open_window),
rumps.MenuItem("Reload configuration", callback=self.reload_config),
rumps.separator,
+ rumps.MenuItem("About Beamer", callback=self.show_about),
rumps.MenuItem("Quit Beamer", callback=self.quit_app),
],
quit_button=None,
@@ -2192,13 +2309,18 @@ class TrayApp(rumps.App):
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())
+ cfg = 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.control_window._load(config_to_raw(cfg))
+ self.controller.update_config(cfg)
self.notify_user("Configuration reloaded", "Beamer is using the config on disk.")
+ def show_about(self, _sender):
+ show_about_panel()
+
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."""
diff --git a/mac_app/pages.py b/mac_app/pages.py
index 87085d2..0c8a404 100644
--- a/mac_app/pages.py
+++ b/mac_app/pages.py
@@ -14,7 +14,8 @@ PAGES = (
("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."),
+ "The key that switches input, which keys and buttons stay on this Mac, and how its 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",
diff --git a/mac_app/settings_store.py b/mac_app/settings_store.py
index 6046410..effe3ab 100644
--- a/mac_app/settings_store.py
+++ b/mac_app/settings_store.py
@@ -6,6 +6,7 @@ from dataclasses import replace
from pathlib import Path
import config as config_module
+import ignored
import protocol
from crossing import CORNERS, EDGES, GLOW_COLOURS, GLOW_STYLES, HAPTIC_FEELS, HAPTIC_STEPS, METHODS, NOTCH_STYLES
@@ -62,6 +63,7 @@ def editable_default_config():
mac_address="",
send_to_windows=True,
allow_windows_to_drive=True,
+ ignored_inputs=[],
)
@@ -83,6 +85,7 @@ def config_to_raw(cfg):
"mac_address": cfg.mac_address,
"send_to_windows": cfg.send_to_windows,
"allow_windows_to_drive": cfg.allow_windows_to_drive,
+ "ignored_inputs": list(cfg.ignored_inputs),
}
@@ -200,5 +203,9 @@ class SettingsStore:
for name in ("haptics", "glow", "block_while_dragging"):
if not isinstance(crossing[name], bool):
raise SettingsError(f"crossing.{name} must be true or false")
+ try:
+ ignored.validate(cfg.ignored_inputs)
+ except ValueError as exc:
+ raise SettingsError(str(exc)) from exc
if cfg.mac_address and parse_mac(cfg.mac_address) is None:
raise SettingsError("mac_address must be six hex pairs, such as 02:1A:2B:3C:0D:4E")
diff --git a/mac_app/setup.py b/mac_app/setup.py
index 89a165e..46e5baf 100644
--- a/mac_app/setup.py
+++ b/mac_app/setup.py
@@ -23,6 +23,7 @@ setup(
"crossing",
"desktop_mac",
"gestures",
+ "ignored",
"input_injector_mac",
"key_codes",
"link_state",
diff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.py
index f05f03f..e867692 100644
--- a/mac_app/tests/test_bridge.py
+++ b/mac_app/tests/test_bridge.py
@@ -1,3 +1,4 @@
+import dataclasses
import errno
import json
import logging
@@ -926,6 +927,41 @@ class ControllerTests(unittest.TestCase):
self.assertTrue(sock.closed)
self.assertIsNone(controller.sock)
+ def test_a_pc_that_answered_before_and_falls_silent_is_not_called_old(self):
+ # 23-09-2026: Windows stalled every app for 40s while it reconfigured its displays, and
+ # the Mac told Toby to update a Beamer that was already current.
+ answering, silent = FakeSocket(), FakeSocket()
+ seed_receiver_reply(answering, protocol.welcome_msg())
+ sockets = iter([answering, silent])
+ controller = KVMController(
+ make_config(),
+ logger=quiet_logger(),
+ quartz=FakeQuartz,
+ clock=self.clock,
+ socket_factory=lambda address, timeout: next(sockets),
+ )
+ self.assertTrue(controller._connect_once())
+ self.assertFalse(controller._connect_once())
+ self.assertEqual(controller.connection_status, "Windows stopped responding")
+ self.assertTrue(silent.closed)
+
+ def test_a_re_pair_forgets_that_the_old_pc_answered(self):
+ # A new token can be a different PC at the same address, and a silent one may be old.
+ answering, silent = FakeSocket(), FakeSocket()
+ seed_receiver_reply(answering, protocol.welcome_msg())
+ sockets = iter([answering, silent])
+ controller = KVMController(
+ make_config(),
+ logger=quiet_logger(),
+ quartz=FakeQuartz,
+ clock=self.clock,
+ socket_factory=lambda address, timeout: next(sockets),
+ )
+ self.assertTrue(controller._connect_once())
+ controller.update_config(dataclasses.replace(make_config(), auth_token="re-paired-token"))
+ self.assertFalse(controller._connect_once())
+ self.assertEqual(controller.connection_status, OLD_RECEIVER_STATUS)
+
def test_other_wire_version_in_the_preamble_is_reported(self):
sock = FakeSocket()
sock.inbound.extend(protocol.WIRE_MAGIC + bytes([protocol.PROTOCOL_VERSION + 1]) + b"\x02" * protocol.NONCE_PREFIX_SIZE)
diff --git a/mac_app/tests/test_ignored.py b/mac_app/tests/test_ignored.py
new file mode 100644
index 0000000..244af59
--- /dev/null
+++ b/mac_app/tests/test_ignored.py
@@ -0,0 +1,56 @@
+"""The ignored-inputs gate both apps share. Byte-identical in mac_app and win_app."""
+
+import unittest
+
+import ignored
+
+
+class GateTests(unittest.TestCase):
+ def test_a_listed_press_and_its_release_stay_here(self):
+ gate = ignored.Gate([ignored.button("back")])
+ self.assertTrue(gate.keeps("button:back", True))
+ self.assertTrue(gate.keeps("button:back", False))
+
+ def test_anything_else_goes_across(self):
+ gate = ignored.Gate([ignored.button("back")])
+ self.assertFalse(gate.keeps("key:12", True))
+ self.assertFalse(gate.keeps("key:12", False))
+
+ def test_a_release_follows_its_press_across_when_the_list_changes_mid_hold(self):
+ gate = ignored.Gate()
+ self.assertFalse(gate.keeps("key:122", True))
+ gate.configure([ignored.key(122)])
+ self.assertFalse(gate.keeps("key:122", True), "an autorepeat of a key already across stays across")
+ self.assertFalse(gate.keeps("key:122", False), "its release must reach the far side")
+ self.assertTrue(gate.keeps("key:122", True), "the next press is kept here")
+
+ def test_a_press_kept_here_keeps_its_release_here_when_taken_off_the_list(self):
+ gate = ignored.Gate([ignored.key(122)])
+ self.assertTrue(gate.keeps("key:122", True))
+ gate.configure([])
+ self.assertTrue(gate.keeps("key:122", False), "the release must reach this machine, which has the press")
+ self.assertFalse(gate.keeps("key:122", True), "the next press goes across")
+
+ def test_a_release_outside_the_list_with_no_press_seen_goes_across(self):
+ gate = ignored.Gate()
+ self.assertFalse(gate.keeps("key:5", False))
+
+ def test_reset_forgets_what_went_across(self):
+ gate = ignored.Gate()
+ gate.keeps("key:5", True)
+ gate.configure(["key:5"])
+ gate.reset()
+ self.assertTrue(gate.keeps("key:5", False))
+
+ def test_validate_takes_every_kind_of_entry(self):
+ entries = [ignored.key(0), ignored.key(0xA3), ignored.button("forward"), ignored.button("6"), ignored.media("volume_up")]
+ self.assertEqual(ignored.validate(entries), entries)
+
+ def test_validate_refuses_what_it_cannot_read(self):
+ for bad in ("f13", ["key:"], ["key:abc"], ["mouse:back"], [12], ["key:1"] * (ignored.MAX_ENTRIES + 1)):
+ with self.subTest(bad=bad), self.assertRaises(ValueError):
+ ignored.validate(bad)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_ignored_inputs.py b/mac_app/tests/test_ignored_inputs.py
new file mode 100644
index 0000000..8c465fb
--- /dev/null
+++ b/mac_app/tests/test_ignored_inputs.py
@@ -0,0 +1,122 @@
+"""Keys and buttons that stay on this Mac while its input is on Windows: the event tap's decision,
+the side buttons now crossing, and the setting's round trip through config.json."""
+
+import json
+import tempfile
+import unittest
+from dataclasses import replace
+from pathlib import Path
+
+import ignored
+import protocol
+import settings_store
+from bridge import KVMController
+from tests.test_bridge import FakeClock, FakeQuartz, make_config, quiet_logger
+
+KEY_F13 = 0x69
+KEY_A = 0x00
+
+
+def key_event(keycode, unicode=""):
+ return {FakeQuartz.kCGKeyboardEventKeycode: keycode, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "unicode": unicode}
+
+
+def other_button(number):
+ return {FakeQuartz.kCGMouseEventButtonNumber: number}
+
+
+class TapTests(unittest.TestCase):
+ def setUp(self):
+ self.controller = KVMController(
+ replace(make_config(), ignored_inputs=[ignored.key(KEY_F13), ignored.button("back"), ignored.media("volume_up")]),
+ logger=quiet_logger(),
+ quartz=FakeQuartz,
+ clock=FakeClock(),
+ system_event_converter=lambda event: event,
+ )
+ self.controller.redirecting = True
+
+ def tap(self, event_type, event):
+ return self.controller._event_tap_callback(None, event_type, event, None)
+
+ def sent(self):
+ messages = []
+ while not self.controller.outbound.empty():
+ messages.append(self.controller.outbound.get_nowait())
+ return [(m["type"], m["data"]) for m in messages]
+
+ def configure(self, entries):
+ self.controller.apply_settings(replace(self.controller.cfg, ignored_inputs=list(entries)))
+
+ def test_an_ignored_key_reaches_this_mac_and_not_windows(self):
+ down, up = key_event(KEY_F13), key_event(KEY_F13)
+ self.assertIs(self.tap(FakeQuartz.kCGEventKeyDown, down), down)
+ self.assertIs(self.tap(FakeQuartz.kCGEventKeyUp, up), up)
+ self.assertEqual(self.sent(), [])
+
+ def test_any_other_key_still_goes_to_windows(self):
+ self.assertIsNone(self.tap(FakeQuartz.kCGEventKeyDown, key_event(KEY_A, "a")))
+ self.assertEqual(self.sent(), [(protocol.MSG_KEYDOWN, {"key": "a"})])
+
+ def test_a_key_ignored_while_held_on_windows_is_still_released_there(self):
+ self.configure([])
+ self.assertIsNone(self.tap(FakeQuartz.kCGEventKeyDown, key_event(KEY_F13)))
+ self.configure([ignored.key(KEY_F13)])
+ self.assertIsNone(self.tap(FakeQuartz.kCGEventKeyUp, key_event(KEY_F13)))
+ self.assertEqual(self.sent(), [(protocol.MSG_KEYDOWN, {"key": "f13"}), (protocol.MSG_KEYUP, {"key": "f13"})])
+
+ def test_the_side_buttons_cross_as_back_and_forward(self):
+ self.configure([])
+ self.assertIsNone(self.tap(FakeQuartz.kCGEventOtherMouseDown, other_button(4)))
+ self.assertIsNone(self.tap(FakeQuartz.kCGEventOtherMouseUp, other_button(4)))
+ self.assertEqual(self.sent(), [
+ (protocol.MSG_MOUSEDOWN, {"button": "forward"}),
+ (protocol.MSG_MOUSEUP, {"button": "forward"}),
+ ])
+
+ def test_an_ignored_button_stays_on_this_mac(self):
+ down, up = other_button(3), other_button(3)
+ self.assertIs(self.tap(FakeQuartz.kCGEventOtherMouseDown, down), down)
+ self.assertIs(self.tap(FakeQuartz.kCGEventOtherMouseUp, up), up)
+ self.assertEqual(self.sent(), [])
+
+ def test_an_ignored_media_key_stays_on_this_mac(self):
+ # NX key 0 is volume up; 0x0A00 is key down.
+ event = (8, (0 << 16) | 0x0A00)
+ self.assertIs(self.controller._handle_system_event(event), event)
+ self.assertEqual(self.sent(), [])
+ mute = (8, (7 << 16) | 0x0A00)
+ self.assertIsNone(self.controller._handle_system_event(mute))
+ self.assertEqual(self.sent(), [(protocol.MSG_KEYDOWN, {"key": "volume_mute"})])
+
+ def test_coming_home_forgets_what_went_across(self):
+ self.configure([])
+ self.tap(FakeQuartz.kCGEventKeyDown, key_event(KEY_F13))
+ self.configure([ignored.key(KEY_F13)])
+ self.controller._return_local()
+ self.controller.redirecting = True
+ up = key_event(KEY_F13)
+ self.assertIs(self.tap(FakeQuartz.kCGEventKeyUp, up), up)
+
+
+class SettingsTests(unittest.TestCase):
+ def test_the_list_survives_a_save_and_a_load(self):
+ with tempfile.TemporaryDirectory() as directory:
+ store = settings_store.SettingsStore(Path(directory) / "config.json")
+ raw = settings_store.config_to_raw(settings_store.editable_default_config())
+ raw["ignored_inputs"] = [ignored.key(KEY_F13), ignored.button("back"), ignored.media("volume_up")]
+ store.save(raw)
+ self.assertEqual(json.loads(store.path.read_text())["ignored_inputs"], raw["ignored_inputs"])
+ self.assertEqual(store.load().ignored_inputs, raw["ignored_inputs"])
+
+ def test_an_unreadable_entry_is_refused(self):
+ with tempfile.TemporaryDirectory() as directory:
+ store = settings_store.SettingsStore(Path(directory) / "config.json")
+ raw = settings_store.config_to_raw(settings_store.editable_default_config())
+ raw["ignored_inputs"] = ["f13"]
+ with self.assertRaises(settings_store.SettingsError):
+ store.save(raw)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_ignored_titles.py b/mac_app/tests/test_ignored_titles.py
new file mode 100644
index 0000000..e5d6431
--- /dev/null
+++ b/mac_app/tests/test_ignored_titles.py
@@ -0,0 +1,83 @@
+"""Display names for ignored_inputs entries, and the recorder's pure decision behind one."""
+
+import unittest
+
+import ignored
+import ignored_titles
+import media_keys
+
+
+class EntryTitleTests(unittest.TestCase):
+ def test_special_key_uses_its_own_title(self):
+ self.assertEqual(ignored_titles.entry_title(ignored.key(0x3D)), "Right Option")
+
+ def test_printable_key_falls_back_to_its_upper_cased_character(self):
+ self.assertEqual(ignored_titles.entry_title(ignored.key(0x00)), "A")
+
+ def test_unrecognised_key_code_names_itself(self):
+ self.assertEqual(ignored_titles.entry_title(ignored.key(9999)), "Key 9999")
+
+ def test_named_buttons(self):
+ for name, title in (
+ ("right", "Right button"),
+ ("middle", "Middle button"),
+ ("back", "Back button"),
+ ("forward", "Forward button"),
+ ):
+ self.assertEqual(ignored_titles.entry_title(ignored.button(name)), title)
+
+ def test_numbered_button(self):
+ self.assertEqual(ignored_titles.entry_title(ignored.button("6")), "Button 6")
+
+ def test_media_keys(self):
+ for name, title in (
+ ("volume_up", "Volume Up"),
+ ("volume_down", "Volume Down"),
+ ("volume_mute", "Mute"),
+ ("media_play_pause", "Play/Pause"),
+ ("media_next", "Next Track"),
+ ("media_prev", "Previous Track"),
+ ):
+ self.assertEqual(ignored_titles.entry_title(ignored.media(name)), title)
+
+
+class RecordedEntryTests(unittest.TestCase):
+ TRIGGER = 0x3D # alt_r
+
+ def test_a_key_becomes_an_entry(self):
+ self.assertEqual(ignored_titles.recorded_entry("key", 0x00, self.TRIGGER), ignored.key(0))
+
+ def test_the_trigger_key_refuses(self):
+ self.assertIsNone(ignored_titles.recorded_entry("key", self.TRIGGER, self.TRIGGER))
+
+ def test_right_mouse_is_always_the_named_button(self):
+ self.assertEqual(ignored_titles.recorded_entry("right", 0, self.TRIGGER), ignored.button("right"))
+
+ def test_other_mouse_maps_the_named_buttons(self):
+ self.assertEqual(ignored_titles.recorded_entry("other", 2, self.TRIGGER), ignored.button("middle"))
+ self.assertEqual(ignored_titles.recorded_entry("other", 3, self.TRIGGER), ignored.button("back"))
+ self.assertEqual(ignored_titles.recorded_entry("other", 4, self.TRIGGER), ignored.button("forward"))
+
+ def test_other_mouse_numbers_a_button_the_wire_has_no_name_for(self):
+ self.assertEqual(ignored_titles.recorded_entry("other", 5, self.TRIGGER), ignored.button("6"))
+
+ def _media_data1(self, nx_key, down):
+ state = 0x0A if down else 0x0B
+ return (nx_key << 16) | (state << 8)
+
+ def test_a_media_key_down_press_becomes_an_entry(self):
+ data1 = self._media_data1(0, down=True) # volume_up
+ self.assertEqual(ignored_titles.recorded_entry("media", data1, self.TRIGGER), ignored.media("volume_up"))
+
+ def test_a_media_key_release_keeps_listening(self):
+ data1 = self._media_data1(0, down=False)
+ self.assertIsNone(ignored_titles.recorded_entry("media", data1, self.TRIGGER))
+
+ def test_a_media_key_beamer_does_not_track_keeps_listening(self):
+ data1 = self._media_data1(99, down=True)
+ self.assertIsNone(ignored_titles.recorded_entry("media", data1, self.TRIGGER))
+ self.assertIsNone(media_keys.decode(media_keys.NX_SUBTYPE_AUX_CONTROL_BUTTONS, data1))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_reload_config_refreshes_window.py b/mac_app/tests/test_reload_config_refreshes_window.py
new file mode 100644
index 0000000..5f3e1b4
--- /dev/null
+++ b/mac_app/tests/test_reload_config_refreshes_window.py
@@ -0,0 +1,65 @@
+import logging
+import unittest
+
+from kvm_bridge_app import TrayApp
+from settings_store import config_to_raw, editable_default_config
+
+
+class _FakeControlWindow:
+ def __init__(self):
+ self.loaded_raw = []
+
+ def _load(self, raw):
+ self.loaded_raw.append(raw)
+
+
+class _FakeController:
+ def __init__(self):
+ self.cfg = None
+
+ def update_config(self, cfg):
+ self.cfg = cfg
+
+
+class _FakeSettingsStore:
+ def __init__(self, cfg):
+ self._cfg = cfg
+
+ def load(self):
+ return self._cfg
+
+
+class _FakeTrayApp:
+ """Stand-in with just what TrayApp.reload_config reads from self."""
+
+ reload_config = TrayApp.reload_config
+
+ def __init__(self, cfg):
+ self.logger = logging.getLogger("test-reload-config")
+ self.settings_store = _FakeSettingsStore(cfg)
+ self.control_window = _FakeControlWindow()
+ self.controller = _FakeController()
+ self.notified = []
+
+ def notify_user(self, title, detail):
+ self.notified.append((title, detail))
+
+
+class ReloadConfigRefreshesWindowTest(unittest.TestCase):
+ def test_reload_config_repopulates_the_open_window(self):
+ """reload_config once only pushed the new config into the controller,
+ so a page already open (Crossing's ways-in ticks, among others) kept
+ showing whatever was on screen when the window was built, not what
+ config.json now says."""
+ cfg = editable_default_config()
+ cfg.crossing["methods"] = ["edge"]
+ app = _FakeTrayApp(cfg)
+
+ app.reload_config(None)
+
+ self.assertEqual(app.control_window.loaded_raw, [config_to_raw(cfg)])
+ self.assertIs(app.controller.cfg, cfg)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_shared_copies.py b/mac_app/tests/test_shared_copies.py
index 70d23eb..1fd722a 100644
--- a/mac_app/tests/test_shared_copies.py
+++ b/mac_app/tests/test_shared_copies.py
@@ -19,8 +19,8 @@ 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",)
+SHARED_MODULES = ("ignored.py", "protocol.py", "receiver.py", "return_edge.py")
+SHARED_TESTS = ("test_ignored.py", "test_shared_copies.py")
def _digest(path):
diff --git a/mac_app/widgets.py b/mac_app/widgets.py
index a62c368..9246ecd 100644
--- a/mac_app/widgets.py
+++ b/mac_app/widgets.py
@@ -14,8 +14,10 @@ import AppKit
import Quartz
import objc
+import media_keys
import theme
-from key_codes import KEY_NAME_TO_CODE, SPECIAL_KEY_NAMES
+from ignored_titles import recorded_entry
+from key_codes import KEY_NAME_TO_CODE, SPECIAL_KEY_NAMES, key_title
def _autolayout(view):
@@ -390,6 +392,12 @@ class Pressable(AppKit.NSView):
inset = getattr(self, "ring_inset", -3.0)
ring.setFrame_(AppKit.NSInsetRect(self.bounds(), inset, inset))
+ def resetCursorRects(self):
+ # A pointing hand is for the one Pressable that opens something outside the app (the
+ # sidebar's link back); every other one is a control, which macOS leaves as the arrow.
+ if getattr(self, "pointer_cursor", False):
+ self.addCursorRect_cursor_(self.bounds(), AppKit.NSCursor.pointingHandCursor())
+
@objc.python_method
def _ring(self, on):
if getattr(self, "ring", None) is None:
@@ -953,27 +961,6 @@ class Ruler:
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.
@@ -1041,6 +1028,92 @@ class KeyRecorder:
paint(self.view, "edge")
+class IgnoredRecorder:
+ """A keycap that records the next key, mouse button or media key as an entry to keep on this
+ Mac while its input is on Windows. Clicking arms it; the left mouse button is never recorded,
+ since a left click on the control is what cancels it. The current trigger key refuses rather
+ than recording -- it always stays with Beamer -- and `on_recorded` is called with None for
+ that refusal. Recorded through a local event monitor, same as KeyRecorder, so it works before
+ either Mac permission is granted."""
+
+ TITLE = "Add a key or button"
+ RECORDING_TITLE = "Press a key or button…"
+ HINT = "Click, then press it"
+ RECORDING_HINT = "Click again to cancel"
+
+ def __init__(self, trigger_code, on_recorded=None):
+ self.trigger_code = trigger_code
+ self.on_recorded = on_recorded
+ self.monitor = None
+ self.view = pressable(self._clicked, "edge", radius=theme.RADIUS["keycap"])
+ self.view.setAccessibilityLabel_("Add a key or button that stays on this Mac")
+ face = box("ground", radius=theme.RADIUS["keycap"] - 1)
+ self.view.addSubview_(face)
+ pin(face, self.view, (1, 1, 3, 1))
+ self.title = Label(self.TITLE, theme.TYPE["keycap"], mono=True, tracking=-0.02)
+ squeeze(self.title.view)
+ self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight)
+ line = stack(vertical=False, spacing=10)
+ line.addArrangedSubview_(self.title.view)
+ line.addArrangedSubview_(self.hint.view)
+ hug(self.title.view, AppKit.NSLayoutPriorityDefaultLow)
+ face.addSubview_(line)
+ pin(line, face, (9, 12, 8, 12))
+
+ def set_trigger_code(self, trigger_code):
+ self.trigger_code = trigger_code
+
+ def _clicked(self):
+ if self.monitor is not None:
+ self._stop()
+ return
+ self.title.set(self.RECORDING_TITLE, ink="signal")
+ self.hint.set(self.RECORDING_HINT)
+ paint(self.view, "signal")
+ mask = (
+ AppKit.NSEventMaskKeyDown
+ | AppKit.NSEventMaskFlagsChanged
+ | AppKit.NSEventMaskRightMouseDown
+ | AppKit.NSEventMaskOtherMouseDown
+ | AppKit.NSEventMaskSystemDefined
+ )
+ self.monitor = AppKit.NSEvent.addLocalMonitorForEventsMatchingMask_handler_(mask, self._recorded)
+
+ def _recorded(self, event):
+ event_type = event.type()
+ if event_type == AppKit.NSEventTypeSystemDefined:
+ # Brightness, Mission Control and several undocumented events share this subtype-8
+ # event type; only NX_SUBTYPE_AUX_CONTROL_BUTTONS is a media key.
+ if int(event.subtype()) != media_keys.NX_SUBTYPE_AUX_CONTROL_BUTTONS:
+ return event
+ entry = recorded_entry("media", int(event.data1()), self.trigger_code)
+ if entry is None:
+ # A key going up, or one Beamer does not track, such as brightness: it keeps
+ # working, and the recorder keeps listening.
+ return event
+ elif event_type == AppKit.NSEventTypeRightMouseDown:
+ entry = recorded_entry("right", 0, self.trigger_code)
+ elif event_type == AppKit.NSEventTypeOtherMouseDown:
+ entry = recorded_entry("other", int(event.buttonNumber()), self.trigger_code)
+ else:
+ entry = recorded_entry("key", int(event.keyCode()), self.trigger_code)
+ self._stop()
+ if self.on_recorded is not None:
+ self.on_recorded(entry)
+ 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.title.set(self.TITLE, ink="ink")
+ self.hint.set(self.HINT)
+ paint(self.view, "edge")
+
+
class _CodeDelegate(AppKit.NSObject):
def controlTextDidChange_(self, notification):
self.owner.changed(notification.object())
@@ -1121,9 +1194,10 @@ 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."""
+ per row; `on_select` gets the key of a row the user chose. `footer_text`, if given, is a quiet
+ line pinned to the foot of the sidebar, opening `on_footer` when clicked."""
- def __init__(self, pages, on_select):
+ def __init__(self, pages, on_select, footer_text=None, footer_label=None, on_footer=None):
self.on_select = on_select
self.keys = [page[0] for page in pages]
self.selected = None
@@ -1199,6 +1273,20 @@ class Sidebar:
self.rows[key] = (name, row, icon, words, bar, dot)
add(column, rows)
+ if footer_text and on_footer is not None:
+ footer = pressable(on_footer)
+ footer.pointer_cursor = True
+ footer.setAccessibilityLabel_(footer_label or footer_text)
+ footer_label_view = Label(footer_text, theme.TYPE["small"], ink="ink_3", wrap=True)
+ footer.addSubview_(footer_label_view.view)
+ pin(footer_label_view.view, footer, (8, 16, 8, 14))
+ self.view.addSubview_(footer)
+ AppKit.NSLayoutConstraint.activateConstraints_([
+ footer.leadingAnchor().constraintEqualToAnchor_(self.view.leadingAnchor()),
+ footer.trailingAnchor().constraintEqualToAnchor_(self.view.trailingAnchor()),
+ footer.bottomAnchor().constraintEqualToAnchor_(self.view.bottomAnchor()),
+ ])
+
def select(self, key):
self.selected = key
for page, (_name, row, icon, words, bar, _dot) in self.rows.items():
diff --git a/win_app/.!55030!kvm_bridge_win.py b/win_app/.!55030!kvm_bridge_win.py
deleted file mode 100644
index e69de29..0000000
diff --git a/win_app/app_config.py b/win_app/app_config.py
index 836e259..e0c9024 100644
--- a/win_app/app_config.py
+++ b/win_app/app_config.py
@@ -7,6 +7,7 @@ import tempfile
from dataclasses import dataclass, field
from pathlib import Path
+import ignored
import protocol
@@ -29,6 +30,19 @@ TRIGGER_KEYS = {
"shift_r": "Right Shift",
"menu": "Menu",
}
+# The virtual key each trigger arrives as, so the ignored list can refuse the trigger.
+TRIGGER_VKS = {
+ "cmd_r": 0xA3,
+ "cmd": 0xA2,
+ "alt_r": 0xA5,
+ "alt": 0xA4,
+ "ctrl_r": 0x5C,
+ "ctrl": 0x5B,
+ "shift_r": 0xA1,
+ "menu": 0x5D,
+}
+
+
class ConfigError(Exception):
pass
@@ -72,6 +86,8 @@ class Config:
# 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
+ # Keys and buttons that stay on this PC while its input is on the Mac; see ignored.py.
+ ignored_inputs: list = field(default_factory=list)
def migrated_port(value) -> int:
@@ -181,6 +197,10 @@ def validate_config(config: Config) -> None:
raise ConfigError("mac_host must be text")
if config.mac_return_edge not in ("",) + EDGES:
raise ConfigError("mac_return_edge must be an edge name, or empty")
+ try:
+ ignored.validate(config.ignored_inputs)
+ except ValueError as exc:
+ raise ConfigError(str(exc)) from exc
def config_from_dict(raw: dict) -> Config:
@@ -212,6 +232,7 @@ def config_from_dict(raw: dict) -> Config:
mac_return_edge=raw.get("mac_return_edge", "") or "",
arrangement_set_at=int(raw.get("arrangement_set_at", 0)),
mac_resistance_px=int(raw.get("mac_resistance_px", 120)),
+ ignored_inputs=raw.get("ignored_inputs", []),
)
except (TypeError, ValueError) as exc:
raise ConfigError(f"config.json contains an invalid value: {exc}") from exc
@@ -263,6 +284,7 @@ def config_to_dict(config: Config) -> dict:
"mac_return_edge": config.mac_return_edge,
"arrangement_set_at": int(config.arrangement_set_at),
"mac_resistance_px": int(config.mac_resistance_px),
+ "ignored_inputs": list(config.ignored_inputs),
}
diff --git a/win_app/capture_win.py b/win_app/capture_win.py
index 84734d2..94a1231 100644
--- a/win_app/capture_win.py
+++ b/win_app/capture_win.py
@@ -79,6 +79,8 @@ WM_RBUTTONUP = 0x0205
WM_MBUTTONDOWN = 0x0207
WM_MBUTTONUP = 0x0208
WM_MOUSEWHEEL = 0x020A
+WM_XBUTTONDOWN = 0x020B
+WM_XBUTTONUP = 0x020C
WM_MOUSEHWHEEL = 0x020E
LLKHF_INJECTED = 0x10
@@ -98,6 +100,77 @@ BUTTON_MESSAGES = {
WM_MBUTTONUP: ("middle", False),
}
+# The side buttons share one pair of messages; the high word of mouseData says which.
+X_BUTTONS = {1: "back", 2: "forward"}
+
+
+def button_of(message: int, mouse_data: int) -> Optional[Tuple[str, bool]]:
+ """(name, down) for a button message, or None for a move or the wheel."""
+ fixed = BUTTON_MESSAGES.get(message)
+ if fixed is not None:
+ return fixed
+ if message in (WM_XBUTTONDOWN, WM_XBUTTONUP):
+ name = X_BUTTONS.get((mouse_data >> 16) & 0xFFFF)
+ if name is not None:
+ return name, message == WM_XBUTTONDOWN
+ return None
+
+
+# What the Keyboard page calls a recorded key, in Windows' own words.
+VK_TITLES: Dict[int, str] = {
+ 0x08: "Backspace", 0x09: "Tab", 0x0D: "Enter", 0x13: "Pause", 0x14: "Caps Lock", 0x1B: "Esc",
+ 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: "Left Windows", 0x5C: "Right Windows", 0x5D: "Menu", 0x6A: "Num *", 0x6B: "Num +",
+ 0x6D: "Num -", 0x6E: "Num .", 0x6F: "Num /", 0x90: "Num Lock", 0x91: "Scroll Lock",
+ 0xA0: "Left Shift", 0xA1: "Right Shift", 0xA2: "Left Ctrl", 0xA3: "Right Ctrl",
+ 0xA4: "Left Alt", 0xA5: "Right Alt", 0xA6: "Browser Back", 0xA7: "Browser Forward",
+ 0xAD: "Mute", 0xAE: "Volume Down", 0xAF: "Volume Up", 0xB0: "Next Track",
+ 0xB1: "Previous Track", 0xB2: "Stop", 0xB3: "Play/Pause", 0xBA: ";", 0xBB: "=", 0xBC: ",",
+ 0xBD: "-", 0xBE: ".", 0xBF: "/", 0xC0: "`", 0xDB: "[", 0xDC: "\\", 0xDD: "]", 0xDE: "'",
+}
+for _index in range(24):
+ VK_TITLES[0x70 + _index] = f"F{_index + 1}"
+for _index in range(10):
+ VK_TITLES[0x60 + _index] = f"Num {_index}"
+BUTTON_TITLES = {"right": "Right button", "middle": "Middle button", "back": "Back button", "forward": "Forward button"}
+
+
+def input_title(entry: str) -> str:
+ """The name an ignored-inputs entry is shown under."""
+ kind, _, value = entry.partition(":")
+ if kind == "button":
+ return BUTTON_TITLES.get(value, f"Button {value}")
+ if kind == "key" and value.isdigit():
+ vk = int(value)
+ if vk in VK_TITLES:
+ return VK_TITLES[vk]
+ if 0x30 <= vk <= 0x39 or 0x41 <= vk <= 0x5A:
+ return chr(vk)
+ return f"Key {vk}"
+ return entry
+
+
+VK_SHIFT_LEFT, VK_SHIFT_RIGHT = 0xA0, 0xA1
+VK_CONTROL_LEFT, VK_CONTROL_RIGHT = 0xA2, 0xA3
+VK_MENU_LEFT, VK_MENU_RIGHT = 0xA4, 0xA5
+_RIGHT_SHIFT_SCAN = 0x36
+_EXTENDED_SCAN = 0x100
+
+
+def hook_vk(vk: int, scan: int) -> int:
+ """The virtual key the low-level hook reports for a key a window saw as `vk` and `scan`. A
+ window is told only Shift, Ctrl or Alt; the hook always knows which side. `scan` carries the
+ extended-key bit at 0x100, which is how Qt reports it, and is what marks the right Ctrl and
+ the right Alt."""
+ if vk == 0x10:
+ return VK_SHIFT_RIGHT if scan & 0xFF == _RIGHT_SHIFT_SCAN else VK_SHIFT_LEFT
+ if vk == 0x11:
+ return VK_CONTROL_RIGHT if scan & _EXTENDED_SCAN else VK_CONTROL_LEFT
+ if vk == 0x12:
+ return VK_MENU_RIGHT if scan & _EXTENDED_SCAN else VK_MENU_LEFT
+ return vk
+
# 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
@@ -290,7 +363,7 @@ 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_key(name, down, vk)` 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
@@ -422,7 +495,7 @@ class Hooks:
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):
+ if self._on_key(name, down, data.vkCode):
return 1
except Exception:
# Never let an exception here swallow a key: fail open, log once
diff --git a/win_app/desktop_win.py b/win_app/desktop_win.py
index f15e19c..119ee8d 100644
--- a/win_app/desktop_win.py
+++ b/win_app/desktop_win.py
@@ -1,6 +1,6 @@
"""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,
+and EnumDisplayMonitors share one coordinate space — virtual-desktop pixels,
DPI-virtualised identically for this process — so values from one feed the
others unconverted."""
@@ -57,36 +57,33 @@ def cursor_position() -> Tuple[int, int]:
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
+_refused_under = [None]
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."""
+ """SetCursorPos returns FALSE with no error code, and SendInput is dropped
+ in silence, whenever Windows' UIPI puts the foreground window above
+ Beamer's integrity level, so a SendInput move is no fallback. The one such
+ window seen so far is GameInput's (see input_injector); for it the
+ placement runs again once the service has been restarted, and anything
+ else in front is named in the log."""
_require()
- if user32.SetCursorPos(int(x), int(y)):
+ x, y = int(x), int(y)
+ if user32.SetCursorPos(x, y):
+ _refused_under[0] = None
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,
- )
+ # Placed through this function again, so a refusal after the restart is logged too.
+ if input_injector.release_gameinput_foreground(after=lambda: set_cursor_position(x, y)):
+ return
+ blocker = input_injector.foreground_class()
+ # A hold at the return edge lands here on every move, so once per blocker.
+ if blocker != _refused_under[0]:
+ _refused_under[0] = blocker
+ LOGGER.warning(
+ "SetCursorPos refused (error %s) with %r in the foreground; Windows refuses Beamer's input "
+ "while a window above its integrity level is in front, until a click on this PC",
+ error, blocker,
+ )
diff --git a/win_app/edge_glow.py b/win_app/edge_glow.py
index 65712f2..0454c08 100644
--- a/win_app/edge_glow.py
+++ b/win_app/edge_glow.py
@@ -14,9 +14,9 @@ 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
+from PySide6.QtCore import QRect, QRectF, Qt, QTimer
+from PySide6.QtGui import QColor, QImage, QLinearGradient, QPainter, QPainterPath, QPen
+from PySide6.QtWidgets import QApplication, QSizePolicy, QWidget
import return_edge as crossing
import tokens
@@ -34,6 +34,13 @@ FINISH_SECONDS = 0.6
FINISH_TRAVERSE_S = 0.35
PROFILE_SAMPLES = 24
+# The Design page's scripted push: pressure builds for PUSH_S and goes through, the breakthrough
+# plays out, then everything rests before the next one. The Mac's previews run the same script.
+PUSH_S = 1.8
+AFTER_S = FINISH_SECONDS + 0.4
+REST_S = 1.0
+PREVIEW_HEIGHT = 96
+
def traverse_seconds(strength: float) -> float:
"""One run of the comet along the whole edge: unhurried at a light lean, quick near breakthrough."""
@@ -50,6 +57,111 @@ def comet_alpha(position: float, centre: float, flash: float) -> float:
return base + (1.0 - base) * reach * reach
+def preview_frame(elapsed: float):
+ """(pressure, phase) `elapsed` seconds into the preview's loop; phases are push, after and
+ rest."""
+ t = elapsed % (PUSH_S + AFTER_S + REST_S)
+ if t < PUSH_S:
+ return (t / PUSH_S) ** 1.6, "push"
+ return 0.0, "after" if t < PUSH_S + AFTER_S else "rest"
+
+
+class GlowState:
+ """What the glow shows at one moment -- the pressure, the breakthrough flash, the beam's run-off
+ and where the comet is -- and how it moves on between frames. The screen's glow and the Design
+ page's previews both run one, so a preview cannot drift from the real thing."""
+
+ def __init__(self) -> None:
+ self.pressure = 0.0
+ self.flash = 0.0
+ self.finish = 0.0
+ self.centre = -COMET / 2.0
+
+ def restart(self) -> None:
+ self.centre = -COMET / 2.0
+
+ def push(self, pressure: float, crossed: bool) -> None:
+ self.pressure = 0.0 if crossed else max(0.0, min(1.0, pressure))
+ if crossed:
+ self.flash = 1.0
+ self.finish = 1.0
+
+ def step(self, elapsed: float, stale: bool) -> bool:
+ """Moves on by `elapsed` seconds and answers whether anything is still lit. `stale` is
+ whether the push has stopped arriving, which is when the pressure fades on its own clock."""
+ if stale:
+ 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
+ return self.pressure > 0.0 or self.flash > 0.0 or self.finish > 0.0
+
+
+def paint(painter: QPainter, rect: QRect, edge: str, style: str, colour: str, state: GlowState, band: float = BAND_PX) -> None:
+ """Draws the glow along `edge` of `rect`, `band` deep: the palette along the edge, cut by a
+ falloff inward from it and, for the beam, the comet's profile along it."""
+ beam = style == "beam"
+ strength = max(state.pressure * 0.85, state.flash, state.finish if beam else 0.0)
+ if strength <= 0.0:
+ return
+ along = edge in ("left", "right")
+ length = rect.height() if along else rect.width()
+ painter.save()
+ painter.translate(rect.topLeft())
+ local = QRect(0, 0, rect.width(), rect.height())
+ painter.setOpacity(strength)
+ painter.fillRect(local, _colours(colour, along, length))
+ painter.setOpacity(1.0)
+ painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_DestinationIn)
+ if beam:
+ painter.fillRect(local, _falloff(edge, local, band, BEAM_FALLOFF))
+ painter.fillRect(local, _comet(along, length, state))
+ else:
+ depth = band * (0.35 + 0.65 * max(state.pressure, state.flash))
+ painter.fillRect(local, _falloff(edge, local, depth, ((0.0, 1.0), (1.0, 0.0))))
+ painter.restore()
+
+
+def _gradient_along(along: bool, length: int) -> QLinearGradient:
+ return QLinearGradient(0, 0, 0, length) if along else QLinearGradient(0, 0, length, 0)
+
+
+def _colours(colour: str, along: bool, length: int) -> QLinearGradient:
+ gradient = _gradient_along(along, length)
+ palette = tokens.PALETTES.get(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(edge: str, rect: QRect, depth: float, stops) -> QLinearGradient:
+ width, height = rect.width(), rect.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(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(along: bool, length: int, state: GlowState) -> QLinearGradient:
+ gradient = _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, state.centre, state.flash))))
+ return gradient
+
+
class EdgeGlow(QWidget):
def __init__(self) -> None:
super().__init__(
@@ -65,10 +177,7 @@ class EdgeGlow(QWidget):
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._state = GlowState()
self._updated_at = 0.0
self._ticked_at = 0.0
self._timer = QTimer(self)
@@ -84,14 +193,11 @@ class EdgeGlow(QWidget):
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._state.push(pressure, crossed)
self._updated_at = now
if self.isHidden():
self._ticked_at = now
- self._centre = -COMET / 2.0
+ self._state.restart()
self.show()
self._timer.start()
self.update()
@@ -117,69 +223,104 @@ class EdgeGlow(QWidget):
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:
+ if not self._state.step(elapsed, now - self._updated_at > STALE_SECONDS):
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))))
+ paint(painter, self.rect(), self._edge, self._style, self._colour, self._state)
+ painter.end()
+
+
+class GlowPreview(QWidget):
+ """A little desktop with the glow playing along the edge that leads to the Mac, painted by the
+ same `paint` and `GlowState` as the real one, at its real depth. `style` is fixed per preview;
+ the colour and the edge follow the settings."""
+
+ def __init__(self, style: str, colour: str = "signal", edge: str = "right", parent: QWidget | None = None) -> None:
+ super().__init__(parent)
+ self.style = style
+ self.colour = colour
+ self.edge = edge
+ self.state = GlowState()
+ self.setFixedHeight(PREVIEW_HEIGHT)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+ self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+
+ def set_look(self, colour: str, edge: str) -> None:
+ if (colour, edge) != (self.colour, self.edge):
+ self.colour, self.edge = colour, edge
+ self.update()
+
+ def paintEvent(self, _event) -> None:
+ painter = QPainter(self)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ frame = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
+ radius = tokens.RADIUS["field"]
+ outline = QPainterPath()
+ outline.addRoundedRect(frame, radius, radius)
+ ground = QLinearGradient(0, 0, 0, self.height())
+ ground.setColorAt(0.0, QColor(tokens.PALETTE["edge"]))
+ ground.setColorAt(1.0, QColor(tokens.PALETTE["well"]))
+ painter.fillPath(outline, ground)
+ # Painted on a layer of its own, as the real glow is on its own window: its masks cut the
+ # glow, and on the widget itself they would cut the ground under it too.
+ ratio = self.devicePixelRatioF()
+ layer = QImage(self.size() * ratio, QImage.Format.Format_ARGB32_Premultiplied)
+ layer.setDevicePixelRatio(ratio)
+ layer.fill(Qt.GlobalColor.transparent)
+ layer_painter = QPainter(layer)
+ paint(layer_painter, self.rect(), self.edge, self.style, self.colour, self.state)
+ layer_painter.end()
+ painter.save()
+ painter.setClipPath(outline)
+ painter.drawImage(0, 0, layer)
+ painter.restore()
+ painter.setPen(QPen(QColor(tokens.PALETTE["rule"]), 1))
+ painter.drawPath(outline)
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 gradient
+
+class PreviewLoop:
+ """Plays every preview from one clock, and only while someone can see them."""
+
+ def __init__(self, parent: QWidget) -> None:
+ self.previews: list = []
+ self._started_at = None
+ self._ticked_at = 0.0
+ self._phase = None
+ self._timer = QTimer(parent)
+ self._timer.setInterval(16)
+ self._timer.timeout.connect(self._tick)
+
+ def add(self, preview: GlowPreview) -> None:
+ self.previews.append(preview)
+
+ def run(self, wanted: bool) -> None:
+ if wanted and self._started_at is None:
+ self._started_at = self._ticked_at = time.monotonic()
+ self._phase = None
+ self._timer.start()
+ elif not wanted and self._started_at is not None:
+ self._started_at = None
+ self._timer.stop()
+ for preview in self.previews:
+ preview.state = GlowState()
+ preview.update()
+
+ def _tick(self) -> None:
+ now = time.monotonic()
+ elapsed, self._ticked_at = now - self._ticked_at, now
+ level, phase = preview_frame(now - self._started_at)
+ crossed = phase == "after" and self._phase == "push"
+ self._phase = phase
+ for preview in self.previews:
+ if crossed:
+ preview.state.push(1.0, True)
+ elif phase == "push":
+ preview.state.push(level, False)
+ preview.state.step(elapsed, phase != "push")
+ preview.update()
diff --git a/win_app/ignored.py b/win_app/ignored.py
new file mode 100644
index 0000000..5bc01a5
--- /dev/null
+++ b/win_app/ignored.py
@@ -0,0 +1,85 @@
+"""Keys and buttons that stay on the machine they were pressed on while its input is on the other
+one: a mouse's back and forward buttons kept for this machine's browser, a volume key kept for its
+speakers. A per-machine setting, so each app records its own keyboard's codes -- a Mac keycode and
+a Windows virtual key are different numbers for the same key, and neither end ever reads the
+other's list.
+
+Each entry is a string: `key:<code>` for a key in the platform's own numbering, `button:<name>`
+for a mouse button, and `media:<name>` for a Mac media key, which arrives as a system event rather
+than a key. Byte-identical in both apps.
+"""
+
+import re
+import threading
+
+MAX_ENTRIES = 64
+_ENTRY = re.compile(r"^(key:[0-9]{1,5}|button:[a-z0-9_]{1,24}|media:[a-z_]{1,24})$")
+
+
+def key(code):
+ return f"key:{int(code)}"
+
+
+def button(name):
+ return f"button:{name}"
+
+
+def media(name):
+ return f"media:{name}"
+
+
+def validate(entries):
+ """The list as saved, or ValueError naming what is wrong with it."""
+ if not isinstance(entries, list):
+ raise ValueError("ignored_inputs must be a list")
+ if len(entries) > MAX_ENTRIES:
+ raise ValueError(f"ignored_inputs holds at most {MAX_ENTRIES} entries")
+ for entry in entries:
+ if not isinstance(entry, str) or not _ENTRY.match(entry):
+ raise ValueError(f"ignored_inputs has an entry Beamer cannot read: {entry!r}")
+ return list(entries)
+
+
+class Gate:
+ """Decides, while input is on the other machine, which presses stay here.
+
+ A press stays when it is on the list. Its release goes wherever its press went, whatever the
+ list says by then: a key sent across and put on the list while still held would otherwise have
+ its release kept here and stay down on the far side, and one kept here and taken off the list
+ would stay down here. `keeps` runs on the one thread that reads input on each platform; `reset`
+ is for when input comes home, since the far side lets go of everything it was holding then, and
+ is called from other threads, hence the lock."""
+
+ def __init__(self, entries=()):
+ self.entries = frozenset(entries)
+ self._sent = set()
+ self._kept = set()
+ self._lock = threading.Lock()
+
+ def configure(self, entries):
+ self.entries = frozenset(entries)
+
+ def keeps(self, entry, down):
+ with self._lock:
+ if entry in self._sent:
+ if not down:
+ self._sent.discard(entry)
+ return False
+ if entry in self._kept:
+ if not down:
+ self._kept.discard(entry)
+ return True
+ if entry in self.entries:
+ if down:
+ self._kept.add(entry)
+ return True
+ if down:
+ self._sent.add(entry)
+ return False
+
+ def reset(self):
+ with self._lock:
+ self._sent.clear()
+ # A release that arrives once input is home is never asked about, so what was kept
+ # here is forgotten too.
+ self._kept.clear()
diff --git a/win_app/input_injector.py b/win_app/input_injector.py
index f28784d..f4cd8db 100644
--- a/win_app/input_injector.py
+++ b/win_app/input_injector.py
@@ -3,8 +3,10 @@
import ctypes
import functools
import logging
+import subprocess
import sys
import threading
+import time
from typing import Callable, Dict, List, Optional, Set, Tuple
@@ -19,6 +21,8 @@ if _IS_WINDOWS:
user32.VkKeyScanW.argtypes = [ctypes.c_wchar]
user32.MapVirtualKeyW.restype = ctypes.c_uint
user32.MapVirtualKeyW.argtypes = [ctypes.c_uint, ctypes.c_uint]
+ user32.GetForegroundWindow.restype = ctypes.c_void_p
+ user32.GetClassNameW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_int]
INPUT_MOUSE = 0
INPUT_KEYBOARD = 1
@@ -43,10 +47,12 @@ MOUSEEVENTF_RIGHTDOWN = 0x0008
MOUSEEVENTF_RIGHTUP = 0x0010
MOUSEEVENTF_MIDDLEDOWN = 0x0020
MOUSEEVENTF_MIDDLEUP = 0x0040
+MOUSEEVENTF_XDOWN = 0x0080
+MOUSEEVENTF_XUP = 0x0100
+XBUTTON1 = 0x0001
+XBUTTON2 = 0x0002
MOUSEEVENTF_WHEEL = 0x0800
MOUSEEVENTF_HWHEEL = 0x1000
-MOUSEEVENTF_VIRTUALDESK = 0x4000
-MOUSEEVENTF_ABSOLUTE = 0x8000
ULONG_PTR = ctypes.c_size_t
@@ -323,25 +329,116 @@ def _mouse_input(dx: int, dy: int, data: int, flags: int) -> INPUT:
def inject_mouse_move(dx: int, dy: int) -> None:
_send_input(_mouse_input(dx, dy, 0, MOUSEEVENTF_MOVE))
+ watch_foreground()
+
+
+# GameInputSvc.exe runs as SYSTEM in the console session and keeps a hidden
+# window of this class, and Windows can hand that window the foreground when
+# the foreground app closes (closing a Hyper-V VM Connection window did it on
+# the rig, 25-09-2026). While it is in front, UIPI refuses every SetCursorPos
+# and silently drops every SendInput from Beamer, which is elevated but not
+# SYSTEM, so the Mac's pointer goes dead on the PC. Nothing Beamer can call
+# takes the foreground back -- SetForegroundWindow, SwitchToThisWindow and an
+# injected Alt tap were all refused -- and moving the PC's own mouse does not
+# either; a click on the PC does, and so does restarting the service, which
+# takes the window with it and leaves Windows to activate an ordinary one.
+GAMEINPUT_WINDOW_CLASS = "GameInputServiceWindow"
+GAMEINPUT_RESTART = ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", "Restart-Service GameInputSvc -Force"]
+# A restart that did not free the pointer must not become a restart loop.
+GAMEINPUT_RESTART_COOLDOWN_SECONDS = 60.0
+
+_seen_foreground = [None]
+_gameinput_lock = threading.Lock()
+_gameinput_restarted_at = [float("-inf")]
+
+
+def _window_class(hwnd) -> str:
+ name = ctypes.create_unicode_buffer(128)
+ user32.GetClassNameW(hwnd, name, 128)
+ return name.value
+
+
+def foreground_class() -> str:
+ hwnd = user32.GetForegroundWindow()
+ return _window_class(hwnd) if hwnd else ""
+
+
+def watch_foreground() -> None:
+ """Called after every move the peer sends: one GetForegroundWindow, and a
+ class lookup only when the foreground has changed since the last move or
+ GameInput's window still holds it."""
+ hwnd = user32.GetForegroundWindow()
+ if hwnd == _seen_foreground[0]:
+ return
+ if hwnd and _window_class(hwnd) == GAMEINPUT_WINDOW_CLASS:
+ # Never marked seen, so a restart that failed or is cooling down is
+ # tried again on a later move.
+ release_gameinput_foreground()
+ return
+ _seen_foreground[0] = hwnd
+
+
+def release_gameinput_foreground(after: Optional[Callable[[], None]] = None) -> bool:
+ """If GameInput's window holds the foreground, restart GameInputSvc on a
+ thread of its own -- it takes a second or two, and the caller is the
+ session thread that must keep draining pings -- then run `after`. False
+ when GameInput is not in front, or a restart is already running or ran
+ within the cooldown."""
+ if foreground_class() != GAMEINPUT_WINDOW_CLASS:
+ return False
+ if time.monotonic() - _gameinput_restarted_at[0] < GAMEINPUT_RESTART_COOLDOWN_SECONDS:
+ return False
+ if not _gameinput_lock.acquire(blocking=False):
+ return False
+ _gameinput_restarted_at[0] = time.monotonic()
+
+ def restart() -> None:
+ try:
+ LOGGER.warning(
+ "GameInput's service window has the foreground, where Windows refuses Beamer's input; restarting GameInputSvc to free it"
+ )
+ try:
+ completed = subprocess.run(
+ GAMEINPUT_RESTART, capture_output=True, text=True, timeout=30,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ LOGGER.exception("Could not restart GameInputSvc; a click on this PC frees the pointer")
+ return
+ if completed.returncode != 0:
+ LOGGER.error("Restarting GameInputSvc failed (%s): %s", completed.returncode, completed.stderr.strip())
+ return
+ LOGGER.info("GameInputSvc restarted; %r now has the foreground", foreground_class())
+ if after is not None:
+ after()
+ except Exception:
+ LOGGER.exception("Freeing the foreground from GameInput failed")
+ finally:
+ _gameinput_lock.release()
-
-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))
+ threading.Thread(target=restart, name="Beamer-gameinput", daemon=True).start()
+ return True
BUTTON_DOWN_FLAGS = {
"left": MOUSEEVENTF_LEFTDOWN,
"right": MOUSEEVENTF_RIGHTDOWN,
"middle": MOUSEEVENTF_MIDDLEDOWN,
+ "back": MOUSEEVENTF_XDOWN,
+ "forward": MOUSEEVENTF_XDOWN,
}
BUTTON_UP_FLAGS = {
"left": MOUSEEVENTF_LEFTUP,
"right": MOUSEEVENTF_RIGHTUP,
"middle": MOUSEEVENTF_MIDDLEUP,
+ "back": MOUSEEVENTF_XUP,
+ "forward": MOUSEEVENTF_XUP,
}
+# Which X button, carried in mouseData: the side buttons share one pair of flags.
+BUTTON_DATA = {"back": XBUTTON1, "forward": XBUTTON2}
+
_buttons_down: Set[str] = set()
@@ -356,7 +453,7 @@ def inject_mouse_button(button: str, down: bool) -> None:
_buttons_down.add(button)
else:
_buttons_down.discard(button)
- _send_input(_mouse_input(0, 0, 0, flags))
+ _send_input(_mouse_input(0, 0, BUTTON_DATA.get(button, 0), flags))
@_locked
diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.py
index 5105c07..e2f917e 100644
--- a/win_app/kvm_bridge_win.py
+++ b/win_app/kvm_bridge_win.py
@@ -11,14 +11,15 @@ 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.QtCore import QEvent, QObject, QRectF, QSize, QTimer, Qt, QUrl, Signal
+from PySide6.QtGui import QColor, QDesktopServices, QIcon, QKeySequence, QPainter, QPixmap, QShortcut
from PySide6.QtWidgets import (
QApplication,
QCheckBox,
QFrame,
QGridLayout,
QHBoxLayout,
+ QLabel,
QLineEdit,
QMenu,
QMessageBox,
@@ -35,6 +36,7 @@ from app_config import (
Config,
ConfigError,
TRIGGER_KEYS,
+ TRIGGER_VKS,
default_config,
default_config_path,
load_config,
@@ -43,8 +45,9 @@ from app_config import (
)
import autostart_win
import capture_win
-from edge_glow import EdgeGlow
+from edge_glow import EdgeGlow, GlowPreview as EdgeGlowPreview, PreviewLoop
import firewall_win
+import ignored
from pairing import PAIRING_PORT, Announcer, local_address_towards
import pages_win
import protocol
@@ -64,6 +67,9 @@ try:
except OSError:
VERSION = "dev"
+HOME_PAGE = "https://kalkmancode.co.uk/beamer"
+HOME_PAGE_TEXT = "kalkmancode.co.uk/beamer"
+
IDLE_CODE = "––– –––"
PAIR_HINT = "Press Pair a Mac, then type this code into Beamer on the Mac."
@@ -224,6 +230,7 @@ class WindowsApplication(QWidget):
self.sender = MacSender(
status_callback=self.bridge.sending.emit,
redirect_callback=self.bridge.redirecting.emit,
+ pressure_callback=self.bridge.pressure.emit,
arrangement_callback=self.bridge.arrangement.emit,
)
self.sender.send_peer_home = self.server.send_home
@@ -244,6 +251,7 @@ class WindowsApplication(QWidget):
self.resize(820, 720)
self.setMinimumSize(*tokens.MIN_WINDOW["windows"])
self.setWindowIcon(QIcon(str(ICON_PATH)))
+ self.preview_loop = PreviewLoop(self)
self._build_window()
self._apply_theme()
self._build_tray()
@@ -272,7 +280,10 @@ class WindowsApplication(QWidget):
row_layout.setContentsMargins(0, 0, 0, 0)
row_layout.setSpacing(0)
- self.sidebar = widgets.Sidebar(pages_win.PAGES, self._select_page)
+ self.sidebar = widgets.Sidebar(
+ # Two lines: one, at the sidebar's fixed width, cuts the address off.
+ pages_win.PAGES, self._select_page, foot=f"Beamer {VERSION}\n{HOME_PAGE_TEXT}", on_foot=self.open_home_page
+ )
self.sidebar.setFixedWidth(theme.SIDEBAR_WIDTH)
row_layout.addWidget(self.sidebar)
row_layout.addWidget(widgets.rule())
@@ -294,6 +305,8 @@ class WindowsApplication(QWidget):
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,
"firewall": self._firewall_page,
@@ -336,6 +349,9 @@ class WindowsApplication(QWidget):
self._page = key
self.stack.setCurrentIndex(index)
self.sidebar.select(key)
+ if key != "keyboard":
+ self.ignored_recorder.cancel()
+ self._run_previews()
# -- Overview ---------------------------------------------------------------------------
@@ -377,6 +393,7 @@ class WindowsApplication(QWidget):
self.send_switch.toggled.connect(self._toggle_sending)
module.body.addWidget(self.send_switch)
self.send_hint = widgets.label("", "note", wrap=True)
+ self.send_hint.setVisible(False)
module.body.addWidget(self.send_hint)
self.logon_switch = widgets.Switch("Start Beamer when you sign in")
self.logon_switch.setFont(theme.font(theme.TYPE["body"]))
@@ -446,8 +463,6 @@ class WindowsApplication(QWidget):
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")
@@ -512,6 +527,7 @@ class WindowsApplication(QWidget):
self.sender.send_arrangement(mac_edge, self._config.arrangement_set_at)
self.server.send_arrangement(mac_edge, self._config.arrangement_set_at)
self.sender.update_config(self._config)
+ self._reflect_look()
def _set_corner(self, corner: str) -> None:
if self._config is None:
@@ -536,6 +552,7 @@ class WindowsApplication(QWidget):
self._persist()
self.sender.update_config(self._config)
self.edge_choice.set_value(pc_edge)
+ self._reflect_look()
def _resistance_module(self, current: Config) -> QWidget:
module = widgets.Module("Resistance")
@@ -572,6 +589,76 @@ class WindowsApplication(QWidget):
if text != self.resistance_hint.text():
self.resistance_hint.setText(text)
+ # -- Keyboard -----------------------------------------------------------------------------
+
+ def _keyboard_page(self, layout, current: Config) -> None:
+ layout.addWidget(self._shortcut_module(current))
+ layout.addWidget(self._ignored_module(current))
+
+ def _ignored_module(self, current: Config) -> QWidget:
+ module = widgets.Module("Stays on this PC")
+ self.ignored_note = widgets.label("", "note", wrap=True)
+ module.body.addWidget(self.ignored_note)
+ self.ignored_list = QVBoxLayout()
+ self.ignored_list.setSpacing(4)
+ module.body.addLayout(self.ignored_list)
+ self.ignored_recorder = widgets.InputRecorder("Add a key or button", self._record_ignored, capture_win.hook_vk)
+ module.body.addWidget(self.ignored_recorder)
+ self._show_ignored(list(current.ignored_inputs))
+ return module
+
+ def _show_ignored(self, entries: list, refused: str = "") -> None:
+ while self.ignored_list.count():
+ item = self.ignored_list.takeAt(0)
+ if item.widget() is not None:
+ item.widget().deleteLater()
+ for entry in entries:
+ row = QFrame()
+ row.setProperty("vernier", "entry")
+ row_layout = QHBoxLayout(row)
+ row_layout.setContentsMargins(12, 6, 6, 6)
+ name = widgets.label(capture_win.input_title(entry), "readout")
+ row_layout.addWidget(name, 1)
+ remove = QPushButton("Remove")
+ remove.setProperty("vernier", "remove")
+ remove.setCursor(Qt.CursorShape.PointingHandCursor)
+ remove.setAccessibleName(f"Remove {capture_win.input_title(entry)}")
+ remove.clicked.connect(lambda _checked=False, e=entry: self._remove_ignored(e))
+ row_layout.addWidget(remove)
+ self.ignored_list.addWidget(row)
+ text = refused or (
+ "These keep working on this PC while its input is on your Mac: a mouse's back button for "
+ "this PC's browser, say, or a volume key for its speakers."
+ if entries
+ else "Nothing yet. Every key and button goes to your Mac while it has input. Add one to keep "
+ "it here: a mouse's back button for this PC's browser, say, or a volume key for its speakers."
+ )
+ self.ignored_note.setText(text)
+ widgets.set_role(self.ignored_note, "note-amber" if refused else "note")
+
+ def _record_ignored(self, kind: str, value) -> None:
+ if self._config is None:
+ return
+ entries = list(self._config.ignored_inputs)
+ if kind == "key" and value == TRIGGER_VKS.get(self._config.trigger_key):
+ self._show_ignored(entries, "That key is the shortcut; it always stays with Beamer.")
+ return
+ entry = ignored.key(value) if kind == "key" else ignored.button(value)
+ if entry not in entries:
+ entries.append(entry)
+ self._set_ignored(entries)
+
+ def _remove_ignored(self, entry: str) -> None:
+ if self._config is None:
+ return
+ self._set_ignored([candidate for candidate in self._config.ignored_inputs if candidate != entry])
+
+ def _set_ignored(self, entries: list) -> None:
+ self._config.ignored_inputs = entries
+ self._persist()
+ self.sender.update_config(self._config)
+ self._show_ignored(entries)
+
def _shortcut_module(self, current: Config) -> QWidget:
module = widgets.Module("Shortcut")
module.body.addWidget(
@@ -636,29 +723,56 @@ class WindowsApplication(QWidget):
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))
+ # -- Design -------------------------------------------------------------------------------
+
+ def _design_page(self, layout, current: Config) -> None:
+ layout.addWidget(self._on_screen_module(current))
+ layout.addWidget(self._edge_look_module(current))
+
+ def _on_screen_module(self, current: Config) -> QWidget:
+ module = widgets.Module("On screen")
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(
+ widgets.label(
+ "Lights the edge of this PC that leads to your Mac as you push toward it. Switched "
+ "off, crossing still works. Your Mac sets how its own edge and notch look.",
+ "note",
+ wrap=True,
+ )
+ )
+ return module
+
+ def _edge_look_module(self, current: Config) -> QWidget:
+ module = widgets.Module("Edge and corner")
+ edge = current.mac_return_edge or "right"
+ self.glow_previews = {
+ style: EdgeGlowPreview(style, current.glow_colour, edge) for style, _title in GLOW_STYLE_CHOICES
+ }
+ for preview in self.glow_previews.values():
+ self.preview_loop.add(preview)
+ self.glow_style_choice = widgets.ChoiceTiles(
+ [
+ ("glow", "Glow", "A band of light that deepens the harder you push.", self.glow_previews["glow"]),
+ ("beam", "Beam", "A thin line with a comet of light running along it.", self.glow_previews["beam"]),
+ ],
+ 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
- )
+ self.glow_colour_choice = widgets.Swatches(GLOW_COLOUR_CHOICES, current.glow_colour, on_change=self._apply_look)
module.body.addWidget(self.glow_colour_choice.view)
+ self._reflect_look()
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."""
+ self._reflect_look()
if self._config is None:
return
self._config.edge_glow = self.glow_toggle.isChecked()
@@ -668,6 +782,22 @@ class WindowsApplication(QWidget):
if not self._config.edge_glow and self.glow is not None:
self.glow.hide()
+ def _reflect_look(self) -> None:
+ on = self.glow_toggle.isChecked()
+ self.glow_style_choice.set_enabled(on)
+ self.glow_colour_choice.set_enabled(on)
+ edge = (self._config.mac_return_edge if self._config is not None else "") or "right"
+ for preview in self.glow_previews.values():
+ preview.set_look(self.glow_colour_choice.value or "signal", edge)
+ self._run_previews()
+
+ def _run_previews(self) -> None:
+ """The previews play only while someone can see them: the Design page open in a visible
+ window, with the glow switched on."""
+ self.preview_loop.run(
+ self.isVisible() and not self.isMinimized() and self._page == "design" and self.glow_toggle.isChecked()
+ )
+
def _debounce_save(self) -> None:
"""A ruler being dragged writes once at the end rather than on every step."""
self._apply_serial += 1
@@ -1044,6 +1174,7 @@ class WindowsApplication(QWidget):
self.drive_action.setChecked(self.allow_switch.isChecked())
self.send_action.setChecked(self.send_switch.isChecked())
menu.addSeparator()
+ menu.addAction("About Beamer").triggered.connect(self.show_about)
menu.addAction("Quit Beamer").triggered.connect(self.quit)
self.tray.setContextMenu(menu)
# Left click opens the window; right click is the
@@ -1080,10 +1211,10 @@ class WindowsApplication(QWidget):
return
self.sender.start(config)
- def _on_hook_key(self, name: str, down: bool) -> bool:
+ def _on_hook_key(self, name: str, down: bool, vk: Optional[int] = None) -> 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."""
+ input, and a key on the ignored list not even then."""
action = self._trigger.feed(name, down, time.monotonic())
if action is not None:
if not self.sender.shortcut_armed:
@@ -1097,7 +1228,7 @@ class WindowsApplication(QWidget):
return True
if self._trigger.claims(name, down, self.sender.redirecting):
return True
- return self.sender.on_key(name, down)
+ return self.sender.on_key(name, down, vk)
def _on_focus(self, target: str) -> None:
"""The Mac took input on this PC, or gave it back. Either way the
@@ -1132,6 +1263,7 @@ class WindowsApplication(QWidget):
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)
+ self._reflect_look()
def _on_sending(self, connected: bool, detail: str) -> None:
self._sending_detail = detail
@@ -1149,6 +1281,39 @@ class WindowsApplication(QWidget):
self.raise_()
self.activateWindow()
+ def open_home_page(self) -> None:
+ QDesktopServices.openUrl(QUrl(HOME_PAGE))
+
+ def show_about(self) -> None:
+ box = QMessageBox(self)
+ box.setWindowTitle("About Beamer")
+ box.setIconPixmap(QIcon(str(ICON_PATH)).pixmap(64, 64))
+ box.setTextFormat(Qt.TextFormat.RichText)
+ box.setText(
+ f"<b>Beamer {VERSION}</b><br>One keyboard and mouse for your Mac and PC.<br><br>"
+ f'<a href="{HOME_PAGE}" style="color: {theme.colour("signal")};">{HOME_PAGE_TEXT}</a>'
+ )
+ box.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
+ for text in box.findChildren(QLabel):
+ text.setOpenExternalLinks(True)
+ box.setStandardButtons(QMessageBox.StandardButton.Ok)
+ box.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
+ box.show()
+
+ def showEvent(self, event) -> None:
+ super().showEvent(event)
+ self._run_previews()
+
+ def hideEvent(self, event) -> None:
+ super().hideEvent(event)
+ self.ignored_recorder.cancel()
+ self._run_previews()
+
+ def changeEvent(self, event) -> None:
+ super().changeEvent(event)
+ if event.type() == QEvent.Type.WindowStateChange:
+ self._run_previews()
+
def quit(self) -> None:
if self._closing:
return
@@ -1244,6 +1409,8 @@ class WindowsApplication(QWidget):
) else self._sending_detail
if send_hint != self.send_hint.text():
self.send_hint.setText(send_hint)
+ # Hidden while empty, or its spacing leaves a gap between the two switches.
+ self.send_hint.setVisible(bool(send_hint))
self.sidebar.set_link(tone, SIDEBAR_LINK_WORDS.get(state, "Unknown"))
self.sidebar.set_dots(pages_win.dots(self._config is None, self._firewall_tone))
self._refresh_pairing()
diff --git a/win_app/pages_win.py b/win_app/pages_win.py
index 72bf28e..ff7505d 100644
--- a/win_app/pages_win.py
+++ b/win_app/pages_win.py
@@ -10,8 +10,13 @@ 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."),
+ "How input leaves this PC: the ways in, the arrangement with your Mac, and how hard the edge "
+ "pushes back first."),
+ ("design", "Design",
+ "How crossing looks on this PC: the light along the edge that leads to your Mac. Every "
+ "change applies as you make it."),
+ ("keyboard", "Keyboard",
+ "The key that sends input to your Mac, and the keys and buttons that stay on this PC."),
("pairing", "Pairing",
"Connect a Mac to this PC by typing the code it shows here. Once per Mac."),
("connection", "Connection",
diff --git a/win_app/sender.py b/win_app/sender.py
index 843f59f..713ea5a 100644
--- a/win_app/sender.py
+++ b/win_app/sender.py
@@ -28,6 +28,7 @@ import threading
import time
from typing import Callable, Optional
+import ignored
import protocol
import return_edge
@@ -169,6 +170,7 @@ class MacSender:
# 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._ignore_gate = ignored.Gate()
self._last_sent_seq = 0
self._last_ack_seq = -1
self._last_ack_at = 0.0
@@ -253,6 +255,7 @@ class MacSender:
with self._config_lock:
previous = self._config
self._config = config
+ self._ignore_gate.configure(getattr(config, "ignored_inputs", None) or ())
edge = getattr(config, "mac_return_edge", "") or None
self._edge = edge if edge in return_edge.EDGES else None
self._rearm_edge()
@@ -287,7 +290,7 @@ class MacSender:
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:
+ def on_key(self, name: str, down: bool, vk: Optional[int] = None) -> 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
@@ -301,6 +304,8 @@ class MacSender:
if not self._link_live():
self._force_local("the link to the Mac went quiet")
return False
+ if vk is not None and self._ignore_gate.keeps(ignored.key(vk), down):
+ return False
if down:
self._keys_down[name] = True
self._enqueue({"type": protocol.MSG_KEYDOWN, "data": {"key": name}})
@@ -343,9 +348,11 @@ class MacSender:
self._press_edge(int(dx), int(dy))
def _send_mouse(self, capture_win, message, mouse_data) -> bool:
- button = capture_win.BUTTON_MESSAGES.get(message)
+ button = capture_win.button_of(message, mouse_data)
if button is not None:
name, down = button
+ if self._ignore_gate.keeps(ignored.button(name), down):
+ return False
self._enqueue(
{"type": protocol.MSG_MOUSEDOWN if down else protocol.MSG_MOUSEUP, "data": {"button": name}}
)
@@ -356,8 +363,8 @@ class MacSender:
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.
+ # Anything else the Mac has no name for: left to Windows rather than
+ # dropped.
return False
def _press_edge(self, dx, dy) -> None:
@@ -368,8 +375,14 @@ class MacSender:
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:
+ and only a breakthrough acts.
+
+ It runs while the Mac is driving this PC too. Every move the Mac makes
+ here carries INJECTED_MARK and never arrives, so what does is this
+ PC's own mouse, and its push out means the pointer is going back to
+ the Mac with this mouse behind it (27-09-2026: it was ignored, and only
+ the Mac's trackpad could take the pointer back)."""
+ if not self.connected:
return
try:
desktop = self._desktop_module()
@@ -391,6 +404,15 @@ class MacSender:
return
self._notify_pressure(model.edge, outcome.pressure, outcome.action == return_edge.CROSS)
if outcome.action == return_edge.CROSS:
+ if self._receiving:
+ # The Mac's input goes home first, over its own link; its
+ # focus back to the Mac clears receiving here too, later, and
+ # finds it already cleared.
+ send_home = self.send_peer_home
+ if send_home is None or not send_home():
+ LOGGER.warning("cannot cross: the Mac is driving this PC and cannot be reached")
+ return
+ self._receiving = False
# The model names the edge on the far side, not the one just left:
# it is the same border, read from the other end.
self.set_redirecting(True, arrival_edge=outcome.edge, offset=outcome.offset)
@@ -438,6 +460,7 @@ class MacSender:
# focus goes home, marked to pass the gate that has just closed.
# The entries stay, so the physical releases here are swallowed.
self.redirecting = False
+ self._ignore_gate.reset()
for name in list(self._keys_down):
self._enqueue_control({"type": protocol.MSG_KEYUP, "data": {"key": name}, _RELEASE_MARK: True})
self._pin_point = None
@@ -759,6 +782,13 @@ class MacSender:
LOGGER.exception("Redirect callback failed")
def _connection_failed(self, reason, expected_socket=None) -> None:
+ with self._socket_lock:
+ stale = expected_socket is not None and self._sock is not expected_socket
+ if stale:
+ # A deliberate stop or a reconnect already dropped this socket --
+ # closing it out from under a worker mid-recv/-send raises an
+ # OSError of its own, which is not a connection failure.
+ return
self._force_local(reason)
self._set_status(reason)
self._drop_connection(expected_socket)
diff --git a/win_app/tests/test_edge_glow.py b/win_app/tests/test_edge_glow.py
index 094c77f..72526f5 100644
--- a/win_app/tests/test_edge_glow.py
+++ b/win_app/tests/test_edge_glow.py
@@ -21,5 +21,37 @@ class BeamMathsTests(unittest.TestCase):
self.assertEqual(edge_glow.comet_alpha(0.0, 0.5, 1.0), 1.0)
[email protected](edge_glow is None, "PySide6 is not installed")
+class GlowStateTests(unittest.TestCase):
+ def test_a_breakthrough_flashes_then_fades_out(self):
+ state = edge_glow.GlowState()
+ state.push(0.6, False)
+ state.push(1.0, True)
+ self.assertEqual((state.pressure, state.flash, state.finish), (0.0, 1.0, 1.0))
+ self.assertTrue(state.step(0.1, stale=True))
+ self.assertFalse(state.step(5.0, stale=True))
+
+ def test_pressure_holds_while_the_push_keeps_arriving(self):
+ state = edge_glow.GlowState()
+ state.push(0.5, False)
+ state.step(0.2, stale=False)
+ self.assertEqual(state.pressure, 0.5)
+
+
[email protected](edge_glow is None, "PySide6 is not installed")
+class PreviewScriptTests(unittest.TestCase):
+ def test_the_push_builds_goes_through_and_rests(self):
+ self.assertEqual(edge_glow.preview_frame(0.0), (0.0, "push"))
+ level, phase = edge_glow.preview_frame(edge_glow.PUSH_S * 0.9)
+ self.assertEqual(phase, "push")
+ self.assertGreater(level, 0.8)
+ self.assertEqual(edge_glow.preview_frame(edge_glow.PUSH_S + 0.1), (0.0, "after"))
+ self.assertEqual(edge_glow.preview_frame(edge_glow.PUSH_S + edge_glow.AFTER_S + 0.1), (0.0, "rest"))
+
+ def test_it_loops(self):
+ loop = edge_glow.PUSH_S + edge_glow.AFTER_S + edge_glow.REST_S
+ self.assertEqual(edge_glow.preview_frame(loop + 0.5), edge_glow.preview_frame(0.5))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/win_app/tests/test_gameinput_foreground.py b/win_app/tests/test_gameinput_foreground.py
new file mode 100644
index 0000000..eb78da8
--- /dev/null
+++ b/win_app/tests/test_gameinput_foreground.py
@@ -0,0 +1,138 @@
+"""GameInput's SYSTEM window taking the foreground, exercised on any platform.
+
+While GameInputSvc's hidden window is in front, Windows refuses Beamer's
+SetCursorPos and drops its SendInput, and the only way out Beamer has is to
+restart the service. user32, subprocess.run and the restart thread are all
+faked here, so this suite runs on the Mac.
+"""
+
+import ctypes
+import subprocess
+import unittest
+from unittest import mock
+
+import desktop_win
+import input_injector
+
+
+class FakeUser32:
+ def __init__(self, classes, foreground=None, set_results=()):
+ self.classes = classes
+ self.foreground = foreground
+ self.set_results = list(set_results)
+ self.set_calls = []
+
+ def GetForegroundWindow(self):
+ return self.foreground
+
+ def GetClassNameW(self, hwnd, buffer, size):
+ buffer.value = self.classes.get(hwnd, "")
+ return len(buffer.value)
+
+ def SetCursorPos(self, x, y):
+ self.set_calls.append((x, y))
+ return self.set_results.pop(0) if self.set_results else 1
+
+
+class InlineThread:
+ """Runs the restart on start(), so a test sees its effects at once."""
+
+ def __init__(self, target, name=None, daemon=None):
+ self.target = target
+
+ def start(self):
+ self.target()
+
+
+GAMEINPUT, EXPLORER = 0x5403CC, 0xD0002E
+CLASSES = {GAMEINPUT: input_injector.GAMEINPUT_WINDOW_CLASS, EXPLORER: "CabinetWClass"}
+
+
+class GameInputForegroundTests(unittest.TestCase):
+ def setUp(self):
+ self.user32 = FakeUser32(CLASSES)
+ self.restarts = []
+
+ def restart(args, **kwargs):
+ self.restarts.append((args, kwargs))
+ self.user32.foreground = EXPLORER
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ self.clock = [1000.0]
+ patches = [
+ mock.patch.object(input_injector, "user32", self.user32),
+ mock.patch.object(desktop_win, "user32", self.user32),
+ mock.patch.object(input_injector.subprocess, "run", side_effect=restart),
+ mock.patch.object(input_injector.threading, "Thread", InlineThread),
+ mock.patch.object(input_injector.time, "monotonic", lambda: self.clock[0]),
+ mock.patch.object(ctypes, "get_last_error", create=True, return_value=0),
+ mock.patch.object(input_injector, "_seen_foreground", [None]),
+ mock.patch.object(input_injector, "_gameinput_restarted_at", [float("-inf")]),
+ mock.patch.object(desktop_win, "_refused_under", [None]),
+ ]
+ for patch in patches:
+ patch.start()
+ self.addCleanup(patch.stop)
+
+ def test_a_move_under_gameinput_restarts_the_service_without_a_console(self):
+ self.user32.foreground = GAMEINPUT
+ input_injector.watch_foreground()
+ self.assertEqual(len(self.restarts), 1)
+ args, kwargs = self.restarts[0]
+ self.assertEqual(args, input_injector.GAMEINPUT_RESTART)
+ self.assertIn("Restart-Service GameInputSvc", args[-1])
+ self.assertEqual(kwargs["creationflags"], getattr(subprocess, "CREATE_NO_WINDOW", 0))
+
+ def test_an_ordinary_foreground_is_left_alone(self):
+ self.user32.foreground = EXPLORER
+ for _ in range(3):
+ input_injector.watch_foreground()
+ self.assertEqual(self.restarts, [])
+
+ def test_the_class_is_read_only_when_the_foreground_changes(self):
+ self.user32.foreground = EXPLORER
+ with mock.patch.object(input_injector, "_window_class", wraps=input_injector._window_class) as lookup:
+ for _ in range(5):
+ input_injector.watch_foreground()
+ self.assertEqual(lookup.call_count, 1)
+
+ def test_a_restart_that_did_not_free_it_waits_out_the_cooldown_then_tries_again(self):
+ self.restarts_leave_gameinput_in_front()
+ self.user32.foreground = GAMEINPUT
+ input_injector.watch_foreground()
+ self.clock[0] += 5
+ input_injector.watch_foreground()
+ self.assertEqual(len(self.restarts), 1)
+ self.clock[0] += input_injector.GAMEINPUT_RESTART_COOLDOWN_SECONDS
+ input_injector.watch_foreground()
+ self.assertEqual(len(self.restarts), 2)
+
+ def test_a_refused_arrival_is_placed_again_once_gameinput_is_gone(self):
+ self.user32.foreground = GAMEINPUT
+ self.user32.set_results = [0]
+ desktop_win.set_cursor_position(1818, 2159)
+ self.assertEqual(len(self.restarts), 1)
+ self.assertEqual(self.user32.set_calls, [(1818, 2159), (1818, 2159)])
+
+ def test_a_refusal_under_anything_else_is_logged_once_per_blocker(self):
+ self.user32.foreground = EXPLORER
+ self.user32.set_results = [0, 0, 0, 1, 0]
+ with self.assertLogs(desktop_win.LOGGER, "WARNING") as logs:
+ for _ in range(3):
+ desktop_win.set_cursor_position(10, 10)
+ desktop_win.set_cursor_position(10, 10)
+ desktop_win.set_cursor_position(10, 10)
+ self.assertEqual(len(logs.records), 2)
+ self.assertIn("CabinetWClass", logs.output[0])
+ self.assertEqual(self.restarts, [])
+
+ def restarts_leave_gameinput_in_front(self):
+ def restart(args, **kwargs):
+ self.restarts.append((args, kwargs))
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ input_injector.subprocess.run.side_effect = restart
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_ignored.py b/win_app/tests/test_ignored.py
new file mode 100644
index 0000000..244af59
--- /dev/null
+++ b/win_app/tests/test_ignored.py
@@ -0,0 +1,56 @@
+"""The ignored-inputs gate both apps share. Byte-identical in mac_app and win_app."""
+
+import unittest
+
+import ignored
+
+
+class GateTests(unittest.TestCase):
+ def test_a_listed_press_and_its_release_stay_here(self):
+ gate = ignored.Gate([ignored.button("back")])
+ self.assertTrue(gate.keeps("button:back", True))
+ self.assertTrue(gate.keeps("button:back", False))
+
+ def test_anything_else_goes_across(self):
+ gate = ignored.Gate([ignored.button("back")])
+ self.assertFalse(gate.keeps("key:12", True))
+ self.assertFalse(gate.keeps("key:12", False))
+
+ def test_a_release_follows_its_press_across_when_the_list_changes_mid_hold(self):
+ gate = ignored.Gate()
+ self.assertFalse(gate.keeps("key:122", True))
+ gate.configure([ignored.key(122)])
+ self.assertFalse(gate.keeps("key:122", True), "an autorepeat of a key already across stays across")
+ self.assertFalse(gate.keeps("key:122", False), "its release must reach the far side")
+ self.assertTrue(gate.keeps("key:122", True), "the next press is kept here")
+
+ def test_a_press_kept_here_keeps_its_release_here_when_taken_off_the_list(self):
+ gate = ignored.Gate([ignored.key(122)])
+ self.assertTrue(gate.keeps("key:122", True))
+ gate.configure([])
+ self.assertTrue(gate.keeps("key:122", False), "the release must reach this machine, which has the press")
+ self.assertFalse(gate.keeps("key:122", True), "the next press goes across")
+
+ def test_a_release_outside_the_list_with_no_press_seen_goes_across(self):
+ gate = ignored.Gate()
+ self.assertFalse(gate.keeps("key:5", False))
+
+ def test_reset_forgets_what_went_across(self):
+ gate = ignored.Gate()
+ gate.keeps("key:5", True)
+ gate.configure(["key:5"])
+ gate.reset()
+ self.assertTrue(gate.keeps("key:5", False))
+
+ def test_validate_takes_every_kind_of_entry(self):
+ entries = [ignored.key(0), ignored.key(0xA3), ignored.button("forward"), ignored.button("6"), ignored.media("volume_up")]
+ self.assertEqual(ignored.validate(entries), entries)
+
+ def test_validate_refuses_what_it_cannot_read(self):
+ for bad in ("f13", ["key:"], ["key:abc"], ["mouse:back"], [12], ["key:1"] * (ignored.MAX_ENTRIES + 1)):
+ with self.subTest(bad=bad), self.assertRaises(ValueError):
+ ignored.validate(bad)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_ignored_inputs.py b/win_app/tests/test_ignored_inputs.py
new file mode 100644
index 0000000..95b8e1b
--- /dev/null
+++ b/win_app/tests/test_ignored_inputs.py
@@ -0,0 +1,166 @@
+"""Keys and buttons that stay on this PC while its input is on the Mac: the sender's decision on
+the hook thread, the side buttons now crossing, and the setting's round trip through config.json."""
+
+import json
+import tempfile
+import time
+import unittest
+from pathlib import Path
+
+import app_config
+import capture_win
+import ignored
+import protocol
+import sender
+from fakes import FakeClipboard, FakeDesktop
+from return_edge import Rect
+
+VK_F13 = 0x7C
+VK_A = 0x41
+
+
+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 app_config.Config(**values)
+
+
+def x_button(message, number):
+ return message, number << 16
+
+
+class SenderTests(unittest.TestCase):
+ def setUp(self):
+ self.sender = sender.MacSender(
+ desktop=FakeDesktop([Rect(0, 0, 1920, 1080)], cursor=(900, 500)),
+ clipboard=FakeClipboard(),
+ is_local=lambda host: False,
+ )
+ self.configure([ignored.key(VK_F13), ignored.button("back")])
+ self.sender._sock = object()
+ self.sender._connected_at = time.monotonic()
+ self.sender._last_ack_at = time.monotonic()
+ self.sender.set_redirecting(True)
+ self.drain()
+
+ def tearDown(self):
+ self.sender._sock = None
+
+ def configure(self, entries):
+ self.sender.update_config(make_config(ignored_inputs=list(entries)))
+
+ def drain(self):
+ messages = []
+ while not self.sender._outbound.empty():
+ messages.append(self.sender._outbound.get_nowait())
+ return [(m["type"], m["data"]) for m in messages if m["type"] in (
+ protocol.MSG_KEYDOWN, protocol.MSG_KEYUP, protocol.MSG_MOUSEDOWN, protocol.MSG_MOUSEUP
+ )]
+
+ def test_an_ignored_key_reaches_this_pc_and_not_the_mac(self):
+ self.assertFalse(self.sender.on_key("f13", True, VK_F13))
+ self.assertFalse(self.sender.on_key("f13", False, VK_F13))
+ self.assertEqual(self.drain(), [])
+
+ def test_any_other_key_still_goes_to_the_mac(self):
+ self.assertTrue(self.sender.on_key("a", True, VK_A))
+ self.assertTrue(self.sender.on_key("a", False, VK_A))
+ self.assertEqual(self.drain(), [
+ (protocol.MSG_KEYDOWN, {"key": "a"}),
+ (protocol.MSG_KEYUP, {"key": "a"}),
+ ])
+
+ def test_a_key_ignored_while_held_on_the_mac_is_still_released_there(self):
+ self.configure([])
+ self.assertTrue(self.sender.on_key("f13", True, VK_F13))
+ self.configure([ignored.key(VK_F13)])
+ self.assertTrue(self.sender.on_key("f13", False, VK_F13))
+ self.assertEqual(self.drain(), [
+ (protocol.MSG_KEYDOWN, {"key": "f13"}),
+ (protocol.MSG_KEYUP, {"key": "f13"}),
+ ])
+
+ def test_the_side_buttons_cross_as_back_and_forward(self):
+ self.configure([])
+ for message in (capture_win.WM_XBUTTONDOWN, capture_win.WM_XBUTTONUP):
+ message, data = x_button(message, 2)
+ self.assertTrue(self.sender.on_mouse(message, 0, 0, data))
+ self.assertEqual(self.drain(), [
+ (protocol.MSG_MOUSEDOWN, {"button": "forward"}),
+ (protocol.MSG_MOUSEUP, {"button": "forward"}),
+ ])
+
+ def test_an_ignored_button_stays_on_this_pc(self):
+ message, data = x_button(capture_win.WM_XBUTTONDOWN, 1)
+ self.assertFalse(self.sender.on_mouse(message, 0, 0, data))
+ message, data = x_button(capture_win.WM_XBUTTONUP, 1)
+ self.assertFalse(self.sender.on_mouse(message, 0, 0, data))
+ self.assertTrue(self.sender.on_mouse(capture_win.WM_MBUTTONDOWN, 0, 0, 0))
+ self.assertEqual(self.drain(), [(protocol.MSG_MOUSEDOWN, {"button": "middle"})])
+
+
+class CaptureTests(unittest.TestCase):
+ def test_x_buttons_are_named_from_the_high_word(self):
+ self.assertEqual(capture_win.button_of(capture_win.WM_XBUTTONDOWN, 1 << 16), ("back", True))
+ self.assertEqual(capture_win.button_of(capture_win.WM_XBUTTONUP, 2 << 16), ("forward", False))
+ self.assertIsNone(capture_win.button_of(capture_win.WM_XBUTTONDOWN, 3 << 16))
+ self.assertIsNone(capture_win.button_of(capture_win.WM_MOUSEWHEEL, 120 << 16))
+ self.assertEqual(capture_win.button_of(capture_win.WM_RBUTTONDOWN, 0), ("right", True))
+
+ def test_entries_are_shown_in_windows_own_words(self):
+ titles = {
+ ignored.key(0xA3): "Right Ctrl",
+ ignored.key(VK_F13): "F13",
+ ignored.key(VK_A): "A",
+ ignored.key(0xAF): "Volume Up",
+ ignored.key(0xFE): "Key 254",
+ ignored.button("back"): "Back button",
+ ignored.button("6"): "Button 6",
+ }
+ for entry, title in titles.items():
+ self.assertEqual(capture_win.input_title(entry), title)
+
+ def test_every_trigger_key_has_its_virtual_key(self):
+ self.assertEqual(set(app_config.TRIGGER_VKS), set(app_config.TRIGGER_KEYS))
+ for name, vk in app_config.TRIGGER_VKS.items():
+ self.assertEqual(capture_win.VK_TO_NAME[vk], name)
+
+ def test_a_windows_modifier_is_recorded_as_the_side_the_hook_reports(self):
+ self.assertEqual(capture_win.hook_vk(0x11, 0x1D), 0xA2)
+ self.assertEqual(capture_win.hook_vk(0x11, 0x11D), 0xA3)
+ self.assertEqual(capture_win.hook_vk(0x12, 0x38), 0xA4)
+ self.assertEqual(capture_win.hook_vk(0x12, 0x138), 0xA5)
+ self.assertEqual(capture_win.hook_vk(0x10, 0x2A), 0xA0)
+ self.assertEqual(capture_win.hook_vk(0x10, 0x36), 0xA1)
+ self.assertEqual(capture_win.hook_vk(VK_A, 0x1E), VK_A)
+
+
+class ConfigTests(unittest.TestCase):
+ def test_the_list_survives_a_save_and_a_load(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "config.json"
+ entries = [ignored.key(VK_F13), ignored.button("back")]
+ app_config.save_config(path, make_config(port=24820, ignored_inputs=entries))
+ self.assertEqual(json.loads(path.read_text())["ignored_inputs"], entries)
+ self.assertEqual(app_config.load_config(path).ignored_inputs, entries)
+
+ def test_an_older_config_has_nothing_ignored(self):
+ raw = app_config.config_to_dict(make_config(port=24820))
+ del raw["ignored_inputs"]
+ self.assertEqual(app_config.config_from_dict(raw).ignored_inputs, [])
+
+ def test_an_unreadable_entry_is_refused(self):
+ with self.assertRaises(app_config.ConfigError):
+ app_config.validate_config(make_config(port=24820, ignored_inputs=["f13"]))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_input_injector.py b/win_app/tests/test_input_injector.py
index 2a0605c..d192a4d 100644
--- a/win_app/tests/test_input_injector.py
+++ b/win_app/tests/test_input_injector.py
@@ -370,6 +370,19 @@ class InjectScrollDispatchTests(unittest.TestCase):
self.assertAlmostEqual(input_injector._scroll_accum[0], 0.1 * WHEEL_UNITS_PER_PIXEL, places=6)
+class InjectSideButtonTests(unittest.TestCase):
+ def tearDown(self):
+ input_injector._buttons_down.clear()
+
+ def test_back_and_forward_are_x_buttons_one_and_two(self):
+ with mock.patch.object(input_injector, "_send_input") as fake_send:
+ input_injector.inject_mouse_button("back", True)
+ input_injector.inject_mouse_button("forward", False)
+ sent = [call.args[0].union.mi for call in fake_send.call_args_list]
+ self.assertEqual((sent[0].dwFlags, sent[0].mouseData), (input_injector.MOUSEEVENTF_XDOWN, 1))
+ self.assertEqual((sent[1].dwFlags, sent[1].mouseData), (input_injector.MOUSEEVENTF_XUP, 2))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/win_app/tests/test_sender.py b/win_app/tests/test_sender.py
index 6a6c47f..ef58353 100644
--- a/win_app/tests/test_sender.py
+++ b/win_app/tests/test_sender.py
@@ -54,7 +54,29 @@ class EdgeTests(unittest.TestCase):
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):
+ def test_the_push_lights_the_edge_it_is_pressing(self):
+ # The app once built its sender with no pressure callback, so the PC's own push out to
+ # the Mac crossed in the dark while the same edge lit for the Mac's push home.
+ seen = []
+ self.link.sender._pressure_callback = lambda edge, pressure, crossed: seen.append((edge, crossed))
+ self.push(4)
+ self.assertTrue(seen, "a push against the edge reported no pressure")
+ self.assertTrue(all(edge == "left" for edge, _ in seen))
+ self.assertEqual(seen[-1][1], True)
+
+ def test_this_pcs_own_mouse_pushing_out_while_the_mac_drives_takes_the_pointer_across(self):
+ # 27-09-2026: the Mac's trackpad crossed to the PC, and the PC's own mouse could not push
+ # back out. The Mac's injected moves carry INJECTED_MARK and never reach on_motion, so a
+ # push here is the hand's: the Mac gets its input back and this mouse follows it across.
+ sent_home = []
+ self.link.sender.send_peer_home = lambda: sent_home.append(True) or True
+ self.link.sender.set_receiving(True)
+ self.push(4)
+ self.assertEqual(sent_home, [True])
+ self.assertTrue(self.link.sender.redirecting)
+
+ def test_a_push_while_the_mac_drives_and_cannot_be_sent_home_stays_here(self):
+ self.link.sender.send_peer_home = lambda: False
self.link.sender.set_receiving(True)
self.push(10)
self.assertFalse(self.link.sender.redirecting)
@@ -258,6 +280,43 @@ class LinkTests(unittest.TestCase):
self.assertEqual(self.clipboard.set_calls[0][0], "copied")
+class ConnectionFailedTests(unittest.TestCase):
+ """A deliberate stop drops the socket before the reader thread's blocked
+ recv() notices, so the OSError it then raises names a socket nobody owns
+ any more -- Windows' WinError 10038 on the off switch, reproduced here
+ without a real stop()."""
+
+ def setUp(self):
+ self.statuses = []
+ self.redirected = []
+ self.sender = sender.MacSender(
+ status_callback=lambda connected, detail: self.statuses.append(detail),
+ redirect_callback=self.redirected.append,
+ )
+
+ def test_an_error_on_an_already_dropped_socket_is_not_a_failure(self):
+ old_sock, peer = socket.socketpair()
+ self.addCleanup(old_sock.close)
+ self.addCleanup(peer.close)
+ self.sender._sock = old_sock
+ self.sender.redirecting = True
+ self.sender._sock = None # what stop()/_drop_connection() does first
+ self.sender._connection_failed("Receiving from the Mac failed: boom", expected_socket=old_sock)
+ self.assertEqual(self.statuses, [])
+ self.assertEqual(self.redirected, [])
+ self.assertTrue(self.sender.redirecting, "a stale error forced input back to this PC")
+
+ def test_an_error_on_the_live_socket_is_still_reported(self):
+ sock, peer = socket.socketpair()
+ self.addCleanup(sock.close)
+ self.addCleanup(peer.close)
+ self.sender._sock = sock
+ self.sender.redirecting = True
+ self.sender._connection_failed("Receiving from the Mac failed: boom", expected_socket=sock)
+ self.assertEqual(self.statuses, ["Receiving from the Mac failed: boom"])
+ self.assertFalse(self.sender.redirecting)
+
+
class NoUnlock:
def is_locked(self):
return None
diff --git a/win_app/tests/test_shared_copies.py b/win_app/tests/test_shared_copies.py
index 70d23eb..1fd722a 100644
--- a/win_app/tests/test_shared_copies.py
+++ b/win_app/tests/test_shared_copies.py
@@ -19,8 +19,8 @@ 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",)
+SHARED_MODULES = ("ignored.py", "protocol.py", "receiver.py", "return_edge.py")
+SHARED_TESTS = ("test_ignored.py", "test_shared_copies.py")
def _digest(path):
diff --git a/win_app/theme.py b/win_app/theme.py
index 4583f01..971b35e 100644
--- a/win_app/theme.py
+++ b/win_app/theme.py
@@ -30,7 +30,8 @@ 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
+# 176, not 168, so the foot's kalkmancode.co.uk/beamer fits as Windows draws it.
+SIDEBAR_WIDTH = 176
# The pairing code sits beside the countdown and the Pair button now, in a page narrower than
# the window used to be with no sidebar -- tokens.TYPE["code"] (92px, shared with the Mac's own
@@ -136,6 +137,7 @@ def stylesheet() -> str:
button=round(TYPE["button"]),
r_field=round(RADIUS["field"]),
r_button=round(RADIUS["button"]),
+ r_keycap=round(RADIUS["keycap"]),
)
return _TEMPLATE.format(**values)
@@ -210,6 +212,54 @@ QPushButton[vernier="page"]:hover {{ background: {well}; color: {ink}; }}
QPushButton[vernier="page"]:checked {{ background: {well}; color: {ink}; font-weight: 700; }}
QPushButton[vernier="page"]:focus {{ border: 1px solid {signal}; padding: 7px 11px; }}
+QPushButton[vernier="foot"] {{
+ background: transparent;
+ border: 0;
+ color: {ink_3};
+ font-size: 11px;
+ font-weight: 400;
+ padding: 12px 4px 14px 16px;
+ text-align: left;
+}}
+QPushButton[vernier="foot"]:hover {{ color: {ink_2}; }}
+QPushButton[vernier="foot"]:focus {{ border: 1px solid {signal}; padding: 11px 3px 13px 15px; }}
+QPushButton[vernier="keycap"] {{
+ background: {ground};
+ border: 1px solid {edge};
+ border-bottom: 3px solid {edge};
+ border-radius: {r_keycap}px;
+ padding: 0;
+}}
+QPushButton[vernier="keycap"]:hover {{ border-color: {ink_3}; }}
+QPushButton[vernier="keycap"]:focus {{ border-color: {signal}; }}
+QPushButton[vernier="keycap-live"] {{
+ background: {ground};
+ border: 1px solid {signal};
+ border-bottom: 3px solid {signal};
+ border-radius: {r_keycap}px;
+ padding: 0;
+}}
+QLabel[vernier="keycap"] {{ color: {ink}; }}
+QLabel[vernier="keycap-live"] {{ color: {signal}; }}
+QLabel[vernier="small"] {{ color: {ink_3}; font-size: {small}px; }}
+QLabel[vernier="tile-name"] {{ color: {ink}; font-size: {body}px; font-weight: 600; }}
+QFrame[vernier="tile"] {{ background: {ground}; border: 1px solid {rule}; border-radius: {r_button}px; }}
+QFrame[vernier="tile"]:hover {{ border-color: {edge}; }}
+QFrame[vernier="tile"]:focus {{ border: 2px solid {signal}; }}
+QFrame[vernier="tile-on"] {{ background: {ground}; border: 2px solid {ink}; border-radius: {r_button}px; }}
+QFrame[vernier="tile-on"]:focus {{ border: 2px solid {signal}; }}
+QFrame[vernier="tile-on"]:disabled {{ border-color: {edge}; }}
+QFrame[vernier="entry"] {{ background: {well}; border: 1px solid {rule}; border-radius: {r_field}px; }}
+QPushButton[vernier="remove"] {{
+ background: transparent;
+ border: 0;
+ color: {ink_3};
+ font-size: {small}px;
+ font-weight: 500;
+ padding: 2px 6px;
+}}
+QPushButton[vernier="remove"]:hover {{ color: {fault}; }}
+QPushButton[vernier="remove"]:focus {{ border: 1px solid {signal}; padding: 1px 5px; }}
QCheckBox {{ background: transparent; color: {ink}; font-size: {body}px; spacing: 8px; }}
QCheckBox::indicator {{ width: 16px; height: 16px; border: 1px solid {edge}; border-radius: 3px; background: {well}; }}
QCheckBox::indicator:hover {{ border-color: {ink_3}; }}
diff --git a/win_app/widgets.py b/win_app/widgets.py
index ccb4fc1..f999a80 100644
--- a/win_app/widgets.py
+++ b/win_app/widgets.py
@@ -3,11 +3,13 @@ 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.QtCore import QEvent, QRectF, QSize, Qt
+from PySide6.QtGui import QColor, QLinearGradient, QPainter, QPen
from PySide6.QtWidgets import (
+ QApplication,
QCheckBox,
QFrame,
+ QGraphicsOpacityEffect,
QGridLayout,
QHBoxLayout,
QLabel,
@@ -153,6 +155,241 @@ class Choice:
button.setEnabled(enabled)
+class _Tile(QFrame):
+ """One tile of ChoiceTiles: the whole tile is the control, by click or by Space from Tab."""
+
+ def __init__(self, choose, parent: QWidget | None = None) -> None:
+ super().__init__(parent)
+ self._choose = choose
+ self.setProperty("vernier", "tile")
+ self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
+
+ def mousePressEvent(self, event) -> None:
+ if event.button() == Qt.MouseButton.LeftButton and self.isEnabled():
+ self._choose()
+ super().mousePressEvent(event)
+
+ def keyPressEvent(self, event) -> None:
+ if event.key() in (Qt.Key.Key_Space, Qt.Key.Key_Return, Qt.Key.Key_Enter):
+ self._choose()
+ return
+ super().keyPressEvent(event)
+
+
+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 chosen tile takes a 2px ink border. `on_change(value)` fires only on a real
+ choice, never on `set_value`."""
+
+ def __init__(self, items, current, on_change=None, parent: QWidget | None = None) -> None:
+ self.on_change = on_change
+ self.value = None
+ self.view = QWidget(parent)
+ self.view.setProperty("vernier", "plain")
+ row = QHBoxLayout(self.view)
+ row.setContentsMargins(0, 0, 0, 0)
+ row.setSpacing(10)
+ self._tiles: dict = {}
+ for value, title, detail, preview in items:
+ tile = _Tile(lambda v=value: self._chosen(v))
+ tile.setAccessibleName(title)
+ column = QVBoxLayout(tile)
+ column.setContentsMargins(8, 8, 8, 12)
+ column.setSpacing(6)
+ column.addWidget(preview)
+ column.addSpacing(4)
+ column.addWidget(label(title, "tile-name"))
+ column.addWidget(label(detail, "small", wrap=True))
+ column.addStretch(1)
+ row.addWidget(tile, 1)
+ self._tiles[value] = tile
+ self.set_value(current)
+
+ def set_value(self, value) -> None:
+ self.value = value
+ for candidate, tile in self._tiles.items():
+ set_role(tile, "tile-on" if candidate == value else "tile")
+
+ def set_enabled(self, enabled: bool) -> None:
+ # Faded whole, previews included, as the Mac's tiles are.
+ fade = QGraphicsOpacityEffect(self.view)
+ fade.setOpacity(1.0 if enabled else 0.45)
+ self.view.setGraphicsEffect(None if enabled else fade)
+ for tile in self._tiles.values():
+ tile.setEnabled(enabled)
+
+ def _chosen(self, value) -> None:
+ if value == self.value:
+ return
+ self.set_value(value)
+ if self.on_change is not None:
+ self.on_change(value)
+
+
+class _Swatch(QPushButton):
+ CHIP = 24
+
+ def __init__(self, colours, title: str, parent: QWidget | None = None) -> None:
+ super().__init__(title, parent)
+ self.colours = list(colours) * (2 if len(colours) == 1 else 1)
+ self.setCheckable(True)
+ self.setAutoExclusive(True)
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.setAccessibleName(title)
+ self.setFixedHeight(self.CHIP + 24)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+
+ def sizeHint(self) -> QSize:
+ return QSize(max(56, self.fontMetrics().horizontalAdvance(self.text()) + 8), self.CHIP + 24)
+
+ def paintEvent(self, _event) -> None:
+ painter = QPainter(self)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ chosen = self.isChecked()
+ enabled = self.isEnabled()
+ chip = QRectF(3, 3, self.width() - 6, self.CHIP)
+ gradient = QLinearGradient(chip.left(), 0, chip.right(), 0)
+ for index, value in enumerate(self.colours):
+ gradient.setColorAt(index / (len(self.colours) - 1), QColor(value))
+ painter.setOpacity(1.0 if enabled else 0.45)
+ painter.setBrush(gradient)
+ ring = "ink" if chosen and enabled else "rule"
+ painter.setPen(QPen(QColor(theme.colour(ring)), 2 if chosen else 1))
+ radius = tokens.RADIUS["field"]
+ painter.drawRoundedRect(chip, radius, radius)
+ if self.hasFocus():
+ painter.setPen(QPen(QColor(theme.colour("signal")), 2))
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.drawRoundedRect(chip.adjusted(-2.5, -2.5, 2.5, 2.5), radius + 2, radius + 2)
+ painter.setPen(QColor(theme.colour("ink" if chosen else "ink_2")))
+ face = theme.font(tokens.TYPE["small"], 600 if chosen else 400)
+ painter.setFont(face)
+ painter.drawText(
+ QRectF(0, chip.bottom() + 4, self.width(), self.height() - chip.bottom() - 4),
+ Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop,
+ self.text(),
+ )
+
+
+class Swatches:
+ """One colour of several from tokens.PALETTES: a chip of each palette's gradient over its name,
+ the chosen chip ringed in ink."""
+
+ def __init__(self, items, current, on_change=None, parent: QWidget | None = None) -> None:
+ self.view = QWidget(parent)
+ self.view.setProperty("vernier", "plain")
+ row = QHBoxLayout(self.view)
+ row.setContentsMargins(0, 0, 0, 0)
+ row.setSpacing(8)
+ self._swatches: dict = {}
+ for value, title in items:
+ swatch = _Swatch(tokens.PALETTES[value], title)
+ swatch.setChecked(value == current)
+ if on_change is not None:
+ swatch.clicked.connect(lambda _checked=False, v=value: on_change(v))
+ row.addWidget(swatch, 1)
+ self._swatches[value] = swatch
+
+ @property
+ def value(self):
+ return next((value for value, swatch in self._swatches.items() if swatch.isChecked()), None)
+
+ def set_value(self, value) -> None:
+ swatch = self._swatches.get(value)
+ if swatch is not None and not swatch.isChecked():
+ swatch.setChecked(True)
+
+ def set_enabled(self, enabled: bool) -> None:
+ for swatch in self._swatches.values():
+ swatch.setEnabled(enabled)
+
+
+class InputRecorder(QPushButton):
+ """A keycap that records the next key or mouse button pressed. Clicking arms it; while armed an
+ application-wide filter takes the next key or non-left button and hands `on_record` a
+ ("key", virtual key) or ("button", name) pair, and a left click anywhere disarms it. The key is
+ read as the low-level hook will report it, so what is recorded is what the hook matches."""
+
+ HINT = "Click, then press it"
+ RECORDING_HINT = "Click again to cancel"
+ BUTTONS = {
+ Qt.MouseButton.RightButton: "right",
+ Qt.MouseButton.MiddleButton: "middle",
+ Qt.MouseButton.BackButton: "back",
+ Qt.MouseButton.ForwardButton: "forward",
+ }
+
+ def __init__(self, title: str, on_record, hook_vk, parent: QWidget | None = None) -> None:
+ super().__init__(parent)
+ self.title = title
+ self.on_record = on_record
+ self.hook_vk = hook_vk
+ self.armed = False
+ self.setProperty("vernier", "keycap")
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.setAccessibleName(title)
+ self.setFixedHeight(42)
+ row = QHBoxLayout(self)
+ row.setContentsMargins(12, 0, 12, 0)
+ row.setSpacing(10)
+ self.key = label(title, "keycap")
+ self.key.setFont(theme.mono_font(tokens.TYPE["field_mono"]))
+ self.hint = label(self.HINT, "small")
+ for part in (self.key, self.hint):
+ part.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ row.addWidget(self.key, 1)
+ row.addWidget(self.hint, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
+ self.clicked.connect(self._toggle)
+
+ def cancel(self) -> None:
+ if not self.armed:
+ return
+ self.armed = False
+ QApplication.instance().removeEventFilter(self)
+ self.key.setText(self.title)
+ set_role(self.key, "keycap")
+ self.hint.setText(self.HINT)
+ set_role(self, "keycap")
+
+ def _toggle(self) -> None:
+ if self.armed:
+ self.cancel()
+ return
+ self.armed = True
+ self.key.setText("Press a key or button…")
+ set_role(self.key, "keycap-live")
+ self.hint.setText(self.RECORDING_HINT)
+ set_role(self, "keycap-live")
+ QApplication.instance().installEventFilter(self)
+
+ def eventFilter(self, watched, event) -> bool:
+ if not self.armed:
+ return False
+ kind = event.type()
+ if kind == QEvent.Type.KeyPress:
+ vk = self.hook_vk(event.nativeVirtualKey(), event.nativeScanCode())
+ if not vk:
+ return True
+ self.cancel()
+ self.on_record("key", vk)
+ return True
+ if kind == QEvent.Type.KeyRelease:
+ return True
+ if kind == QEvent.Type.MouseButtonPress:
+ name = self.BUTTONS.get(event.button())
+ if name is None:
+ # The left button disarms, and the press goes where it was aimed -- except onto
+ # this keycap, where it would arm it again.
+ inside = isinstance(watched, QWidget) and (watched is self or self.isAncestorOf(watched))
+ self.cancel()
+ return inside
+ self.cancel()
+ self.on_record("button", name)
+ return True
+ return False
+
+
class PageButton(QPushButton):
"""One entry in the sidebar's page list, with an optional tone dot for a page that
needs attention."""
@@ -186,7 +423,7 @@ 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:
+ def __init__(self, pages, on_select, foot: str = "", on_foot=None, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setProperty("vernier", "sidebar")
outer = QVBoxLayout(self)
@@ -215,7 +452,17 @@ class Sidebar(QWidget):
list_layout.addWidget(button)
self._buttons[key] = button
list_layout.addStretch(1)
- outer.addLayout(list_layout)
+ outer.addLayout(list_layout, 1)
+ if foot:
+ # The version and the way back to Beamer's page: one quiet line, never a control
+ # anyone has to look past to reach a setting.
+ self.foot = QPushButton(foot)
+ self.foot.setProperty("vernier", "foot")
+ self.foot.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.foot.setToolTip("Open in your browser")
+ if on_foot is not None:
+ self.foot.clicked.connect(on_foot)
+ outer.addWidget(self.foot)
def select(self, key: str) -> None:
button = self._buttons.get(key)