Skip to content

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

Beamer 1.4.0

Toby Kalkman6b9fc3e4e875
diff --git a/.gitattributes b/.gitattributes
index 2579dbd..1e30bde 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,8 +1,7 @@
# The repo is LF throughout, and half of it is edited on Windows. Without this,
# every tool that rewrites a file there stores it with CRLF and the diff is the
-# whole file for no change at all -- which happened to seventeen files on
-# 17-09-2026 and had to be undone by hand. Git now normalises on commit, so it
-# cannot happen again whichever machine the edit was made on.
+# whole file for no change at all. Git normalises on commit, so it cannot happen
+# whichever machine the edit was made on.
* text=auto eol=lf
# Vendored as they came: a third party's licence file is not ours to reflow.
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index e2f2bf5..0a565d5 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -14,7 +14,7 @@ body:
attributes:
label: Beamer version
description: Shown in About Beamer on each machine. Say if the two differ.
- placeholder: "1.3.3"
+ placeholder: "1.4.0"
validations:
required: true
- type: input
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index 9b173ab..ffa2e90 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -1,5 +1,8 @@
-blank_issues_enabled: true
+blank_issues_enabled: false
contact_links:
- name: Security problem
url: https://github.com/kalkman-code/beamer/security/advisories/new
about: Report it privately, as SECURITY.md describes, not in a public issue.
+ - name: A question
+ url: https://kalkmancode.co.uk/contact
+ about: For anything that is not a bug or a feature request.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 0000000..0c37cae
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,18 @@
+name: Feature request
+description: Something Beamer does not do yet.
+labels: [enhancement]
+body:
+ - type: textarea
+ id: what
+ attributes:
+ label: What you would like
+ description: What you are trying to do, and what Beamer would need to do for it.
+ validations:
+ required: true
+ - type: textarea
+ id: today
+ attributes:
+ label: What you do today instead
+ - type: markdown
+ attributes:
+ value: To support an existing request, add a reaction to it rather than a comment.
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000..d1da59e
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,5 @@
+# Code of conduct
+
+Be straightforward and respectful in issues, pull requests and anywhere else in this repository.
+No harassment, no personal attacks, no discrimination. Anything that falls short can be hidden,
+closed or locked. To report someone's conduct, email [email protected].
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..8814de0
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,27 @@
+# Contributing
+
+Beamer is written and kept up by one person, in spare time. Issues are welcome and read, but a
+reply is not guaranteed.
+
+## Bug reports
+
+Use the bug report form, and attach both machines' logs where you can:
+`~/Library/Logs/Beamer/Beamer.log` on the Mac and `%LOCALAPPDATA%\Beamer\Beamer.log` on Windows.
+They hold your machines' names and local network addresses, so look them over first.
+
+## Feature requests
+
+Use the feature request form, or add a reaction to an existing request rather than a "+1"
+comment. There is no roadmap and no promise that anything gets built. Some things are out of scope
+by design: Beamer is one Mac and one Windows PC, so a third machine and Linux are not planned.
+
+## Pull requests
+
+Beamer is GPL-3.0 and has one author. A pull request from anyone else changes that, so before one
+is merged I will ask you to confirm the change is your own work and that you license it under
+GPL-3.0, and possibly more. For anything bigger than a small, obvious fix, open an issue first so
+we agree the approach before you write code.
+
+## Building it
+
+The README's "Building from source" and "Development checks" sections cover both platforms.
diff --git a/README.md b/README.md
index f85e5a5..59b0035 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@
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.
+still work, and what you type never leaves your network.
## Download
@@ -20,7 +20,7 @@ Free, with no account. Every installer is on the [releases page](https://github.
| Platform | Get it | Notes |
|---|---|---|
-| macOS 13 or later, Apple silicon | `Beamer-<version>.dmg` | Signed and notarised by Apple. Not for Intel Macs yet |
+| macOS 13 or later, Apple silicon | `Beamer-<version>.dmg` | Signed and notarised by Apple. Not for Intel Macs |
| 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 |
@@ -34,10 +34,11 @@ Free, with no account. Every installer is on the [releases page](https://github.
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.
- If the PC never appears in the list, as on guest Wi-Fi or across a VPN, type the PC's address
- on the Mac's Connection page and the same token on both machines' Connection pages instead.
+2. **Pair them.** Both Overview pages lead with pairing until it is done. On the PC, press Pair a
+ Mac; a six-digit code appears. On the Mac, choose the PC from the list and type the code. It
+ lasts a minute and works once. If the PC never appears in the list, as on guest Wi-Fi or across
+ a VPN, type the address the PC shows next to its code into "PC not listed?" on the Mac and press
+ Find. The PC joins the list, and you pair with the code as before.
3. **Cross.** Push the Mac's pointer off the right-hand edge of its screen, or double-tap Right
Option, and the Mac's keyboard and trackpad are on the PC. Push back through the PC's left edge,
or double-tap again, to come home. The PC's own keyboard and mouse go the other way: push
@@ -48,16 +49,23 @@ 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, Send input and Pause crossing, 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"> |
+In your own appearance: light if your GitHub is light, dark if it is dark.
+
+<table>
+<tr><th>Mac</th><th>Windows</th></tr>
+<tr><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/mac-overview-light.png"><img src="assets/mac-overview-dark.png" width="400" alt="Beamer's Overview page on the Mac: where input is, whether the link is up, Send input and Pause crossing, and a switch for each direction"></picture></td><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/windows-overview-light.png"><img src="assets/windows-overview-dark.png" width="400" alt="Beamer's Overview page on Windows: where input is, Send input and Pause crossing, and a switch for each direction"></picture></td></tr>
+<tr><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/mac-crossing-light.png"><img src="assets/mac-crossing-dark.png" width="400" alt="Beamer's Crossing page on the Mac: a drawing of the Mac and the PC side by side with the crossing edge lit, and the ways in"></picture></td><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/windows-crossing-light.png"><img src="assets/windows-crossing-dark.png" width="400" alt="Beamer's Crossing page on Windows: a drawing of the Mac and the PC with the crossing edge lit, the ways in and where the Mac sits"></picture></td></tr>
+<tr><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/mac-design-light.png"><img src="assets/mac-design-dark.png" width="400" alt="Beamer's Design page on the Mac: a tile for each crossing style, shown at the edge, a corner or the notch, and the colours"></picture></td><td><picture><source media="(prefers-color-scheme: light)" srcset="assets/windows-design-light.png"><img src="assets/windows-design-dark.png" width="400" alt="Beamer's Design page on Windows: a tile for each crossing style, shown at the edge, a corner or the notch, and the colours"></picture></td></tr>
+</table>
## 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.
+- **Push through the edge.** Off the edge that faces the other machine, only along the parts of it
+ you pick, through a corner, or up through the MacBook's notch. The pointer arrives at the same
+ point along the border, on the right display however your monitors are stacked or staggered. The
+ edge lights up as you push, and the trackpad ticks as the push builds.
+- **See where you land.** A switch by the key or a menu plays a short arrival around the pointer on
+ the machine that takes over, so you never hunt for it.
- **Or press a key.** Double-tap or hold a trigger key to switch without moving the pointer. Right
Option on the Mac and Right Ctrl on the PC to start with; on either machine it can be any key
that types nothing, recorded by pressing it.
@@ -76,14 +84,21 @@ machine's settings.
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.
+- **Make it yours.** Glow and Beam, or nine other effects in three families (Membrane, Sparks
+ and Instrument), each with colour packs of its own and any colour with any effect. The
+ notch as an outline or an island with a meter, how hard you push before it crosses, and settings
+ windows that follow the system's light or dark appearance or keep your own choice.
+- **Feels like your own.** Each machine sets how the other's pointer moves and scrolls on it, from
+ 25% to 400%, and can reverse its scrolling, so a Mac trackpad and a PC mouse each feel right on
+ the other screen.
- **Out of the way when it should be.** A full-screen app holds the edges, so a game or a film never
loses the pointer; the trigger key still works. Pause crossing does the same by hand. A drag
that reaches the edge stays a drag. Switch to a machine that is asleep and Beamer wakes it, where
that machine answers wake-on-LAN: a PC usually does, a MacBook on Wi-Fi usually does not.
- **Your network, nobody else's.** No server in the middle. The two machines talk to each other
- directly, encrypted, and you pair them once with a six-digit code. More in [SECURITY.md](SECURITY.md).
+ directly, encrypted, and you pair them once with a six-digit code. The only thing that ever goes
+ further is a once-a-day check of GitHub's public releases for a newer version, which you can
+ switch off on Overview. More in [SECURITY.md](SECURITY.md).
- **Free and open source.** No account, no subscription, GPL-3.0.
## Settings
@@ -94,13 +109,12 @@ About Beamer.
| Page | Mac | Windows |
|---|---|---|
-| Overview | Where input is, the link and its round trip, Send input and Pause crossing, a switch per direction, start at login | Where input is, the link and its round trip, Send input and Pause crossing, a switch per direction, start at sign-in |
-| Crossing | Ways in (edge, corner, notch, shortcut), which edge, never while dragging, resistance | Ways in (edge, corner, shortcut), the arrangement with the Mac, never while dragging, 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, what stays on this Mac, modifier style | Trigger key (recorded), double-tap or hold, what stays on this PC, modifier style |
-| 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 |
+| Overview | Pairing (first, until it is done), where input is, the link and its round trip, Send input and Pause crossing, a switch per direction, start at login, the update check | Pairing (first, until it is done), where input is, the link and its round trip, Send input and Pause crossing, a switch per direction, start at sign-in, the update check |
+| Permissions | Accessibility and Input Monitoring, with Relaunch Beamer | None; the firewall check is on Connection |
+| Crossing | A drawing of the arrangement, the ways in (edge, part of the edge, corner, notch), where the PC is, never while dragging, resistance, the shortcut | A drawing of the arrangement, the ways in (edge, part of the edge, corner), where your Mac is, never while dragging, resistance, the shortcut |
+| Keyboard | Same shortcuts or same positions, what stays on this Mac, the PC's pointer and scroll speed here | Same shortcuts or same positions, what stays on this PC, the Mac's pointer and scroll speed here |
+| Design | Crossing and switch styles, each playing as you point at it, colours, show where the pointer lands, notch style, trackpad ticks, the window's appearance (System, Light or Dark) | Crossing and switch styles, each playing as you point at it, at the edge or a corner, colours, show where the pointer lands, the window's appearance (System, Light or Dark) |
+| Connection | Hide addresses, the PC's address, port and token | Whether Windows Firewall lets the Mac in, with a one-button fix; hide addresses; this PC's address, port and token |
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.
@@ -114,12 +128,14 @@ step, so the border is always the same one seen from both ends.
- **AltGr is out of reach from the Mac.**
- **A dead key typed on the PC does not cross**, so an accent typed as two keys on the PC's
layout arrives on the Mac without it. Shortcuts and letters follow each machine's own layout.
-- **Intel Macs are not supported yet.** The Mac app is built for Apple silicon only.
+- **Intel Macs are not supported.** The Mac app is built for Apple silicon only.
- **The Windows installer is unsigned.** SmartScreen warns until it has a download history; winget
avoids it.
- **macOS 27 beta 4 could block a signed app's local-network access** even when Terminal could
- reach the PC. The 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.
+ reach the PC. The released macOS 27 does not, so the DMG no longer carries a workaround; for that
+ beta, `mac_app/Beamer Tunnel.command` in this repository forwards the link over SSH: open it,
+ leave its window running, then open Beamer, which uses the tunnel only when its direct connection
+ is blocked.
## In detail
@@ -161,18 +177,21 @@ time you overshoot a close button. The default is 120 points; zero switches on c
| 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 |
+| Edge | The whole of one outer edge | Yes | Yes |
+| Part of the edge | Only the thirds of that edge you pick (start, middle, end), measured on the display under the pointer | 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.
+Any combination can be on, except Edge and Part of the edge, which exclude each other. On the Mac,
+shortcut and the right-hand edge are on to start with.
-- The notch has no pixels to light, so a push there draws on the notch itself. Beam, the default,
+- The notch has no pixels to light, so a push there draws on the notch itself. Outline, the default,
runs a comet of light round a small tab under the notch that brightens and speeds up with the
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.
+- An edge counts wherever no display of the same machine lies beyond it, so an edge between two
+ displays behaves as the system intends, and the edge of a MacBook under a wider external display
+ still crosses.
- 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.
@@ -181,7 +200,8 @@ Any combination can be on. On the Mac, shortcut and the right-hand edge are on t
- 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.
+ way back never depends on the edge alone. The PC's edge facing the Mac leads home even when the
+ Mac has only its shortcut on.
- Switching to a PC that is asleep sends wake-on-LAN. The PC's hardware address is read from the
Mac's ARP table after a successful connection, never typed.
@@ -263,7 +283,8 @@ carries the Mac's clipboard to the PC, and switching back carries the PC's to th
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.
+already ships. A switch sends the clipboard only when it has changed since it last crossed, so a
+large image is not re-sent every time.
</details>
@@ -290,6 +311,19 @@ proving it knows the six-digit code. What that does and does not protect against
</details>
+<details>
+<summary><strong>Update check</strong></summary>
+
+Once a day, and at start, Beamer asks GitHub's public releases API for the latest release of this
+repository and compares its version with its own. A new minor or major version is always offered;
+a patch release (1.4.0 to 1.4.1) only when its release notes ask for it, so a run of small fixes
+does not nag. Drafts and pre-releases never count and nothing is downloaded. When a newer one is out, the menu says Beamer X is available and Overview offers a
+Download button that opens the release page. The request is an ordinary HTTPS request, so GitHub
+sees the address it came from, as it would for a browser. Switch it off with Check for updates on
+Overview.
+
+</details>
+
<details>
<summary><strong>Windows specifics</strong></summary>
@@ -304,7 +338,7 @@ 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
+elevated start. Connection 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
@@ -399,9 +433,10 @@ It runs the tests, builds `Beamer.exe` and compiles `Beamer-Setup.iss` with Inno
GPL-3.0; see [LICENSE](LICENSE). Releases up to and including 1.2.0 were MIT.
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:
+reply. Before a pull request, read [CONTRIBUTING.md](CONTRIBUTING.md). Report security problems privately, as [SECURITY.md](SECURITY.md) describes. Home page:
[kalkmancode.co.uk/beamer](https://kalkmancode.co.uk/beamer).
-A bug report is far easier to act on with each machine's log attached. Beamer keeps one on each:
-`~/Library/Logs/Beamer/Beamer.log` on the Mac and `%LOCALAPPDATA%\Beamer\Beamer.log` on Windows.
+A bug report is far easier to act on with each machine's log attached. Open log folder in each
+machine's menu opens it: `~/Library/Logs/Beamer/Beamer.log` on the Mac and
+`%LOCALAPPDATA%\Beamer\Beamer.log` on Windows.
They hold your machines' names and local network addresses, so look them over before posting.
diff --git a/SECURITY.md b/SECURITY.md
index f1aa133..640aaed 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -18,7 +18,9 @@ them matters. This is what it protects, what it does not, and how to report a pr
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.
+ networks only. The one request that leaves your network is the update check: once a day, an
+ ordinary HTTPS request to GitHub's public releases API, carrying nothing about you or your
+ machines beyond the address any request comes from. Check for updates on Overview turns it off.
- **Strangers cannot tie it up cheaply.** A connection must authenticate within a deadline and
within 4KB, and only a handful of unauthenticated connections are held at once.
diff --git a/VERSION b/VERSION
index 31e5c84..88c5fb8 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.3.3
+1.4.0
diff --git a/assets/mac-crossing-dark.png b/assets/mac-crossing-dark.png
new file mode 100644
index 0000000..afc1b16
Binary files /dev/null and b/assets/mac-crossing-dark.png differ
diff --git a/assets/mac-crossing-light.png b/assets/mac-crossing-light.png
new file mode 100644
index 0000000..7976f78
Binary files /dev/null and b/assets/mac-crossing-light.png differ
diff --git a/assets/mac-design-dark.png b/assets/mac-design-dark.png
new file mode 100644
index 0000000..b799add
Binary files /dev/null and b/assets/mac-design-dark.png differ
diff --git a/assets/mac-design-light.png b/assets/mac-design-light.png
new file mode 100644
index 0000000..79800a7
Binary files /dev/null and b/assets/mac-design-light.png differ
diff --git a/assets/mac-design.png b/assets/mac-design.png
deleted file mode 100644
index ae7f652..0000000
Binary files a/assets/mac-design.png and /dev/null differ
diff --git a/assets/mac-overview-dark.png b/assets/mac-overview-dark.png
new file mode 100644
index 0000000..95e2397
Binary files /dev/null and b/assets/mac-overview-dark.png differ
diff --git a/assets/mac-overview-light.png b/assets/mac-overview-light.png
new file mode 100644
index 0000000..13a73f3
Binary files /dev/null and b/assets/mac-overview-light.png differ
diff --git a/assets/mac-overview.png b/assets/mac-overview.png
deleted file mode 100644
index ad0e502..0000000
Binary files a/assets/mac-overview.png and /dev/null differ
diff --git a/assets/windows-crossing-dark.png b/assets/windows-crossing-dark.png
new file mode 100644
index 0000000..bf94a8e
Binary files /dev/null and b/assets/windows-crossing-dark.png differ
diff --git a/assets/windows-crossing-light.png b/assets/windows-crossing-light.png
new file mode 100644
index 0000000..29ae858
Binary files /dev/null and b/assets/windows-crossing-light.png differ
diff --git a/assets/windows-design-dark.png b/assets/windows-design-dark.png
new file mode 100644
index 0000000..eaadd96
Binary files /dev/null and b/assets/windows-design-dark.png differ
diff --git a/assets/windows-design-light.png b/assets/windows-design-light.png
new file mode 100644
index 0000000..996cd3e
Binary files /dev/null and b/assets/windows-design-light.png differ
diff --git a/assets/windows-design.png b/assets/windows-design.png
deleted file mode 100644
index 48ca1ea..0000000
Binary files a/assets/windows-design.png and /dev/null differ
diff --git a/assets/windows-overview-dark.png b/assets/windows-overview-dark.png
new file mode 100644
index 0000000..609ce39
Binary files /dev/null and b/assets/windows-overview-dark.png differ
diff --git a/assets/windows-overview-light.png b/assets/windows-overview-light.png
new file mode 100644
index 0000000..ad7de00
Binary files /dev/null and b/assets/windows-overview-light.png differ
diff --git a/assets/windows-overview.png b/assets/windows-overview.png
deleted file mode 100644
index b298368..0000000
Binary files a/assets/windows-overview.png and /dev/null differ
diff --git a/config.example.json b/config.example.json
index 9ad9693..baabeff 100644
--- a/config.example.json
+++ b/config.example.json
@@ -1,16 +1,5 @@
{
"host": "192.168.1.20",
"port": 24820,
- "auth_token": "CHANGE_ME",
- "trigger_key": "alt_r",
- "double_tap_ms": 300,
- "key_map": {
- "cmd": "ctrl",
- "cmd_r": "ctrl",
- "ctrl": "cmd",
- "ctrl_r": "cmd",
- "alt": "alt",
- "alt_r": "alt"
- },
- "reconnect_interval_s": 2.0
+ "auth_token": "CHANGE_ME"
}
diff --git a/mac_app/Install-Beamer-Mac.command b/mac_app/Install-Beamer-Mac.command
index 9bc2c44..d7a34ee 100755
--- a/mac_app/Install-Beamer-Mac.command
+++ b/mac_app/Install-Beamer-Mac.command
@@ -5,41 +5,21 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_SOURCE="$SCRIPT_DIR/dist/Beamer.app"
DEST_APP="/Applications/Beamer.app"
-DEST_TUNNEL="/Applications/Beamer Tunnel.command"
trap 'status=$?; echo "Installation failed."; read -r -p "Press Return to close"; exit $status' ERR
"$SCRIPT_DIR/build_dmg.sh"
killall Beamer 2>/dev/null || true
-# The app was called OpenKB until 19-08-2026. Two copies in /Applications is
-# how Spotlight ends up offering both, so the old one goes. Its data directory
-# is deliberately left alone -- it still holds the config and auth token.
-killall OpenKB 2>/dev/null || true
-rm -rf "/Applications/OpenKB.app" "/Applications/OpenKB Tunnel.command"
-
-# The app was called Beamy until 10-09-2026. Same reasoning as the OpenKB
-# cleanup above: two copies in /Applications is how Spotlight ends up
-# offering both, so the old one goes.
-killall Beamy 2>/dev/null || true
-rm -rf "/Applications/Beamy.app" "/Applications/Beamy Tunnel.command"
-# Beamy shared the OpenKB bundle id (never got its own); Beamer uses a new
-# one, so uk.co.kalkman.openkb.desktop's grants now belong to an app that no
-# longer exists.
-tccutil reset Accessibility uk.co.kalkman.openkb.desktop >/dev/null 2>&1 || true
-tccutil reset ListenEvent uk.co.kalkman.openkb.desktop >/dev/null 2>&1 || true
-
rm -rf "$DEST_APP"
ditto "$APP_SOURCE" "$DEST_APP"
-ditto "$SCRIPT_DIR/Beamer Tunnel.command" "$DEST_TUNNEL"
-chmod +x "$DEST_TUNNEL"
xattr -cr "$DEST_APP"
# An ad-hoc build is a different code identity on every build wearing the same bundle id. macOS
# keeps the old grant against the old identity, which is why such a reinstall can sit in the
# Privacy pane with a tick beside it and still receive no events -- the tick belongs to a build
# that no longer exists. Revoking turns that silent failure into a visible prompt.
-# Only ad-hoc builds need it. Since 31-08-2026 build_dmg.sh signs with a real identity where one
+# Only ad-hoc builds need it. build_dmg.sh signs with a real identity where one
# is reachable, and that identity is stable across rebuilds, so the grants carry over and
# revoking them would throw away the very thing the signing bought. The ad-hoc path still
# exists for builds driven over SSH, where the login keychain cannot be unlocked.
@@ -66,7 +46,6 @@ fi
rm -rf "$SCRIPT_DIR/build" "$SCRIPT_DIR/dist"
echo "Beamer is installed at $DEST_APP"
-echo "The macOS 27 fallback is installed at $DEST_TUNNEL"
if [ "$REVOKED" -eq 1 ]; then
echo "This build is ad-hoc signed, so its privacy permissions were revoked on install. Grant Accessibility and Input Monitoring again, one at a time, inside the app."
else
diff --git a/mac_app/bridge.py b/mac_app/bridge.py
index e4c5416..4c2f29a 100644
--- a/mac_app/bridge.py
+++ b/mac_app/bridge.py
@@ -8,6 +8,7 @@ import struct
import threading
import time
import types
+import dataclasses
from dataclasses import dataclass
import objc
@@ -544,6 +545,13 @@ class KVMController:
# range needs NSScreen, so the app measures it on the main thread and
# assigns it here. on_crossing is fed (kind, step) off the tap and
# ack threads for haptics and the glow; the app marshals it.
+ # A PC whose address changed, after a router restart hands it a new lease, still beacons
+ # under its name. With `discovery` set, a failed connect tries the address the paired PC's
+ # name is heard at, and only once that address has passed the authenticated handshake does
+ # it become cfg.host and reach `on_host_learned(host)` on the connection thread, for the app
+ # to save. A spoofed beacon costs one failed attempt and changes nothing.
+ self.discovery = None
+ self.on_host_learned = None
self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)
self.desktop_bounds = desktop_bounds or self._default_desktop_bounds
self.notch_range = None
@@ -552,6 +560,8 @@ class KVMController:
self._crossing_failed_at = 0.0
self._bounds_cache = None
self._bounds_at = 0.0
+ self._displays_cache = None
+ self._displays_at = 0.0
# Both hold the pointer methods off while the shortcut keeps working. Paused is the
# person's own choice from the menu and deliberately not a setting, so a pause nobody
# remembers cannot survive a restart; full_screen_app is the name of the frontmost app
@@ -692,10 +702,16 @@ class KVMController:
self.crossing = crossing.CrossingEngine.from_config(cfg.crossing)
self._crossing_failed = False
- def set_redirecting(self, value, edge=None, offset=None):
+ def set_redirecting(self, value, edge=None, offset=None, came_home=True):
"""`edge` and `offset` are the Windows edge and fraction along it a
crossing arrives at; absent for the shortcut, when Windows leaves its
- pointer where it is. The way home is sent on every switch."""
+ pointer where it is. The way home is sent on every switch.
+
+ Input coming home this way is a switch, the shortcut, the menu or the
+ PC sending it back, and says so through on_crossing as "home" with
+ where the pointer is, for the arrival that shows it. `came_home` is
+ False for the two ways back that show their own: a crossing that lands
+ here, and the PC taking this Mac over."""
value = bool(value)
if value == self.redirecting:
return False
@@ -744,6 +760,10 @@ class KVMController:
return True
self._return_local()
self.logger.info("input returned to this Mac")
+ if came_home:
+ pin = self._capture_cursor_pin_point()
+ if pin is not None:
+ self._notify_crossing("home", crossing.Step(pin=(pin[0], pin[1])))
return True
def _return_local(self):
@@ -776,7 +796,7 @@ class KVMController:
if value == self.receiving:
return
if value and self.redirecting:
- self.set_redirecting(False)
+ self.set_redirecting(False, came_home=False)
self.receiving = value
self.crossing.reset()
@@ -1092,6 +1112,9 @@ class KVMController:
self.clock(),
notch_range=self.notch_range,
dragging=event_type != quartz.kCGEventMouseMoved,
+ # Each display's own edges count where nothing lies beyond them, and Part of the
+ # edge measures its thirds along the pointer's display.
+ displays=self._current_displays(),
)
except Exception:
self._crossing_failed = True
@@ -1104,7 +1127,6 @@ class KVMController:
# The PC is driving this Mac and this Mac's own pointer pushed through: the PC's
# input goes home first, over its own link, and this Mac's follows it across. The
# PC's focus home clears receiving here too, later, and finds it already clear.
- # The Mac half of the PC's own push back (27-09-2026).
send_home = self.send_peer_home
if send_home is None or not send_home():
self.logger.warning("cannot cross: Windows is driving this Mac and cannot be reached")
@@ -1129,6 +1151,22 @@ class KVMController:
self._bounds_at = now
return self._bounds_cache
+ def _current_displays(self):
+ now = self.clock()
+ if self._displays_cache is None or now - self._displays_at > DESKTOP_BOUNDS_MAX_AGE_SECONDS:
+ quartz = self.quartz
+ try:
+ displays = [
+ (rect.origin.x, rect.origin.y, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height)
+ for rect in (quartz.CGDisplayBounds(display) for display in desktop_mac.display_ids(quartz))
+ ]
+ except Exception:
+ # Without them the engine measures against the whole desktop, as it always could.
+ return None
+ self._displays_cache = displays or None
+ self._displays_at = now
+ return self._displays_cache
+
def _default_desktop_bounds(self):
quartz = self.quartz
left = top = float("inf")
@@ -1174,17 +1212,23 @@ class KVMController:
genuinely came home."""
if not isinstance(data, dict) or data.get("target") != "mac":
return
- self.set_redirecting(False)
edge = data.get("edge")
offset = data.get("offset")
- if edge in crossing.EDGES and isinstance(offset, (int, float)) and not isinstance(offset, bool):
+ crossed = edge in crossing.EDGES and isinstance(offset, (int, float)) and not isinstance(offset, bool)
+ # Without an edge the PC sent this Mac's input home by its own switch: that is a switch
+ # arriving here, and shows where the pointer is.
+ self.set_redirecting(False, came_home=not crossed)
+ point = None
+ if crossed:
try:
- point = crossing.CrossingEngine.arrival_point(edge, offset, self._current_desktop_bounds())
+ point = crossing.CrossingEngine.arrival_point(
+ edge, offset, self._current_desktop_bounds(), displays=self._current_displays())
except Exception:
self.logger.exception("failed to place the pointer on arrival")
else:
self._warp_cursor_to(point)
- self._notify_crossing("arrive", crossing.Step(mac_edge=edge if edge in crossing.EDGES else None))
+ # `pin` is where the pointer landed, for the arrival effect; None when it was not placed.
+ self._notify_crossing("arrive", crossing.Step(mac_edge=edge if edge in crossing.EDGES else None, pin=point))
def _handle_system_event(self, event):
"""Forward a media/volume key press. Anything that is not one --
@@ -1342,32 +1386,53 @@ class KVMController:
def _connection_worker(self):
while not self.stop_event.is_set():
if not self.connected and self._config_ready():
- self._connect_once()
+ if not self._connect_once():
+ self._follow_the_pc()
self.stop_event.wait(self.cfg.reconnect_interval_s)
+ def _follow_the_pc(self):
+ """Try the address the paired PC is beaconing from now, if it is not the saved one."""
+ discovery, cfg = self.discovery, self.cfg
+ if discovery is None or not cfg.pc_name:
+ return
+ moved = next((pc["address"] for pc in discovery.pcs()
+ if pc["name"] == cfg.pc_name and pc["port"] == cfg.port and pc["address"] != cfg.host), None)
+ if moved is None or not self._connect_once(host=moved):
+ return
+ self.logger.info("%s moved from %s to %s", cfg.pc_name, cfg.host, moved)
+ self.cfg = dataclasses.replace(self.cfg, host=moved)
+ if self.on_host_learned is not None:
+ try:
+ self.on_host_learned(moved)
+ except Exception:
+ self.logger.exception("saving the PC's new address failed")
+
def _config_ready(self):
return bool(self.cfg.host and self.cfg.auth_token and 1 <= self.cfg.port <= 65535)
- def _connect_once(self):
+ def _connect_once(self, host=None):
sock = None
fallback = False
# Read once: update_config can replace self.cfg from the AppKit thread mid-handshake.
- endpoint = (self.cfg.host, self.cfg.port, self.cfg.auth_token)
- self.connection_status = f"Connecting to {self.cfg.host}:{self.cfg.port}"
+ endpoint = (host or self.cfg.host, self.cfg.port, self.cfg.auth_token)
+ # The tunnel leads to the saved address, so a new one is tried directly or not at all.
+ tunnel_allowed = host is None
+ host, port = endpoint[0], endpoint[1]
+ self.connection_status = f"Connecting to {host}:{port}"
try:
try:
sock = self.socket_factory(
- (self.cfg.host, self.cfg.port),
+ (host, port),
timeout=CONNECT_TIMEOUT_SECONDS,
)
except OSError as exc:
- if exc.errno != errno.EHOSTUNREACH:
+ if exc.errno != errno.EHOSTUNREACH or not tunnel_allowed:
raise
sock = self._connect_via_ssh_fallback()
fallback = True
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
- session = protocol.SecureSession(self.cfg.auth_token)
+ session = protocol.SecureSession(endpoint[2])
sock.sendall(session.preamble())
sock.settimeout(AUTH_TIMEOUT_SECONDS)
try:
@@ -1452,6 +1517,7 @@ class KVMController:
return False
self.sock = sock
self.session = session
+ self.clipboard.forget_sync()
now = self.clock()
with self.sequence_lock:
self.last_ack_seq = -1
@@ -1463,8 +1529,8 @@ class KVMController:
self.connection_status = "Connected to Windows via secure macOS 27 fallback"
self.logger.info("connected to Windows through the SSH fallback")
else:
- self.connection_status = f"Connected to {self.cfg.host}:{self.cfg.port}"
- self.logger.info("connected to Windows at %s:%s", self.cfg.host, self.cfg.port)
+ self.connection_status = f"Connected to {host}:{port}"
+ self.logger.info("connected to Windows at %s:%s", host, port)
return True
def _connect_via_ssh_fallback(self):
@@ -1517,11 +1583,12 @@ class KVMController:
def _send_local_clipboard(self):
"""Expand the local-clipboard sentinel: read this Mac's clipboard and
- send it as a clipboard message. Text over CLIPBOARD_MAX_BYTES and an
+ send it as a clipboard message, unless it is unchanged since it was
+ last sent or written from the PC. Text over CLIPBOARD_MAX_BYTES and an
image over CLIPBOARD_IMAGE_MAX_BYTES are each dropped on their own,
so an oversized screenshot still lets its text through; with nothing
left the message is skipped and the focus message still goes out."""
- text, image = self.clipboard.get_contents()
+ text, image = self.clipboard.changed_contents()
if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:
self.logger.warning("local clipboard text is too large; skipping the text")
text = None
@@ -1533,7 +1600,7 @@ class KVMController:
)
image = None
if not text and image is None:
- self.logger.debug("local clipboard is empty; skipping clipboard sync")
+ self.logger.debug("local clipboard is empty or unchanged since the last sync; not sending it")
return
self._send_raw(protocol.clipboard_msg(text or None, image))
diff --git a/mac_app/build_dmg.sh b/mac_app/build_dmg.sh
index 7bc49d9..a5a8e17 100755
--- a/mac_app/build_dmg.sh
+++ b/mac_app/build_dmg.sh
@@ -42,8 +42,8 @@ export BEAMER_BUILD="$(git -C "$PROJECT_DIR" rev-list --count HEAD)"
xcrun clang --version
if [ "$RELEASE" -eq 1 ]; then
- # docs/ is not part of the build and other sessions write there; anything else uncommitted would
- # ship code that no commit records.
+ # docs/ holds working notes, not build output, and is excluded from this check; anything else
+ # uncommitted would ship code that no commit records.
if [ -n "$(git -C "$PROJECT_DIR" status --porcelain -- . ':(exclude)docs')" ]; then
echo "uncommitted changes outside docs/ - commit them so the release matches a commit" >&2
exit 1
@@ -84,7 +84,7 @@ done
# The packages py2app copies whole (rumps, cryptography, cffi, setuptools) arrive with the
# __pycache__ pip compiled at install time, whose code objects name the venv's path on this Mac, and
-# py2app writes the building python's path into Info.plist. 1.3.0 shipped both (27-09-2026). The
+# py2app writes the building python's path into Info.plist. A shipped build once carried both. The
# caches go, inside the zip too, where zipimport never reads a __pycache__ anyway; the loose packages
# are compiled again under a relative name, since the app never writes bytecode into its own bundle.
find "$APP" -name __pycache__ -type d -prune -exec rm -rf {} +
@@ -180,12 +180,11 @@ if [ "$RELEASE" -eq 1 ]; then
xcrun stapler staple "$APP"
fi
-mkdir "$STAGING_DIR/image"
-cp -R "$APP" "$STAGING_DIR/image/"
-cp "$SCRIPT_DIR/Beamer Tunnel.command" "$STAGING_DIR/image/"
-ln -s /Applications "$STAGING_DIR/image/Applications"
+# The window a downloader sees: Beamer, an arrow and Applications on a background that says what to
+# do, laid out by dmgbuild so no Finder scripting (and no Automation prompt) is involved.
rm -f "$DMG"
-diskutil image create from --format UDZO --volumeName "Beamer" "$STAGING_DIR/image" "$DMG"
+.venv/bin/python3 -m dmgbuild -s "$SCRIPT_DIR/dmg/settings.py" -D app="$APP" \
+ -D background="$SCRIPT_DIR/dmg/background.png" "Beamer" "$DMG"
if [ "$RELEASE" -eq 1 ]; then
codesign --force --sign "$IDENTITY" --timestamp "$DMG"
diff --git a/mac_app/clipboard_mac.py b/mac_app/clipboard_mac.py
index e636049..7dc39c4 100644
--- a/mac_app/clipboard_mac.py
+++ b/mac_app/clipboard_mac.py
@@ -7,7 +7,7 @@ Windows). Apple doesn't document NSPasteboard as thread-safe, but
reading/writing the general pasteboard from a background thread is widely
relied upon in practice and has not shown problems in manual testing. Flagging
here as the one part of this feature that still wants confirmation on a real
-machine under load (see the runtime-verification notes in the task writeup).
+machine under load.
AppKit is imported at module level (pyobjc is already a hard dependency of
this app -- bridge.py imports Quartz/objc the same way) but guarded so the
@@ -25,6 +25,11 @@ except ImportError: # pragma: no cover - exercised only off macOS
LOGGER = logging.getLogger("Beamer")
+# The pasteboard's changeCount when it was last sent to the peer or written from it; None until
+# then and after forget_sync. A switch sends the clipboard only when the count has moved since,
+# so an unchanged screenshot is not pushed across on every switch.
+_synced_count = None
+
def _text_from_pasteboard(pasteboard):
text = pasteboard.stringForType_(AppKit.NSPasteboardTypeString)
@@ -65,11 +70,41 @@ def get_contents():
return None, None
+def _change_count():
+ try:
+ return AppKit.NSPasteboard.generalPasteboard().changeCount()
+ except Exception:
+ return None
+
+
+def changed_contents():
+ """get_contents(), or (None, None) when the pasteboard has not changed since it was last sent
+ to or written from the peer. Either way the current contents count as sent from here on."""
+ global _synced_count
+ if AppKit is None:
+ return None, None
+ count = _change_count()
+ if count is not None and count == _synced_count:
+ return None, None
+ text, png = get_contents()
+ # Only what was read counts as sent: a failed read must not hold this clipboard back.
+ if text is not None or png is not None:
+ _synced_count = count
+ return text, png
+
+
+def forget_sync():
+ """A new link: the peer may have lost what it was sent, so the next switch sends again."""
+ global _synced_count
+ _synced_count = None
+
+
def set_contents(text, png):
"""Replace the general pasteboard with `text` and/or `png`. Returns True
when at least one of them was set, False otherwise. Only the PNG
representation is written for the image; every current app pastes it,
and a TIFF alongside would double the memory for nothing. Never raises."""
+ global _synced_count
if AppKit is None or (text is None and png is None):
return False
try:
@@ -81,6 +116,8 @@ def set_contents(text, png):
if png is not None:
data = AppKit.NSData.dataWithBytes_length_(png, len(png))
wrote |= bool(pasteboard.setData_forType_(data, AppKit.NSPasteboardTypePNG))
+ if wrote:
+ _synced_count = pasteboard.changeCount()
return wrote
except Exception:
LOGGER.exception("failed to set the macOS clipboard")
diff --git a/mac_app/config.py b/mac_app/config.py
index 05670e6..44daa3d 100644
--- a/mac_app/config.py
+++ b/mac_app/config.py
@@ -4,6 +4,7 @@ import json
import os
from dataclasses import dataclass, field
+import effects
from crossing import DEFAULT_CROSSING
DEFAULT_CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
@@ -17,9 +18,10 @@ DEFAULT_KEY_MAP = {
"cmd_r": "ctrl",
}
-# The positional map Beamer shipped before 09-09-2026, written verbatim into
-# every existing config.json. A saved key_map beats the default, so without
-# this an upgraded install would silently keep sending Cmd as the Windows key.
+# The positional map Beamer used to ship as the default, written verbatim
+# into every existing config.json. A saved key_map beats the default, so
+# without this an upgraded install would silently keep sending Cmd as the
+# Windows key.
# A saved map whose every entry matches this one is the old default rather
# than a deliberate choice, so it is discarded.
LEGACY_POSITIONAL_KEY_MAP = {
@@ -34,7 +36,12 @@ LEGACY_POSITIONAL_KEY_MAP = {
# The two modifier styles the settings window offers. A saved key_map may be one of these
# names instead of a JSON object; Positional has to be saved by name, because its object form is
-# the pre-09-09-2026 default and is discarded on load (see LEGACY_POSITIONAL_KEY_MAP).
+# the old default and is discarded on load (see LEGACY_POSITIONAL_KEY_MAP).
+# The settings window's palette: follow the Mac, or keep one. tokens.APPEARANCES is the home of these
+# values; this copy keeps config importable without the repo root, and test_shared_copies holds the
+# two together.
+APPEARANCES = ("system", "light", "dark")
+
KEY_MAP_STYLES = {
"semantic": DEFAULT_KEY_MAP,
"positional": LEGACY_POSITIONAL_KEY_MAP,
@@ -64,6 +71,15 @@ 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
+ # Ask GitHub once a day whether a newer release is out; see updates.py.
+ check_updates: bool = True
+ # Every address the window shows is hidden; see pages.redact.
+ hide_addresses: bool = False
+ # How the PC's pointer and scroll feel on this Mac; see receiver.InputScale.
+ pointer_speed: float = 1.0
+ scroll_speed: float = 1.0
+ reverse_scroll: bool = False
+ appearance: str = "system"
# Keys and buttons that stay on this Mac while its input is on Windows; see ignored.py.
ignored_inputs: list = field(default_factory=list)
@@ -115,7 +131,11 @@ def load_config(path: str = None) -> Config:
if not isinstance(saved_crossing, dict):
raise ConfigError("config.json crossing must be a JSON object")
crossing.update(saved_crossing)
+ crossing["glow_style"], crossing["glow_colour"], crossing["shortcut_arrival_style"] = effects.offered(
+ crossing["glow_style"], crossing["glow_colour"], crossing["shortcut_arrival_style"])
crossing["methods"] = list(crossing["methods"])
+ if isinstance(crossing["edge_parts"], list):
+ crossing["edge_parts"] = list(crossing["edge_parts"])
crossing["resistance_px"] = int(crossing["resistance_px"])
return Config(
@@ -132,5 +152,11 @@ 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,
+ check_updates=raw.get("check_updates", True) is not False,
+ hide_addresses=raw.get("hide_addresses", False) is True,
+ pointer_speed=raw.get("pointer_speed", 1.0),
+ scroll_speed=raw.get("scroll_speed", 1.0),
+ reverse_scroll=raw.get("reverse_scroll", False),
+ appearance=raw.get("appearance") if raw.get("appearance") in APPEARANCES else "system",
ignored_inputs=raw.get("ignored_inputs", []),
)
diff --git a/mac_app/crossing.py b/mac_app/crossing.py
index 121704d..3dd6b86 100644
--- a/mac_app/crossing.py
+++ b/mac_app/crossing.py
@@ -13,9 +13,11 @@ mechanism is what keeps a slow lean against the edge from ever building a switch
from dataclasses import dataclass
+import return_edge
+
EDGES = ("left", "right", "top", "bottom")
CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")
-METHODS = ("shortcut", "edge", "corner", "notch")
+METHODS = ("shortcut", "edge", "part", "corner", "notch")
NOTCH_STYLES = ("beam", "island")
HAPTIC_FEELS = ("light", "medium", "firm")
HAPTIC_STEPS = ("quarters", "halves", "breakthrough")
@@ -38,6 +40,14 @@ DEFAULT_CROSSING = {
"glow_style": "glow",
"glow_colour": "signal",
"block_while_dragging": True,
+ # "Part of the edge": the thirds of `edge` that cross, as return_edge.PARTS names them.
+ "edge_parts": ["middle"],
+ # A switch by the shortcut or a menu, not a crossing, plays an arrival around the pointer.
+ "shortcut_arrival": True,
+ # What that plays: "match" for whatever the crossing style plays, else see effects.SWITCH_STYLES.
+ "shortcut_arrival_style": "match",
+ # How long an effect takes to play through once the pointer crosses: see effects.LENGTHS.
+ "effect_length": "normal",
# Unix seconds at the moment this Mac last changed the arrangement -- which
# edge leads to the PC. Either machine may change it, so when two ends meet
# holding different answers the newer stamp wins. Never read by the engine;
@@ -93,9 +103,11 @@ class CrossingEngine:
corner="top_right",
resistance_px=120,
block_while_dragging=True,
+ parts=("middle",),
):
self.methods = frozenset(methods)
self.edge = edge
+ self.parts = frozenset(parts)
self.corner = corner
self.resistance_px = float(resistance_px)
self.block_while_dragging = block_while_dragging
@@ -109,11 +121,12 @@ class CrossingEngine:
corner=crossing["corner"],
resistance_px=crossing["resistance_px"],
block_while_dragging=crossing["block_while_dragging"],
+ parts=crossing.get("edge_parts", ("middle",)),
)
@property
def armed(self):
- return bool(self.methods & {"edge", "corner", "notch"})
+ return bool(self.methods & {"edge", "part", "corner", "notch"})
def reset(self):
self.touching = False
@@ -128,19 +141,18 @@ class CrossingEngine:
def home_edge(self, mac_edge=None):
"""The Windows edge the pointer comes home through: opposite the Mac edge it left by or,
- for a shortcut switch, opposite whichever pointer method is on. None when only the
- shortcut is on. The configured `edge` keeps its value while the edge method is off, so
- reading it unconditionally armed a Windows edge nobody had enabled and left the notch's
- own way home dead after every shortcut switch."""
+ for a shortcut switch, opposite whichever pointer method is on. The notch and a corner come
+ first because the configured `edge` keeps its value while the edge method is off, and
+ reading it then armed the wrong Windows edge and left the notch's way home dead. With only
+ the shortcut on it is still the PC's edge facing this Mac: turning this Mac's own edge off
+ says nothing about the PC's, and the PC also learns from it which way its own push goes."""
if mac_edge is None:
- if "edge" in self.methods:
- mac_edge = self.edge
- elif "notch" in self.methods:
+ if "notch" in self.methods and not self.methods & {"edge", "part"}:
mac_edge = "top"
- elif "corner" in self.methods:
+ elif "corner" in self.methods and not self.methods & {"edge", "part"}:
mac_edge = self.corner.split("_")[1]
else:
- return None
+ mac_edge = self.edge
return OPPOSITE[mac_edge]
def pressure_at(self, now):
@@ -151,7 +163,9 @@ class CrossingEngine:
remaining = self.pressure - self._decay(now - self._last_at)
return max(0.0, min(1.0, remaining / self.resistance_px))
- def feed(self, x, y, dx, dy, bounds, now, notch_range=None, dragging=False):
+ def feed(self, x, y, dx, dy, bounds, now, notch_range=None, dragging=False, displays=None):
+ """`displays` is each display's (left, top, right, bottom), which Part of the edge measures
+ its thirds along; without them it measures along `bounds`."""
if self._last_at is not None:
self.pressure = max(0.0, self.pressure - self._decay(now - self._last_at))
self._last_at = now
@@ -161,14 +175,20 @@ class CrossingEngine:
self.touching = False
return self._release()
- target = self._target(x, y, bounds, notch_range)
+ target = self._target(x, y, bounds, notch_range, displays)
# Whether the pointer is at an armed region at all, whatever the pressure: a slow push
# drains to nothing between events and releases, but is still against the edge.
self.touching = target is not None
if target is None:
return self._release()
mac_edge, region, diagonal, via = target
- outward, inward = self._push(mac_edge, diagonal, x, y, dx, dy, previous_x, previous_y, bounds)
+ outward, inward = self._push(mac_edge, diagonal, x, y, dx, dy, previous_x, previous_y, self._push_box)
+ if via == "corner" and outward <= 0.0:
+ # A straight push in the corner's box is still a push on the edge it sits on, as on the PC.
+ edge_target = self._target(x, y, bounds, notch_range, displays, corner=False)
+ if edge_target is not None:
+ mac_edge, region, diagonal, via = edge_target
+ outward, inward = self._push(mac_edge, diagonal, x, y, dx, dy, previous_x, previous_y, self._push_box)
before = self.pressure
self.pressure = max(0.0, self.pressure + outward - inward)
if self.pressure <= 0.0:
@@ -182,6 +202,7 @@ class CrossingEngine:
step = Step(
pressure=1.0,
crossed=True,
+ pin=self.pin,
edge=OPPOSITE[mac_edge],
offset=self._offset(mac_edge, self.pin, bounds),
mac_edge=mac_edge,
@@ -207,18 +228,23 @@ class CrossingEngine:
)
@staticmethod
- def arrival_point(edge, offset, bounds, inset=2.0):
+ def arrival_point(edge, offset, bounds, inset=2.0, displays=None):
"""Where the pointer lands when input comes home through a Mac `edge`, `offset` of the
- way along it, a couple of points inside so the arrival itself is not already a push."""
+ way along it, a couple of points inside so the arrival itself is not already a push. With
+ `displays`, on the display return_edge.landing_monitor picks, so a staggered or stacked
+ arrangement never lands it in a gap or on the wrong display."""
left, top, right, bottom = bounds
offset = max(0.0, min(1.0, float(offset)))
- if edge in ("left", "right"):
- y = top + offset * (bottom - 1 - top)
- x = left + inset if edge == "left" else right - 1 - inset
- else:
- x = left + offset * (right - 1 - left)
- y = top + inset if edge == "top" else bottom - 1 - inset
- return (x, y)
+ side = edge in ("left", "right")
+ along = top + offset * (bottom - 1 - top) if side else left + offset * (right - 1 - left)
+ if displays:
+ rects = [return_edge.Rect(d[0], d[1], d[2] - d[0], d[3] - d[1]) for d in displays]
+ owner = displays[rects.index(return_edge.landing_monitor(rects, edge, along))]
+ left, top, right, bottom = owner
+ along = min(max(along, top if side else left), (bottom if side else right) - 1)
+ if side:
+ return (left + inset if edge == "left" else right - 1 - inset, along)
+ return (along, top + inset if edge == "top" else bottom - 1 - inset)
def _decay(self, elapsed):
if elapsed <= 0 or self.resistance_px <= 0:
@@ -243,7 +269,7 @@ class CrossingEngine:
return 0
return min(3, int(4 * pressure / self.resistance_px))
- def _target(self, x, y, bounds, notch_range):
+ def _target(self, x, y, bounds, notch_range, displays=None, corner=True):
"""Which armed region the pointer is touching, as (mac_edge, region, diagonal, method). The
corner wins over the edge it sits on, since its box is inside that edge's strip."""
left, top, right, bottom = bounds
@@ -254,7 +280,16 @@ class CrossingEngine:
"top": y <= top + EDGE_TOLERANCE,
"bottom": y >= y_max - EDGE_TOLERANCE,
}
- if "corner" in self.methods:
+ own = next((d for d in displays or () if d[0] <= x < d[2] and d[1] <= y < d[3]), None)
+ edge_box = bounds
+ if own is not None and not at[self.edge] and self._exposed(self.edge, x, y, own, displays):
+ # The edge of a display that stops short of the desktop's, with nothing beyond it: a
+ # wall all the same, as on the PC. Against the whole desktop it could never be reached.
+ at[self.edge] = True
+ edge_box = own
+ # What the push is measured against: the display's own edge when that is the wall.
+ self._push_box = bounds
+ if corner and "corner" in self.methods:
vertical, horizontal = self.corner.split("_")
near_x = x <= left + CORNER_PX if horizontal == "left" else x >= x_max - CORNER_PX
near_y = y <= top + CORNER_PX if vertical == "top" else y >= y_max - CORNER_PX
@@ -263,13 +298,45 @@ class CrossingEngine:
box_y = top if vertical == "top" else y_max - CORNER_PX + 1
return horizontal, (box_x, box_y, CORNER_PX, CORNER_PX), vertical, "corner"
if "edge" in self.methods and at[self.edge]:
- return self.edge, self._strip(self.edge, bounds), None, "edge"
+ self._push_box = edge_box
+ return self.edge, self._strip(self.edge, edge_box), None, "edge"
+ if "part" in self.methods and at[self.edge]:
+ # The thirds are the pointer's own display's, as the PC measures them: along the whole
+ # desktop, a short display beside a tall one could hold none of the middle third.
+ part = return_edge.part_of(self._offset(self.edge, (x, y), own or bounds))
+ if part in self.parts:
+ self._push_box = edge_box
+ return self.edge, self._part_strip(self.edge, own or bounds, part), None, "edge"
if "notch" in self.methods and notch_range is not None and at["top"]:
notch_left, notch_right = notch_range
if notch_left <= x <= notch_right:
return "top", (notch_left, top, notch_right - notch_left, 1), None, "notch"
return None
+ @staticmethod
+ def _exposed(edge, x, y, own, displays):
+ """Whether the pointer is at `own`'s `edge` with no display just beyond it."""
+ left, top, right, bottom = own
+ near = {
+ "left": x <= left + EDGE_TOLERANCE,
+ "right": x >= right - 1 - EDGE_TOLERANCE,
+ "top": y <= top + EDGE_TOLERANCE,
+ "bottom": y >= bottom - 1 - EDGE_TOLERANCE,
+ }[edge]
+ if not near:
+ return False
+ beyond = {"left": (left - 1, y), "right": (right, y), "top": (x, top - 1), "bottom": (x, bottom)}[edge]
+ return not any(d[0] <= beyond[0] < d[2] and d[1] <= beyond[1] < d[3] for d in displays)
+
+ @classmethod
+ def _part_strip(cls, edge, bounds, part):
+ """The third of `edge`'s strip that `part` names, which is all the glow lights."""
+ x, y, w, h = cls._strip(edge, bounds)
+ index = return_edge.PARTS.index(part)
+ if edge in ("left", "right"):
+ return (x, y + h * index / 3.0, w, h / 3.0)
+ return (x + w * index / 3.0, y, w / 3.0, h)
+
@staticmethod
def _strip(edge, bounds):
left, top, right, bottom = bounds
diff --git a/mac_app/desktop_mac.py b/mac_app/desktop_mac.py
index c09fbda..9fc524a 100644
--- a/mac_app/desktop_mac.py
+++ b/mac_app/desktop_mac.py
@@ -32,8 +32,8 @@ def _require():
def display_ids(quartz=None) -> list:
"""The displays that make up the desktop: the active list, unless it is empty. It is empty
while the displays sleep, and a sleeping display is still where it was, so the online list
- stands in (27-09-2026: with the Mac's display asleep, the PC's pointer arriving and this Mac's
- own push both failed on the empty list, and each turned its crossing off)."""
+ stands in -- with the Mac's display asleep, the PC's pointer arriving and this Mac's own push
+ both failed on the empty list, and each turned its crossing off."""
quartz = quartz or _require()
error, ids, count = quartz.CGGetActiveDisplayList(MAX_DISPLAYS, None, None)
if error == 0 and count:
diff --git a/mac_app/diagram.py b/mac_app/diagram.py
new file mode 100644
index 0000000..c147766
--- /dev/null
+++ b/mac_app/diagram.py
@@ -0,0 +1,278 @@
+"""The Crossing page's two drawings, in Core Animation layers so every change can move: the
+arrangement, which shows where the PC sits and what crosses, and the push strip, which shows how
+far the pointer is pushed past the edge before it gives."""
+
+from __future__ import annotations
+
+import AppKit
+import Quartz
+import objc
+
+import motion
+import pages
+import theme
+
+
+def _rect(frame):
+ x, y, w, h = frame
+ return ((x, y), (w, h))
+
+
+def _text_width(text, font):
+ return AppKit.NSAttributedString.alloc().initWithString_attributes_(
+ text, {AppKit.NSFontAttributeName: font}
+ ).size().width
+
+
+def _text_layer(size, ink, align=Quartz.kCAAlignmentCenter):
+ layer = Quartz.CATextLayer.layer()
+ layer.setFont_(theme.font(size, 500))
+ layer.setFontSize_(size)
+ theme.tint(layer, foreground=ink)
+ layer.setAlignmentMode_(align)
+ layer.setTruncationMode_(Quartz.kCATruncationEnd)
+ layer.setContentsScale_(2.0)
+ return layer
+
+
+def _box(fill=None, stroke=None, radius=0.0):
+ layer = Quartz.CALayer.layer()
+ theme.tint(layer, background=fill, border=stroke)
+ if stroke:
+ layer.setBorderWidth_(1)
+ layer.setCornerRadius_(radius)
+ return layer
+
+
+def _collapsed(frame, side):
+ """`frame` shrunk to its middle along the side it runs down, where a mark grows from."""
+ x, y, w, h = frame
+ if side in ("left", "right"):
+ return (x, y + h / 2, w, 0.0)
+ return (x + w / 2, y, 0.0, h)
+
+
+class ArrangementDiagram(AppKit.NSView):
+ """This Mac's screen with the PC's beside it on the chosen side, lit where a way in crosses."""
+
+ HEIGHT = 186.0
+
+ def isFlipped(self):
+ return True
+
+ @objc.python_method
+ def setup(self):
+ self.setTranslatesAutoresizingMaskIntoConstraints_(False)
+ self.heightAnchor().constraintEqualToConstant_(self.HEIGHT).setActive_(True)
+ self.setWantsLayer_(True)
+ root = self.layer()
+ theme.tint(root, background="ground", border="rule")
+ root.setBorderWidth_(1)
+ root.setCornerRadius_(3)
+ self.other = _box("panel", "rule", 4)
+ self.this = _box("well", "edge", 4)
+ self.this_label = _text_layer(theme.TYPE["small"], "ink_2")
+ self.other_label = _text_layer(theme.TYPE["small"], "ink_3")
+ self.notch = _box("ground", None, 2)
+ self.side = _box("signal", None, 1.5)
+ self.thirds = {part: _box("signal", None, 1.5) for part in ("start", "middle", "end")}
+ self.corner = _box("signal", None, 2)
+ self.key = _box("well", "edge", theme.RADIUS["keycap"])
+ # The shortcut as a key cap in the corner, and how it is pressed beside it: a legend, not a
+ # sentence, since the note above the drawing already says it in words.
+ self.key_label = _text_layer(theme.TYPE["small"], "ink", Quartz.kCAAlignmentCenter)
+ self.key_label.setFont_(theme.font(theme.TYPE["small"], 600))
+ self.key.addSublayer_(self.key_label)
+ self.key_how = _text_layer(theme.TYPE["small"], "ink_3", Quartz.kCAAlignmentLeft)
+ for layer in (self.other, self.this, self.this_label, self.other_label, self.notch, self.side,
+ *self.thirds.values(), self.corner, self.key, self.key_how):
+ root.addSublayer_(layer)
+ self.state = None
+ self.lit = {}
+ self.setAccessibilityElement_(True)
+ self.setAccessibilityRole_(AppKit.NSAccessibilityImageRole)
+ return self
+
+ def layout(self):
+ objc.super(ArrangementDiagram, self).layout()
+ if self.state is not None:
+ self._draw(False)
+
+ @objc.python_method
+ def show(self, side, methods, parts, corner, key_text, other_name, has_notch, description, key_how=""):
+ """Draws the arrangement for these settings, moving from the last one when on screen.
+ `key_text` is the shortcut's key as its cap reads, `key_how` how it is pressed."""
+ state = (side, frozenset(methods), frozenset(parts), corner, key_text, other_name, has_notch, key_how)
+ if state == self.state:
+ return
+ first = self.state is None
+ self.state = state
+ self.setAccessibilityLabel_(description)
+ self._draw(not first and motion.live(self))
+
+ @objc.python_method
+ def _draw(self, animate):
+ side, methods, parts, corner, key_text, other_name, has_notch, key_how = self.state
+ bounds = self.bounds().size
+ if bounds.width <= 0:
+ return
+ this, other = pages.arrangement(bounds.width, bounds.height, side)
+ motion.transaction(animate)
+ self.this.setFrame_(_rect(this))
+ self.other.setFrame_(_rect(other))
+ self.this_label.setString_("This Mac")
+ self.other_label.setString_(other_name)
+ line = theme.TYPE["small"] + 4
+ for layer, (x, y, w, h) in ((self.this_label, this), (self.other_label, other)):
+ layer.setFrame_(((x + 6, y + (h - line) / 2 + (4 if layer is self.this_label and has_notch else 0)), (w - 12, line)))
+ self.notch.setFrame_(_rect(pages.notch_mark(this)))
+ self.notch.setHidden_(not has_notch)
+ lit_notch = has_notch and "notch" in methods
+ self.notch.setBorderWidth_(1.5 if lit_notch else 0)
+ theme.tint(self.notch, border="signal", background=("signal", 0.25) if lit_notch else "ground")
+ part = "part" in methods
+ self._mark("side", self.side, pages.side_mark(this, side), "edge" in methods, side, animate)
+ for name, frame in pages.third_marks(this, side).items():
+ layer = self.thirds[name]
+ chosen = part and name in parts
+ # Unchosen thirds stay as a dim track while Part of the edge is on, so the gaps read
+ # as walls rather than as nothing.
+ theme.tint(layer, background="signal" if chosen else "edge")
+ self._mark(name, layer, frame, part, side, animate, lit=chosen)
+ self._mark("corner", self.corner, pages.corner_mark(this, corner), "corner" in methods, None, animate)
+ shortcut = "shortcut" in methods and bool(key_text)
+ self.key_label.setString_(key_text)
+ self.key_how.setString_(key_how)
+ width = min(bounds.width - 20, 24 + _text_width(key_text, theme.font(theme.TYPE["small"], 600)))
+ top = bounds.height - 36
+ self.key.setFrame_(((12, top), (width, 24)))
+ self.key_label.setFrame_(((0, (24 - line) / 2), (width, line)))
+ self.key_how.setFrame_(((12 + width + 8, top + (24 - line) / 2), (max(0, bounds.width - width - 32), line)))
+ for layer in (self.key, self.key_how):
+ layer.setOpacity_(1.0 if shortcut else 0.0)
+ Quartz.CATransaction.commit()
+
+ @objc.python_method
+ def _mark(self, key, layer, frame, on, side, animate, lit=None):
+ """Places a mark; switched on or newly lit while moving, it grows out from its middle as
+ it fades in."""
+ # The side is part of the state: moved to another side, a mark grows in afresh there, which
+ # reads far better than a strip stretching across the screen from one side to the other.
+ state = (on, on if lit is None else lit, self.state[0])
+ was = self.lit.get(key)
+ self.lit[key] = state
+ if not (on and was != state and animate):
+ layer.setFrame_(_rect(frame))
+ layer.setOpacity_(1.0 if on else 0.0)
+ return
+ # Explicit animations from the collapsed mark: an implicit one would start from wherever
+ # the mark was drawn before, inside this same transaction.
+ start = _collapsed(frame, side) if side else (frame[0] + frame[2] / 2, frame[1] + frame[3] / 2, 0, 0)
+ motion.transaction(False)
+ layer.setFrame_(_rect(frame))
+ layer.setOpacity_(1.0)
+ Quartz.CATransaction.commit()
+ x, y, w, h = frame
+ sx, sy, sw, sh = start
+ for key, old, new in (
+ ("bounds", AppKit.NSValue.valueWithRect_(((0, 0), (sw, sh))), AppKit.NSValue.valueWithRect_(((0, 0), (w, h)))),
+ ("position", AppKit.NSValue.valueWithPoint_((sx + sw / 2, sy + sh / 2)), AppKit.NSValue.valueWithPoint_((x + w / 2, y + h / 2))),
+ ("opacity", 0.0, 1.0),
+ ):
+ grow = Quartz.CABasicAnimation.animationWithKeyPath_(key)
+ grow.setFromValue_(old)
+ grow.setToValue_(new)
+ grow.setDuration_(motion.DURATION)
+ grow.setTimingFunction_(motion.timing())
+ layer.addAnimation_forKey_(grow, key)
+
+
+class PushStrip(AppKit.NSView):
+ """The last stretch of this Mac's screen, the edge, and the PC beyond it, with the push past the
+ edge drawn in: its depth is the resistance, out of the ruler's 500 px."""
+
+ HEIGHT = 44.0
+ EDGE_AT = 0.36
+ REST = 0.55
+
+ def isFlipped(self):
+ return True
+
+ @objc.python_method
+ def setup(self):
+ self.setTranslatesAutoresizingMaskIntoConstraints_(False)
+ self.heightAnchor().constraintEqualToConstant_(self.HEIGHT).setActive_(True)
+ self.setWantsLayer_(True)
+ root = self.layer()
+ root.setCornerRadius_(3)
+ root.setMasksToBounds_(True)
+ theme.tint(root, background="ground", border="rule")
+ root.setBorderWidth_(1)
+ self.this = _box("well")
+ self.fill = Quartz.CAGradientLayer.layer()
+ theme.tint(self.fill, colours=[("signal", 0.9), ("signal", 0.15)])
+ self.fill.setStartPoint_((0.0, 0.5))
+ self.fill.setEndPoint_((1.0, 0.5))
+ self.fill.setOpacity_(self.REST)
+ self.edge = _box("ink_3")
+ self.pointer = Quartz.CAShapeLayer.layer()
+ path = Quartz.CGPathCreateMutable()
+ for index, (x, y) in enumerate(((0, 0), (0, 14), (3.6, 10.6), (6.2, 16), (8.2, 15), (5.7, 9.8), (10, 9.8))):
+ (Quartz.CGPathMoveToPoint if index == 0 else Quartz.CGPathAddLineToPoint)(path, None, x, y)
+ Quartz.CGPathCloseSubpath(path)
+ self.pointer.setPath_(path)
+ theme.tint(self.pointer, fill="ink", stroke="ground")
+ self.pointer.setLineWidth_(1)
+ self.pointer.setBounds_(((0, 0), (10, 16)))
+ self.pointer.setAnchorPoint_((0.0, 0.0))
+ self.this_label = _text_layer(theme.TYPE["eyebrow"], "ink_3", Quartz.kCAAlignmentLeft)
+ self.other_label = _text_layer(theme.TYPE["eyebrow"], "ink_3", Quartz.kCAAlignmentRight)
+ for layer in (self.this, self.fill, self.edge, self.this_label, self.other_label, self.pointer):
+ root.addSublayer_(layer)
+ self.fraction = None
+ self.other_name = "PC"
+ self.setAccessibilityElement_(False)
+ return self
+
+ def layout(self):
+ objc.super(PushStrip, self).layout()
+ if self.fraction is not None:
+ self._draw(False)
+
+ @objc.python_method
+ def show(self, fraction, other_name="PC"):
+ fraction = min(1.0, max(0.0, float(fraction)))
+ if fraction == self.fraction and other_name == self.other_name:
+ return
+ moving = self.fraction is not None and motion.live(self)
+ self.fraction, self.other_name = fraction, other_name
+ self._draw(moving)
+ if moving and fraction > 0:
+ # The push brightens as it moves, then settles back.
+ pulse = Quartz.CABasicAnimation.animationWithKeyPath_("opacity")
+ pulse.setFromValue_(1.0)
+ pulse.setToValue_(self.REST)
+ pulse.setDuration_(0.6)
+ pulse.setTimingFunction_(motion.timing())
+ self.fill.addAnimation_forKey_(pulse, "pulse")
+
+ @objc.python_method
+ def _draw(self, animate):
+ width, height = self.bounds().size.width, self.bounds().size.height
+ if width <= 0:
+ return
+ edge = round(width * self.EDGE_AT)
+ # The full 500 px stops short of the PC's name, so the name is never under the push.
+ room = width - edge - 120
+ depth = room * self.fraction
+ motion.transaction(animate)
+ self.this.setFrame_(((0, 0), (edge, height)))
+ self.edge.setFrame_(((edge - 1, 0), (2, height)))
+ self.fill.setFrame_(((edge, 0), (depth, height)))
+ self.pointer.setPosition_((edge + depth - 1, (height - 16) / 2))
+ line = theme.TYPE["eyebrow"] + 4
+ self.this_label.setString_("THIS MAC")
+ self.other_label.setString_(self.other_name.upper())
+ self.this_label.setFrame_(((10, (height - line) / 2), (edge - 20, line)))
+ self.other_label.setFrame_(((edge + 10, (height - line) / 2), (width - edge - 20, line)))
+ Quartz.CATransaction.commit()
diff --git a/mac_app/dmg/background.png b/mac_app/dmg/background.png
new file mode 100644
index 0000000..d0749e6
Binary files /dev/null and b/mac_app/dmg/background.png differ
diff --git a/mac_app/dmg/[email protected] b/mac_app/dmg/[email protected]
new file mode 100644
index 0000000..942b8b8
Binary files /dev/null and b/mac_app/dmg/[email protected] differ
diff --git a/mac_app/dmg/draw_background.py b/mac_app/dmg/draw_background.py
new file mode 100644
index 0000000..e790ea1
--- /dev/null
+++ b/mac_app/dmg/draw_background.py
@@ -0,0 +1,104 @@
+"""Draws the DMG window's background, background.png and [email protected] beside this file, from
+Beamer's own palette and type. Run it again after changing the palette or the layout in
+dmg_settings.py; the build only reads the PNGs.
+
+Finder writes the icon names itself, white in Dark Mode and black in Light Mode, so the icons sit
+on a shelf whose tone reads against both: `edge` has a contrast of about 5:1 with white and 4:1 with
+black. Everything else is Beamer's dark ground."""
+
+import sys
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE.parent.parent))
+
+import AppKit # noqa: E402
+
+import theme # noqa: E402
+import tokens # noqa: E402
+
+# The window's content, in points; dmg_settings.py places the icons on these centres.
+WIDTH, HEIGHT = 640, 400
+APP_AT, APPLICATIONS_AT = (170, 240), (470, 240)
+SHELF = (40, 150, 560, 210)
+
+
+def colour(hex_value, alpha=1.0):
+ r, g, b = theme.rgb(hex_value)
+ return AppKit.NSColor.colorWithSRGBRed_green_blue_alpha_(r, g, b, alpha)
+
+
+def text(words, size, weight, ink, centre_y):
+ style = AppKit.NSMutableParagraphStyle.alloc().init()
+ style.setAlignment_(AppKit.NSTextAlignmentCenter)
+ attributes = {
+ AppKit.NSFontAttributeName: theme.font(size, weight),
+ AppKit.NSForegroundColorAttributeName: colour(ink),
+ AppKit.NSParagraphStyleAttributeName: style,
+ }
+ string = AppKit.NSAttributedString.alloc().initWithString_attributes_(words, attributes)
+ height = string.size().height
+ string.drawInRect_(AppKit.NSMakeRect(0, HEIGHT - centre_y - height / 2, WIDTH, height))
+
+
+def draw(scale):
+ palette = tokens.PALETTE
+ rep = AppKit.NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
+ None, WIDTH * scale, HEIGHT * scale, 8, 4, True, False, AppKit.NSDeviceRGBColorSpace, 0, 0
+ )
+ rep.setSize_((WIDTH, HEIGHT))
+ AppKit.NSGraphicsContext.saveGraphicsState()
+ AppKit.NSGraphicsContext.setCurrentContext_(AppKit.NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep))
+
+ colour(palette["ground"]).setFill()
+ AppKit.NSRectFill(AppKit.NSMakeRect(0, 0, WIDTH, HEIGHT))
+
+ text("Drag Beamer to Applications", 24, 600, palette["ink"], 58)
+ text("Then open it from Applications. The first time, it asks for two permissions.",
+ 13, 400, palette["ink_2"], 92)
+
+ x, y, w, h = SHELF
+ shelf = AppKit.NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
+ AppKit.NSMakeRect(x, HEIGHT - y - h, w, h), 14, 14
+ )
+ gradient = AppKit.NSGradient.alloc().initWithStartingColor_endingColor_(
+ colour("#76776e"), colour("#65665e")
+ )
+ gradient.drawInBezierPath_angle_(shelf, -90)
+ # A lit top edge, so the shelf reads as a tray the icons sit in rather than a flat block.
+ rim = AppKit.NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(
+ AppKit.NSMakeRect(x + 0.5, HEIGHT - y - h + 0.5, w - 1, h - 1), 13.5, 13.5
+ )
+ colour("#8c8d83").set()
+ rim.setLineWidth_(1)
+ rim.stroke()
+
+ # The arrow runs between the two icons at their centre height, dark on the shelf.
+ start, end = APP_AT[0] + 84, APPLICATIONS_AT[0] - 84
+ mid = HEIGHT - APP_AT[1]
+ colour(palette["ground"]).set()
+ line = AppKit.NSBezierPath.bezierPath()
+ line.setLineWidth_(5)
+ line.setLineCapStyle_(AppKit.NSLineCapStyleRound)
+ line.moveToPoint_((start, mid))
+ line.lineToPoint_((end - 6, mid))
+ line.stroke()
+ head = AppKit.NSBezierPath.bezierPath()
+ head.moveToPoint_((end + 6, mid))
+ head.lineToPoint_((end - 14, mid + 13))
+ head.lineToPoint_((end - 14, mid - 13))
+ head.closePath()
+ head.fill()
+
+ AppKit.NSGraphicsContext.restoreGraphicsState()
+ data = rep.representationUsingType_properties_(AppKit.NSBitmapImageFileTypePNG, {})
+ name = "background.png" if scale == 1 else f"background@{scale}x.png"
+ data.writeToFile_atomically_(str(HERE / name), True)
+ return HERE / name
+
+
+if __name__ == "__main__":
+ AppKit.NSApplication.sharedApplication()
+ theme.init_fonts()
+ for scale in (1, 2):
+ print(draw(scale))
diff --git a/mac_app/dmg/settings.py b/mac_app/dmg/settings.py
new file mode 100644
index 0000000..2ffc494
--- /dev/null
+++ b/mac_app/dmg/settings.py
@@ -0,0 +1,24 @@
+# dmgbuild settings for Beamer's disk image: the app, a link to Applications and a background
+# that says what to do. build_dmg.sh passes -D app=<Beamer.app> -D background=<background.png>;
+# dmgbuild finds [email protected] beside it for Retina screens.
+
+import os.path
+
+application = defines["app"] # noqa: F821 - dmgbuild provides `defines`
+background = defines["background"] # noqa: F821
+
+format = "UDZO"
+files = [application]
+symlinks = {"Applications": "/Applications"}
+
+# The same centres draw_background.py draws the shelf and the arrow for, in a 640 x 400 window.
+icon_locations = {os.path.basename(application): (170, 240), "Applications": (470, 240)}
+window_rect = ((200, 160), (640, 400))
+default_view = "icon-view"
+icon_size = 128
+text_size = 13
+show_status_bar = False
+show_tab_view = False
+show_toolbar = False
+show_pathbar = False
+show_sidebar = False
diff --git a/mac_app/effects.py b/mac_app/effects.py
new file mode 100644
index 0000000..ab4ac74
--- /dev/null
+++ b/mac_app/effects.py
@@ -0,0 +1,959 @@
+"""Crossing effects: the departure and arrival animations, drawn once here and replayed natively by
+each app.
+
+An effect draws into a Pen, which offers the part of the HTML canvas API the original designs were
+written against, so each fx_*.py module is a line-for-line port of its design's animation logic. The
+Pen does not draw: it records operations in screen points with every transform already applied, arcs
+already turned into curves, and colours already parsed. The Mac replays them into Core Graphics and
+Windows into QPainter, both checked against the original animation for fidelity.
+
+`Player` owns the timing both apps share: pressure, the quarter ticks, breakthrough, the departure
+finishing and the arrival playing out, so an effect looks the same on both machines.
+
+This file and every fx_*.py are byte-identical in mac_app/ and win_app/; test_shared_copies checks.
+"""
+
+from __future__ import annotations
+
+import colorsys
+import functools
+import math
+import re
+from types import SimpleNamespace
+
+TAU = math.pi * 2.0
+IDENTITY = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)
+
+
+def hash_n(n):
+ """The harness's stable pseudo-random number in [0, 1) for integer `n`; the designs' only
+ randomness, so every frame is a function of its state."""
+ x = math.sin(n * 127.1 + 311.7) * 43758.5453
+ return x - math.floor(x)
+
+
+def clamp(v, a=0.0, b=1.0):
+ return max(a, min(b, v))
+
+
+def lerp(a, b, u):
+ return a + (b - a) * u
+
+
+def ease_out(u):
+ return 1.0 - (1.0 - u) ** 3
+
+
+def ease_in_out(u):
+ return 2.0 * u * u if u < 0.5 else 1.0 - ((-2.0 * u + 2.0) ** 2) / 2.0
+
+
+_NAMED = {"black": (0.0, 0.0, 0.0, 1.0), "white": (1.0, 1.0, 1.0, 1.0), "transparent": (0.0, 0.0, 0.0, 0.0)}
+_RGB = re.compile(r"rgba?\(\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*(?:,\s*([-\d.]+)\s*)?\)$")
+
+
+def parse_colour(value):
+ """A CSS colour as the designs write them, "#rgb", "#rrggbb", "#rrggbbaa", "rgb()" or "rgba()",
+ or an (r, g, b[, a]) tuple of 0 to 1 floats, as (r, g, b, a) floats. Anything else is black, as
+ a canvas would leave the previous style; a design that relies on that is a bug to fix there."""
+ if isinstance(value, tuple):
+ return value if len(value) == 4 else (value[0], value[1], value[2], 1.0)
+ return _parse_text(str(value))
+
+
[email protected]_cache(maxsize=4096)
+def _parse_text(value):
+ """parse_colour for text. Cached: the heavier effects parse the same few colours a hundred
+ times a frame."""
+ text = value.strip().lower()
+ if text in _NAMED:
+ return _NAMED[text]
+ if text.startswith("#"):
+ digits = text[1:]
+ if len(digits) in (3, 4):
+ digits = "".join(c * 2 for c in digits)
+ if len(digits) in (6, 8):
+ parts = [int(digits[i:i + 2], 16) / 255.0 for i in range(0, len(digits), 2)]
+ return tuple(parts) if len(parts) == 4 else (parts[0], parts[1], parts[2], 1.0)
+ match = _RGB.match(text)
+ if match:
+ r, g, b = (clamp(float(match.group(i)) / 255.0) for i in (1, 2, 3))
+ a = clamp(float(match.group(4))) if match.group(4) is not None else 1.0
+ return (r, g, b, a)
+ return (0.0, 0.0, 0.0, 1.0)
+
+
+# The least HLS lightness a colour is drawn at on a dark wallpaper, and the most on a light one
+# by the effects in LIGHT_AS_GIVEN.
+DARK_FLOOR = 0.45
+LIGHT_CEILING = 0.6
+
+
+def legible(palette, dark, fx=None):
+ """`palette` as `fx` draws it. On a dark wallpaper every colour darker than DARK_FLOOR is
+ lifted to it, keeping its hue and saturation: the Ink packs lead with near-black inks and Ember
+ ends on a deep red, and effects that drew those, additively on dark most of all, all but
+ vanished. On a light one the effects that draw a pack's colours as given have every colour
+ lighter than LIGHT_CEILING brought down to it, as Mono, Pearl and Contrast all but vanished."""
+ if dark:
+ low, high = DARK_FLOOR, 1.0
+ elif getattr(fx, "id", None) in LIGHT_AS_GIVEN:
+ low, high = 0.0, LIGHT_CEILING
+ else:
+ return list(palette)
+ out = []
+ for colour in palette:
+ r, g, b, _a = parse_colour(colour)
+ h, lightness, sat = colorsys.rgb_to_hls(r, g, b)
+ if not low <= lightness <= high:
+ r, g, b = colorsys.hls_to_rgb(h, clamp(lightness, low, high), sat)
+ out.append("#%02x%02x%02x" % tuple(int(round(v * 255)) for v in (r, g, b)))
+ return out
+
+
+def _apply(m, x, y):
+ a, b, c, d, e, f = m
+ return (a * x + c * y + e, b * x + d * y + f)
+
+
+def _multiply(m, n):
+ """m then n in canvas order: the result maps a point through n first, then m."""
+ a, b, c, d, e, f = m
+ a2, b2, c2, d2, e2, f2 = n
+ return (a * a2 + c * b2, b * a2 + d * b2, a * c2 + c * d2, b * c2 + d * d2, a * e2 + c * f2 + e, b * e2 + d * f2 + f)
+
+
+def _scale_of(m):
+ return math.sqrt(abs(m[0] * m[3] - m[1] * m[2]))
+
+
+class Gradient:
+ """A canvas gradient, its geometry already in screen points. `kind` is "linear" (x0, y0, x1, y1),
+ "radial" (x0, y0, r0, x1, y1, r1) or "conic" (start angle, cx, cy); stops are (offset, rgba)."""
+
+ def __init__(self, kind, geometry):
+ self.kind = kind
+ self.geometry = geometry
+ self.stops = []
+
+ def addColorStop(self, offset, colour):
+ self.stops.append((clamp(float(offset)), parse_colour(colour)))
+
+
+class Pen:
+ """The recording canvas. Style properties keep their canvas names so ports stay line-for-line.
+
+ `ops` is a list of ("fill", path, paint, alpha, composite, rule) and
+ ("stroke", path, paint, alpha, composite, width, cap, join), where path is a list of
+ ("M", x, y), ("L", x, y), ("Q", cx, cy, x, y), ("C", c1x, c1y, c2x, c2y, x, y) and ("Z",),
+ and paint is an rgba tuple or a Gradient. `bounds` is a conservative box round everything drawn."""
+
+ def __init__(self):
+ self.ops = []
+ self.bounds = None
+ self._stack = []
+ self._path = []
+ self._start = None
+ self._current = None
+ self.fillStyle = "#000"
+ self.strokeStyle = "#000"
+ self.lineWidth = 1.0
+ self.lineCap = "butt"
+ self.lineJoin = "miter"
+ self.globalAlpha = 1.0
+ self.globalCompositeOperation = "source-over"
+ self._matrix = IDENTITY
+ # (left, top, right, bottom) of the display this Pen is for, which the replay clips to.
+ self.clip = None
+
+ def save(self):
+ self._stack.append((self.fillStyle, self.strokeStyle, self.lineWidth, self.lineCap, self.lineJoin,
+ self.globalAlpha, self.globalCompositeOperation, self._matrix))
+
+ def restore(self):
+ if self._stack:
+ (self.fillStyle, self.strokeStyle, self.lineWidth, self.lineCap, self.lineJoin,
+ self.globalAlpha, self.globalCompositeOperation, self._matrix) = self._stack.pop()
+
+ def transform(self, a, b, c, d, e, f):
+ self._matrix = _multiply(self._matrix, (a, b, c, d, e, f))
+
+ def setTransform(self, a, b, c, d, e, f):
+ self._matrix = (a, b, c, d, e, f)
+
+ def translate(self, x, y):
+ self.transform(1, 0, 0, 1, x, y)
+
+ def scale(self, x, y):
+ self.transform(x, 0, 0, y, 0, 0)
+
+ def rotate(self, angle):
+ cos, sin = math.cos(angle), math.sin(angle)
+ self.transform(cos, sin, -sin, cos, 0, 0)
+
+ def beginPath(self):
+ self._path = []
+ self._start = None
+ self._current = None
+
+ def moveTo(self, x, y):
+ p = _apply(self._matrix, x, y)
+ self._path.append(("M",) + p)
+ self._start = self._current = p
+
+ def lineTo(self, x, y):
+ if self._current is None:
+ self.moveTo(x, y)
+ return
+ p = _apply(self._matrix, x, y)
+ self._path.append(("L",) + p)
+ self._current = p
+
+ def quadraticCurveTo(self, cx, cy, x, y):
+ if self._current is None:
+ self.moveTo(cx, cy)
+ c = _apply(self._matrix, cx, cy)
+ p = _apply(self._matrix, x, y)
+ self._path.append(("Q",) + c + p)
+ self._current = p
+
+ def bezierCurveTo(self, c1x, c1y, c2x, c2y, x, y):
+ if self._current is None:
+ self.moveTo(c1x, c1y)
+ c1 = _apply(self._matrix, c1x, c1y)
+ c2 = _apply(self._matrix, c2x, c2y)
+ p = _apply(self._matrix, x, y)
+ self._path.append(("C",) + c1 + c2 + p)
+ self._current = p
+
+ def closePath(self):
+ if self._current is not None:
+ self._path.append(("Z",))
+ self._current = self._start
+
+ def rect(self, x, y, w, h):
+ self.moveTo(x, y)
+ self.lineTo(x + w, y)
+ self.lineTo(x + w, y + h)
+ self.lineTo(x, y + h)
+ self.closePath()
+ self.moveTo(x, y)
+
+ def arc(self, x, y, r, a0, a1, anticlockwise=False):
+ """Canvas arc semantics: a line from the current point to the arc's start, then the sweep,
+ drawn as cubic curves in user space so any transform, mirrors included, stays exact."""
+ r = abs(r)
+ if anticlockwise:
+ sweep = -TAU if a0 - a1 >= TAU else -((a0 - a1) % TAU)
+ else:
+ sweep = TAU if a1 - a0 >= TAU else (a1 - a0) % TAU
+ sx, sy = x + r * math.cos(a0), y + r * math.sin(a0)
+ if self._current is None:
+ self.moveTo(sx, sy)
+ else:
+ self.lineTo(sx, sy)
+ if sweep == 0.0 or r == 0.0:
+ return
+ # An eighth of a turn per curve: a quarter's error, 0.03% of the radius at its midpoint,
+ # moved the antialiasing of thin stroked rings visibly against a native arc.
+ pieces = max(1, int(math.ceil(abs(sweep) / (math.pi / 4.0) - 1e-9)))
+ step = sweep / pieces
+ k = 4.0 / 3.0 * math.tan(step / 4.0)
+ angle = a0
+ for _ in range(pieces):
+ end = angle + step
+ c0, s0, c1, s1 = math.cos(angle), math.sin(angle), math.cos(end), math.sin(end)
+ self.bezierCurveTo(x + r * (c0 - k * s0), y + r * (s0 + k * c0),
+ x + r * (c1 + k * s1), y + r * (s1 - k * c1),
+ x + r * c1, y + r * s1)
+ angle = end
+
+ def createLinearGradient(self, x0, y0, x1, y1):
+ return Gradient("linear", _apply(self._matrix, x0, y0) + _apply(self._matrix, x1, y1))
+
+ def createRadialGradient(self, x0, y0, r0, x1, y1, r1):
+ k = _scale_of(self._matrix)
+ return Gradient("radial", _apply(self._matrix, x0, y0) + (r0 * k,) + _apply(self._matrix, x1, y1) + (r1 * k,))
+
+ def createConicGradient(self, angle, x, y):
+ m = self._matrix
+ return Gradient("conic", (angle + math.atan2(m[1], m[0]),) + _apply(m, x, y))
+
+ def fill(self, rule="nonzero"):
+ if self._path:
+ self._record(("fill", list(self._path), self._paint(self.fillStyle), clamp(self.globalAlpha),
+ self.globalCompositeOperation, rule), 0.0)
+
+ def stroke(self):
+ if self._path and self.lineWidth > 0:
+ width = self.lineWidth * _scale_of(self._matrix)
+ self._record(("stroke", list(self._path), self._paint(self.strokeStyle), clamp(self.globalAlpha),
+ self.globalCompositeOperation, width, self.lineCap, self.lineJoin), width)
+
+ def fillRect(self, x, y, w, h):
+ saved = (self._path, self._start, self._current)
+ self.beginPath()
+ self.rect(x, y, w, h)
+ self.fill()
+ self._path, self._start, self._current = saved
+
+ @staticmethod
+ def _paint(style):
+ return style if isinstance(style, Gradient) else parse_colour(style)
+
+ def _record(self, op, width):
+ if op[3] <= 0.0:
+ return
+ paint = op[2]
+ if not isinstance(paint, Gradient) and paint[3] <= 0.0:
+ return
+ xs, ys = [], []
+ for segment in op[1]:
+ xs.extend(segment[1::2])
+ ys.extend(segment[2::2])
+ if not xs:
+ return
+ pad = width / 2.0 + (width * 5.0 if op[0] == "stroke" and op[7] == "miter" else 0.0) + 2.0
+ box = (min(xs) - pad, min(ys) - pad, max(xs) + pad, max(ys) + pad)
+ if self.bounds is None:
+ self.bounds = box
+ else:
+ b = self.bounds
+ self.bounds = (min(b[0], box[0]), min(b[1], box[1]), max(b[2], box[2]), max(b[3], box[3]))
+ self.ops.append(op)
+
+
+def round_rect(pen, x, y, w, h, r):
+ """The harness's BeamerDraw.roundRect: a new path, not a fill."""
+ pen.beginPath()
+ pen.moveTo(x + r, y)
+ _arc_to(pen, x + w, y, x + w, y + h, r)
+ _arc_to(pen, x + w, y + h, x, y + h, r)
+ _arc_to(pen, x, y + h, x, y, r)
+ _arc_to(pen, x, y, x + w, y, r)
+ pen.closePath()
+
+
+def _arc_to(pen, x1, y1, x2, y2, r):
+ """canvas arcTo from the pen's current point, in user space. Only round_rect uses it, whose
+ corners are always right angles, so the tangent points are r along each side."""
+ m = pen._matrix
+ inverse = _invert(m)
+ x0, y0 = _apply(inverse, *pen._current)
+ d1 = math.hypot(x1 - x0, y1 - y0) or 1.0
+ d2 = math.hypot(x2 - x1, y2 - y1) or 1.0
+ ax, ay = x1 - (x1 - x0) / d1 * r, y1 - (y1 - y0) / d1 * r
+ bx, by = x1 + (x2 - x1) / d2 * r, y1 + (y2 - y1) / d2 * r
+ pen.lineTo(ax, ay)
+ k = 0.5522847498
+ pen.bezierCurveTo(ax + (x1 - ax) * k, ay + (y1 - ay) * k, bx + (x1 - bx) * k, by + (y1 - by) * k, bx, by)
+
+
+def _invert(m):
+ a, b, c, d, e, f = m
+ det = a * d - b * c or 1.0
+ return (d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det)
+
+
+def point(x, y):
+ return SimpleNamespace(x=float(x), y=float(y))
+
+
+def state(screen_w, screen_h, os_name, method, palette, *, reduced=False, dark=True, notch=None, **fields):
+ """The `s` an effect reads, with the harness's field names. Departure passes region, point,
+ along (the fraction along the edge), pressure, tick (the last quarter tick, or None) and since
+ (seconds since breakthrough); arrival passes point, edge and since (seconds since landing)."""
+ s = SimpleNamespace(
+ screen=SimpleNamespace(w=float(screen_w), h=float(screen_h), os=os_name),
+ method=method, palette=list(palette), reduced=bool(reduced), scale=1.0, dark=bool(dark),
+ hash=hash_n, memo={},
+ )
+ if notch is not None:
+ s.notch = SimpleNamespace(**notch)
+ for key, value in fields.items():
+ setattr(s, key, value)
+ return s
+
+
+def nearest_edge(x, y, w, h):
+ """The screen edge closest to (x, y). A switch arrival is oriented by it: every effect reads
+ `s.edge`, and the ones that would draw at the edge itself look for method "switch" instead."""
+ return min((("left", x), ("right", w - x), ("top", y), ("bottom", h - y)), key=lambda pair: pair[1])[0]
+
+
+def display_for(at, displays):
+ """The display in `displays`, each (x, y, w, h), that holds the point `at`, else the nearest,
+ and `at` moved onto it: a point on no display is where the OS puts the pointer, on the nearest."""
+ x, y = at
+
+ def gap(rect):
+ rx, ry, rw, rh = rect
+ return math.hypot(max(rx - x, 0.0, x - (rx + rw - 1.0)), max(ry - y, 0.0, y - (ry + rh - 1.0)))
+
+ rx, ry, rw, rh = (float(v) for v in min(displays, key=gap))
+ return (rx, ry, rw, rh), (min(max(float(x), rx), rx + rw - 1.0), min(max(float(y), ry), ry + rh - 1.0))
+
+
+class Effect:
+ def __init__(self, id, name, intensity, blurb, depart, arrive, depart_seconds, arrive_seconds):
+ self.id = id
+ self.name = name
+ self.intensity = intensity
+ self.blurb = blurb
+ self.depart = depart
+ self.arrive = arrive
+ self.depart_seconds = min(0.8, float(depart_seconds))
+ self.arrive_seconds = min(0.8, float(arrive_seconds))
+
+
+# Every direction built, in the order the Design pages list them: each direction's quiet, medium
+# and showpiece effect, and its three colour packs. Ids are the settings values, so never rename one.
+ALL_DIRECTIONS = (
+ ("fx_membrane", "Membrane", ("skin", "film", "rupture"), ("oil_slick", "soap_bubble", "pearl")),
+ ("fx_sparks", "Sparks", ("flint", "filings", "discharge"), ("ember", "forge", "sparkler_gold")),
+ ("fx_instrument", "Instrument", ("rule", "gauge", "rangefinder"), ("phosphor", "sodium", "contrast")),
+ ("fx_ink", "Ink", ("capillary", "viscous_drop", "sumi_bloom"), ("indigo_ink", "matcha", "terracotta")),
+ ("fx_warp", "Warp", ("light_slit", "hyperdrive", "wormhole"), ("neon", "vaporwave", "cyber")),
+)
+# Directions kept in the code but offered nowhere: not on the Design pages, not as a setting. A
+# setting that chose one of their effects or packs becomes its stand-in when it is read, and a
+# switch that played one plays whatever the crossing plays.
+HIDDEN = ("fx_ink", "fx_warp")
+STAND_INS = {"capillary": "glow", "viscous_drop": "glow", "sumi_bloom": "glow",
+ "indigo_ink": "colourful", "matcha": "colourful", "terracotta": "colourful",
+ "light_slit": "beam", "hyperdrive": "glow", "wormhole": "glow",
+ "neon": "colourful", "vaporwave": "colourful", "cyber": "colourful"}
+DIRECTIONS = tuple(direction for direction in ALL_DIRECTIONS if direction[0] not in HIDDEN)
+EFFECT_IDS = tuple(effect for _module, _name, effects, _packs in DIRECTIONS for effect in effects)
+# The effects whose designs draw a pack's colours as given on a light wallpaper; the others shade
+# them for light themselves.
+LIGHT_AS_GIVEN = tuple(effect for module, _name, effects, _packs in ALL_DIRECTIONS if module in ("fx_ink", "fx_warp")
+ for effect in effects)
+PACK_IDS = tuple(pack for _module, _name, _effects, packs in DIRECTIONS for pack in packs)
+
+_loaded = None
+
+
+def _load():
+ """Imports the fx_* modules on first use, hidden ones included; each has EFFECTS (Effect list)
+ and PACKS (dict of id to (name, colours)), in ALL_DIRECTIONS order."""
+ global _loaded
+ if _loaded is None:
+ import importlib
+ effects, packs = {}, {}
+ for module_name, _name, effect_ids, pack_ids in ALL_DIRECTIONS:
+ module = importlib.import_module(module_name)
+ by_id = {effect.id: effect for effect in module.EFFECTS}
+ for effect_id in effect_ids:
+ effects[effect_id] = by_id[effect_id]
+ for pack_id in pack_ids:
+ packs[pack_id] = module.PACKS[pack_id]
+ _loaded = (effects, packs)
+ return _loaded
+
+
+def effect(effect_id):
+ return _load()[0].get(effect_id)
+
+
+def _locator_arrive(pen, s):
+ """Glow and Beam have no arrival, so a switch into this machine shows where the pointer is with
+ one ring in the chosen colours closing onto its tip: 220pt across to 32pt in 0.45s, decelerating,
+ thickening as it closes, then a soft glow at the tip and gone by 0.72s. A dark halo under the
+ colour keeps it legible on a light wallpaper. Reduce motion keeps the size fixed: two still
+ rings fading in and out."""
+ t = s.since
+ x, y = s.point.x, s.point.y
+ colours = s.palette or ["#5fd4f4"]
+ if s.reduced:
+ a = clamp(t / 0.1) * (1.0 - clamp((t - 0.35) / 0.35))
+ rings = ((16.0, 3.0, a), (30.0, 2.0, 0.55 * a))
+ else:
+ # A cubic ease-out: a quintic closed the ring within 0.15s, too fast for the eye to follow in.
+ k = ease_out(clamp(t / 0.45))
+ a = clamp(t / 0.08) * (1.0 - clamp((t - 0.52) / 0.2))
+ rings = ((lerp(110.0, 16.0, k), lerp(2.0, 3.0, k), a),)
+ if t > 0.38:
+ bloom = clamp((t - 0.38) / 0.12) * (1.0 - clamp((t - 0.5) / 0.22))
+ glow = pen.createRadialGradient(x, y, 0.0, x, y, 26.0)
+ r, g, b, _a = parse_colour(colours[0])
+ glow.addColorStop(0.0, (r, g, b, 0.45 * bloom))
+ glow.addColorStop(1.0, (r, g, b, 0.0))
+ pen.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ pen.fillStyle = glow
+ pen.beginPath()
+ pen.arc(x, y, 26.0, 0.0, TAU)
+ pen.fill()
+ pen.globalCompositeOperation = "source-over"
+ pen.lineJoin = "round"
+ for radius, width, alpha in rings:
+ if alpha <= 0.0:
+ continue
+ pen.globalAlpha = alpha
+ pen.beginPath()
+ pen.arc(x, y, radius, 0.0, TAU)
+ pen.strokeStyle = "rgba(0,0,0,0.3)" if s.dark else "rgba(0,0,0,0.5)"
+ pen.lineWidth = width + 3.0
+ pen.stroke()
+ if len(colours) == 1:
+ pen.strokeStyle = colours[0]
+ else:
+ ring = pen.createConicGradient(-math.pi / 2.0, x, y)
+ for index, colour in enumerate(list(colours) + [colours[0]]):
+ ring.addColorStop(index / len(colours), colour)
+ pen.strokeStyle = ring
+ pen.lineWidth = width
+ pen.stroke()
+ pen.globalAlpha = 1.0
+
+
+# What a switch plays when the chosen style is Glow or Beam, which have no arrival of their own.
+LOCATOR = Effect("locator", "Ring", "quiet", "A ring in the chosen colours closes onto the pointer.",
+ lambda pen, s: None, _locator_arrive, 0.0, 0.72)
+
+
+# Glow and Beam as the Design pages' large previews draw them, in the same scene as the effects. On
+# screen each app draws them with its own glow window, which these follow: a band along the edge,
+# deepening with the push and flashing through at breakthrough, or a thin line with a comet running
+# along it that runs off the end; in a corner, the band along both walls, brightest where they meet.
+CLASSIC_BAND = 44.0
+CLASSIC_ARM = 200.0
+CLASSIC_FLASH_S = 0.35
+CLASSIC_FINISH_S = 0.6
+_CLASSIC_COMET = 0.3
+_CLASSIC_STOPS = 24
+_CLASSIC_LAYERS = 10
+
+
+def _palette_at(palette, u):
+ colours = [parse_colour(c) for c in (palette or ["#5fd4f4"])]
+ if len(colours) == 1:
+ return colours[0]
+ at = clamp(u) * (len(colours) - 1)
+ i = min(len(colours) - 2, int(at))
+ a, b = colours[i], colours[i + 1]
+ k = at - i
+ return tuple(lerp(a[n], b[n], k) for n in range(4))
+
+
+def _classic_wall(pen, s, beam, x, y, length, inward, horizontal, strength, depth, alpha_at):
+ """One wall's light: `length` along from (x, y), horizontally or not, falling off over `depth`
+ in the direction `inward` (+1 or -1). One gradient along the wall carries the palette and how lit
+ each point is; canvas has no mask to cut it with a falloff inward, so it is stacked in layers of
+ shrinking depth, which add up to the falloff."""
+ along = pen.createLinearGradient(x, y, x + length, y) if horizontal else pen.createLinearGradient(x, y, x, y + length)
+ for i in range(_CLASSIC_STOPS + 1):
+ u = i / _CLASSIC_STOPS
+ r, g, b, _a = _palette_at(s.palette, u)
+ along.addColorStop(u, (r, g, b, clamp(strength * alpha_at(u))))
+ pen.fillStyle = along
+ # The beam is a thin line with a short glow behind it; the glow a band that falls off evenly.
+ profile = ((0.05, 0.75), (0.16, 0.3), (0.45, 0.12)) if beam else tuple(((k + 1) / _CLASSIC_LAYERS, 1.0 / _CLASSIC_LAYERS)
+ for k in range(_CLASSIC_LAYERS))
+ for reach, alpha in profile:
+ d = depth * reach
+ pen.globalAlpha = alpha
+ if horizontal:
+ pen.fillRect(x, y if inward > 0 else y - d, length, d)
+ else:
+ pen.fillRect(x if inward > 0 else x - d, y, d, length)
+ pen.globalAlpha = 1.0
+
+
+def _comet(position, centre, flash):
+ base = max(0.2, min(1.0, flash))
+ reach = max(0.0, 1.0 - abs(position - centre) / (_CLASSIC_COMET / 2.0))
+ return base + (1.0 - base) * reach * reach
+
+
+def _classic_depart(beam):
+ def depart(pen, s):
+ since = getattr(s, "since", None)
+ pressure = 0.0 if since is not None else s.pressure
+ flash = 0.0 if since is None else max(0.0, 1.0 - since / CLASSIC_FLASH_S)
+ finish = 0.0 if since is None else max(0.0, 1.0 - since / CLASSIC_FINISH_S)
+ strength = max(pressure * 0.85, flash, finish if beam else 0.0)
+ if strength <= 0.0:
+ return
+ depth = CLASSIC_BAND if beam else CLASSIC_BAND * (0.35 + 0.65 * max(pressure, flash))
+ # The comet sweeps as the push builds, then runs off the far end after breakthrough.
+ centre = -0.15 + 1.1 * pressure if since is None else 0.95 + (1.0 + _CLASSIC_COMET) * (1.0 - finish)
+ lit = (lambda u: _comet(u, centre, flash)) if beam else (lambda u: 1.0)
+ r = s.region
+ w, h = s.screen.w, s.screen.h
+ pen.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ if r.kind == "corner":
+ vertical, horizontal = getattr(r, "corner", "top_right").split("_")
+ arm = min(CLASSIC_ARM, w, h)
+ right, bottom = horizontal == "right", vertical == "bottom"
+ fade = lambda d: max(0.0, 1.0 - d) ** 1.4
+ # The comet runs in along the top or bottom wall and out along the side.
+ wall_y = h if bottom else 0.0
+ x0 = w - arm if right else 0.0
+ along_h = (lambda u: fade(1.0 - u) * (_comet(0.5 * u, centre, flash) if beam else 1.0)) if right else \
+ (lambda u: fade(u) * (_comet(0.5 * (1.0 - u), centre, flash) if beam else 1.0))
+ _classic_wall(pen, s, beam, x0, wall_y, arm, -1 if bottom else 1, True, strength, depth, along_h)
+ wall_x = w if right else 0.0
+ y0 = h - arm if bottom else 0.0
+ along_v = (lambda u: fade(1.0 - u) * (_comet(1.0 - 0.5 * u, centre, flash) if beam else 1.0)) if bottom else \
+ (lambda u: fade(u) * (_comet(0.5 + 0.5 * u, centre, flash) if beam else 1.0))
+ _classic_wall(pen, s, beam, wall_x, y0, arm, -1 if right else 1, False, strength, depth, along_v)
+ elif r.kind == "notch":
+ # At the notch Glow and Beam do not draw: the Mac's notch style plays there instead.
+ pass
+ elif r.edge in ("left", "right"):
+ x = r.x if r.edge == "left" else r.x + r.w
+ _classic_wall(pen, s, beam, x, r.y, r.h, 1 if r.edge == "left" else -1, False, strength, depth, lit)
+ else:
+ y = r.y if r.edge == "top" else r.y + r.h
+ _classic_wall(pen, s, beam, r.x, y, r.w, 1 if r.edge == "top" else -1, True, strength, depth, lit)
+ pen.globalCompositeOperation = "source-over"
+ return depart
+
+
+CLASSIC = {
+ "glow": Effect("glow", "Glow", "classic", "A band of light that deepens the harder you push.",
+ _classic_depart(False), lambda pen, s: None, CLASSIC_FLASH_S, 0.0),
+ "beam": Effect("beam", "Beam", "classic", "A thin line with a comet of light running along it.",
+ _classic_depart(True), lambda pen, s: None, CLASSIC_FINISH_S, 0.0),
+}
+
+
+def preview_effect(style):
+ """The Effect the Design pages' previews play for `style`: one of the effects, or Glow and Beam
+ as CLASSIC draws them. None for anything else."""
+ return CLASSIC.get(style) or (effect(style) if style in EFFECT_IDS else None)
+
+
+# What a switch into a machine may play, the Design pages' own choice for it: whatever the crossing
+# style plays ("match", which is the ring for Glow and Beam), the ring, or any one effect.
+SWITCH_STYLES = ("match", "locator") + EFFECT_IDS
+
+
+def offered(style, colour, switch):
+ """A saved crossing style, colour and switch style, each hidden one swapped for its stand-in."""
+ hidden = {effect for module, _name, effects, _packs in ALL_DIRECTIONS if module in HIDDEN for effect in effects}
+ return STAND_INS.get(style, style), STAND_INS.get(colour, colour), "match" if switch in hidden else switch
+
+
+def switch_style_groups():
+ """The Design pages' choices for SWITCH_STYLES, as (group title or None, ((value, name), ...)),
+ the effects grouped by direction as the style tiles are. Only the first group when the effects
+ cannot load; the overlay has already said why."""
+ groups = [(None, (("match", "Same as crossing"), ("locator", "Ring")))]
+ try:
+ found = [(title, tuple((effect_id, effect(effect_id).name) for effect_id in effect_ids))
+ for _module, title, effect_ids, _packs in DIRECTIONS]
+ except Exception:
+ return groups
+ return groups + found
+
+
+def switch_effect(choice, crossing_style):
+ """The Effect a switch plays for the `choice` setting beside the crossing's `crossing_style`."""
+ style = crossing_style if choice == "match" else choice
+ return effect(style) if style in EFFECT_IDS else LOCATOR
+
+
+def pack(pack_id):
+ """(name, colours) for a pack id, or None."""
+ return _load()[1].get(pack_id)
+
+
+def draw(effect_obj, kind, s, origin=(0.0, 0.0)):
+ """One frame of `kind` ("depart" or "arrive") into a new Pen, or None when it draws nothing.
+ `origin` shifts everything drawn, for a scene holding more than one screen. A failing effect
+ raises; the caller logs it once and turns the effects off for the run."""
+ limit = effect_obj.depart_seconds if kind == "depart" else effect_obj.arrive_seconds
+ since = getattr(s, "since", None)
+ if since is not None and since > limit + 0.05:
+ return None
+ if kind == "depart" and since is None and s.pressure <= 0.0:
+ return None
+ pen = Pen()
+ if origin != (0.0, 0.0):
+ pen.translate(*origin)
+ (effect_obj.depart if kind == "depart" else effect_obj.arrive)(pen, s)
+ if kind == "depart" and since is None and s.pressure < PUSH_FADE:
+ # Several designs' reduced-motion pushes draw at a floor opacity however light the push, so
+ # the first touch and the drain to nothing each popped by that floor.
+ k = s.pressure / PUSH_FADE
+ pen.ops = [op[:3] + (op[3] * k,) + op[4:] for op in pen.ops]
+ return pen if pen.ops else None
+
+
+# The pressure below which a push fades in and out as a whole.
+PUSH_FADE = 0.1
+
+
+PREVIEW_SCREEN = (800.0, 450.0)
+PREVIEW_GAP = 40.0
+PREVIEW_NOTCH = {"x": 307.5, "y": 0.0, "w": 185.0, "h": 32.0, "r": 10.0}
+PREVIEW_LOOP_S = 4.4
+_P_GLIDE, _P_PUSH, _P_CROSS, _P_REST = 0.4, 0.6, 2.2, 3.4
+
+
+def preview_size(method):
+ """The preview scene's size in its own points: two screens side by side for an edge or a
+ corner, stacked with the PC above for the notch. The Design pages scale it to fit."""
+ w, h = PREVIEW_SCREEN
+ if method == "switch":
+ return (w, h)
+ return (w, h * 2 + PREVIEW_GAP) if method == "notch" else (w * 2 + PREVIEW_GAP, h)
+
+
+def preview_scene(fx, t, method, palette, reduced=False, dark=True, pace=1.0):
+ """The Design pages' loop, identical on both apps: the pointer glides to the Mac's boundary,
+ pushes through with three ticks, lands on the PC, and rests. Returns dict(screens=[(x, y, w,
+ h, os)], notch=(x, y, w, h, r) or None, pointer=(x, y, os) or None, pens=[Pen]) for time `t`
+ seconds; the caller draws the screens, then the pens, then the pointer, then the notch."""
+ t = t % PREVIEW_LOOP_S
+ w, h = PREVIEW_SCREEN
+ if method == "notch":
+ pc_origin, mac_origin = (0.0, 0.0), (0.0, h + PREVIEW_GAP)
+ region = {"kind": "notch", "edge": "top", "x": PREVIEW_NOTCH["x"], "y": 0.0, "w": PREVIEW_NOTCH["w"], "h": 1.0}
+ at, start = (w / 2.0, 0.0), (w / 2.0 - 90.0, 220.0)
+ land, land_edge, inside = (w / 2.0 + 10.0, h - 2.0), "bottom", (w / 2.0 + 40.0, h - 140.0)
+ notch = PREVIEW_NOTCH
+ else:
+ mac_origin, pc_origin = (0.0, 0.0), (w + PREVIEW_GAP, 0.0)
+ if method == "corner":
+ region = {"kind": "corner", "edge": "right", "corner": "top_right", "x": w - 8.0, "y": 0.0, "w": 8.0, "h": 8.0}
+ at, start, land, inside = (w - 1.0, 0.0), (w - 220.0, 160.0), (2.0, 4.0), (200.0, 140.0)
+ else:
+ region = {"kind": "edge", "edge": "right", "x": w - 1.0, "y": 0.0, "w": 1.0, "h": h}
+ at, start, land, inside = (w - 1.0, h * 0.45), (w - 260.0, h * 0.55), (2.0, h * 0.45), (240.0, h * 0.5)
+ land_edge, notch = "left", None
+ scene = {
+ "screens": [mac_origin + (w, h, "mac"), pc_origin + (w, h, "windows")],
+ "notch": None if notch is None else (mac_origin[0] + notch["x"], mac_origin[1], notch["w"], notch["h"], notch["r"]),
+ "pointer": None,
+ "pens": [],
+ }
+ common = dict(reduced=reduced, dark=dark)
+ palette = legible(palette, dark, fx)
+ mac_notch = notch if method == "notch" else None
+ if t < _P_CROSS:
+ if t < _P_GLIDE:
+ u = ease_in_out(t / _P_GLIDE)
+ p = (lerp(start[0], at[0], u), lerp(start[1], at[1], u))
+ else:
+ p = at
+ scene["pointer"] = (mac_origin[0] + p[0], mac_origin[1] + p[1], "mac")
+ if t >= _P_PUSH:
+ u = (t - _P_PUSH) / (_P_CROSS - _P_PUSH)
+ pressure = clamp(0.5 - 0.5 * math.cos(math.pi * u))
+ index = min(3, int(pressure * 4.0))
+ tick = None
+ if index:
+ crossed_at = _P_PUSH + (_P_CROSS - _P_PUSH) * math.acos(1.0 - 2.0 * index / 4.0) / math.pi
+ tick = SimpleNamespace(index=index, age=t - crossed_at)
+ s = state(w, h, "mac", method, palette, notch=mac_notch, region=SimpleNamespace(**region),
+ point=point(*at), along=at[1] / h if region["edge"] == "right" else at[0] / w,
+ pressure=pressure, tick=tick, since=None, **common)
+ pen = draw(fx, "depart", s, mac_origin)
+ if pen is not None:
+ scene["pens"].append(pen)
+ return scene
+ since = (t - _P_CROSS) / pace
+ s = state(w, h, "mac", method, palette, notch=mac_notch, region=SimpleNamespace(**region), point=point(*at),
+ along=0.5, pressure=0.0, tick=None, since=since, **common)
+ pen = draw(fx, "depart", s, mac_origin)
+ if pen is not None:
+ scene["pens"].append(pen)
+ s = state(w, h, "windows", method, palette, point=point(*land), edge=land_edge, since=since, **common)
+ pen = draw(fx, "arrive", s, pc_origin)
+ if pen is not None:
+ scene["pens"].append(pen)
+ u = ease_in_out(clamp((t - _P_CROSS - 0.1) / (_P_REST - _P_CROSS - 0.1)))
+ p = (lerp(land[0], inside[0], u), lerp(land[1], inside[1], u))
+ scene["pointer"] = (pc_origin[0] + p[0], pc_origin[1] + p[1], "windows")
+ return scene
+
+
+# How long a switch arrival waits for a crossing arrival that would replace it. Both come in over
+# the LAN within a few milliseconds of each other.
+SWITCH_SETTLE_S = 0.12
+
+
+SWITCH_LOOP_S = 2.0
+_S_START = 0.35
+
+
+def preview_switch_scene(fx, t, palette, os_name="mac", reduced=False, dark=True, pace=1.0):
+ """The Design pages' loop for what a switch plays, in preview_scene's shape: one screen, the
+ pointer still near its middle, and `fx`'s switch arrival round it every SWITCH_LOOP_S."""
+ t = t % SWITCH_LOOP_S
+ w, h = PREVIEW_SCREEN
+ at = (w * 0.46, h * 0.44)
+ scene = {"screens": [(0.0, 0.0, w, h, os_name)], "notch": None, "pointer": (at[0], at[1], os_name), "pens": []}
+ since = (t - _S_START) / pace
+ if since >= 0.0:
+ s = state(w, h, os_name, "switch", legible(palette, dark, fx), reduced=reduced, dark=dark, point=point(*at),
+ edge=nearest_edge(at[0], at[1], w, h), since=since)
+ pen = draw(fx, "arrive", s)
+ if pen is not None:
+ scene["pens"].append(pen)
+ return scene
+
+
+# The Design pages' Length: how long an effect takes to play through once the pointer crosses, and
+# to land, as a multiple of its own timing. The push itself follows the hand, so it has no pace.
+LENGTHS = (("short", "Short"), ("normal", "Normal"), ("long", "Long"))
+PACES = {"short": 0.75, "normal": 1.0, "long": 1.5}
+
+
+def pace(length):
+ return PACES.get(length, 1.0)
+
+
+class Player:
+ """The timeline of one machine's effects, fed the same events the glow is fed today.
+
+ `push` while pressure builds against a boundary, `cross` when it gives, `arrive` when the
+ pointer lands on this machine by a crossing, `switched` when input arrives any other way, then
+ `frames(now)` returns the Pens to draw, or an empty list once everything has played out. Both a
+ departure (finishing after a cross) and an arrival can be in flight at once. Coordinates are
+ points relative to the desktop's top-left corner.
+
+ Every event may name its `display`, (x, y, w, h) in the same coordinates: the effect then plays
+ on that display alone, as the designs were drawn for one screen, and its Pen is clipped to it.
+ Without one it plays on the whole `screen` given to `frames`."""
+
+ def __init__(self, pace=1.0):
+ self.depart = None
+ self.arrival = None
+ self.crossed_at = None
+ # How long everything after the push takes, as a multiple of each effect's own timing.
+ self.pace = pace
+
+ def push(self, now, method, region, at, pressure, tick_index=None, display=None):
+ """`region` is dict(kind, edge, corner?, x, y, w, h); `at` is (x, y) of the pinned pointer.
+ `tick_index` is the quarter just passed (1 to 3), if one was."""
+ d = self.depart
+ if d is None or d["crossed_at"] is not None:
+ d = self.depart = {"method": method, "tick": None, "crossed_at": None, "display": None}
+ # A push that goes on without naming its display, as a drain between events does, stays
+ # on the one it started on.
+ d.update(region=dict(region), at=at, pressure=clamp(pressure), method=method,
+ display=d["display"] if display is None else display)
+ if tick_index:
+ d["tick"] = (int(tick_index), now)
+
+ def cross(self, now):
+ if self.depart is not None:
+ self.depart.update(crossed_at=now, pressure=0.0)
+
+ def release(self):
+ """The push stopped short: pressure is already draining through `push` calls, so this
+ only forgets a departure that has drained to nothing."""
+ if self.depart is not None and self.depart["crossed_at"] is None and self.depart["pressure"] <= 0.0:
+ self.depart = None
+
+ def arrive(self, now, method, at, edge, display=None):
+ """A crossing landed the pointer here. It replaces a switch arrival still waiting to start."""
+ self.arrival = {"method": method, "at": at, "edge": edge, "started": now, "switch": False, "display": display}
+ self.crossed_at = now
+
+ def crossed_in(self, now):
+ """A crossing landed the pointer here and something else draws it, as Glow and Beam do: a
+ switch arrival gives way to it all the same."""
+ if self.arrival is not None and self.arrival["switch"]:
+ self.arrival = None
+ self.crossed_at = now
+
+ def switched(self, now, at, edge, fx=None, display=None):
+ """Input came here by the shortcut, a menu or a switch rather than a crossing. It starts
+ SWITCH_SETTLE_S later and gives way to a crossing in that time: one machine's crossing can
+ send this machine's own input home over one link while its pointer lands here over the
+ other, and only the crossing should show. `fx` is what it plays when that is not the
+ effect `frames` is given, which the Design pages let differ from the crossing's."""
+ if self.crossed_at is not None and now - self.crossed_at < SWITCH_SETTLE_S:
+ return
+ self.arrival = {"method": "switch", "at": at, "edge": edge, "started": now + SWITCH_SETTLE_S, "switch": True,
+ "fx": fx, "display": display}
+
+ def frames(self, now, fx, screen, palette, reduced, dark, notch=None):
+ """Pens for this frame. `screen` is (w, h, os name); `notch` the Mac's dict(x, y, w, h, r)."""
+ pens = []
+ w, h, os_name = screen
+ d = self.depart
+ if d is not None:
+ since = None if d["crossed_at"] is None else (now - d["crossed_at"]) / self.pace
+ if since is not None and since > fx.depart_seconds + 0.05:
+ self.depart = None
+ elif since is not None or d["pressure"] > 0.0:
+ frame, local_notch = _frame(d.get("display"), w, h, notch)
+ ox, oy, fw, fh = frame
+ region = _region_on(d["region"], frame)
+ x, y = d["at"][0] - ox, d["at"][1] - oy
+ along = clamp(y / fh if region["edge"] in ("left", "right") else x / fw)
+ # A tick is the push's: the designs' own departures play with none, and one carried
+ # past the crossing flashed a quarter mark into Rule's shutter.
+ tick = None
+ if d["tick"] is not None and since is None:
+ tick = SimpleNamespace(index=d["tick"][0], age=now - d["tick"][1])
+ s = state(fw, fh, os_name, d["method"], legible(palette, dark, fx), reduced=reduced, dark=dark,
+ notch=local_notch, region=SimpleNamespace(**region), point=point(x, y), along=along,
+ pressure=d["pressure"], tick=tick, since=since)
+ pen = _clipped(draw(fx, "depart", s, (ox, oy)), frame)
+ if pen is not None:
+ pens.append(pen)
+ a = self.arrival
+ if a is not None:
+ since = (now - a["started"]) / self.pace
+ arrival_fx = a.get("fx") or fx
+ if since > arrival_fx.arrive_seconds + 0.05:
+ self.arrival = None
+ elif since >= 0.0:
+ frame, local_notch = _frame(a.get("display"), w, h, notch)
+ ox, oy, fw, fh = frame
+ # A switch lands wherever the pointer was, often below the notch but nowhere near it,
+ # and effects that see a notch above the pointer draw round the notch.
+ s = state(fw, fh, os_name, a["method"], legible(palette, dark, arrival_fx), reduced=reduced,
+ dark=dark, notch=None if a["switch"] else local_notch,
+ point=point(a["at"][0] - ox, a["at"][1] - oy), edge=a["edge"], since=since)
+ pen = _clipped(draw(arrival_fx, "arrive", s, (ox, oy)), frame)
+ if pen is not None:
+ pens.append(pen)
+ return pens
+
+ @property
+ def busy(self):
+ return self.depart is not None or self.arrival is not None
+
+
+def _frame(display, w, h, notch):
+ """The (x, y, w, h) an effect plays in, and the notch in that frame's own coordinates, or None
+ when the notch is not on it."""
+ if display is None:
+ return (0.0, 0.0, float(w), float(h)), notch
+ x, y, dw, dh = (float(v) for v in display)
+ if notch is not None and x <= notch["x"] and notch["x"] + notch["w"] <= x + dw and y <= notch["y"] < y + dh:
+ notch = dict(notch, x=notch["x"] - x, y=notch["y"] - y)
+ else:
+ notch = None
+ return (x, y, dw, dh), notch
+
+
+def _region_on(region, frame):
+ """`region` in `frame`'s coordinates and cut to it: an edge strip measured along the whole
+ desktop runs past a shorter display, and an effect drawing along its strip would draw there."""
+ x, y, w, h = frame
+ left, top = max(region["x"] - x, 0.0), max(region["y"] - y, 0.0)
+ right, bottom = min(region["x"] - x + region["w"], w), min(region["y"] - y + region["h"], h)
+ return dict(region, x=left, y=top, w=max(right - left, 1.0), h=max(bottom - top, 1.0))
+
+
+def _clipped(pen, frame):
+ """`pen` clipped to `frame`, its bounds cut to match, or None when nothing is left inside."""
+ if pen is None or pen.bounds is None:
+ return pen
+ x, y, w, h = frame
+ b = pen.bounds
+ box = (max(b[0], x), max(b[1], y), min(b[2], x + w), min(b[3], y + h))
+ if box[2] <= box[0] or box[3] <= box[1]:
+ return None
+ pen.bounds = box
+ pen.clip = (x, y, x + w, y + h)
+ return pen
diff --git a/mac_app/effects_overlay.py b/mac_app/effects_overlay.py
new file mode 100644
index 0000000..fbdbaf7
--- /dev/null
+++ b/mac_app/effects_overlay.py
@@ -0,0 +1,621 @@
+"""The crossing effects on the Mac: effects.py's recorded Pens replayed into Core Graphics, over the
+desktop while a crossing plays and in the Design page's previews.
+
+`replay` is the whole port of the Pen to Quartz, and takes the Quartz module as an argument so the
+tests can hand it a recording fake. `EffectsOverlay` owns one effects.Player, fed the same events
+today's glow is fed, and shows its frames in click-through panels at 60Hz only while something is
+playing. It keeps one panel per display the frame touches, because a window spanning two displays
+shows on only one of them while displays have separate Spaces, which is macOS's default.
+
+Main thread only. Any failure logs once with the effect's id and turns the effects off for the run;
+the app then falls back to today's glow, which never depended on this.
+"""
+
+import math
+import time
+
+import AppKit
+import Quartz
+import objc
+import rumps
+
+import crossing
+import desktop_mac
+import effects
+import notch_beam
+import notch_island
+
+# Canvas's line caps and joins, as Core Graphics names them.
+_CAPS = {"butt": "kCGLineCapButt", "round": "kCGLineCapRound", "square": "kCGLineCapSquare"}
+_JOINS = {"miter": "kCGLineJoinMiter", "round": "kCGLineJoinRound", "bevel": "kCGLineJoinBevel"}
+CONIC_WEDGES = 72
+NOTCH_RADIUS = 10.0
+
+
+def replay(cg, ctx, pens):
+ """Draws `pens` into `ctx` in their own coordinates, each inside its display when it names one.
+ Each op runs inside its own saved graphics state, so its alpha, blend mode and clip end with
+ it. At most one CGGradient is built per Gradient per call."""
+ space = cg.CGColorSpaceCreateWithName(cg.kCGColorSpaceSRGB)
+ gradients = {}
+ for pen in pens:
+ clip = getattr(pen, "clip", None)
+ if clip is not None:
+ cg.CGContextSaveGState(ctx)
+ cg.CGContextClipToRect(ctx, ((clip[0], clip[1]), (clip[2] - clip[0], clip[3] - clip[1])))
+ try:
+ for op in pen.ops:
+ _replay_op(cg, ctx, op, space, gradients)
+ finally:
+ if clip is not None:
+ cg.CGContextRestoreGState(ctx)
+
+
+def _replay_op(cg, ctx, op, space, gradients):
+ kind, path, paint, alpha, composite = op[:5]
+ cg.CGContextSaveGState(ctx)
+ try:
+ cg.CGContextSetAlpha(ctx, alpha)
+ cg.CGContextSetBlendMode(ctx, cg.kCGBlendModePlusLighter if composite == "lighter" else cg.kCGBlendModeNormal)
+ _add_path(cg, ctx, path)
+ gradient = isinstance(paint, effects.Gradient)
+ if kind == "stroke":
+ width, cap, join = op[5:8]
+ cg.CGContextSetLineWidth(ctx, width)
+ cg.CGContextSetLineCap(ctx, getattr(cg, _CAPS.get(cap, "kCGLineCapButt")))
+ cg.CGContextSetLineJoin(ctx, getattr(cg, _JOINS.get(join, "kCGLineJoinMiter")))
+ if gradient:
+ cg.CGContextReplacePathWithStrokedPath(ctx)
+ cg.CGContextClip(ctx)
+ _draw_gradient(cg, ctx, paint, space, gradients)
+ else:
+ cg.CGContextSetRGBStrokeColor(ctx, *paint)
+ cg.CGContextStrokePath(ctx)
+ else:
+ evenodd = op[5] == "evenodd"
+ if gradient:
+ (cg.CGContextEOClip if evenodd else cg.CGContextClip)(ctx)
+ _draw_gradient(cg, ctx, paint, space, gradients)
+ else:
+ cg.CGContextSetRGBFillColor(ctx, *paint)
+ (cg.CGContextEOFillPath if evenodd else cg.CGContextFillPath)(ctx)
+ finally:
+ cg.CGContextRestoreGState(ctx)
+
+
+def _add_path(cg, ctx, path):
+ cg.CGContextBeginPath(ctx)
+ for segment in path:
+ verb = segment[0]
+ if verb == "M":
+ cg.CGContextMoveToPoint(ctx, segment[1], segment[2])
+ elif verb == "L":
+ cg.CGContextAddLineToPoint(ctx, segment[1], segment[2])
+ elif verb == "Q":
+ cg.CGContextAddQuadCurveToPoint(ctx, *segment[1:5])
+ elif verb == "C":
+ cg.CGContextAddCurveToPoint(ctx, *segment[1:7])
+ elif verb == "Z":
+ cg.CGContextClosePath(ctx)
+
+
+def _stops(paint):
+ """Canvas sorts stops by offset, keeping insertion order among equals; one stop is a flat
+ colour, which CGGradient needs as two."""
+ stops = sorted(paint.stops, key=lambda stop: stop[0])
+ if len(stops) == 1:
+ stops = [(0.0, stops[0][1]), (1.0, stops[0][1])]
+ return stops
+
+
+def _draw_gradient(cg, ctx, paint, space, gradients):
+ stops = _stops(paint)
+ if not stops:
+ return
+ held = gradients.get(id(paint))
+ if held is None:
+ components = [value for _offset, rgba in stops for value in rgba]
+ held = gradients[id(paint)] = (
+ paint,
+ cg.CGGradientCreateWithColorComponents(space, components, [offset for offset, _rgba in stops], len(stops)),
+ )
+ made = held[1]
+ extend = cg.kCGGradientDrawsBeforeStartLocation | cg.kCGGradientDrawsAfterEndLocation
+ g = paint.geometry
+ if paint.kind == "linear":
+ cg.CGContextDrawLinearGradient(ctx, made, (g[0], g[1]), (g[2], g[3]), extend)
+ elif paint.kind == "radial":
+ cg.CGContextDrawRadialGradient(ctx, made, (g[0], g[1]), g[2], (g[3], g[4]), g[5], extend)
+ elif hasattr(cg, "CGContextDrawConicGradient"):
+ # In a flipped context this starts at the angle and turns clockwise on screen, as canvas does.
+ cg.CGContextDrawConicGradient(ctx, made, (g[1], g[2]), g[0])
+ else:
+ _conic_wedges(cg, ctx, g, stops)
+
+
+def _colour_at(stops, offset):
+ if offset <= stops[0][0]:
+ return stops[0][1]
+ for (o0, c0), (o1, c1) in zip(stops, stops[1:]):
+ if offset <= o1:
+ u = 0.0 if o1 <= o0 else (offset - o0) / (o1 - o0)
+ return tuple(a + (b - a) * u for a, b in zip(c0, c1))
+ return stops[-1][1]
+
+
+def _conic_wedges(cg, ctx, geometry, stops):
+ """A conic gradient on a macOS without CGContextDrawConicGradient: filled wedges out to the
+ clip's farthest corner, each the colour at its middle."""
+ start, cx, cy = geometry
+ box = cg.CGContextGetClipBoundingBox(ctx)
+ (x, y), (w, h) = box
+ reach = max(math.hypot(px - cx, py - cy) for px in (x, x + w) for py in (y, y + h)) + 2.0
+ step = effects.TAU / CONIC_WEDGES
+ # The wedges overlap so no seam shows, and are copied, not blended, inside a layer that takes
+ # the op's alpha and blend mode as a whole: blended, every overlap doubles a translucent colour
+ # into a spoke.
+ cg.CGContextBeginTransparencyLayer(ctx, None)
+ cg.CGContextSetAlpha(ctx, 1.0)
+ cg.CGContextSetBlendMode(ctx, cg.kCGBlendModeCopy)
+ for index in range(CONIC_WEDGES):
+ a0 = start + index * step
+ a1 = a0 + step * 1.02
+ cg.CGContextSetRGBFillColor(ctx, *_colour_at(stops, (index + 0.5) / CONIC_WEDGES))
+ cg.CGContextBeginPath(ctx)
+ cg.CGContextMoveToPoint(ctx, cx, cy)
+ cg.CGContextAddLineToPoint(ctx, cx + reach * math.cos(a0), cy + reach * math.sin(a0))
+ cg.CGContextAddLineToPoint(ctx, cx + reach * math.cos(a1), cy + reach * math.sin(a1))
+ cg.CGContextClosePath(ctx)
+ cg.CGContextFillPath(ctx)
+ cg.CGContextEndTransparencyLayer(ctx)
+
+
+def palette(name):
+ """The colours of a glow_colour setting, today's palettes and the effects' packs alike."""
+ return notch_beam.palette_values(name)
+
+
+def style_is_effect(style):
+ return style in effects.EFFECT_IDS
+
+
+def reduce_motion():
+ try:
+ return bool(AppKit.NSWorkspace.sharedWorkspace().accessibilityDisplayShouldReduceMotion())
+ except Exception:
+ return False
+
+
+dark_appearance = notch_beam.dark_appearance
+
+
+def corner_name(region, box):
+ """Which corner of the desktop a corner region's box sits in, as crossing.CORNERS names them."""
+ x, y, w, h = region
+ left, top, right, bottom = box
+ vertical = "top" if y - top <= bottom - (y + h) else "bottom"
+ horizontal = "left" if x - left <= right - (x + w) else "right"
+ return f"{vertical}_{horizontal}"
+
+
+def region_of(via, mac_edge, region, box):
+ """effects.Player's region dict for an engine strip, relative to the desktop's top-left."""
+ x, y, w, h = region
+ found = {"kind": via or "edge", "edge": mac_edge, "x": x - box[0], "y": y - box[1], "w": w, "h": h}
+ if via == "corner":
+ found["corner"] = corner_name(region, box)
+ return found
+
+
+# The screens in a preview, drawn the way the settings window draws everything else.
+_SCREEN_DARK = ("#2a2b26", "#161714")
+_SCREEN_LIGHT = ("#d9d8cf", "#b9b8ae")
+
+
+def _rgb(hex_value, alpha=1.0):
+ value = hex_value.lstrip("#")
+ return tuple(int(value[index:index + 2], 16) / 255.0 for index in (0, 2, 4)) + (alpha,)
+
+
+def draw_scene(cg, ctx, scene, width, height, method, dark, crop=None, pointer=18.0):
+ """One effects.preview_scene frame fitted into `width` x `height`: the screens, the pens, the
+ pointer (`pointer` points tall however far the scene is scaled), then the notch. `crop`
+ (x, y, w, h) shows only that part of the scene."""
+ scene_w, scene_h = effects.preview_size(method) if crop is None else crop[2:]
+ ox, oy = (0.0, 0.0) if crop is None else crop[:2]
+ scale = min(width / scene_w, height / scene_h)
+ cg.CGContextSaveGState(ctx)
+ try:
+ cg.CGContextTranslateCTM(ctx, (width - scene_w * scale) / 2.0, (height - scene_h * scale) / 2.0)
+ cg.CGContextScaleCTM(ctx, scale, scale)
+ cg.CGContextTranslateCTM(ctx, -ox, -oy)
+ cg.CGContextClipToRect(ctx, ((ox, oy), (scene_w, scene_h)))
+ top, bottom = _SCREEN_DARK if dark else _SCREEN_LIGHT
+ space = cg.CGColorSpaceCreateWithName(cg.kCGColorSpaceSRGB)
+ ground = cg.CGGradientCreateWithColorComponents(space, list(_rgb(top) + _rgb(bottom)), [0.0, 1.0], 2)
+ for x, y, w, h, _os in scene["screens"]:
+ cg.CGContextSaveGState(ctx)
+ path = cg.CGPathCreateWithRoundedRect(((x, y), (w, h)), 14.0, 14.0, None)
+ cg.CGContextAddPath(ctx, path)
+ cg.CGContextClip(ctx)
+ cg.CGContextDrawLinearGradient(ctx, ground, (x, y), (x, y + h), 0)
+ cg.CGContextRestoreGState(ctx)
+ replay(cg, ctx, scene["pens"])
+ if scene["pointer"] is not None:
+ _pointer(cg, ctx, scene["pointer"][0], scene["pointer"][1], pointer / scale)
+ if scene["notch"] is not None:
+ x, y, w, h, r = scene["notch"]
+ cg.CGContextSetRGBFillColor(ctx, 0.0, 0.0, 0.0, 1.0)
+ cg.CGContextAddPath(ctx, cg.CGPathCreateWithRoundedRect(((x, y - r), (w, h + r)), r, r, None))
+ cg.CGContextFillPath(ctx)
+ finally:
+ cg.CGContextRestoreGState(ctx)
+
+
+def _pointer(cg, ctx, x, y, size):
+ """The arrow pointer, `size` tall in the scene's own units."""
+ unit = size / 18.0
+ shape = ((0.0, 0.0), (0.0, 1.0), (0.26, 0.76), (0.44, 1.12), (0.56, 1.06), (0.39, 0.7), (0.72, 0.7))
+ cg.CGContextBeginPath(ctx)
+ for index, (px, py) in enumerate(shape):
+ (cg.CGContextMoveToPoint if index == 0 else cg.CGContextAddLineToPoint)(ctx, x + px * size, y + py * size)
+ cg.CGContextClosePath(ctx)
+ cg.CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0)
+ cg.CGContextSetRGBStrokeColor(ctx, 0.0, 0.0, 0.0, 1.0)
+ cg.CGContextSetLineWidth(ctx, 1.2 * unit)
+ cg.CGContextSetLineJoin(ctx, cg.kCGLineJoinRound)
+ cg.CGContextDrawPath(ctx, cg.kCGPathFillStroke)
+
+
+class EffectsCanvas(AppKit.NSView):
+ """A flipped view that draws through a Python callable, `painter(ctx, width, height)`. A failure
+ is logged to `logger` here, where its traceback is, and then reported to `on_error` from the
+ main queue rather than raised inside AppKit's drawing."""
+
+ def isFlipped(self):
+ return True
+
+ def drawRect_(self, _rect):
+ painter = getattr(self, "painter", None)
+ if painter is None:
+ return
+ try:
+ ctx = AppKit.NSGraphicsContext.currentContext().CGContext()
+ bounds = self.bounds()
+ painter(ctx, bounds.size.width, bounds.size.height)
+ except Exception:
+ self.painter = None
+ logger = getattr(self, "logger", None)
+ if logger is not None:
+ logger.exception("drawing a crossing effect failed")
+ on_error = getattr(self, "on_error", None)
+ if on_error is not None:
+ AppKit.NSOperationQueue.mainQueue().addOperationWithBlock_(on_error)
+
+
+class EffectsOverlay:
+ """The chosen effect over the desktop, fed by the app: `departure` with the Mac's own crossing
+ events, `return_push` with the PC-driven return edge's pressure, `arrival` whenever a
+ crossing lands the pointer on this Mac, and `switched` when input arrives any other way.
+ Coordinates in are Quartz global points."""
+
+ FRAME_S = 1 / 60
+ PAD = 2.0
+
+ def __init__(self, controller, logger):
+ self.controller = controller
+ self.logger = logger
+ self.player = effects.Player()
+ self.disabled = False
+ self.fx = None
+ self.palette = None
+ self.reduced = False
+ self.dark = True
+ self.notch = None
+ self.box = None
+ self.displays = []
+ self.pressure_now = None
+ self.panels = {}
+ self.timer = rumps.Timer(self._tick, self.FRAME_S)
+ # Every module up front: a bundle without them (build 329) turns the effects off here, once,
+ # and today's glow draws everything, instead of the first crossing finding out.
+ try:
+ effects._load()
+ except Exception:
+ self._fail()
+
+ def wanted(self, feel):
+ return not self.disabled and bool(feel["glow"]) and style_is_effect(feel["glow_style"])
+
+ def wanted_switch(self, feel):
+ """Whether a switch into this Mac shows where the pointer is: any style, Glow and Beam by
+ the locator, while crossings are animated at all and the switch for it is on."""
+ return not self.disabled and bool(feel["glow"]) and bool(feel.get("shortcut_arrival", True))
+
+ def departure(self, kind, step):
+ """One of the Mac engine's pressure, tick or cross events, as EdgeGlow gets them."""
+ self._guard(self._departure, kind, step)
+
+ def _departure(self, kind, step):
+ if step.region is None or kind not in ("pressure", "tick", "cross"):
+ return
+ now = time.monotonic()
+ self._begin()
+ # The notch as the engine measured it can disagree with the geometry read at the start; an
+ # effect told it is at the notch with no notch to draw against plays it as the top edge.
+ via = step.via or "edge"
+ if via == "notch" and self.notch is None:
+ via = "edge"
+ region = region_of(via, step.mac_edge, step.region, self.box)
+ at = _centre(region) if step.pin is None else (step.pin[0] - self.box[0], step.pin[1] - self.box[1])
+ display, at = self._display(at)
+ if kind == "cross":
+ depart = self.player.depart
+ if depart is None or depart["crossed_at"] is not None:
+ # Crossed on its first event: the push starts and gives at once, where it gave.
+ self.player.push(now, via, region, at, 1.0, display=display)
+ self.player.cross(now)
+ else:
+ tick = min(3, int(step.pressure * 4)) if step.tick else None
+ self.player.push(now, via, region, at, step.pressure, tick, display=display)
+ self.pressure_now = self.controller.crossing_pressure_now
+ self._run()
+
+ def return_push(self, edge, pressure, crossed, cursor, corner=None):
+ """The PC is driving this Mac and pushing at the way home, through `edge` or into `corner`.
+ The receiver reports pressure per movement, not between them, so it drains here at the
+ engine's own rate."""
+ self._guard(self._return_push, edge, pressure, crossed, cursor, corner)
+
+ def _return_push(self, edge, pressure, crossed, cursor, corner=None):
+ now = time.monotonic()
+ self._begin()
+ bounds = display_at(cursor, self.box)
+ if corner is not None:
+ region = dict(region_of("corner", edge, corner_box(corner, bounds), self.box), corner=corner)
+ else:
+ region = region_of("edge", edge, crossing.CrossingEngine._strip(edge, bounds), self.box)
+ via = region["kind"]
+ display, at = self._display((cursor[0] - self.box[0], cursor[1] - self.box[1]))
+ if crossed:
+ depart = self.player.depart
+ if depart is None or depart["crossed_at"] is not None:
+ self.player.push(now, via, region, at, 1.0, display=display)
+ self.player.cross(now)
+ else:
+ self.player.push(now, via, region, at, pressure, display=display)
+ level, since = float(pressure), now
+ self.pressure_now = lambda: max(0.0, level - (time.monotonic() - since) / crossing.DECAY_S)
+ self._run()
+
+ def arrival(self, method, x, y, edge):
+ self._guard(self._arrival, method, x, y, edge)
+
+ def _arrival(self, method, x, y, edge):
+ self._begin()
+ display, at = self._display((x - self.box[0], y - self.box[1]))
+ self.player.arrive(time.monotonic(), method, at, edge, display)
+ self._run()
+
+ def crossed_in(self):
+ """A crossing landed here that today's glow draws, not this overlay: a switch waiting to
+ play gives way to it."""
+ self._guard(lambda: self.player.crossed_in(time.monotonic()))
+
+ def switched(self, x, y):
+ """Input came to this Mac without a crossing and the pointer is at (x, y)."""
+ self._guard(self._switched, x, y)
+
+ def _switched(self, x, y):
+ self._begin()
+ display, at = self._display((x - self.box[0], y - self.box[1]))
+ edge = effects.nearest_edge(at[0] - display[0], at[1] - display[1], display[2], display[3])
+ feel = self.controller.cfg.crossing
+ fx = effects.switch_effect(feel.get("shortcut_arrival_style", "match"), feel["glow_style"])
+ self.player.switched(time.monotonic(), at, edge, fx, display)
+ self._run()
+
+ def _begin(self):
+ """Settles what plays when nothing is playing yet: the effect, its colours, reduced motion,
+ the appearance and the notch are read as an effect starts, never per frame."""
+ if self.player.busy and self.fx is not None:
+ return
+ feel = self.controller.cfg.crossing
+ # Glow and Beam are drawn elsewhere and have no arrival: all this overlay plays for them is
+ # a switch, by the locator.
+ style = feel["glow_style"]
+ self.fx = effects.effect(style) if style_is_effect(style) else effects.LOCATOR
+ if self.fx is None:
+ raise ValueError(f"no crossing effect called {feel['glow_style']!r}")
+ self.palette = palette(feel["glow_colour"])
+ self.player.pace = effects.pace(feel.get("effect_length"))
+ self.reduced = reduce_motion()
+ self.dark = dark_appearance()
+ self.box = tuple(self.controller._current_desktop_bounds())
+ self.displays = [(r.x - self.box[0], r.y - self.box[1], r.width, r.height) for r in desktop_mac.monitors()]
+ self.notch = self._notch()
+
+ def _display(self, at):
+ """The display `at` is on, as (x, y, w, h) relative to the desktop box, and `at` itself kept
+ inside it: a point in the box that no display covers, as an arrival along a staggered
+ edge can be, is where macOS puts the pointer, on the nearest display."""
+ return effects.display_for(at, self.displays or [(0.0, 0.0, self.box[2] - self.box[0], self.box[3] - self.box[1])])
+
+ def _notch(self):
+ geometry = notch_island.notch_geometry()
+ if geometry is None:
+ return None
+ left, right, top, height = geometry
+ primary_height = AppKit.NSScreen.screens()[0].frame().size.height
+ return {"x": left - self.box[0], "y": primary_height - top - self.box[1], "w": right - left, "h": height,
+ "r": NOTCH_RADIUS}
+
+ def _run(self):
+ """Events only move the Player on; the timer draws. Drawing here would put a frame on the
+ main queue for every movement event, and at a 1000Hz mouse the ticks and the thud queue
+ behind them."""
+ if not getattr(self.timer, "is_alive", lambda: False)():
+ self.timer.start()
+
+ def _tick(self, _timer):
+ self._guard(self._draw)
+
+ def _draw(self):
+ now = time.monotonic()
+ depart = self.player.depart
+ if depart is not None and depart["crossed_at"] is None and self.pressure_now is not None:
+ level = self.pressure_now()
+ self.player.push(now, depart["method"], depart["region"], depart["at"], level)
+ if level <= 0.0:
+ self.player.release()
+ pens = []
+ if self.fx is not None:
+ w, h = self.box[2] - self.box[0], self.box[3] - self.box[1]
+ pens = self.player.frames(now, self.fx, (w, h, "mac"), self.palette, self.reduced, self.dark, self.notch)
+ if not pens:
+ self._hide()
+ if not self.player.busy:
+ self.timer.stop()
+ self.fx = None
+ self.pressure_now = None
+ return
+ self._show(pens)
+
+ def _show(self, pens):
+ boxes = [padded(pen, self.PAD) for pen in pens]
+ x0, y0 = min(b[0] for b in boxes), min(b[1] for b in boxes)
+ x1, y1 = max(b[2] for b in boxes), max(b[3] for b in boxes)
+ screens = AppKit.NSScreen.screens()
+ primary_height = screens[0].frame().size.height
+ shown = set()
+ for index, screen in enumerate(screens):
+ frame = screen.frame()
+ # This display in the effect's space: Quartz global, then relative to the desktop box.
+ sx = frame.origin.x - self.box[0]
+ sy = primary_height - (frame.origin.y + frame.size.height) - self.box[1]
+ left, top = max(x0, sx), max(y0, sy)
+ right, bottom = min(x1, sx + frame.size.width), min(y1, sy + frame.size.height)
+ if right - left < 1.0 or bottom - top < 1.0:
+ continue
+ panel, view = self._panel(index)
+ origin = (left, top)
+ panel.setFrame_display_(AppKit.NSMakeRect(
+ left + self.box[0], primary_height - (top + self.box[1]) - (bottom - top), right - left, bottom - top,
+ ), False)
+ view.painter = lambda ctx, _w, _h, origin=origin: self._paint(ctx, pens, origin)
+ view.setNeedsDisplay_(True)
+ if not panel.isVisible():
+ panel.orderFrontRegardless()
+ shown.add(index)
+ for index, (panel, _view) in self.panels.items():
+ if index not in shown and panel.isVisible():
+ panel.orderOut_(None)
+
+ @staticmethod
+ def _paint(ctx, pens, origin):
+ Quartz.CGContextTranslateCTM(ctx, -origin[0], -origin[1])
+ replay(Quartz, ctx, pens)
+
+ def _panel(self, index):
+ found = self.panels.get(index)
+ if found is not None:
+ return found
+ panel = AppKit.NSPanel.alloc().initWithContentRect_styleMask_backing_defer_(
+ AppKit.NSMakeRect(0, 0, 1, 1),
+ AppKit.NSWindowStyleMaskBorderless | AppKit.NSWindowStyleMaskNonactivatingPanel,
+ AppKit.NSBackingStoreBuffered,
+ False,
+ )
+ panel.setLevel_(AppKit.NSStatusWindowLevel)
+ panel.setOpaque_(False)
+ panel.setHasShadow_(False)
+ panel.setBackgroundColor_(AppKit.NSColor.clearColor())
+ panel.setIgnoresMouseEvents_(True)
+ panel.setHidesOnDeactivate_(False)
+ panel.setCollectionBehavior_(
+ AppKit.NSWindowCollectionBehaviorCanJoinAllSpaces
+ | AppKit.NSWindowCollectionBehaviorFullScreenAuxiliary
+ | AppKit.NSWindowCollectionBehaviorIgnoresCycle
+ | AppKit.NSWindowCollectionBehaviorStationary
+ )
+ view = EffectsCanvas.alloc().initWithFrame_(AppKit.NSMakeRect(0, 0, 1, 1))
+ view.logger = self.logger
+ view.on_error = lambda: self._fail(logged=True)
+ panel.setContentView_(view)
+ self.panels[index] = (panel, view)
+ return panel, view
+
+ def _hide(self):
+ for panel, _view in self.panels.values():
+ if panel.isVisible():
+ panel.orderOut_(None)
+
+ def _guard(self, work, *args):
+ if self.disabled:
+ return
+ try:
+ work(*args)
+ except Exception:
+ self._fail()
+
+ def _fail(self, logged=False):
+ if self.disabled:
+ return
+ self.disabled = True
+ effect_id = getattr(self.fx, "id", None) or self.controller.cfg.crossing.get("glow_style")
+ if logged:
+ self.logger.error("crossing effect %r failed; effects off for this run", effect_id)
+ else:
+ self.logger.exception("crossing effect %r failed; effects off for this run", effect_id)
+ self.player = effects.Player()
+ try:
+ self.timer.stop()
+ self._hide()
+ except Exception:
+ pass
+
+
+def _centre(region):
+ return (region["x"] + region["w"] / 2.0, region["y"] + region["h"] / 2.0)
+
+
+def padded(pen, pad):
+ """`pen`'s bounds grown by `pad`, but never past the display it is clipped to, where the pad
+ would open an empty panel on the display beside it."""
+ x0, y0, x1, y1 = pen.bounds[0] - pad, pen.bounds[1] - pad, pen.bounds[2] + pad, pen.bounds[3] + pad
+ clip = getattr(pen, "clip", None)
+ if clip is not None:
+ x0, y0, x1, y1 = max(x0, clip[0]), max(y0, clip[1]), min(x1, clip[2]), min(y1, clip[3])
+ return (x0, y0, x1, y1)
+
+
+def strip_on_display(region, point, box):
+ """A Quartz (x, y, w, h) strip cut to the display holding `point`: the engine measures an edge
+ along the whole desktop, and a band along all of it spans displays one panel cannot show on,
+ and empty space beside a shorter display."""
+ if point is None or box is None:
+ return region
+ left, top, right, bottom = display_at(point, box)
+ x, y, w, h = region
+ x0, y0, x1, y1 = max(x, left), max(y, top), min(x + w, right), min(y + h, bottom)
+ return region if x1 <= x0 or y1 <= y0 else (x0, y0, x1 - x0, y1 - y0)
+
+
+def corner_box(corner, display):
+ """The Quartz (x, y, w, h) box of `corner` of `display` (left, top, right, bottom), as the
+ engine reports a corner push."""
+ left, top, right, bottom = display
+ vertical, horizontal = corner.split("_")
+ size = crossing.CORNER_PX
+ return (left if horizontal == "left" else right - size, top if vertical == "top" else bottom - size, size, size)
+
+
+def display_at(point, box):
+ """(left, top, right, bottom) of the display under `point` in Quartz points, else the desktop
+ box: on displays of different sizes the way home runs along the pointer's own display, not
+ along empty space in the box."""
+ x, y = point
+ for rect in desktop_mac.monitors():
+ if rect.x <= x < rect.x + rect.width and rect.y <= y < rect.y + rect.height:
+ return (rect.x, rect.y, rect.x + rect.width, rect.y + rect.height)
+ return box
diff --git a/mac_app/fx_ink.py b/mac_app/fx_ink.py
new file mode 100644
index 0000000..d0e587f
--- /dev/null
+++ b/mac_app/fx_ink.py
@@ -0,0 +1,958 @@
+"""Ink: liquid moving between vessels. A viscous drop swells, necks and drips through the boundary,
+blooming into fluid wash on arrival.
+"""
+
+import math
+
+import effects
+
+
+def _colour_at(pal, i):
+ """pal[i]; past the pack's length JS reads undefined there, and a colour assignment from
+ undefined is invalid CSS, so canvas leaves fillStyle/strokeStyle at whatever it already was."""
+ return pal[i] if i < len(pal) else None
+
+
+def get_depart_geometry(s):
+ r = s.region
+ bx, by = s.point.x, s.point.y
+ nx = ny = tx = ty = 0.0
+ is_corner = r.kind == "corner"
+ is_notch = r.kind == "notch"
+
+ if is_notch:
+ n = getattr(s, "notch", None)
+ if n is None:
+ from types import SimpleNamespace
+ n = SimpleNamespace(x=771, y=0, w=185, h=32, r=10)
+ bx = effects.clamp(s.point.x, n.x + 24, n.x + n.w - 24)
+ by = n.h # Bottom lip of the hardware notch
+ nx, ny = 0, 1 # Inward into Mac screen space below notch
+ tx, ty = 1, 0 # Along bottom lip
+ elif is_corner:
+ corner = getattr(r, "corner", "top_right")
+ right, top = "right" in corner, "top" in corner
+ bx, by = (s.screen.w if right else 0), (0 if top else s.screen.h)
+ nx, ny = (-0.7071 if right else 0.7071), (0.7071 if top else -0.7071)
+ tx, ty = ny, -nx
+ else:
+ edge = r.edge
+ if edge == "right":
+ bx, by = s.screen.w, s.point.y
+ nx, ny, tx, ty = -1, 0, 0, 1
+ elif edge == "left":
+ bx, by = 0, s.point.y
+ nx, ny, tx, ty = 1, 0, 0, 1
+ elif edge == "top":
+ bx, by = s.point.x, 0
+ nx, ny, tx, ty = 0, 1, 1, 0
+ else: # bottom
+ bx, by = s.point.x, s.screen.h
+ nx, ny, tx, ty = 0, -1, 1, 0
+
+ return bx, by, nx, ny, tx, ty, is_corner, is_notch
+
+
+def get_arrive_geometry(s):
+ if s.edge == "right":
+ nx, ny = -1, 0
+ elif s.edge == "left":
+ nx, ny = 1, 0
+ elif s.edge == "top":
+ nx, ny = 0, 1
+ else:
+ nx, ny = 0, -1
+
+ near_top, near_bottom = s.point.y < 50, s.point.y > s.screen.h - 50
+ is_corner = s.method == "corner" and s.edge in ("left", "right") and (near_top or near_bottom)
+ if is_corner:
+ nx, ny = 0.7071 * nx, 0.7071 if near_top else -0.7071
+ is_notch = s.method == "notch"
+ return nx, ny, is_corner, is_notch
+
+
+def inward_quarter(nx, ny):
+ """The start and end angles of the quarter turn a corner's wedge fills, centred on the corner's
+ inward normal: the design drew the top right corner's, pi/2 to pi, for every corner."""
+ middle = math.atan2(ny, nx)
+ return middle - math.pi / 4, middle + math.pi / 4
+
+
+def tick_ripple(tick):
+ if tick is None:
+ return 0.0
+ return math.sin(tick.age * 28) * math.exp(-tick.age * 7)
+
+
+def draw_halo(ctx, s, alpha):
+ if s.dark:
+ ctx.strokeStyle = "#ffffff"
+ ctx.globalAlpha = 0.28 * alpha
+ else:
+ ctx.strokeStyle = "#000000"
+ ctx.globalAlpha = 0.16 * alpha
+
+
+# ----------------------------------------------------
+# Effect 1: Capillary (Quiet)
+# ----------------------------------------------------
+
+def _capillary_depart(ctx, s):
+ pal = s.palette
+ bx, by, nx, ny, tx, ty, is_corner, _is_notch = get_depart_geometry(s)
+
+ since = getattr(s, "since", None)
+ if since is not None:
+ if since >= 0.45:
+ return
+ t = since / 0.45
+ alpha = max(0.0, 1 - t * 1.5)
+ if alpha <= 0.001:
+ return
+
+ if s.reduced:
+ ctx.globalAlpha = alpha * 0.4
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx + nx * 4, by + ny * 4, 16, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ # Snapped bead moving forward into the boundary
+ bead_dist = t * 16
+ bead_r = max(0.0, 4.5 * (1 - t))
+ if bead_r > 0.5:
+ ctx.globalAlpha = alpha * 0.85
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx - nx * bead_dist, by - ny * bead_dist, bead_r, 0, math.pi * 2)
+ ctx.fill()
+
+ # Meniscus recoil against wall
+ recoil = max(0.0, 1 - t * 2.2)
+ if recoil > 0.01:
+ span = 36 * recoil
+ depth = 8 * recoil
+ ctx.globalAlpha = alpha * 0.5
+ ctx.fillStyle = pal[min(1, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.quadraticCurveTo(bx + nx * depth, by + ny * depth, bx + tx * span, by + ty * span)
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ p = s.pressure
+ if p <= 0.001:
+ return
+
+ if s.reduced:
+ alpha = 0.15 + 0.65 * p
+ if is_corner:
+ ctx.globalAlpha = alpha * 0.4
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.arc(bx, by, 36, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.85
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx, by, 22, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+ else:
+ span = 42
+ depth = 14
+ ctx.globalAlpha = alpha * 0.4
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 4), by - ty * (span + 4))
+ ctx.quadraticCurveTo(bx + nx * (depth + 4), by + ny * (depth + 4), bx + tx * (span + 4), by + ty * (span + 4))
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.85
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.quadraticCurveTo(bx + nx * depth, by + ny * depth, bx + tx * span, by + ty * span)
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ ripple = tick_ripple(getattr(s, "tick", None))
+ vis_p = effects.clamp(p ** 1.2 + ripple * 0.08, 0.0, 1.2)
+ span = 24 + 48 * vis_p
+ depth = 6 + 22 * vis_p
+
+ if is_corner:
+ cr = 8 + 36 * vis_p
+ # Soft outer wash
+ ctx.globalAlpha = 0.3 * p
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr + 6, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ # Main pigment body
+ ctx.globalAlpha = 0.7 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ # Dense inner core
+ ctx.globalAlpha = 0.9 * p
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr * 0.55, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ # Straight edge and notch meniscus
+ draw_halo(ctx, s, p * 0.4)
+ ctx.lineWidth = 1.5 / s.scale
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 4), by - ty * (span + 4))
+ ctx.quadraticCurveTo(bx + nx * (depth + 4), by + ny * (depth + 4), bx + tx * (span + 4), by + ty * (span + 4))
+ ctx.stroke()
+
+ # Layer 1: Outer wash
+ ctx.globalAlpha = 0.3 * p
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 6), by - ty * (span + 6))
+ ctx.quadraticCurveTo(bx + nx * (depth + 5), by + ny * (depth + 5), bx + tx * (span + 6), by + ty * (span + 6))
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 2: Main fluid body with wetting fillets
+ ctx.globalAlpha = 0.7 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.bezierCurveTo(
+ bx - tx * span * 0.5 + nx * depth * 0.4, by - ty * span * 0.5 + ny * depth * 0.4,
+ bx - tx * span * 0.2 + nx * depth, by - ty * span * 0.2 + ny * depth,
+ bx + nx * depth, by + ny * depth,
+ )
+ ctx.bezierCurveTo(
+ bx + tx * span * 0.2 + nx * depth, by + ty * span * 0.2 + ny * depth,
+ bx + tx * span * 0.5 + nx * depth * 0.4, by + ty * span * 0.5 + ny * depth * 0.4,
+ bx + tx * span, by + ty * span,
+ )
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 3: Concentrated core near wall
+ ctx.globalAlpha = 0.9 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span * 0.6), by - ty * (span * 0.6))
+ ctx.quadraticCurveTo(bx + nx * (depth * 0.5), by + ny * (depth * 0.5), bx + tx * (span * 0.6), by + ty * (span * 0.6))
+ ctx.closePath()
+ ctx.fill()
+
+
+def _capillary_arrive(ctx, s):
+ since = getattr(s, "since", None)
+ if since is None or since >= 0.50 or since < 0:
+ return
+ pal = s.palette
+ t = since / 0.50
+ alpha = max(0.0, 1 - t)
+ if alpha <= 0.001:
+ return
+
+ nx, ny, _is_corner, _is_notch = get_arrive_geometry(s)
+
+ if s.reduced:
+ a = math.sin(t * math.pi)
+ ctx.globalAlpha = a * 0.4
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.arc(s.point.x, s.point.y, 32, 0, math.pi * 2)
+ ctx.fill()
+
+ ctx.globalAlpha = a * 0.8
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(s.point.x, s.point.y, 18, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ u = effects.ease_out(t)
+ radius = 10 + 44 * u
+ cx = s.point.x + nx * (8 * u)
+ cy = s.point.y + ny * (8 * u)
+
+ # Halo for dark background contrast
+ draw_halo(ctx, s, alpha * 0.6)
+ ctx.lineWidth = 1.5 / s.scale
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius + 2, 0, math.pi * 2)
+ ctx.stroke()
+
+ # Outer soft wash
+ ctx.globalAlpha = alpha * 0.3
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius, 0, math.pi * 2)
+ ctx.fill()
+
+ # Mid pigment bleed
+ ctx.globalAlpha = alpha * 0.6
+ ctx.fillStyle = pal[min(1, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius * 0.62, 0, math.pi * 2)
+ ctx.fill()
+
+ # Dense landing core
+ ctx.globalAlpha = alpha * 0.9
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius * 0.28, 0, math.pi * 2)
+ ctx.fill()
+
+ # Subtle capillary perimeter rim
+ ctx.globalAlpha = alpha * 0.45
+ ctx.strokeStyle = pal[0]
+ ctx.lineWidth = 1 / s.scale
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius, 0, math.pi * 2)
+ ctx.stroke()
+
+
+# ----------------------------------------------------
+# Effect 2: Viscous Drop (Medium)
+# ----------------------------------------------------
+
+def _viscous_drop_depart(ctx, s):
+ pal = s.palette
+ bx, by, nx, ny, tx, ty, is_corner, _is_notch = get_depart_geometry(s)
+
+ since = getattr(s, "since", None)
+ if since is not None:
+ if since >= 0.55:
+ return
+ t = since / 0.55
+ alpha = max(0.0, 1 - t * 1.3)
+ if alpha <= 0.001:
+ return
+
+ if s.reduced:
+ ctx.globalAlpha = alpha * 0.5
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx + nx * 6, by + ny * 6, 22, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ # Detached droplet travelling across boundary
+ drop_dist = t * 24
+ drop_r = max(0.0, 6 * (1 - t * 0.8))
+ if drop_r > 0.5:
+ ctx.globalAlpha = alpha * 0.9
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx - nx * drop_dist, by - ny * drop_dist, drop_r, 0, math.pi * 2)
+ ctx.fill()
+
+ # Secondary satellite droplet (capillary pinch-off)
+ sat_dist = t * 12
+ sat_r = max(0.0, 2.2 * (1 - t))
+ if sat_r > 0.5:
+ ctx.globalAlpha = alpha * 0.7
+ ctx.beginPath()
+ ctx.arc(bx - nx * sat_dist, by - ny * sat_dist, sat_r, 0, math.pi * 2)
+ ctx.fill()
+
+ # Snapped meniscus recoiling and rippling
+ recoil = max(0.0, 1 - t * 1.8) * math.cos(t * 12)
+ if abs(recoil) > 0.01:
+ span = 42 * (1 - t)
+ depth = 12 * recoil
+ ctx.globalAlpha = alpha * 0.55
+ ctx.fillStyle = pal[min(1, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.quadraticCurveTo(bx + nx * depth, by + ny * depth, bx + tx * span, by + ty * span)
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ p = s.pressure
+ if p <= 0.001:
+ return
+
+ if s.reduced:
+ alpha = 0.15 + 0.75 * p
+ if is_corner:
+ ctx.globalAlpha = alpha * 0.4
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.arc(bx, by, 44, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.9
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx, by, 26, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+ else:
+ span = 52
+ depth = 18
+ ctx.globalAlpha = alpha * 0.4
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 4), by - ty * (span + 4))
+ ctx.quadraticCurveTo(bx + nx * (depth + 4), by + ny * (depth + 4), bx + tx * (span + 4), by + ty * (span + 4))
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.9
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.quadraticCurveTo(bx + nx * depth, by + ny * depth, bx + tx * span, by + ty * span)
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ ripple = tick_ripple(getattr(s, "tick", None))
+ vis_p = effects.clamp(p ** 1.25 + ripple * 0.12, 0.0, 1.3)
+ span = 28 + 44 * vis_p
+ depth = 8 + 32 * vis_p
+ neck_w = span * (1 - vis_p * 0.38)
+
+ if is_corner:
+ cr = 10 + 44 * vis_p
+ ctx.globalAlpha = 0.3 * p
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr + 8, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = 0.75 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ # Bulging droplet apex in corner
+ hx, hy = bx + nx * (cr * 0.75), by + ny * (cr * 0.75)
+ ctx.globalAlpha = 0.95 * p
+ ctx.beginPath()
+ ctx.arc(hx, hy, 10 + 12 * vis_p, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ # Straight edge and notch necked droplet
+ draw_halo(ctx, s, p * 0.45)
+ ctx.lineWidth = 2 / s.scale
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 6), by - ty * (span + 6))
+ ctx.quadraticCurveTo(bx + nx * (depth + 6), by + ny * (depth + 6), bx + tx * (span + 6), by + ty * (span + 6))
+ ctx.stroke()
+
+ # Outer soft wash
+ ctx.globalAlpha = 0.32 * p
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 5), by - ty * (span + 5))
+ ctx.bezierCurveTo(
+ bx - tx * neck_w + nx * (depth * 0.4), by - ty * neck_w + ny * (depth * 0.4),
+ bx - tx * (span * 0.3) + nx * (depth + 4), by - ty * (span * 0.3) + ny * (depth + 4),
+ bx + nx * (depth + 4), by + ny * (depth + 4),
+ )
+ ctx.bezierCurveTo(
+ bx + tx * (span * 0.3) + nx * (depth + 4), by + ty * (span * 0.3) + ny * (depth + 4),
+ bx + tx * neck_w + nx * (depth * 0.4), by + ty * neck_w + ny * (depth * 0.4),
+ bx + tx * (span + 5), by + ty * (span + 5),
+ )
+ ctx.closePath()
+ ctx.fill()
+
+ # Main viscous droplet with necking
+ ctx.globalAlpha = 0.8 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.bezierCurveTo(
+ bx - tx * neck_w * 0.8 + nx * (depth * 0.3), by - ty * neck_w * 0.8 + ny * (depth * 0.3),
+ bx - tx * (neck_w * 0.4) + nx * (depth * 0.8), by - ty * (neck_w * 0.4) + ny * (depth * 0.8),
+ bx + nx * depth, by + ny * depth,
+ )
+ ctx.bezierCurveTo(
+ bx + tx * (neck_w * 0.4) + nx * (depth * 0.8), by + ty * (neck_w * 0.4) + ny * (depth * 0.8),
+ bx + tx * neck_w * 0.8 + nx * (depth * 0.3), by + ty * neck_w * 0.8 + ny * (depth * 0.3),
+ bx + tx * span, by + ty * span,
+ )
+ ctx.closePath()
+ ctx.fill()
+
+ # Dense concentrated core droplet at apex
+ ctx.globalAlpha = 0.95 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx + nx * (depth * 0.72), by + ny * (depth * 0.72), 6 + 10 * vis_p, 0, math.pi * 2)
+ ctx.fill()
+
+
+def _viscous_drop_arrive(ctx, s):
+ since = getattr(s, "since", None)
+ if since is None or since >= 0.60 or since < 0:
+ return
+ pal = s.palette
+ t = since / 0.60
+ alpha = max(0.0, 1 - t)
+ if alpha <= 0.001:
+ return
+
+ nx, ny, _is_corner, _is_notch = get_arrive_geometry(s)
+
+ if s.reduced:
+ a = math.sin(t * math.pi)
+ cx, cy = s.point.x, s.point.y
+ ctx.globalAlpha = a * 0.42
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ for i in range(0, 37):
+ ang = (i / 36) * math.pi * 2
+ r = 38 * (1 + 0.2 * math.sin(6 * ang))
+ px, py = cx + math.cos(ang) * r, cy + math.sin(ang) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = a * 0.85
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(cx, cy, 20, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ u = effects.ease_out(t)
+ base_r = 12 + 62 * u
+ cx = s.point.x + nx * (12 * u)
+ cy = s.point.y + ny * (12 * u)
+
+ # Organic 6-lobed bloom boundary
+ draw_halo(ctx, s, alpha * 0.65)
+ ctx.lineWidth = 1.5 / s.scale
+ ctx.beginPath()
+ for i in range(0, 41):
+ a = (i / 40) * math.pi * 2
+ r = (base_r + 2) * (1 + 0.25 * math.sin(6 * a + 0.4) + 0.08 * math.cos(3 * a))
+ px, py = cx + math.cos(a) * r, cy + math.sin(a) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.stroke()
+
+ # Layer 1: Outer wash bloom
+ ctx.globalAlpha = alpha * 0.32
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ for i in range(0, 41):
+ a = (i / 40) * math.pi * 2
+ r = base_r * (1 + 0.26 * math.sin(6 * a + 0.4) + 0.08 * math.cos(3 * a))
+ px, py = cx + math.cos(a) * r, cy + math.sin(a) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 2: Mid-tone pigment diffusion
+ ctx.globalAlpha = alpha * 0.62
+ ctx.fillStyle = pal[min(1, len(pal) - 1)]
+ ctx.beginPath()
+ for i in range(0, 33):
+ a = (i / 32) * math.pi * 2
+ r = (base_r * 0.62) * (1 + 0.22 * math.sin(5 * a + 1.2))
+ px, py = cx + math.cos(a) * r, cy + math.sin(a) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 3: Central dense impact droplet
+ ctx.globalAlpha = alpha * 0.92
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(cx, cy, base_r * 0.28, 0, math.pi * 2)
+ ctx.fill()
+
+ # 8 micro-satellite droplets radiating outward
+ num_sats = 8
+ for j in range(num_sats):
+ ang = (j / num_sats) * math.pi * 2 + s.hash(j) * 0.4
+ dist = base_r * 0.7 + 36 * u * s.hash(j + 10)
+ sat_r = max(0.0, (2.8 - 2.2 * u) * s.hash(j + 20))
+ if sat_r > 0.4:
+ ctx.globalAlpha = alpha * 0.75 * (1 - u * 0.6)
+ colour = _colour_at(pal, 0 if j % 2 == 0 else 1)
+ if colour is not None:
+ ctx.fillStyle = colour
+ ctx.beginPath()
+ ctx.arc(cx + math.cos(ang) * dist, cy + math.sin(ang) * dist, sat_r, 0, math.pi * 2)
+ ctx.fill()
+
+
+# ----------------------------------------------------
+# Effect 3: Sumi Bloom (Showpiece)
+# ----------------------------------------------------
+
+def _sumi_bloom_depart(ctx, s):
+ pal = s.palette
+ bx, by, nx, ny, tx, ty, is_corner, _is_notch = get_depart_geometry(s)
+
+ since = getattr(s, "since", None)
+ if since is not None:
+ if since >= 0.70:
+ return
+ t = since / 0.70
+ alpha = max(0.0, 1 - t * 1.25)
+ if alpha <= 0.001:
+ return
+
+ if s.reduced:
+ ctx.globalAlpha = alpha * 0.6
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx + nx * 8, by + ny * 8, 28, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ # Rayleigh-Plateau droplet train breaking into seam
+ num_drops = 4
+ for k in range(num_drops):
+ lead = t * (28 + k * 10)
+ r_drop = max(0.0, (5.5 - k * 1.1) * (1 - t * 0.9))
+ if r_drop > 0.4:
+ ctx.globalAlpha = alpha * (0.92 - k * 0.15)
+ colour = _colour_at(pal, 0 if k % 2 == 0 else 1)
+ if colour is not None:
+ ctx.fillStyle = colour
+ ctx.beginPath()
+ ctx.arc(bx - nx * lead + tx * ((s.hash(k + 30) - 0.5) * 8), by - ny * lead + ty * ((s.hash(k + 30) - 0.5) * 8), r_drop, 0, math.pi * 2)
+ ctx.fill()
+
+ # Parent meniscus recoil & damped oscillation
+ recoil = max(0.0, 1 - t * 1.6) * math.cos(t * 14)
+ if abs(recoil) > 0.01:
+ span = 56 * (1 - t)
+ depth = 16 * recoil
+ ctx.globalAlpha = alpha * 0.65
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.bezierCurveTo(
+ bx - tx * (span * 0.4) + nx * depth, by - ty * (span * 0.4) + ny * depth,
+ bx + tx * (span * 0.4) + nx * depth, by + ty * (span * 0.4) + ny * depth,
+ bx + tx * span, by + ty * span,
+ )
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ p = s.pressure
+ if p <= 0.001:
+ return
+
+ if s.reduced:
+ alpha = 0.2 + 0.8 * p
+ if is_corner:
+ ctx.globalAlpha = alpha * 0.45
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.arc(bx, by, 54, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.95
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx, by, 32, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+ else:
+ span = 64
+ depth = 24
+ ctx.globalAlpha = alpha * 0.45
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 6), by - ty * (span + 6))
+ ctx.quadraticCurveTo(bx + nx * (depth + 6), by + ny * (depth + 6), bx + tx * (span + 6), by + ty * (span + 6))
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.95
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.quadraticCurveTo(bx + nx * depth, by + ny * depth, bx + tx * span, by + ty * span)
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ ripple = tick_ripple(getattr(s, "tick", None))
+ vis_p = effects.clamp(p ** 1.3 + ripple * 0.16, 0.0, 1.35)
+ span = 36 + 54 * vis_p
+ depth = 12 + 42 * vis_p
+ neck_w = span * (1 - vis_p * 0.46)
+
+ if is_corner:
+ cr = 14 + 56 * vis_p
+ ctx.globalAlpha = 0.35 * p
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr + 10, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = 0.8 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ # Fluid bridge head pulling diagonally inward
+ hx, hy = bx + nx * (cr * 0.8), by + ny * (cr * 0.8)
+ ctx.globalAlpha = 0.95 * p
+ ctx.beginPath()
+ ctx.arc(hx, hy, 12 + 16 * vis_p, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ # Straight edge and notch: full fluid bridge with Rayleigh instability ripples
+ draw_halo(ctx, s, p * 0.55)
+ ctx.lineWidth = 2 / s.scale
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 8), by - ty * (span + 8))
+ ctx.quadraticCurveTo(bx + nx * (depth + 8), by + ny * (depth + 8), bx + tx * (span + 8), by + ty * (span + 8))
+ ctx.stroke()
+
+ # Layer 1: Wide pigment seepage
+ ctx.globalAlpha = 0.35 * p
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 8), by - ty * (span + 8))
+ ctx.bezierCurveTo(
+ bx - tx * neck_w + nx * (depth * 0.4), by - ty * neck_w + ny * (depth * 0.4),
+ bx - tx * (span * 0.25) + nx * (depth + 6), by - ty * (span * 0.25) + ny * (depth + 6),
+ bx + nx * (depth + 6), by + ny * (depth + 6),
+ )
+ ctx.bezierCurveTo(
+ bx + tx * (span * 0.25) + nx * (depth + 6), by + ty * (span * 0.25) + ny * (depth + 6),
+ bx + tx * neck_w + nx * (depth * 0.4), by + ty * neck_w + ny * (depth * 0.4),
+ bx + tx * (span + 8), by + ty * (span + 8),
+ )
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 2: Main calligraphic fluid bridge with necking
+ ctx.globalAlpha = 0.82 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.bezierCurveTo(
+ bx - tx * neck_w * 0.85 + nx * (depth * 0.35), by - ty * neck_w * 0.85 + ny * (depth * 0.35),
+ bx - tx * (neck_w * 0.35) + nx * (depth * 0.85), by - ty * (neck_w * 0.35) + ny * (depth * 0.85),
+ bx + nx * depth, by + ny * depth,
+ )
+ ctx.bezierCurveTo(
+ bx + tx * (neck_w * 0.35) + nx * (depth * 0.85), by + ty * (neck_w * 0.35) + ny * (depth * 0.85),
+ bx + tx * neck_w * 0.85 + nx * (depth * 0.35), by + ty * neck_w * 0.85 + ny * (depth * 0.35),
+ bx + tx * span, by + ty * span,
+ )
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 3: Pendent droplet bulb with intense Sumi density
+ ctx.globalAlpha = 0.95 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx + nx * (depth * 0.76), by + ny * (depth * 0.76), 8 + 14 * vis_p, 0, math.pi * 2)
+ ctx.fill()
+
+
+def _sumi_bloom_arrive(ctx, s):
+ since = getattr(s, "since", None)
+ if since is None or since >= 0.75 or since < 0:
+ return
+ pal = s.palette
+ t = since / 0.75
+ alpha = max(0.0, 1 - t)
+ if alpha <= 0.001:
+ return
+
+ nx, ny, _is_corner, _is_notch = get_arrive_geometry(s)
+
+ if s.reduced:
+ a = math.sin(t * math.pi)
+ cx, cy = s.point.x, s.point.y
+ ctx.globalAlpha = a * 0.45
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.arc(cx, cy, 42, 0, math.pi * 2)
+ ctx.fill()
+
+ ctx.globalAlpha = a * 0.75
+ colour = _colour_at(pal, 1)
+ if colour is not None:
+ ctx.fillStyle = colour
+ ctx.beginPath()
+ ctx.arc(cx, cy, 26, 0, math.pi * 2)
+ ctx.fill()
+
+ ctx.globalAlpha = a * 0.95
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(cx, cy, 14, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ u = effects.ease_out(t)
+ base_r = 14 + 76 * u
+ cx = s.point.x + nx * (14 * u)
+ cy = s.point.y + ny * (14 * u)
+
+ # Halo for contrast
+ draw_halo(ctx, s, alpha * 0.75)
+ ctx.lineWidth = 1.5 / s.scale
+ ctx.beginPath()
+ ctx.arc(cx, cy, base_r + 2, 0, math.pi * 2)
+ ctx.stroke()
+
+ # Layer 1: Outermost dilute pigment wash
+ ctx.globalAlpha = alpha * 0.28
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ for i in range(0, 45):
+ a = (i / 44) * math.pi * 2
+ r = base_r * (1 + 0.22 * math.sin(7 * a + 0.5) + 0.1 * math.cos(3 * a))
+ px, py = cx + math.cos(a) * r, cy + math.sin(a) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 2: Mid-tone pigment diffusion
+ ctx.globalAlpha = alpha * 0.55
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ for i in range(0, 37):
+ a = (i / 36) * math.pi * 2
+ r = (base_r * 0.68) * (1 + 0.24 * math.sin(5 * a + 1.1))
+ px, py = cx + math.cos(a) * r, cy + math.sin(a) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 3: Inner dense wash
+ ctx.globalAlpha = alpha * 0.8
+ ctx.fillStyle = pal[min(1, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.arc(cx, cy, base_r * 0.38, 0, math.pi * 2)
+ ctx.fill()
+
+ # Layer 4: Deep Sumi stone core
+ ctx.globalAlpha = alpha * 0.95
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(cx, cy, base_r * 0.18, 0, math.pi * 2)
+ ctx.fill()
+
+ # 16 curling ink-in-water filament tendrils
+ num_filaments = 16
+ ctx.lineWidth = (1.5 - 0.8 * u) / s.scale
+ for m in range(num_filaments):
+ start_ang = (m / num_filaments) * math.pi * 2 + s.hash(m + 50) * 0.3
+ curl_dir = 1 if m % 2 == 0 else -1
+ r1 = base_r * 0.35
+ r2 = base_r * (0.8 + 0.35 * s.hash(m + 70))
+ x1 = cx + math.cos(start_ang) * r1
+ y1 = cy + math.sin(start_ang) * r1
+ mid_ang = start_ang + curl_dir * (0.4 + 0.3 * u)
+ x_mid = cx + math.cos(mid_ang) * (r1 + (r2 - r1) * 0.55)
+ y_mid = cy + math.sin(mid_ang) * (r1 + (r2 - r1) * 0.55)
+ end_ang = mid_ang + curl_dir * 0.25
+ x2 = cx + math.cos(end_ang) * r2
+ y2 = cy + math.sin(end_ang) * r2
+
+ ctx.globalAlpha = alpha * 0.7 * (1 - u * 0.4)
+ colour = _colour_at(pal, m % 3)
+ if colour is not None:
+ ctx.strokeStyle = colour
+ ctx.beginPath()
+ ctx.moveTo(x1, y1)
+ ctx.quadraticCurveTo(x_mid, y_mid, x2, y2)
+ ctx.stroke()
+
+
+EFFECTS = [
+ effects.Effect(
+ "capillary", "Capillary", "quiet",
+ "A soft pigment meniscus swells against the boundary with viscous surface tension. On "
+ "breakthrough, it releases cleanly and diffuses as a calm, translucent wash on the "
+ "arrival screen.",
+ _capillary_depart, _capillary_arrive, 0.45, 0.50,
+ ),
+ effects.Effect(
+ "viscous_drop", "Viscous drop", "medium",
+ "An organic ink droplet gathers at the pointer, flattening against the glass edge before "
+ "necking through the seam. On arrival, it splashes into a multi-lobed pigment bloom that "
+ "bleeds outward.",
+ _viscous_drop_depart, _viscous_drop_arrive, 0.55, 0.60,
+ ),
+ effects.Effect(
+ "sumi_bloom", "Sumi bloom", "showpiece",
+ "Dense calligraphic ink pulls from the boundary into a viscous bridge that necks and "
+ "snaps through the seam. It arrives as an ink-in-water vortex bloom, unfurling delicate "
+ "pigment filaments that dissolve into the screen.",
+ _sumi_bloom_depart, _sumi_bloom_arrive, 0.70, 0.75,
+ ),
+]
+
+PACKS = {
+ "indigo_ink": ("Indigo ink", ["#16243b", "#253d66", "#3f639e", "#6891ce", "#a8c5ed"]),
+ "matcha": ("Matcha", ["#233818", "#3e5c2c", "#638a44", "#92b86e", "#cde6b0"]),
+ "terracotta": ("Terracotta", ["#4d1f16", "#7c3423", "#b35338", "#d97b5d", "#f3b59f"]),
+}
diff --git a/mac_app/fx_instrument.py b/mac_app/fx_instrument.py
new file mode 100644
index 0000000..84bbc5a
--- /dev/null
+++ b/mac_app/fx_instrument.py
@@ -0,0 +1,733 @@
+"""Instrument: crossing is a measurement taken, read off a scale one click at a time, closed by a
+shutter where you left and locked on by the same instrument where you land.
+
+Effects: Rule (quiet), Gauge (medium), Rangefinder (showpiece). Packs: Phosphor, Sodium, Contrast.
+"""
+
+from __future__ import annotations
+
+import math
+from types import SimpleNamespace
+
+from effects import Effect, clamp, lerp
+
+PI = math.pi
+TAU = PI * 2.0
+SQ = math.sqrt(0.5)
+
+
+def roles(s):
+ p = s.palette
+ n = len(p)
+ return SimpleNamespace(lit=p[0], dim=p[1 % n], hot=p[n - 1])
+
+
+# Pen.arc's own one-cubic-Bezier-per-pi/2 tessellation reads as visibly faceted next to the design's
+# native canvas arc at the dial and reticle radii drawn here. Doubling the density (pi/4 a piece)
+# is the best trade-off found by measurement: finer still fixes some states and reopens others
+# elsewhere in the same sweep, so this is the port's fix, not a tuned-away symptom.
+def detent(u, n, slide=0.4):
+ """n equal detents, each move taking the first `slide` of its slot and then holding."""
+ if u <= 0:
+ return 0.0
+ if u >= 1:
+ return 1.0
+ k = math.floor(u * n)
+ f = u * n - k
+ return min(1.0, (k + clamp(f / slide)) / n)
+
+
+def ink(ctx, s, colour, w, alpha, build):
+ if alpha <= 0.003:
+ return
+ ctx.beginPath()
+ build()
+ ctx.lineCap = "butt"
+ ctx.lineJoin = "miter"
+ if s.dark:
+ ctx.globalAlpha = alpha * 0.14
+ ctx.strokeStyle = colour
+ ctx.lineWidth = w + 5
+ ctx.stroke()
+ ctx.globalAlpha = alpha * (0.5 if s.dark else 0.62)
+ ctx.strokeStyle = "#000"
+ ctx.lineWidth = w + 2
+ ctx.stroke()
+ ctx.globalAlpha = alpha
+ ctx.strokeStyle = colour
+ ctx.lineWidth = w
+ ctx.stroke()
+
+
+def fill_with(ctx, colour, alpha, build):
+ if alpha <= 0.003:
+ return
+ ctx.beginPath()
+ build()
+ ctx.globalAlpha = alpha
+ ctx.fillStyle = colour
+ ctx.fill()
+
+
+def tick_to(ctx, ray, d, o1, o2):
+ p = ray.at(d)
+ ctx.moveTo(p.x + p.nx * o1, p.y + p.ny * o1)
+ ctx.lineTo(p.x + p.nx * o2, p.y + p.ny * o2)
+
+
+def rail_to(ctx, ray, d0, d1, o, move=True):
+ n = max(1, math.ceil(abs(d1 - d0) / 3))
+ for i in range(n + 1):
+ p = ray.at(d0 + (d1 - d0) * i / n)
+ x, y = p.x + p.nx * o, p.y + p.ny * o
+ if i == 0 and move:
+ ctx.moveTo(x, y)
+ else:
+ ctx.lineTo(x, y)
+
+
+def band_to(ctx, ray, d0, d1, o1, o2):
+ rail_to(ctx, ray, d0, d1, o1, True)
+ rail_to(ctx, ray, d1, d0, o2, False)
+ ctx.closePath()
+
+
+# The hardware notch as a rail: down its left side, round the bottom, up its right side, and out
+# along the top edge either way, so a scale can hug it and never draw inside the black.
+def notch_track(n):
+ r, v, q, b = n.r, n.h - n.r, PI / 2 * n.r, n.w - 2 * n.r
+ L = 2 * v + 2 * q + b
+
+ def at(t):
+ if t < -1e-6:
+ return SimpleNamespace(x=n.x + t, y=0, nx=0, ny=1)
+ if t < v:
+ return SimpleNamespace(x=n.x, y=max(0, t), nx=-1, ny=0)
+ if t < v + q:
+ a = PI - (t - v) / q * PI / 2
+ c, si = math.cos(a), math.sin(a)
+ return SimpleNamespace(x=n.x + r + r * c, y=v + r * si, nx=c, ny=si)
+ if t < v + q + b:
+ return SimpleNamespace(x=n.x + r + (t - v - q), y=n.h, nx=0, ny=1)
+ if t < v + 2 * q + b:
+ a = PI / 2 - (t - v - q - b) / q * PI / 2
+ c, si = math.cos(a), math.sin(a)
+ return SimpleNamespace(x=n.x + n.w - r + r * c, y=v + r * si, nx=c, ny=si)
+ if t <= L + 1e-6:
+ return SimpleNamespace(x=n.x + n.w, y=max(0, L - t), nx=1, ny=0)
+ return SimpleNamespace(x=n.x + n.w + (t - L), y=0, nx=0, ny=1)
+
+ def t_of(px):
+ lx, rx = n.x + r, n.x + n.w - r
+ if lx <= px <= rx:
+ return v + q + (px - lx)
+ if px < lx:
+ return v + (PI - math.acos(clamp((px - lx) / r, -1, 0))) / (PI / 2) * q
+ return v + q + b + (PI / 2 - math.acos(clamp((px - rx) / r, 0, 1))) / (PI / 2) * q
+
+ return SimpleNamespace(L=L, at=at, tOf=t_of)
+
+
+# Sets up the drawing frame for where the crossing happens and returns rays running outward from
+# the pointer along the boundary. Edge and corner transform the context so local x runs along
+# the edge and local y points into the screen; the notch stays in screen points.
+def frame(ctx, s, depart):
+ W, H, P = s.screen.w, s.screen.h, s.point
+ right = bottom = False
+ if depart:
+ r = s.region
+ kind, edge = r.kind, r.edge
+ if kind == "corner":
+ right = "right" in r.corner
+ bottom = "bottom" in r.corner
+ else:
+ edge, kind = s.edge, "edge"
+ n = getattr(s, "notch", None)
+ if n and edge == "top" and n.x - 2 <= P.x <= n.x + n.w + 2:
+ kind = "notch"
+ else:
+ cx = 0 if P.x < 24 else (1 if P.x > W - 24 else -1)
+ cy = 0 if P.y < 24 else (1 if P.y > H - 24 else -1)
+ if cx >= 0 and cy >= 0:
+ kind = "corner"
+ right, bottom = cx == 1, cy == 1
+ if kind == "notch":
+ tr = notch_track(s.notch)
+ tp = tr.tOf(P.x)
+ c = tr.at(tp)
+ return SimpleNamespace(
+ kind=kind, track=tr, tp=tp, centre=c, tangent=SimpleNamespace(x=-c.ny, y=c.nx),
+ rays=[SimpleNamespace(at=lambda d: tr.at(tp + d), max=tr.L - tp),
+ SimpleNamespace(at=lambda d: tr.at(tp - d), max=tp)],
+ )
+ if kind == "corner":
+ ctx.transform(-1 if right else 1, 0, 0, -1 if bottom else 1, W if right else 0, H if bottom else 0)
+ return SimpleNamespace(
+ kind=kind, centre=SimpleNamespace(x=0, y=0, nx=SQ, ny=SQ), tangent=SimpleNamespace(x=SQ, y=-SQ),
+ rays=[SimpleNamespace(at=lambda d: SimpleNamespace(x=d, y=0, nx=0, ny=1), max=400),
+ SimpleNamespace(at=lambda d: SimpleNamespace(x=0, y=d, nx=1, ny=0), max=400)],
+ )
+ if edge == "right":
+ ctx.transform(0, 1, -1, 0, W, P.y)
+ lo, hi = P.y, H - P.y
+ elif edge == "left":
+ ctx.transform(0, 1, 1, 0, 0, P.y)
+ lo, hi = P.y, H - P.y
+ elif edge == "top":
+ ctx.transform(1, 0, 0, 1, P.x, 0)
+ lo, hi = P.x, W - P.x
+ else:
+ ctx.transform(1, 0, 0, -1, P.x, H)
+ lo, hi = P.x, W - P.x
+ return SimpleNamespace(
+ kind="edge", centre=SimpleNamespace(x=0, y=0, nx=0, ny=1), tangent=SimpleNamespace(x=1, y=0),
+ rays=[SimpleNamespace(at=lambda d: SimpleNamespace(x=d, y=0, nx=0, ny=1), max=hi),
+ SimpleNamespace(at=lambda d: SimpleNamespace(x=-d, y=0, nx=0, ny=1), max=lo)],
+ )
+
+
+def tick_flash(s, span=0.22):
+ return 1 - s.tick.age / span if s.tick is not None and s.tick.age < span else 0
+
+
+def comb(ctx, items):
+ def build():
+ for ray, d, a, b in items:
+ tick_to(ctx, ray, d, a, b)
+ return build
+
+
+def normal_line(ctx, c, o1, o2):
+ def build():
+ ctx.moveTo(c.x + c.nx * o1, c.y + c.ny * o1)
+ ctx.lineTo(c.x + c.nx * o2, c.y + c.ny * o2)
+ return build
+
+
+def rule_depart(ctx, s):
+ C, SP, N = roles(s), 6, 12
+ p, reach, done = s.pressure, SP * N, False
+ if s.since is None:
+ alpha = clamp(p * 3)
+ else:
+ u = s.since / 0.45
+ if u >= 1:
+ return
+ p, done = 1, True
+ if s.reduced:
+ alpha = 1 - detent(u, 4, 0.25)
+ else:
+ reach = SP * N * (1 - detent(u, 4))
+ alpha = 1 - clamp((u - 0.75) / 0.25)
+ if alpha <= 0:
+ return
+ flash, k = tick_flash(s), frame(ctx, s, True)
+ off, on, hot = [], [], []
+ for ray in k.rays:
+ for i in range(1, N + 1):
+ d = i * SP
+ if d > ray.max or d > reach + 0.01:
+ break
+ major = i % 3 == 0
+ length = 10 if major else 5
+ (on if (done or i / N <= p + 1e-6) else off).append((ray, d, 2, 2 + length))
+ if flash and major and i == s.tick.index * 3:
+ hot.append((ray, d, 2, 2 + length + (0 if s.reduced else 7 * flash)))
+ if reach > 0.5:
+ def rails():
+ for ray in k.rays:
+ rail_to(ctx, ray, 0, min(reach, ray.max), 2)
+ ink(ctx, s, C.dim, 1, alpha * 0.45, rails)
+ ink(ctx, s, C.dim, 1.25, alpha * 0.5, comb(ctx, off))
+ ink(ctx, s, C.hot if done else C.lit, 1.25, alpha, comb(ctx, on))
+ ink(ctx, s, C.hot, 1.5, alpha * flash, comb(ctx, hot))
+ ink(ctx, s, C.hot if done else C.lit, 1.5, alpha, normal_line(ctx, k.centre, 2, 17))
+
+
+def rule_arrive(ctx, s):
+ t = s.since
+ if t >= 0.6:
+ return
+ C = roles(s)
+ c = 1 if s.reduced else detent(t / 0.28, 3)
+ locked = t >= 0.26
+ flash = clamp(1 - (t - 0.26) / 0.12) if locked else 0
+ alpha = 1 if t < 0.38 else 1 - (t - 0.38) / 0.22
+ if s.method == "switch":
+ # A switch came in by no edge, so there is no register to mark: only the cross.
+ rule_cross(ctx, s, C, c, locked, flash, alpha)
+ return
+ ctx.save()
+ k = frame(ctx, s, False)
+
+ def ticks():
+ for ray in k.rays:
+ for i in range(1, 5):
+ if i * 6 <= ray.max:
+ tick_to(ctx, ray, i * 6, 2, 10 if i == 4 else 6)
+ ink(ctx, s, C.lit, 1.25, alpha * 0.9, ticks)
+ ink(ctx, s, C.lit, 1.5, alpha, normal_line(ctx, k.centre, 2, 12))
+ if k.kind == "notch":
+ o = lerp(28, 12, c)
+
+ def hug():
+ for ray in k.rays:
+ rail_to(ctx, ray, 0, min(38, ray.max), o)
+ ink(ctx, s, C.lit if locked else C.dim, 1.25, alpha, hug)
+ ink(ctx, s, C.hot, 2, alpha * flash, hug)
+ ink(ctx, s, C.hot, 1.5, alpha, lambda: tick_to(ctx, k.rays[0], 0, o, o + 10))
+ ctx.restore()
+ return
+ ctx.restore()
+ rule_cross(ctx, s, C, c, locked, flash, alpha)
+
+
+def rule_cross(ctx, s, C, c, locked, flash, alpha):
+ r, P = lerp(40, 22, c), s.point
+
+ def arms():
+ for a in range(4):
+ dx, dy = math.cos(a * PI / 2), math.sin(a * PI / 2)
+ ctx.moveTo(P.x + dx * r, P.y + dy * r)
+ ctx.lineTo(P.x + dx * (r + 9), P.y + dy * (r + 9))
+ ink(ctx, s, C.lit if locked else C.dim, 1.5, alpha, arms)
+ ink(ctx, s, C.hot, 2, alpha * flash, arms)
+
+
+def gauge_notch(ctx, s, k, C):
+ tr, J = k.track, 32
+ L = tr.L
+ ray = SimpleNamespace(at=tr.at)
+ if s.since is None:
+ p = s.pressure
+ alpha = clamp(p * 3)
+ q = detent(p, 16, 0.5)
+ lit_to = (math.floor(p * 16 + 1e-6) / 16) if s.reduced else q
+ flash = tick_flash(s)
+ off, on, hot = [], [], []
+ for j in range(J + 1):
+ major = j % 8 == 0
+ length = 10 if major else 5
+ (on if j / J <= lit_to + 1e-6 else off).append((ray, j * L / J, 4, 4 + length))
+ if flash and j == s.tick.index * 8:
+ hot.append((ray, j * L / J, 4, 4 + length + (0 if s.reduced else 7 * flash)))
+ ink(ctx, s, C.dim, 1, alpha * 0.45, lambda: rail_to(ctx, ray, 0, L, 2))
+ if lit_to > 0:
+ ink(ctx, s, C.lit, 2, alpha, lambda: rail_to(ctx, ray, 0, L * lit_to, 2))
+ ink(ctx, s, C.dim, 1.25, alpha * 0.5, comb(ctx, off))
+ ink(ctx, s, C.lit, 1.25, alpha, comb(ctx, on))
+ ink(ctx, s, C.hot, 1.5, alpha * flash, comb(ctx, hot))
+ if not s.reduced:
+ ink(ctx, s, C.lit, 2, alpha, lambda: tick_to(ctx, ray, L * q, 2, 22))
+ return
+ u = s.since
+ if u >= 0.6:
+ return
+ fade = 1 if u < 0.4 else 1 - (u - 0.4) / 0.2
+ shut = 1 if s.reduced else detent(u / 0.36, 4)
+ a, b = k.tp * shut, L - (L - k.tp) * shut
+
+ def blades():
+ band_to(ctx, ray, 0, max(a, 0.5), 2, 20)
+ band_to(ctx, ray, min(b, L - 0.5), L, 2, 20)
+ fill_with(ctx, "#000", 0.5 * fade, blades)
+
+ def edges():
+ tick_to(ctx, ray, a, 2, 20)
+ tick_to(ctx, ray, b, 2, 20)
+ ink(ctx, s, C.lit, 1.5, fade, edges)
+
+ def teeth():
+ for j in range(J + 1):
+ d = j * L / J
+ if a < d < b:
+ tick_to(ctx, ray, d, 4, 14 if j % 8 == 0 else 9)
+ ink(ctx, s, C.hot, 1.25, fade * 0.9, teeth)
+ ink(ctx, s, C.hot, 2, fade, lambda: rail_to(ctx, ray, 0, L, 2))
+
+
+def gauge_depart(ctx, s):
+ C, G = roles(s), 16
+ k = frame(ctx, s, True)
+ if k.kind == "notch":
+ return gauge_notch(ctx, s, k, C)
+ R0 = 58 if k.kind == "corner" else 46
+ sweep = PI / 2 if k.kind == "corner" else PI
+
+ def grads(o, lit_to, flash_k, flash_len):
+ off, on, hot = [], [], []
+ for j in range(G + 1):
+ ang = sweep * j / G
+ cs, sn = math.cos(ang), math.sin(ang)
+ length = 10 if j % 4 == 0 else 5
+ (on if j / G <= lit_to + 1e-6 else off).append((cs, sn, R0 - length, R0))
+ if j == flash_k:
+ hot.append((cs, sn, R0 - length, R0 + flash_len))
+
+ def draw(items):
+ def build():
+ for cs, sn, a, b in items:
+ ctx.moveTo(cs * a, sn * a)
+ ctx.lineTo(cs * b, sn * b)
+ return build
+ return SimpleNamespace(off=draw(off), on=draw(on), hot=draw(hot))
+
+ if s.since is None:
+ p = s.pressure
+ alpha = clamp(p * 3)
+ q = detent(p, G, 0.5)
+ lit_to = (math.floor(p * G + 1e-6) / G) if s.reduced else q
+ flash = tick_flash(s)
+ g = grads(0, lit_to, s.tick.index * 4 if flash else -1, 0 if s.reduced else 8 * flash)
+ ink(ctx, s, C.dim, 1, alpha * 0.45, lambda: ctx.arc(0, 0, R0 + 3, 0, sweep))
+ if lit_to > 0:
+ ink(ctx, s, C.lit, 2.2, alpha, lambda: ctx.arc(0, 0, R0 + 3, 0, sweep * lit_to))
+ ink(ctx, s, C.dim, 1.25, alpha * 0.5, g.off)
+ ink(ctx, s, C.lit, 1.25, alpha, g.on)
+ ink(ctx, s, C.hot, 1.5, alpha * flash, g.hot)
+ if not s.reduced:
+ ang = sweep * q
+
+ def needle():
+ ctx.moveTo(math.cos(ang) * 9, math.sin(ang) * 9)
+ ctx.lineTo(math.cos(ang) * (R0 - 13), math.sin(ang) * (R0 - 13))
+ ink(ctx, s, C.lit, 2, alpha, needle)
+ ink(ctx, s, C.lit, 1.25, alpha, lambda: ctx.arc(0, 0, 5, 0, sweep))
+ return
+ u = s.since
+ if u >= 0.6:
+ return
+ fade = (1 - detent(u / 0.6, 4, 0.25)) if s.reduced else (1 if u < 0.4 else 1 - (u - 0.4) / 0.2)
+ shut = 1 if s.reduced else detent(u / 0.36, 4)
+ a = R0 * (1 - shut)
+ rot = shut * PI / 6
+
+ def blade():
+ ctx.moveTo(R0, 0)
+ ctx.arc(0, 0, R0, 0, sweep)
+ if a > 0.5:
+ ctx.lineTo(a * math.cos(sweep), a * math.sin(sweep))
+ ctx.arc(0, 0, a, sweep, 0, True)
+ else:
+ ctx.lineTo(0, 0)
+ ctx.closePath()
+ fill_with(ctx, "#000", 0.5 * fade, blade)
+ length = math.sqrt(max(0, R0 * R0 - a * a))
+ if length > 0.5:
+ def spokes():
+ for i in range(6):
+ f = i * PI / 3 + rot
+ px, py = a * math.cos(f), a * math.sin(f)
+ ctx.moveTo(px, py)
+ ctx.lineTo(px - math.sin(f) * length, py + math.cos(f) * length)
+ ink(ctx, s, C.lit, 1.25, fade, spokes)
+ g = grads(0, 1, -1, 0)
+ ink(ctx, s, C.hot, 1.25, fade * 0.9, g.on)
+ ink(ctx, s, C.hot, 2, fade, lambda: ctx.arc(0, 0, R0 + 3, 0, sweep))
+
+
+def gauge_arrive(ctx, s):
+ t = s.since
+ if t >= 0.7:
+ return
+ C = roles(s)
+ c = 1 if s.reduced else detent(t / 0.34, 4)
+ lock_at = 0.3
+ locked = t >= lock_at
+ flash = clamp(1 - (t - lock_at) / 0.14) if locked else 0
+ alpha = 1 if t < 0.46 else 1 - (t - 0.46) / 0.24
+ ctx.save()
+ k = frame(ctx, s, False)
+ if k.kind == "notch":
+ tr, L = k.track, k.track.L
+ o = lerp(34, 10, c)
+ ray = SimpleNamespace(at=tr.at)
+
+ def ticks():
+ for j in range(25):
+ tick_to(ctx, ray, j * L / 24, o, o + (8 if j % 6 == 0 else 4))
+ ink(ctx, s, C.lit, 1.5, alpha, lambda: rail_to(ctx, ray, 0, L, o))
+ ink(ctx, s, C.lit if locked else C.dim, 1.25, alpha, ticks)
+ ink(ctx, s, C.hot, 1.75, alpha * flash, ticks)
+ ink(ctx, s, C.hot, 2, alpha, lambda: tick_to(ctx, ray, k.tp, o, o + 14))
+ ctx.restore()
+ return
+ if k.kind == "corner" and s.method != "switch":
+ # A switch came in by no edge, so a pointer that happens to sit near a corner has no
+ # corner register to mark, as Rule and Rangefinder skip theirs.
+ J = lerp(96, 30, c)
+
+ def bracket():
+ ctx.moveTo(J, 1)
+ ctx.lineTo(1, 1)
+ ctx.lineTo(1, J)
+ ink(ctx, s, C.lit, 1.75, alpha, bracket)
+ ctx.restore()
+ P, r, rot = s.point, lerp(96, 30, c), c * PI / 3
+
+ def ticks():
+ for j in range(24):
+ a = rot + j * TAU / 24
+ length = 8 if j % 6 == 0 else 4
+ ctx.moveTo(P.x + math.cos(a) * r, P.y + math.sin(a) * r)
+ ctx.lineTo(P.x + math.cos(a) * (r - length), P.y + math.sin(a) * (r - length))
+ ink(ctx, s, C.lit, 1.5, alpha, lambda: ctx.arc(P.x, P.y, r, 0, TAU))
+ ink(ctx, s, C.lit if locked else C.dim, 1.25, alpha, ticks)
+ ink(ctx, s, C.hot, 1.75, alpha * flash, ticks)
+
+ def cross():
+ for q in range(4):
+ dx, dy = math.cos(q * PI / 2), math.sin(q * PI / 2)
+ ctx.moveTo(P.x + dx * (r + 3), P.y + dy * (r + 3))
+ ctx.lineTo(P.x + dx * (r + 15), P.y + dy * (r + 15))
+ ink(ctx, s, C.lit, 1.5, alpha, cross)
+
+
+def lamps(ctx, s, k, C, count, flash, alpha):
+ c, t = k.centre, k.tangent
+ spots = []
+ for i in range(3):
+ if k.kind == "corner":
+ o = 32 + 11 * i
+ spots.append((c.x + c.nx * o, c.y + c.ny * o))
+ else:
+ spots.append((c.x + c.nx * 38 + t.x * 10 * (i - 1), c.y + c.ny * 38 + t.y * 10 * (i - 1)))
+
+ def box(items):
+ def build():
+ for x, y in items:
+ ctx.rect(x - 2.5, y - 2.5, 5, 5)
+ return build
+ lit, dark = spots[:count], spots[count:]
+ ink(ctx, s, C.dim, 1, alpha * 0.6, box(dark))
+ if lit:
+ def halo():
+ for x, y in lit:
+ ctx.rect(x - 3.5, y - 3.5, 7, 7)
+ fill_with(ctx, "#000", alpha * 0.6, halo)
+ fill_with(ctx, C.lit, alpha, box(lit))
+ if flash:
+ fill_with(ctx, C.hot, alpha * flash, box(lit[-1:]))
+
+
+def rangefinder_depart(ctx, s):
+ C = roles(s)
+ k = frame(ctx, s, True)
+ SP = 6
+ SPAN = 108 if k.kind == "notch" else 150
+ if s.since is None:
+ p = s.pressure
+ alpha = clamp(p * 3)
+ flash = tick_flash(s)
+ close = 0 if s.reduced else detent(p, 16, 0.45)
+ off, on, jaws = [], [], []
+ for ray in k.rays:
+ lim = min(SPAN, ray.max)
+ J = lerp(lim, 8, close)
+ lit_from = lim * (1 - p) if s.reduced else J
+ jaws.append((ray, J))
+ i = 1
+ while i * SP <= lim:
+ (on if i * SP >= lit_from - 0.01 else off).append((ray, i * SP, 1, 1 + (12 if i % 5 == 0 else 5)))
+ i += 1
+
+ def rails():
+ for ray in k.rays:
+ rail_to(ctx, ray, 0, min(SPAN, ray.max), 1)
+ ink(ctx, s, C.dim, 1, alpha * 0.45, rails)
+ ink(ctx, s, C.dim, 1.25, alpha * 0.5, comb(ctx, off))
+ ink(ctx, s, C.lit, 1.25, alpha, comb(ctx, on))
+ ink(ctx, s, C.dim, 1, alpha * 0.7, normal_line(ctx, k.centre, 1, 28))
+
+ def jaw_marks():
+ for ray, J in jaws:
+ tick_to(ctx, ray, J, 0, 24)
+ rail_to(ctx, ray, J, J + 7, 24)
+ ink(ctx, s, C.lit, 2, alpha, jaw_marks)
+
+ def jaw_fill():
+ for ray, J in jaws:
+ a, b, c = ray.at(J), ray.at(J - 3), ray.at(J + 3)
+ ctx.moveTo(a.x + a.nx * 1, a.y + a.ny * 1)
+ ctx.lineTo(b.x + b.nx * 8, b.y + b.ny * 8)
+ ctx.lineTo(c.x + c.nx * 8, c.y + c.ny * 8)
+ ctx.closePath()
+ fill_with(ctx, C.lit, alpha, jaw_fill)
+
+ def jaw_flash():
+ for ray, J in jaws:
+ tick_to(ctx, ray, J, 0, 24 if s.reduced else 24 + 16 * flash)
+ ink(ctx, s, C.hot, 1.25, alpha * flash, jaw_flash)
+ lamps(ctx, s, k, C, s.tick.index if s.tick else 0, flash, alpha)
+ return
+ u = s.since
+ if u >= 0.8:
+ return
+ fade = 1 if u < 0.55 else 1 - (u - 0.55) / 0.25
+ A = 0 if s.reduced else SPAN * (1 - detent(u / 0.42, 4))
+ slit = 70 if s.reduced else 70 * (1 - detent(u / 0.55, 5))
+ blades, on = [], []
+ for ray in k.rays:
+ lim = min(SPAN, ray.max)
+ if A < lim:
+ blades.append((ray, A, lim))
+ i = 1
+ while i * SP <= min(A, lim):
+ on.append((ray, i * SP, 1, 1 + (12 if i % 5 == 0 else 5)))
+ i += 1
+
+ def band():
+ for ray, a, b in blades:
+ band_to(ctx, ray, a, b, 0, 26)
+ fill_with(ctx, "#000", 0.5 * fade, band)
+
+ def rails2():
+ for ray, a, b in blades:
+ rail_to(ctx, ray, a, b, 26)
+ ink(ctx, s, C.dim, 1, fade * 0.7, rails2)
+
+ def edges():
+ for ray, a, _b in blades:
+ tick_to(ctx, ray, a, 0, 26)
+ ink(ctx, s, C.lit, 2, fade, edges)
+ ink(ctx, s, C.hot, 1.25, fade, comb(ctx, on))
+ if slit > 0.5:
+ ink(ctx, s, C.hot, 2.5, fade, normal_line(ctx, k.centre, 0, slit))
+ lamps(ctx, s, k, C, 3, 0, fade)
+
+
+def rangefinder_arrive(ctx, s):
+ t = s.since
+ if t >= 0.8:
+ return
+ C = roles(s)
+ c = 1 if s.reduced else detent(t / 0.4, 4)
+ LOCK = 0.34
+ locked = t >= LOCK
+ flash = clamp(1 - (t - LOCK) / 0.18) if locked else 0
+ alpha = 1 if t < 0.55 else 1 - (t - 0.55) / 0.25
+ if s.method == "switch":
+ # A switch came in by no edge, so there are no jaws to close along it: only the dial.
+ rangefinder_dial(ctx, s, C, c, locked, flash, alpha)
+ return
+ ctx.save()
+ k = frame(ctx, s, False)
+ JM = 60 if k.kind == "notch" else 104
+ on, jaws = [], []
+ for ray in k.rays:
+ J = min(JM, ray.max) * c
+ if J > 1:
+ jaws.append((ray, J))
+ i = 1
+ while i * 6 <= J:
+ on.append((ray, i * 6, 1, 1 + (12 if i % 5 == 0 else 5)))
+ i += 1
+ ink(ctx, s, C.lit, 1.25, alpha, comb(ctx, on))
+
+ def jaw_marks():
+ for ray, J in jaws:
+ tick_to(ctx, ray, J, 0, 22)
+ rail_to(ctx, ray, J, J + 7, 22)
+ ink(ctx, s, C.lit, 2, alpha, jaw_marks)
+ if k.kind == "notch":
+ tr, L = k.track, k.track.L
+ o = lerp(28, 9, c)
+ ray = SimpleNamespace(at=tr.at)
+
+ def outline():
+ rail_to(ctx, ray, 0, L, o)
+ ink(ctx, s, C.lit if locked else C.dim, 1.5, alpha, outline)
+ ink(ctx, s, C.hot, 2.25, alpha * flash, outline)
+
+ def teeth():
+ for j in range(37):
+ tick_to(ctx, ray, j * L / 36, o, o + (7 if j % 9 == 0 else 3))
+ ink(ctx, s, C.dim, 1, alpha * 0.8, teeth)
+ ink(ctx, s, C.hot, 2, alpha, lambda: tick_to(ctx, ray, k.tp, o, o + 16))
+ ctx.restore()
+ return
+ ctx.restore()
+ rangefinder_dial(ctx, s, C, c, locked, flash, alpha)
+
+
+def rangefinder_dial(ctx, s, C, c, locked, flash, alpha):
+ P = s.point
+ r = lerp(96, 34, c)
+ rot = c * 4 * (TAU / 36) * 2
+ ink(ctx, s, C.lit, 1.5, alpha, lambda: ctx.arc(P.x, P.y, r, 0, TAU))
+
+ def grads():
+ for j in range(36):
+ a = rot + j * TAU / 36
+ length = 9 if j % 9 == 0 else 4
+ ctx.moveTo(P.x + math.cos(a) * r, P.y + math.sin(a) * r)
+ ctx.lineTo(P.x + math.cos(a) * (r + length), P.y + math.sin(a) * (r + length))
+ ink(ctx, s, C.dim, 1.1, alpha * 0.85, grads)
+ ink(ctx, s, C.hot, 1.5, alpha * flash, grads)
+
+ def outer_ticks():
+ for q in range(4):
+ dx, dy = math.cos(q * PI / 2), math.sin(q * PI / 2)
+ ctx.moveTo(P.x + dx * (r + 12), P.y + dy * (r + 12))
+ ctx.lineTo(P.x + dx * (r + 22), P.y + dy * (r + 22))
+ ink(ctx, s, C.lit, 1.25, alpha, outer_ticks)
+
+ def spokes():
+ for q in range(4):
+ dx, dy = math.cos(q * PI / 2), math.sin(q * PI / 2)
+ a = max(20, 0.6 * r)
+ ctx.moveTo(P.x + dx * a, P.y + dy * a)
+ ctx.lineTo(P.x + dx * (r - 6), P.y + dy * (r - 6))
+ ink(ctx, s, C.dim, 1, alpha * 0.8, spokes)
+
+ b = r * 0.66
+
+ def brackets():
+ for sx, sy in ((1, 1), (-1, 1), (-1, -1), (1, -1)):
+ ctx.moveTo(P.x + sx * (b - 9), P.y + sy * b)
+ ctx.lineTo(P.x + sx * b, P.y + sy * b)
+ ctx.lineTo(P.x + sx * b, P.y + sy * (b - 9))
+ ink(ctx, s, C.lit if locked else C.dim, 1.75, alpha, brackets)
+ ink(ctx, s, C.hot, 2.25, alpha * flash, brackets)
+ if locked:
+ def corners():
+ for q in range(4):
+ dx, dy = math.cos(q * PI / 2), math.sin(q * PI / 2)
+ ctx.rect(P.x + dx * (r + 6) - 2, P.y + dy * (r + 6) - 2, 4, 4)
+ fill_with(ctx, C.hot, alpha, corners)
+
+
+EFFECTS = [
+ Effect(
+ "rule", "Rule", "quiet",
+ "A fine ruler rises along the edge round the pointer and lights outward one division at a "
+ "time as the push builds, the three quarter detents marked long. At breakthrough it closes "
+ "on the pointer in four clicks; on the other screen a short register mark sits where you "
+ "came in and a four-arm cross steps in three clicks onto the landing point.",
+ rule_depart, rule_arrive, 0.45, 0.6,
+ ),
+ Effect(
+ "gauge", "Gauge", "medium",
+ "A half dial seated on the edge at the pointer, a quarter dial in the corner and a "
+ "graduated collar round the notch, whose needle clicks round sixteen detents as the push "
+ "builds. At breakthrough an iris shuts over the dial in four steps; on the other screen a "
+ "graduated ring contracts onto the landing point, turning one graduation per click, and "
+ "flashes as it locks.",
+ gauge_depart, gauge_arrive, 0.6, 0.7,
+ ),
+ Effect(
+ "rangefinder", "Rangefinder", "showpiece",
+ "A long scale runs along the edge and a pair of caliper jaws closes on the pointer in "
+ "detents, lighting the divisions it passes, while three tally lamps light at each quarter. "
+ "At breakthrough shutter blades slide in from both ends and a bright slit at the pointer "
+ "shuts; on the far screen the jaws open outward from the entry point as a graduated "
+ "reticle with corner brackets steps in, turns and locks onto the landing point.",
+ rangefinder_depart, rangefinder_arrive, 0.8, 0.8,
+ ),
+]
+
+PACKS = {
+ "phosphor": ("Phosphor", ["#3dff7f", "#1f9e52", "#caffdc"]),
+ "sodium": ("Sodium", ["#ffa51f", "#c46a12", "#ffe0a3"]),
+ "contrast": ("Contrast", ["#f0e442", "#56b4e9", "#ffffff"]),
+}
diff --git a/mac_app/fx_membrane.py b/mac_app/fx_membrane.py
new file mode 100644
index 0000000..8f2c89b
--- /dev/null
+++ b/mac_app/fx_membrane.py
@@ -0,0 +1,546 @@
+"""Membrane: crossing is pushing through a skin, the boundary stretching thin under the pointer
+until it tears, and the same skin on the other screen rippling out from where you came through and
+healing behind you.
+"""
+
+import math
+from types import SimpleNamespace
+
+import effects
+
+TAU = effects.TAU
+clamp = effects.clamp
+lerp = effects.lerp
+ease_out = effects.ease_out
+
+
+# The radius of a switch's ring round the pointer, before the effect's own gap from the edge.
+POINT_RING = 14
+
+
+def smooth(a, b, x):
+ u = clamp((x - a) / (b - a))
+ return u * u * (3 - 2 * u)
+
+
+def bump(x):
+ return math.exp(-x * x)
+
+
+def rgb(h):
+ return [int(h[1:3], 16), int(h[3:5], 16), int(h[5:7], 16)]
+
+
+def hue(pal, u):
+ n = len(pal)
+ f = math.fmod(math.fmod(u, n) + n, n)
+ i = int(math.floor(f)) % n
+ k = f - math.floor(f)
+ a, b = pal[i], pal[(i + 1) % n]
+ return [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k]
+
+
+def rgba(c, a):
+ return f"rgba({math.trunc(c[0])},{math.trunc(c[1])},{math.trunc(c[2])},{clamp(a):.3f})"
+
+
+def ink(a):
+ return f"rgba(0,0,0,{clamp(a):.3f})"
+
+
+def line(a, b):
+ length = math.hypot(b[0] - a[0], b[1] - a[1])
+
+ def at(u):
+ return (a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u)
+
+ return SimpleNamespace(len=length, at=at)
+
+
+def arc(cx, cy, r, a0, a1, mapper):
+ length = abs(a1 - a0) * r
+
+ def at(u):
+ a = a0 + (a1 - a0) * u
+ return mapper(cx + r * math.cos(a), cy + r * math.sin(a))
+
+ return SimpleNamespace(len=length, at=at)
+
+
+def same(x, y):
+ return (x, y)
+
+
+def sample(segs, anchor, ref):
+ pts = []
+ for j, sg in enumerate(segs):
+ n = max(1, math.ceil(sg.len / 4))
+ for i in range(1 if j else 0, n + 1):
+ x, y = sg.at(i / n)
+ pts.append(SimpleNamespace(x=x, y=y))
+ t = 0.0
+ i0 = 0
+ best = math.inf
+ for i, p in enumerate(pts):
+ if i:
+ t += math.hypot(p.x - pts[i - 1].x, p.y - pts[i - 1].y)
+ p.t = t
+ a = pts[max(0, i - 1)]
+ b = pts[min(len(pts) - 1, i + 1)]
+ tx, ty = b.x - a.x, b.y - a.y
+ m = math.hypot(tx, ty) or 1.0
+ p.nx, p.ny = -ty / m, tx / m
+ dd = (p.x - anchor[0]) ** 2 + (p.y - anchor[1]) ** 2
+ if dd < best:
+ best, i0 = dd, i
+ o = pts[i0]
+ flip = -1.0 if o.nx * (o.x - ref[0]) + o.ny * (o.y - ref[1]) < 0 else 1.0
+ for p in pts:
+ p.nx *= flip
+ p.ny *= flip
+ p.d = p.t - o.t
+ p.end = min(p.t, t - p.t)
+ return SimpleNamespace(pts=pts, total=t)
+
+
+def edge_geo(s, edge):
+ W, H = s.screen.w, s.screen.h
+ side = edge in ("left", "right")
+
+ def mapper(u, v):
+ if edge == "left":
+ return (v, u)
+ if edge == "right":
+ return (W - v, u)
+ if edge == "top":
+ return (u, v)
+ return (u, H - v)
+
+ u0 = s.point.y if side else s.point.x
+ return SimpleNamespace(kind="edge", map=mapper, u0=u0, centre=mapper(u0, 0))
+
+
+def geo_of(s, leaving):
+ W, H = s.screen.w, s.screen.h
+ p = s.point
+ n = getattr(s, "notch", None)
+ if leaving:
+ r = s.region
+ if r.kind == "notch":
+ return SimpleNamespace(kind="notch", anchor=(p.x, p.y), centre=(p.x, 0))
+ if r.kind == "corner":
+ cx = W if "right" in r.corner else 0
+ cy = H if "bottom" in r.corner else 0
+ return SimpleNamespace(kind="corner", cx=cx, cy=cy, centre=(cx, cy))
+ return edge_geo(s, r.edge)
+ if s.method == "switch":
+ # A switch, away from any edge: the skin closes as a small ring round the pointer.
+ return SimpleNamespace(kind="point", centre=(p.x, p.y))
+ if n is not None and s.edge == "top" and n.x - 24 < p.x < n.x + n.w + 24:
+ return SimpleNamespace(kind="notch", anchor=(p.x, p.y), centre=(p.x, p.y))
+ cx = 0 if p.x < 20 else (W if p.x > W - 20 else -1)
+ cy = 0 if p.y < 20 else (H if p.y > H - 20 else -1)
+ if cx >= 0 and cy >= 0:
+ return SimpleNamespace(kind="corner", cx=cx, cy=cy, centre=(cx, cy))
+ return edge_geo(s, s.edge)
+
+
+def contour(s, geo, g, L, o):
+ if geo.kind == "edge":
+ mapper, u0 = geo.map, geo.u0
+ return sample([line(mapper(u0 - L, g), mapper(u0 + L, g))], mapper(u0, g), geo.centre)
+ if geo.kind == "point":
+ cx, cy = geo.centre
+ R = POINT_RING + g
+ # Starting opposite the top, so the ring's gap and bulge sit above the pointer's tip.
+ return sample([arc(cx, cy, R, math.pi / 2, math.pi / 2 + TAU, same)], (cx, cy - R), geo.centre)
+ if geo.kind == "corner":
+ sx = -1 if geo.cx else 1
+ sy = -1 if geo.cy else 1
+
+ def M(a, b):
+ return (geo.cx + sx * a, geo.cy + sy * b)
+
+ rho = max(3, o["rho"])
+ c = g + rho
+ arm = max(c + 12, L)
+ k = c - rho / math.sqrt(2)
+ return sample([line(M(arm, g), M(c, g)), arc(c, c, rho, -math.pi / 2, -math.pi, M),
+ line(M(g, c), M(g, arm))], M(k, k), geo.centre)
+ n = s.notch
+ lo = n.h - n.r
+ x0, x1 = n.x - g, n.x + n.w + g
+ R = n.r + g
+ arm = o.get("arm") or 0
+ f = max(2, min(8, lo - g - 2))
+ segs = []
+ if arm:
+ segs.append(line((x0 - f - arm, g), (x0 - f, g)))
+ segs.append(arc(x0 - f, g + f, f, -math.pi / 2, 0, same))
+ segs.append(line((x0, g + f), (x0, lo)))
+ else:
+ segs.append(line((x0, 0), (x0, lo)))
+ segs.append(arc(n.x + n.r, lo, R, math.pi, math.pi / 2, same))
+ segs.append(line((n.x + n.r, n.h + g), (n.x + n.w - n.r, n.h + g)))
+ segs.append(arc(n.x + n.w - n.r, lo, R, math.pi / 2, 0, same))
+ if arm:
+ segs.append(line((x1, lo), (x1, g + f)))
+ segs.append(arc(x1 + f, g + f, f, math.pi, math.pi * 1.5, same))
+ segs.append(line((x1 + f, g), (x1 + f + arm, g)))
+ else:
+ segs.append(line((x1, lo), (x1, 0)))
+ return sample(segs, geo.anchor, (n.x + n.w / 2, 0))
+
+
+def trace(ctx, C, off, keep):
+ ctx.beginPath()
+ pen = False
+ for p in C.pts:
+ if keep and not keep(p):
+ pen = False
+ continue
+ o = off(p)
+ x, y = p.x + p.nx * o, p.y + p.ny * o
+ if pen:
+ ctx.lineTo(x, y)
+ else:
+ ctx.moveTo(x, y)
+ pen = True
+
+
+def along(ctx, C, stop):
+ P = C.pts
+ A, Z = P[0], P[-1]
+ dx, dy = Z.x - A.x, Z.y - A.y
+ l2 = (dx * dx + dy * dy) or 1.0
+ g = ctx.createLinearGradient(A.x, A.y, Z.x, Z.y)
+ every = max(1, math.ceil(len(P) / 30))
+ idx = list(range(0, len(P), every))
+ if idx[-1] != len(P) - 1:
+ idx.append(len(P) - 1)
+ last = 0.0
+ for i in idx:
+ p = P[i]
+ q = clamp(((p.x - A.x) * dx + (p.y - A.y) * dy) / l2)
+ if q < last:
+ q = last
+ last = q
+ g.addColorStop(q, stop(p))
+ return g
+
+
+def film_layer(C, off, keep, lw, alpha, colour, halo=1):
+ def path(ctx):
+ trace(ctx, C, off, keep)
+
+ def paint(ctx, U):
+ if U:
+ return along(ctx, C, lambda p: ink(alpha(p) * U))
+ return along(ctx, C, lambda p: rgba(colour(p), alpha(p)))
+
+ return SimpleNamespace(lw=lw, halo=halo, path=path, paint=paint)
+
+
+def ring_layer(c, r, lw, a, pal, phase):
+ def path(ctx):
+ ctx.beginPath()
+ ctx.arc(c[0], c[1], r, 0, TAU)
+
+ def paint(ctx, U):
+ if U:
+ return ink(a * U)
+ g = ctx.createConicGradient(phase, c[0], c[1])
+ for j in range(13):
+ g.addColorStop(j / 12, rgba(hue(pal, phase + (j / 12) * len(pal) * 2), a))
+ return g
+
+ return SimpleNamespace(lw=lw, halo=1, path=path, paint=paint)
+
+
+def render(ctx, s, layers):
+ ctx.lineJoin = "round"
+ ctx.lineCap = "round"
+ U = 0.32 if s.dark else 0.58
+ pad = 1.6 if s.dark else 2.4
+ ctx.globalCompositeOperation = "source-over"
+ for l in layers:
+ h = l.halo
+ l.path(ctx)
+ ctx.lineWidth = l.lw + pad * h
+ ctx.strokeStyle = l.paint(ctx, U * h)
+ ctx.stroke()
+ ctx.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ for l in layers:
+ l.path(ctx)
+ ctx.lineWidth = l.lw
+ ctx.strokeStyle = l.paint(ctx, 0)
+ ctx.stroke()
+
+
+def sheen(ctx, s, C, off, keep, base, alpha, colour):
+ runs = []
+ cur = None
+ for p in C.pts:
+ if keep and not keep(p):
+ cur = None
+ continue
+ if cur is None:
+ cur = []
+ runs.append(cur)
+ cur.append(p)
+ ctx.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ ctx.fillStyle = along(ctx, C, lambda p: rgba(colour(p), alpha(p)))
+ ctx.beginPath()
+ for run in runs:
+ if len(run) < 2:
+ continue
+ for i, p in enumerate(run):
+ o = off(p)
+ x, y = p.x + p.nx * o, p.y + p.ny * o
+ if i:
+ ctx.lineTo(x, y)
+ else:
+ ctx.moveTo(x, y)
+ for i in range(len(run) - 1, -1, -1):
+ p = run[i]
+ ctx.lineTo(p.x - p.nx * base, p.y - p.ny * base)
+ ctx.closePath()
+ ctx.fill()
+
+
+def _sign(x):
+ return (x > 0) - (x < 0)
+
+
+def _depart(ctx, s, P):
+ broke = s.since is not None
+ t = s.since if broke else 0.0
+ secs = P["departSeconds"]
+ if broke and t >= secs:
+ return
+ p = 1.0 if broke else s.pressure
+ if not (p > 0):
+ return
+ red = s.reduced
+ pal = [rgb(h) for h in s.palette]
+ geo = geo_of(s, True)
+ notch = geo.kind == "notch"
+ corner = geo.kind == "corner"
+ g = 5 if notch else P["g"]
+ L = 250 if notch else (P["L"] * 0.8 if corner else P["L"])
+ u = t / secs
+ if broke:
+ level = ((1 - u) ** 1.25) * (1 + 0.6 * math.exp(-t * 18))
+ else:
+ level = smooth(0, 0.14, p) * (0.42 + 0.58 * p)
+ tick = getattr(s, "tick", None)
+ age = tick.age if (tick and not broke) else -1
+ wob = math.exp(-age * 10) * math.sin(age * 44) if (age >= 0 and not red) else 0.0
+ pulse = 0.5 * math.exp(-age * 9) if (age >= 0 and red) else 0.0
+ w = 44.0 if red else lerp(86, 34, p)
+ D = min(g, 0.6 * g if red else g * (0.18 + 0.82 * p) * (1 + 0.4 * wob))
+ if broke and not red:
+ D *= math.exp(-7 * t) * math.cos(21 * t)
+ gap = (18.0 if red else 3 + P["retract"] * t) if broke else -1.0
+ curl = P["curl"] * min(1.0, t * 14) if (broke and not red) else 0.0
+ keep = (lambda q: abs(q.d) >= gap) if broke else None
+ phase = 0.0 if red else 1.3 * p + (2.4 * t if broke else 0.0)
+ pS = 0.5 if red else p
+ rho = 20.0 if red else lerp(44, 9, p)
+
+ def wave(d):
+ if not P["waves"] or age < 0 or red:
+ return 0.0
+ front = abs(d) - 240 * age
+ return 3.2 * math.exp(-3.2 * age) * math.sin(front / 5) * bump(front / 24)
+
+ layers = []
+ main = None
+ for k in range(P["fringes"]):
+ vis = clamp((p - k / 4) / 0.04) if k else 1.0
+ if vis <= 0:
+ continue
+ C = contour(s, geo, g + k * P["sp"], L, {"rho": rho, "arm": 60})
+ crowd = k * P["sp"] * 0.62 * pS
+
+ def off(q, crowd=crowd, k=k):
+ base = -(D + crowd) * bump(q.d / w) + wave(q.d)
+ if curl:
+ base += curl * smooth(gap + 16, gap, abs(q.d))
+ return base
+
+ lw = (1.1 if s.dark else 1.4) if k else P["lw"] * (0.85 if red else 1 - 0.3 * p)
+
+ def alpha(q, vis=vis, k=k):
+ a = level * vis * (1 + pulse) * (1 - smooth(0.45 * L, L, abs(q.d))) * smooth(0, 24, q.end)
+ if notch:
+ a *= 0.55 + 0.45 * bump(q.d / 150)
+ if not broke:
+ a *= 1 - 0.5 * (p ** 4) * bump(q.d / (0.45 * w))
+ return a * (0.8 if k else 1.0)
+
+ def colour(q, k=k):
+ return hue(pal, phase + q.d / 88 + k * 0.9 + 1.4 * pS * bump(q.d / w))
+
+ layers.append(film_layer(C, off, keep, lw, alpha, colour, (0.7 if s.dark else 0.4) if k else 1))
+ if not k:
+ main = SimpleNamespace(C=C, off=off, alpha=alpha, colour=colour)
+
+ if P["sheen"]:
+ sheen(ctx, s, main.C, main.off, keep, g, lambda q: main.alpha(q) * (0.2 if s.dark else 0.3), main.colour)
+ render(ctx, s, layers)
+ if P["beads"] and broke and not red:
+ U = 0.32 if s.dark else 0.58
+ for sgn in (-1, 1):
+ q = None
+ best = math.inf
+ for c in main.C.pts:
+ if _sign(c.d) == sgn and abs(c.d) >= gap and abs(c.d) - gap < best:
+ best = abs(c.d) - gap
+ q = c
+ if q is None:
+ continue
+ a = main.alpha(q)
+ if a <= 0.01:
+ continue
+ o = main.off(q)
+ x, y = q.x + q.nx * o, q.y + q.ny * o
+ r = 1.4 + 2.2 * min(1.0, t * 6)
+ ctx.globalCompositeOperation = "source-over"
+ ctx.fillStyle = ink(a * U)
+ ctx.beginPath()
+ ctx.arc(x, y, r + 1.2, 0, TAU)
+ ctx.fill()
+ ctx.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ ctx.fillStyle = rgba(main.colour(q), a)
+ ctx.beginPath()
+ ctx.arc(x, y, r, 0, TAU)
+ ctx.fill()
+
+
+def _arrive(ctx, s, P):
+ t = s.since
+ secs = P["arriveSeconds"]
+ if not (t < secs):
+ return
+ red = s.reduced
+ pal = [rgb(h) for h in s.palette]
+ geo = geo_of(s, False)
+ u = t / secs
+ notch = geo.kind == "notch"
+ corner = geo.kind == "corner"
+ g = 6 if notch else P["g"]
+ L = P["aL"] * 0.85 if corner else P["aL"]
+ if red:
+ level = smooth(0, 0.05, t) * (1 - smooth(0.4, 1, u))
+ else:
+ level = 1 - smooth(0.45, 1, u)
+ gap = -1.0 if red else P["gap0"] * (max(0.0, 1 - t / 0.2) ** 1.5)
+ bul = 0.45 * P["bulge"] if red else max(-0.7 * g, P["bulge"] * math.exp(-6.5 * t) * math.cos(17 * t))
+
+ def wave(d):
+ if not P["aWave"] or red:
+ return 0.0
+ front = abs(d) - 300 * t
+ return 2.6 * math.exp(-3 * t) * math.sin(front / 5) * bump(front / 26)
+
+ C = contour(s, geo, g, L, {"rho": 22, "arm": 64})
+ keep = (lambda q: abs(q.d) >= gap) if gap > 0 else None
+
+ def off(q):
+ return bul * bump(q.d / 30) + wave(q.d)
+
+ phase = 0.0 if red else 2.6 - 1.8 * u
+
+ def alpha(q):
+ return level * (1 - smooth(0.5 * L, L, abs(q.d))) * smooth(0, 20, q.end)
+
+ def colour(q):
+ return hue(pal, phase + q.d / 88 + 1.2 * bump(q.d / 30))
+
+ layers = [film_layer(C, off, keep, P["lw"], alpha, colour)]
+ for i, R in enumerate(P["rings"]):
+ tau = t - i * P["stagger"]
+ if tau < 0 or tau >= P["ringDur"]:
+ continue
+ v = tau / P["ringDur"]
+ r = P["still"][i] if red else 8 + (R - 8) * ease_out(v)
+ a = (math.sin(math.pi * v) if red else (1 - v) ** 1.3) * (0.85 if i else 1.0)
+ lw = 1.5 if red else lerp(2.6, 0.9, v)
+ if notch:
+ Cr = contour(s, geo, g + 0.6 * r, 0, {"arm": 0})
+ layers.append(film_layer(
+ Cr, lambda q: 0, None, lw,
+ (lambda q, a=a: a * (1 - smooth(50, 140, abs(q.d)))),
+ (lambda q, i=i: hue(pal, phase + i * 1.1 + q.d / 70)),
+ ))
+ else:
+ layers.append(ring_layer(geo.centre, r, lw, a, pal, phase + i * 1.1))
+
+ if P["disc"]:
+ c = geo.anchor if notch else geo.centre
+ Rd = 64.0 if red else 10 + 104 * ease_out(min(1.0, t / 0.55))
+ aD = (0.5 * math.sin(math.pi * u) if red else 0.6 * ((1 - u) ** 1.2)) * (1.0 if s.dark else 0.7)
+ rg = ctx.createRadialGradient(c[0], c[1], 0, c[0], c[1], Rd)
+ for j in range(17):
+ q = j / 16
+ rg.addColorStop(q, rgba(
+ hue(pal, phase + q * 3),
+ aD * (0.5 + 0.5 * math.cos(q * TAU * 3.5)) * ((1 - q) ** 0.8) * smooth(0, 0.15, q),
+ ))
+ ctx.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ ctx.fillStyle = rg
+ ctx.beginPath()
+ ctx.arc(c[0], c[1], Rd, 0, TAU)
+ ctx.fill()
+ render(ctx, s, layers)
+
+
+def _make(id_, name, intensity, blurb, depart_seconds, arrive_seconds, P):
+ def depart(ctx, s):
+ _depart(ctx, s, P)
+
+ def arrive(ctx, s):
+ _arrive(ctx, s, P)
+
+ return effects.Effect(id_, name, intensity, blurb, depart, arrive, depart_seconds, arrive_seconds)
+
+
+EFFECTS = [
+ _make("skin", "Skin", "quiet",
+ "A single iridescent hairline sits just inside the edge and dimples under the pointer as "
+ "you push, thinning and shifting colour. It parts at the pointer and the two ends pull "
+ "back; on the other screen the same hairline closes behind the pointer and one ripple "
+ "spreads out.",
+ 0.45, 0.6,
+ {"departSeconds": 0.45, "arriveSeconds": 0.6, "g": 6, "L": 110, "lw": 2.0, "fringes": 1,
+ "sp": 0, "retract": 300, "curl": 3, "sheen": False, "beads": False, "waves": False,
+ "aL": 84, "gap0": 16, "bulge": 9, "rings": [58], "still": [40], "stagger": 0,
+ "ringDur": 0.5, "disc": False, "aWave": False}),
+ _make("film", "Film", "medium",
+ "A band of interference fringes, one added at each quarter tick, crowds and thins into the "
+ "dent under the pointer, so the band itself is the pressure meter. At breakthrough the film "
+ "tears and each fringe peels back with a curled rim; on the other side the skin bulges in "
+ "around the arriving pointer, springs back, heals, and throws two ripples.",
+ 0.55, 0.7,
+ {"departSeconds": 0.55, "arriveSeconds": 0.7, "g": 7, "L": 150, "lw": 2.2, "fringes": 4,
+ "sp": 3.6, "retract": 330, "curl": 5, "sheen": False, "beads": False, "waves": False,
+ "aL": 110, "gap0": 26, "bulge": 14, "rings": [74, 104], "still": [44, 80],
+ "stagger": 0.09, "ringDur": 0.55, "disc": False, "aWave": False}),
+ _make("rupture", "Rupture", "showpiece",
+ "The whole edge becomes a visible soap film with a sheen behind its fringes; every tick "
+ "sends a shudder along it, and at breakthrough it bursts, the torn rims racing away along "
+ "the edge carrying beads of film. The arrival opens a set of Newton's rings around the "
+ "entry point while the skin bulges in, heals and sends a surface wave along the edge.",
+ 0.7, 0.8,
+ {"departSeconds": 0.7, "arriveSeconds": 0.8, "g": 8, "L": 220, "lw": 2.6, "fringes": 4,
+ "sp": 4, "retract": 420, "curl": 6, "sheen": True, "beads": True, "waves": True,
+ "aL": 118, "gap0": 34, "bulge": 18, "rings": [70, 96, 118], "still": [36, 64, 92],
+ "stagger": 0.08, "ringDur": 0.6, "disc": True, "aWave": True}),
+]
+
+PACKS = {
+ "oil_slick": ("Oil slick", ["#8a4dff", "#2f7dff", "#16c6b0", "#9fdc4a", "#f0c23c", "#e8477f"]),
+ "soap_bubble": ("Soap bubble", ["#ffd98e", "#ff9cc2", "#c3a6ff", "#8fcfff", "#9ef2cf"]),
+ "pearl": ("Pearl", ["#fbf4e8", "#f2c9d6", "#c6dcf2", "#d9f0dc", "#ffffff"]),
+}
diff --git a/mac_app/fx_sparks.py b/mac_app/fx_sparks.py
new file mode 100644
index 0000000..b60128f
--- /dev/null
+++ b/mac_app/fx_sparks.py
@@ -0,0 +1,484 @@
+"""Sparks: crossing is a charge that discharges, sparks gathering at the pointer, sucked through
+the point at breakthrough, and thrown back out where it lands."""
+
+from __future__ import annotations
+
+import math
+from types import SimpleNamespace
+
+import effects
+from effects import TAU, clamp, lerp
+
+INWARD = {"right": (-1, 0), "left": (1, 0), "top": (0, 1), "bottom": (0, -1)}
+
+
+def ease_out(u):
+ return 1 - (1 - clamp(u)) ** 3
+
+
+def ease_in(u):
+ return clamp(u) * clamp(u)
+
+
+def rot(n, a):
+ c, k = math.cos(a), math.sin(a)
+ return (n[0] * c - n[1] * k, n[0] * k + n[1] * c)
+
+
+def turn(a, b):
+ return math.atan2(math.sin(a - b), math.cos(a - b))
+
+
+def rgba(hex_colour, a):
+ v = int(hex_colour[1:], 16)
+ return f"rgba({(v >> 16) & 255},{(v >> 8) & 255},{v & 255},{clamp(a):.3f})"
+
+
+def heat(s, pal, h):
+ k = clamp(h) if s.dark else 0.46 * clamp(h)
+ return pal[min(len(pal) - 1, math.floor((1 - k) * len(pal)))]
+
+
+def shade(s, a):
+ return f"rgba(0,0,0,{clamp(a * (0.3 if s.dark else 0.62)):.3f})"
+
+
+def glow_mode(ctx, s):
+ ctx.globalCompositeOperation = "lighter" if s.dark else "source-over"
+
+
+def depart_frame(s):
+ r, p, W, H = s.region, s.point, s.screen.w, s.screen.h
+ if r.kind == "notch" and getattr(s, "notch", None):
+ n = s.notch
+ x = clamp(p.x, n.x + n.r + 6, n.x + n.w - n.r - 6)
+ return SimpleNamespace(kind="notch", o=SimpleNamespace(x=x, y=n.y + n.h + 1), n=(0, 1),
+ spread=1.25, sink=SimpleNamespace(x=x, y=n.y + n.h - 12))
+ if r.kind == "corner":
+ c = SimpleNamespace(x=W if "right" in r.corner else 0, y=0 if "top" in r.corner else H)
+ e = (-1 if c.x else 1, -1 if c.y else 1)
+ return SimpleNamespace(kind="corner", c=c, e=e,
+ o=SimpleNamespace(x=c.x + e[0] * 2, y=c.y + e[1] * 2),
+ n=(e[0] * math.sqrt(0.5), e[1] * math.sqrt(0.5)), spread=0.66,
+ sink=SimpleNamespace(x=c.x - e[0] * 8, y=c.y - e[1] * 8))
+ n = INWARD[r.edge]
+ return SimpleNamespace(kind="edge", o=SimpleNamespace(x=p.x + n[0], y=p.y + n[1]), n=n,
+ spread=1.34, sink=SimpleNamespace(x=p.x - n[0] * 8, y=p.y - n[1] * 8))
+
+
+def arrive_frame(s):
+ p, W, H = s.point, s.screen.w, s.screen.h
+ if s.method == "switch":
+ # A switch, away from any edge: the sparks go off all round the pointer, thrown up and falling.
+ return SimpleNamespace(kind="point", o=SimpleNamespace(x=p.x, y=p.y), n=(0, -1), spread=math.pi)
+ nt = getattr(s, "notch", None)
+ if nt and s.edge == "top" and nt.x - 4 <= p.x <= nt.x + nt.w + 4:
+ x = clamp(p.x, nt.x + nt.r + 4, nt.x + nt.w - nt.r - 4)
+ return SimpleNamespace(kind="notch", o=SimpleNamespace(x=x, y=nt.y + nt.h + 1),
+ src=SimpleNamespace(x=x, y=nt.y + nt.h - 10), n=(0, 1), spread=1.3)
+ n0, near = INWARD[s.edge], 30
+ ex, ey, corner = n0[0], n0[1], False
+ if ex != 0:
+ if p.y < near:
+ ey, corner = 1, True
+ elif p.y > H - near:
+ ey, corner = -1, True
+ else:
+ if p.x < near:
+ ex, corner = 1, True
+ elif p.x > W - near:
+ ex, corner = -1, True
+ if corner:
+ c = SimpleNamespace(x=0 if ex > 0 else W, y=0 if ey > 0 else H)
+ return SimpleNamespace(kind="corner", c=c, e=(ex, ey),
+ o=SimpleNamespace(x=c.x + ex * 3, y=c.y + ey * 3),
+ n=(ex * math.sqrt(0.5), ey * math.sqrt(0.5)), spread=0.66)
+ return SimpleNamespace(kind="edge", o=SimpleNamespace(x=p.x, y=p.y), n=(ex, ey), spread=1.34)
+
+
+def boundary(ctx, s, f, length, a, colour, width):
+ if a <= 0.01 or length <= 0.5 or f.kind == "point":
+ return
+ W, H = s.screen.w, s.screen.h
+ ctx.beginPath()
+ if f.kind == "notch":
+ n, d = s.notch, 1.6
+ ctx.moveTo(n.x - d, n.y)
+ ctx.lineTo(n.x - d, n.y + n.h - n.r)
+ ctx.quadraticCurveTo(n.x - d, n.y + n.h + d, n.x + n.r, n.y + n.h + d)
+ ctx.lineTo(n.x + n.w - n.r, n.y + n.h + d)
+ ctx.quadraticCurveTo(n.x + n.w + d, n.y + n.h + d, n.x + n.w + d, n.y + n.h - n.r)
+ ctx.lineTo(n.x + n.w + d, n.y)
+
+ def grad(colour_fn):
+ g = ctx.createLinearGradient(f.o.x - length, 0, f.o.x + length, 0)
+ g.addColorStop(0, colour_fn(0))
+ g.addColorStop(0.5, colour_fn(1))
+ g.addColorStop(1, colour_fn(0))
+ return g
+ elif f.kind == "corner":
+ c, e = f.c, f.e
+ ix, iy = c.x + e[0] * 1, c.y + e[1] * 1
+ ctx.moveTo(c.x + e[0] * length, iy)
+ ctx.lineTo(ix, iy)
+ ctx.lineTo(ix, c.y + e[1] * length)
+
+ def grad(colour_fn):
+ g = ctx.createRadialGradient(c.x, c.y, 0, c.x, c.y, length)
+ g.addColorStop(0, colour_fn(1))
+ g.addColorStop(1, colour_fn(0))
+ return g
+ else:
+ n = f.n
+ t = (-n[1], n[0])
+ if n[0] != 0:
+ b = SimpleNamespace(x=1 if n[0] > 0 else W - 1, y=f.o.y)
+ else:
+ b = SimpleNamespace(x=f.o.x, y=1 if n[1] > 0 else H - 1)
+ x0, y0 = b.x - t[0] * length, b.y - t[1] * length
+ x1, y1 = b.x + t[0] * length, b.y + t[1] * length
+ ctx.moveTo(x0, y0)
+ ctx.lineTo(x1, y1)
+
+ def grad(colour_fn):
+ g = ctx.createLinearGradient(x0, y0, x1, y1)
+ g.addColorStop(0, colour_fn(0))
+ g.addColorStop(0.5, colour_fn(1))
+ g.addColorStop(1, colour_fn(0))
+ return g
+ ctx.lineCap = "round"
+ ctx.lineJoin = "round"
+ ctx.globalCompositeOperation = "source-over"
+ ctx.lineWidth = width + 2
+ ctx.strokeStyle = grad(lambda x: shade(s, x * a))
+ ctx.stroke()
+ glow_mode(ctx, s)
+ ctx.lineWidth = width
+ ctx.strokeStyle = grad(lambda x: rgba(colour, x * a))
+ ctx.stroke()
+
+
+def streak(ctx, s, x0, y0, x1, y1, w, colour, a):
+ if a <= 0.01:
+ return
+ ctx.beginPath()
+ ctx.moveTo(x0, y0)
+ ctx.lineTo(x1, y1)
+ ctx.lineCap = "round"
+ ctx.globalCompositeOperation = "source-over"
+ ctx.strokeStyle = shade(s, a)
+ ctx.lineWidth = w + (1.8 if s.dark else 1.4)
+ ctx.stroke()
+ glow_mode(ctx, s)
+ ctx.strokeStyle = rgba(colour, a)
+ ctx.lineWidth = w
+ ctx.stroke()
+
+
+def glow(ctx, s, x, y, r, colour, a):
+ if a <= 0.01 or r <= 0.3:
+ return
+ if not s.dark:
+ d = ctx.createRadialGradient(x, y, 0, x, y, r * 0.75)
+ d.addColorStop(0, f"rgba(0,0,0,{clamp(0.4 * a):.3f})")
+ d.addColorStop(1, "rgba(0,0,0,0)")
+ ctx.globalCompositeOperation = "source-over"
+ ctx.fillStyle = d
+ ctx.beginPath()
+ ctx.arc(x, y, r * 0.75, 0, TAU)
+ ctx.fill()
+ g = ctx.createRadialGradient(x, y, 0, x, y, r)
+ g.addColorStop(0, rgba(colour, a))
+ g.addColorStop(0.28, rgba(colour, a * 0.5))
+ g.addColorStop(1, rgba(colour, 0))
+ glow_mode(ctx, s)
+ ctx.fillStyle = g
+ ctx.beginPath()
+ ctx.arc(x, y, r, 0, TAU)
+ ctx.fill()
+
+
+def dot(ctx, s, x, y, r, colour, a):
+ if a <= 0.01 or r <= 0.2:
+ return
+ ctx.globalCompositeOperation = "source-over"
+ ctx.fillStyle = shade(s, a)
+ ctx.beginPath()
+ ctx.arc(x, y, r + 1, 0, TAU)
+ ctx.fill()
+ glow_mode(ctx, s)
+ ctx.fillStyle = rgba(colour, a)
+ ctx.beginPath()
+ ctx.arc(x, y, r, 0, TAU)
+ ctx.fill()
+
+
+def crackle(ctx, s, ax, ay, bx, by, seed, colour, a):
+ if a <= 0.01:
+ return
+ dx, dy = bx - ax, by - ay
+ L = math.hypot(dx, dy) or 1
+ nx, ny = -dy / L, dx / L
+ ctx.beginPath()
+ ctx.moveTo(ax, ay)
+ for k in range(1, 7):
+ u = k / 7
+ j = (s.hash(seed * 13 + k) * 2 - 1) * min(14, L * 0.2) * math.sin(math.pi * u)
+ ctx.lineTo(ax + dx * u + nx * j, ay + dy * u + ny * j)
+ ctx.lineTo(bx, by)
+ ctx.lineJoin = "miter"
+ ctx.lineCap = "round"
+ ctx.globalCompositeOperation = "source-over"
+ ctx.strokeStyle = shade(s, a)
+ ctx.lineWidth = 2.8
+ ctx.stroke()
+ glow_mode(ctx, s)
+ ctx.strokeStyle = rgba(colour, a)
+ ctx.lineWidth = 1.1
+ ctx.stroke()
+
+
+def filing(s, f, i, R, p, align):
+ h1, h2, h3, h4 = s.hash(i * 7 + 1), s.hash(i * 7 + 2), s.hash(i * 7 + 3), s.hash(i * 7 + 4)
+ direction = rot(f.n, (h1 * 2 - 1) * f.spread)
+ r0 = R * (0.3 + 0.7 * math.sqrt(h2))
+ r = r0 * (1 - 0.6 * ease_in(p))
+ radial, loose = math.atan2(-direction[1], -direction[0]), h4 * TAU
+ k = clamp(p * 1.8) if align else 1
+ orient = loose + turn(radial, loose) * k + math.sin(p * 29 + i * 1.7) * 0.35 * (1 - k)
+ return SimpleNamespace(x=f.o.x + direction[0] * r, y=f.o.y + direction[1] * r, orient=orient,
+ appear=0.02 + h3 * 0.7, near=1 - r / R)
+
+
+def crawler_at(s, f, side, dist):
+ if f.kind == "notch":
+ n = s.notch
+ x = f.o.x + side * dist
+ cx = clamp(x, n.x - 2.5, n.x + n.w + 2.5)
+ over = abs(x - cx)
+ return SimpleNamespace(x=cx, y=max(1, n.y + n.h + 2.5 - over))
+ if f.kind == "corner":
+ if side > 0:
+ return SimpleNamespace(x=f.c.x + f.e[0] * (dist + 3), y=f.c.y + f.e[1] * 2.5)
+ return SimpleNamespace(x=f.c.x + f.e[0] * 2.5, y=f.c.y + f.e[1] * (dist + 3))
+ t = (-f.n[1], f.n[0])
+ return SimpleNamespace(x=f.o.x + t[0] * side * dist + f.n[0] * 2.5,
+ y=f.o.y + t[1] * side * dist + f.n[1] * 2.5)
+
+
+def make_depart(cfg):
+ def depart(ctx, s):
+ t, pal = s.since, s.palette
+ if t is not None and t >= cfg.departSeconds:
+ return
+ if t is None and s.pressure <= 0:
+ return
+ f = depart_frame(s)
+ if s.reduced:
+ depart_still(ctx, s, f, cfg)
+ return
+ p = s.pressure if t is None else 1
+ tick = 1 - s.tick.age / 0.16 if (t is None and s.tick and s.tick.age < 0.16) else 0
+
+ def length(q):
+ return cfg.len0 + cfg.len1 * q
+
+ if t is None:
+ if cfg.flash:
+ boundary(ctx, s, f, cfg.R * (0.45 + 0.75 * p), (0.2 + 0.55 * p + 0.3 * tick) * clamp(p * 4),
+ heat(s, pal, 0.55 + 0.45 * p), 1.4 + 0.6 * p)
+ for i in range(cfg.N):
+ q = filing(s, f, i, cfg.R, p, cfg.align)
+ vis = clamp((p - q.appear) / 0.1)
+ if vis <= 0:
+ continue
+ pull = tick * 0.16
+ x, y = lerp(q.x, f.o.x, pull), lerp(q.y, f.o.y, pull)
+ l = length(p) * (1 + tick * 0.6)
+ cx, cy = math.cos(q.orient) * l / 2, math.sin(q.orient) * l / 2
+ streak(ctx, s, x - cx, y - cy, x + cx, y + cy, 1 + 0.6 * p,
+ heat(s, pal, 0.2 + 0.45 * p + 0.35 * q.near), vis * (0.35 + 0.65 * p))
+ for j in range(cfg.crawl):
+ side = 1 if j % 2 else -1
+ u = (s.hash(j * 5 + 200) + p * 1.7) % 1
+ a = clamp((p - 0.18) / 0.2) * (0.4 + 0.6 * p) * clamp(u * 5) * clamp((1 - u) * 6)
+ L = cfg.R * 1.3
+ d = L * (1 - u)
+ head, tail = crawler_at(s, f, side, d), crawler_at(s, f, side, d + 7)
+ streak(ctx, s, tail.x, tail.y, head.x, head.y, 1.3, heat(s, pal, 0.8), a)
+ if tick and cfg.arcs:
+ for k in range(2):
+ q = filing(s, f, (s.tick.index * 11 + k * 17) % cfg.N, cfg.R, p, True)
+ crackle(ctx, s, q.x, q.y, f.o.x, f.o.y, s.tick.index * 3 + k, heat(s, pal, 1), tick)
+ glow(ctx, s, f.o.x, f.o.y, cfg.core * (0.35 + 0.65 * p) * (1 + 0.4 * tick),
+ heat(s, pal, 0.6 + 0.4 * p), 0.25 + 0.6 * p)
+ dot(ctx, s, f.o.x, f.o.y, 1.2 + 1.6 * p + tick, heat(s, pal, 1), 0.5 + 0.5 * p)
+ return
+
+ u = clamp(t / cfg.implode)
+ if u < 1:
+ for i in range(cfg.N):
+ q = filing(s, f, i, cfg.R, 1, cfg.align)
+ e1, e0 = ease_in(u), ease_in(u - 0.32)
+ dx, dy = f.sink.x - q.x, f.sink.y - q.y
+ dl = math.hypot(dx, dy) or 1
+ half = length(1) * 0.5 * (1 - u)
+ ax, ay = dx / dl * half, dy / dl * half
+ streak(ctx, s, lerp(q.x, f.sink.x, e0) - ax, lerp(q.y, f.sink.y, e0) - ay,
+ lerp(q.x, f.sink.x, e1) + ax, lerp(q.y, f.sink.y, e1) + ay,
+ 1.3 + 0.9 * u, heat(s, pal, 0.7 + 0.3 * u), 1)
+ for j in range(cfg.crawl):
+ side = 1 if j % 2 else -1
+ d0 = cfg.R * 1.3 * (1 - (s.hash(j * 5 + 200) + 1.7) % 1)
+ head = crawler_at(s, f, side, d0 * (1 - ease_in(u)))
+ tail = crawler_at(s, f, side, d0 * (1 - ease_in(u - 0.35)) + 4)
+ streak(ctx, s, tail.x, tail.y, head.x, head.y, 1.5, heat(s, pal, 0.9), 1 - u * 0.5)
+ if cfg.arcs and t < 0.14:
+ if f.kind == "notch":
+ ends = [crawler_at(s, f, -1, 200), crawler_at(s, f, 1, 200)]
+ else:
+ ends = [crawler_at(s, f, -1, cfg.flash * 0.8), crawler_at(s, f, 1, cfg.flash * 0.8)]
+ for k, e in enumerate(ends):
+ crackle(ctx, s, e.x, e.y, f.o.x, f.o.y, 40 + k, heat(s, pal, 1), 1 - t / 0.14)
+ fade = 1 - t / cfg.departSeconds
+ if cfg.flash:
+ boundary(ctx, s, f, cfg.flash * (1 - ease_out(t / (cfg.departSeconds * 0.85))), fade,
+ heat(s, pal, 1), 2)
+ glow(ctx, s, f.o.x, f.o.y, cfg.core * 1.3 * (1 - ease_in(t / (cfg.implode + 0.1))), heat(s, pal, 1), 1)
+ dot(ctx, s, f.o.x, f.o.y, 3 * fade, heat(s, pal, 1), fade)
+ return depart
+
+
+def spark_pos(src, direction, v, drag, g, tt):
+ d = v / drag * (1 - math.exp(-drag * tt))
+ return SimpleNamespace(x=src.x + direction[0] * d, y=src.y + direction[1] * d + 0.5 * g * tt * tt)
+
+
+def make_arrive(cfg):
+ def arrive(ctx, s):
+ t, pal = s.since, s.palette
+ if t >= cfg.arriveSeconds:
+ return
+ f = arrive_frame(s)
+ if s.reduced:
+ arrive_still(ctx, s, f, cfg)
+ return
+ src = getattr(f, "src", None) or f.o
+ if cfg.flash:
+ boundary(ctx, s, f, 4 + cfg.flash * ease_out(t / 0.2),
+ 0.95 * (1 - clamp(t / (cfg.arriveSeconds * 0.7))), heat(s, pal, 1), 1.8)
+ pv = clamp(t / 0.16)
+ glow(ctx, s, f.o.x, f.o.y, cfg.pop * (0.35 + 0.65 * ease_out(pv)), heat(s, pal, 1), 1 - pv)
+ for i in range(cfg.M):
+ h1, h2, h3, h4 = s.hash(i * 5 + 101), s.hash(i * 5 + 102), s.hash(i * 5 + 103), s.hash(i * 5 + 104)
+ direction = rot(f.n, (h1 * 2 - 1) * f.spread * (0.86 if f.kind == "edge" else 1))
+ v = cfg.V * (0.5 + 0.5 * h2)
+ life = cfg.life * (0.5 + 0.5 * h3)
+ tt = t - h4 * 0.04
+ if tt <= 0:
+ continue
+ if tt < life:
+ k = tt / life
+ head = spark_pos(src, direction, v, cfg.drag, cfg.G, tt)
+ tail = spark_pos(src, direction, v, cfg.drag, cfg.G, max(0, tt - 0.045))
+ flick = 1 if i % 3 else 0.7 + 0.3 * math.cos(tt * 70 + i)
+ streak(ctx, s, tail.x, tail.y, head.x, head.y, 0.9 + 1.1 * (1 - k),
+ heat(s, pal, 1 - k * 0.6), (1 - k) ** 0.45 * flick)
+ if i < cfg.branch:
+ ts = life * 0.42
+ bt = tt - ts
+ bl = life * 0.55
+ if 0 < bt < bl:
+ o = spark_pos(src, direction, v, cfg.drag, cfg.G, ts)
+ d = v / cfg.drag * math.exp(-cfg.drag * ts) * cfg.drag
+ for sgn in (-1, 1):
+ bd = rot(direction, sgn * (0.5 + 0.4 * h4))
+ k = bt / bl
+ head = spark_pos(o, bd, d * 0.45, cfg.drag, cfg.G, bt)
+ tail = spark_pos(o, bd, d * 0.45, cfg.drag, cfg.G, max(0, bt - 0.03))
+ streak(ctx, s, tail.x, tail.y, head.x, head.y, 0.8 + 0.6 * (1 - k),
+ heat(s, pal, 0.9 - k * 0.8), 1 - k)
+ dot(ctx, s, f.o.x, f.o.y, 2.6 * (1 - clamp(t / 0.3)), heat(s, pal, 1), 1 - clamp(t / 0.3))
+ return arrive
+
+
+def still_fan(ctx, s, f, count, r0, r1, pal, alpha_of):
+ for i in range(count):
+ a = alpha_of(i)
+ if a <= 0.01:
+ continue
+ direction = rot(f.n, lerp(-f.spread * 0.92, f.spread * 0.92, 0.5 if count == 1 else i / (count - 1)))
+ k = 0.72 if i % 2 else 1
+ streak(ctx, s, f.o.x + direction[0] * r0, f.o.y + direction[1] * r0,
+ f.o.x + direction[0] * (r0 + (r1 - r0) * k), f.o.y + direction[1] * (r0 + (r1 - r0) * k),
+ 1.6, heat(s, pal, 0.55 if i % 2 else 0.95), a)
+
+
+def depart_still(ctx, s, f, cfg):
+ t, pal = s.since, s.palette
+ p = s.pressure if t is None else 1
+ A = 1 if t is None else 1 - clamp(t / cfg.departSeconds)
+ tick = 1 - s.tick.age / 0.2 if (t is None and s.tick and s.tick.age < 0.2) else 0
+
+ def lit(i):
+ return A * clamp((p - (i % 4) * 0.25) / 0.06) * (0.45 + 0.55 * p)
+
+ if cfg.flash:
+ boundary(ctx, s, f, cfg.R * 0.9, A * (0.2 + 0.6 * p), heat(s, pal, 1), 1.6)
+ still_fan(ctx, s, f, cfg.still, cfg.stillR[0], cfg.stillR[1], pal, lit)
+ glow(ctx, s, f.o.x, f.o.y, cfg.core * 0.7, heat(s, pal, 0.6 + 0.4 * p), A * clamp(0.25 + 0.55 * p + 0.3 * tick))
+ dot(ctx, s, f.o.x, f.o.y, 2.2, heat(s, pal, 1), A * (0.5 + 0.5 * p))
+
+
+def arrive_still(ctx, s, f, cfg):
+ t, pal = s.since, s.palette
+ A = 0.35 + 0.65 * t / 0.08 if t < 0.08 else 1 - clamp((t - 0.08) / (cfg.arriveSeconds - 0.08))
+ if cfg.flash:
+ boundary(ctx, s, f, cfg.flash * 0.6, A * 0.8, heat(s, pal, 1), 1.8)
+ still_fan(ctx, s, f, cfg.still, cfg.stillR[0] + 4, cfg.stillR[1] + 8, pal, lambda i: A)
+ glow(ctx, s, f.o.x, f.o.y, cfg.pop * 0.8, heat(s, pal, 1), A * 0.9)
+ dot(ctx, s, f.o.x, f.o.y, 2.4, heat(s, pal, 1), A)
+
+
+def effect(id_, name, intensity, blurb, depart_cfg, arrive_cfg):
+ cfg = SimpleNamespace(**depart_cfg, **arrive_cfg)
+ return effects.Effect(id_, name, intensity, blurb, make_depart(cfg), make_arrive(cfg),
+ depart_cfg["departSeconds"], arrive_cfg["arriveSeconds"])
+
+
+EFFECTS = [
+ effect(
+ "flint", "Flint", "quiet",
+ "A single hot point at the pointer draws in a few close sparks as you push, snaps them "
+ "through the edge, and a pinch of sparks pops out where you land. Small enough to leave on "
+ "all day.",
+ dict(N=8, R=40, align=False, len0=2, len1=5, crawl=0, arcs=False, flash=0, core=13,
+ implode=0.14, departSeconds=0.4, still=5, stillR=(8, 16)),
+ dict(M=12, V=420, drag=7, G=260, life=0.45, branch=0, pop=11, arriveSeconds=0.45),
+ ),
+ effect(
+ "filings", "Filings", "medium",
+ "Scattered sparks swing round to point at the pointer and creep in like iron filings to a "
+ "magnet, the edge warming beside it; at breakthrough they are sucked through the point, and "
+ "on the other screen the same sparks are thrown back out and fall.",
+ dict(N=24, R=72, align=True, len0=2.5, len1=8, crawl=0, arcs=False, flash=70, core=18,
+ implode=0.2, departSeconds=0.55, still=9, stillR=(12, 26)),
+ dict(M=26, V=500, drag=6.5, G=320, life=0.62, branch=0, pop=20, arriveSeconds=0.65),
+ ),
+ effect(
+ "discharge", "Discharge", "showpiece",
+ "The boundary charges up: sparks crawl along it and forty filings wheel in, with a crackle "
+ "arcing to the pointer at every tick. At breakthrough the whole charge implodes through the "
+ "point with a last arc; where it lands it goes off like a sparkler, stars splitting as they "
+ "fall.",
+ dict(N=40, R=104, align=True, len0=3, len1=11, crawl=8, arcs=True, flash=120, core=26,
+ implode=0.24, departSeconds=0.75, still=13, stillR=(14, 34)),
+ dict(M=30, V=600, drag=6, G=260, life=0.72, branch=9, pop=30, arriveSeconds=0.78),
+ ),
+]
+
+PACKS = {
+ "ember": ("Ember", ["#ffe4ad", "#ffb04a", "#ff6a24", "#d8321a", "#8e1a10"]),
+ "forge": ("Forge", ["#fff4dc", "#ffc15e", "#ff7f2a", "#b8c4d2", "#5d7896"]),
+ "sparkler_gold": ("Sparkler gold", ["#ffffff", "#fff1bf", "#ffd35c", "#f0a531"]),
+}
diff --git a/mac_app/fx_warp.py b/mac_app/fx_warp.py
new file mode 100644
index 0000000..2adb36c
--- /dev/null
+++ b/mac_app/fx_warp.py
@@ -0,0 +1,291 @@
+"""Warp: crossing is travel through a portal, the edge opening as a slot that stretches light and
+the pointer's trail into speed lines, arriving as a streak that decelerates into the pointer.
+"""
+
+import math
+
+import effects
+
+PACKS = {
+ "neon": ("Neon", ["#ff0055", "#00ffcc", "#ffcc00"]),
+ "vaporwave": ("Vaporwave", ["#ff71ce", "#01cdfe", "#05ffa1", "#b967ff", "#fffb96"]),
+ "cyber": ("Cyber", ["#fcee0a", "#00f0ff", "#ff003c"]),
+}
+
+
+def _normal_for_depart(s):
+ nx, ny = 0, 0
+ if s.region.edge == "right":
+ nx = 1
+ elif s.region.edge == "left":
+ nx = -1
+ elif s.region.edge == "top":
+ ny = -1
+ elif s.region.edge == "bottom":
+ ny = 1
+
+ if s.region.kind == "corner":
+ # From the corner's name: the region's edge is the side the other machine is on, which
+ # for a corner push is often the vertical side.
+ corner = getattr(s.region, "corner", "")
+ nx = 1 if "right" in corner else -1
+ ny = -1 if "top" in corner else 1
+ length = math.hypot(nx, ny)
+ nx /= length
+ ny /= length
+ return nx, ny
+
+
+def _normal_for_arrive(s):
+ nx, ny = 0, 0
+ if s.edge == "right":
+ nx = -1
+ elif s.edge == "left":
+ nx = 1
+ elif s.edge == "top":
+ ny = 1
+ elif s.edge == "bottom":
+ ny = -1
+
+ if s.edge in ("left", "right") and (s.point.y < 20 or s.point.y > s.screen.h - 20):
+ ny = 1 if s.point.y < 20 else -1
+ length = math.hypot(nx, ny)
+ nx /= length
+ ny /= length
+ return nx, ny
+
+
+def _draw_slot(ctx, s, p, thickness):
+ r = s.region
+ col = s.palette[0]
+
+ if r.kind == "notch":
+ n = s.notch
+ out = thickness * p
+ ctx.globalAlpha = p * 0.8
+ ctx.fillStyle = col
+ effects.round_rect(ctx, n.x - out, -20, n.w + out * 2, n.h + 20 + out, 14)
+ ctx.fill()
+ ctx.globalAlpha = p * 0.4
+ ctx.fillStyle = "#fff"
+ effects.round_rect(ctx, n.x - out / 2, -20, n.w + out, n.h + 20 + out / 2, 14)
+ ctx.fill()
+ return
+
+ w = thickness * p
+ length = 40 + 120 * p
+ x = y = 0
+
+ if r.kind == "corner":
+ size = 8 + w
+ corner = getattr(r, "corner", "top_right")
+ right, bottom = "right" in corner, "bottom" in corner
+ x0 = s.screen.w - size if right else 0
+ y0 = s.screen.h - size if bottom else 0
+ ctx.globalAlpha = p * 0.8
+ ctx.fillStyle = col
+ ctx.fillRect(x0, y0, size, size)
+ ctx.fillStyle = "#fff"
+ ctx.globalAlpha = p * 0.4
+ ctx.fillRect(s.screen.w - size / 2 if right else 0, s.screen.h - size / 2 if bottom else 0, size / 2, size / 2)
+ return
+
+ ctx.globalAlpha = p * 0.8
+ ctx.fillStyle = col
+ if r.edge == "right":
+ x, y = s.screen.w - w, s.point.y - length / 2
+ ctx.fillRect(x, y, w, length)
+ elif r.edge == "left":
+ x, y = 0, s.point.y - length / 2
+ ctx.fillRect(x, y, w, length)
+ elif r.edge == "top":
+ x, y = s.point.x - length / 2, 0
+ ctx.fillRect(x, y, length, w)
+ elif r.edge == "bottom":
+ x, y = s.point.x - length / 2, s.screen.h - w
+ ctx.fillRect(x, y, length, w)
+
+ ctx.fillStyle = "#fff"
+ ctx.globalAlpha = p * 0.4
+ w = w / 2
+ if r.edge == "right":
+ x, y = s.screen.w - w, s.point.y - length / 2
+ ctx.fillRect(x, y, w, length)
+ elif r.edge == "left":
+ x, y = 0, s.point.y - length / 2
+ ctx.fillRect(x, y, w, length)
+ elif r.edge == "top":
+ x, y = s.point.x - length / 2, 0
+ ctx.fillRect(x, y, length, w)
+ elif r.edge == "bottom":
+ x, y = s.point.x - length / 2, s.screen.h - w
+ ctx.fillRect(x, y, length, w)
+
+
+def _draw_converge(ctx, s, p, max_len, thickness, num_lines, colour):
+ """A switch, away from any edge: the streaks come in from all round and decelerate onto the
+ pointer. Reduce motion holds them still round it and only fades them."""
+ count = max(6, num_lines)
+ ctx.lineCap = "round"
+ for i in range(count):
+ rand = s.hash(i)
+ angle = math.pi * 2 * (i + 0.35 * (rand - 0.5)) / count
+ dx, dy = math.cos(angle), math.sin(angle)
+ if s.reduced:
+ inner, length = 14, max_len * 0.25 * (0.6 + 0.4 * rand)
+ else:
+ inner, length = 12 + max_len * 0.45 * p * p, max_len * 0.45 * p * (0.5 + 0.5 * rand)
+ ctx.globalAlpha = p * (0.5 + 0.5 * rand)
+ ctx.strokeStyle = colour
+ ctx.lineWidth = thickness * (0.5 + 0.5 * rand)
+ ctx.beginPath()
+ ctx.moveTo(s.point.x + dx * (inner + length), s.point.y + dy * (inner + length))
+ ctx.lineTo(s.point.x + dx * inner, s.point.y + dy * inner)
+ ctx.stroke()
+
+
+def _draw_arrival(ctx, s, p, max_len, thickness, num_lines, colour):
+ if s.method == "switch":
+ _draw_converge(ctx, s, p, max_len, thickness, num_lines, colour)
+ return
+ if s.reduced:
+ # A fixed slot along the edge where the pointer came in, so Reduce motion still marks the
+ # landing; the design's lone dot, a few points across, did not.
+ nx, ny = _normal_for_arrive(s)
+ tx, ty = -ny, nx
+ half = 28 + thickness * 2
+ ctx.globalAlpha = p
+ ctx.lineCap = "round"
+ ctx.strokeStyle = "rgba(0,0,0,0.45)" if not s.dark else "rgba(0,0,0,0.25)"
+ ctx.lineWidth = thickness + 3
+ ctx.beginPath()
+ ctx.moveTo(s.point.x - tx * half, s.point.y - ty * half)
+ ctx.lineTo(s.point.x + tx * half, s.point.y + ty * half)
+ ctx.stroke()
+ ctx.strokeStyle = colour
+ ctx.lineWidth = thickness
+ ctx.stroke()
+ ctx.fillStyle = colour
+ ctx.beginPath()
+ ctx.arc(s.point.x + nx * 10, s.point.y + ny * 10, thickness, 0, math.pi * 2)
+ ctx.fill()
+ return
+ nx, ny = _normal_for_arrive(s)
+ dx, dy = nx, ny
+
+ for i in range(num_lines):
+ rand = s.hash(i)
+ offset = (rand - 0.5) * 40
+ ox = dy * offset
+ oy = -dx * offset
+ length = max_len * p * (0.5 + 0.5 * rand)
+
+ ctx.globalAlpha = p * (0.5 + 0.5 * rand)
+ ctx.strokeStyle = colour
+ ctx.lineWidth = thickness * (0.5 + 0.5 * rand)
+ ctx.lineCap = "round"
+ ctx.beginPath()
+ ctx.moveTo(s.point.x + ox, s.point.y + oy)
+ ctx.lineTo(s.point.x + ox + dx * length, s.point.y + oy + dy * length)
+ ctx.stroke()
+
+ ctx.globalAlpha = p
+ ctx.strokeStyle = "#fff"
+ ctx.lineWidth = thickness * 0.5
+ ctx.beginPath()
+ ctx.moveTo(s.point.x, s.point.y)
+ ctx.lineTo(s.point.x + dx * max_len * p, s.point.y + dy * max_len * p)
+ ctx.stroke()
+
+
+def _draw_depart_trails(ctx, s, p, max_len, thickness, num_lines, colour):
+ if s.reduced:
+ return
+ nx, ny = _normal_for_depart(s)
+ dx, dy = -nx, -ny
+ for i in range(num_lines):
+ rand = s.hash(i + 100)
+ offset = (rand - 0.5) * (140 if s.region.kind == "notch" else 60)
+ ox = dy * offset
+ oy = -dx * offset
+ length = max_len * p * (0.5 + 0.5 * rand)
+
+ ctx.globalAlpha = p * (0.5 + 0.5 * rand)
+ ctx.strokeStyle = colour
+ ctx.lineWidth = thickness * rand
+ ctx.lineCap = "round"
+ ctx.beginPath()
+ ctx.moveTo(s.point.x + ox, s.point.y + oy)
+ ctx.lineTo(s.point.x + ox + dx * length, s.point.y + oy + dy * length)
+ ctx.stroke()
+
+
+def _light_slit_depart(ctx, s):
+ p = s.pressure
+ t = s.since
+ if t is not None:
+ p = max(0.0, 1 - (t / 0.4))
+ if p <= 0:
+ return
+ _draw_slot(ctx, s, p, 10)
+ if t is not None:
+ _draw_depart_trails(ctx, s, max(0.0, 1 - t / 0.4), 60, 4, 3, s.palette[0])
+
+
+def _light_slit_arrive(ctx, s):
+ p = max(0.0, 1 - (s.since / 0.4))
+ if p <= 0:
+ return
+ _draw_arrival(ctx, s, p, 60, 4, 3, s.palette[len(s.palette) - 1])
+
+
+def _hyperdrive_depart(ctx, s):
+ p = s.pressure
+ t = s.since
+ if t is not None:
+ p = max(0.0, 1 - (t / 0.6))
+ if p <= 0:
+ return
+ _draw_slot(ctx, s, p, 20)
+ if t is not None:
+ _draw_depart_trails(ctx, s, max(0.0, 1 - t / 0.6), 100, 6, 8, s.palette[1 % len(s.palette)])
+ elif p > 0.1:
+ _draw_depart_trails(ctx, s, p, 40, 2, 4, s.palette[0])
+
+
+def _hyperdrive_arrive(ctx, s):
+ p = max(0.0, 1 - (s.since / 0.6))
+ if p <= 0:
+ return
+ _draw_arrival(ctx, s, p, 100, 6, 8, s.palette[len(s.palette) - 1])
+
+
+def _wormhole_depart(ctx, s):
+ p = s.pressure
+ t = s.since
+ if t is not None:
+ p = max(0.0, 1 - (t / 0.8))
+ if p <= 0:
+ return
+ _draw_slot(ctx, s, p, 32)
+ if t is not None:
+ _draw_depart_trails(ctx, s, max(0.0, 1 - t / 0.8), 160, 8, 15, s.palette[2 % len(s.palette)])
+ elif p > 0.1:
+ _draw_depart_trails(ctx, s, p, 80, 4, 8, s.palette[1 % len(s.palette)])
+
+
+def _wormhole_arrive(ctx, s):
+ p = max(0.0, 1 - (s.since / 0.8))
+ if p <= 0:
+ return
+ _draw_arrival(ctx, s, p, 160, 8, 15, s.palette[len(s.palette) - 1])
+
+
+EFFECTS = [
+ effects.Effect("light_slit", "Light slit", "quiet", "A subtle slit opens, pulling in faint trails.",
+ _light_slit_depart, _light_slit_arrive, 0.4, 0.4),
+ effects.Effect("hyperdrive", "Hyperdrive", "medium", "Speed lines accelerate towards the portal.",
+ _hyperdrive_depart, _hyperdrive_arrive, 0.6, 0.6),
+ effects.Effect("wormhole", "Wormhole", "showpiece", "A dynamic stretching grid of light.",
+ _wormhole_depart, _wormhole_arrive, 0.8, 0.8),
+]
diff --git a/mac_app/gestures.py b/mac_app/gestures.py
index 185b77e..0f64d0a 100644
--- a/mac_app/gestures.py
+++ b/mac_app/gestures.py
@@ -2,8 +2,7 @@
Two numberings share the values 29-32 and must not be confused:
-At the CGEvent tap (bridge.py), measured on macOS 26.6.2 and documented in
-docs/gestures-scope-06-09-2026.md:
+At the CGEvent tap (bridge.py), measured on macOS 26.6.2:
29 Gesture -- everything two-finger, discriminated by field 110
30 DockControl -- a three/four-finger system swipe or thumb-and-three
diff --git a/mac_app/input_injector_mac.py b/mac_app/input_injector_mac.py
index 5727e3d..f4d1057 100644
--- a/mac_app/input_injector_mac.py
+++ b/mac_app/input_injector_mac.py
@@ -8,9 +8,9 @@ nothing is translated on arrival.
Every event posted from here carries INJECTED_MARK in its source user data,
which is how bridge.py's event tap tells Beamer's own injection apart from
-Toby's hands on the Mac: without that the tap would read a pointer the PC is
-driving as a push against the Mac's crossing edge and switch input straight
-back.
+a real hand on the Mac's own keyboard or trackpad: without that the tap
+would read a pointer the PC is driving as a push against the Mac's crossing
+edge and switch input straight back.
Quartz is imported at module level and guarded the same way clipboard_mac
guards AppKit, so this module stays importable, and its behaviour fakeable,
diff --git a/mac_app/key_codes.py b/mac_app/key_codes.py
index 313beb0..51e0c76 100644
--- a/mac_app/key_codes.py
+++ b/mac_app/key_codes.py
@@ -133,3 +133,13 @@ KEY_TITLES = {
def key_title(name):
return KEY_TITLES.get(name, name.replace("_", " ").title())
+
+
+# The symbol printed on a Mac's modifier keys, for a key drawn as a cap.
+KEY_SYMBOLS = {"alt": "⌥", "cmd": "⌘", "ctrl": "⌃", "shift": "⇧", "caps_lock": "⇪"}
+
+
+def key_cap(name):
+ """A key as its cap reads: the modifier's symbol, then its name ("⌥ Right Option")."""
+ symbol = KEY_SYMBOLS.get(name[:-2] if name.endswith("_r") else name)
+ return f"{symbol} {key_title(name)}" if symbol else key_title(name)
diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.py
index 522b9fc..af33cc3 100644
--- a/mac_app/kvm_bridge_app.py
+++ b/mac_app/kvm_bridge_app.py
@@ -23,11 +23,17 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import config as config_module
import crossing
+import return_edge
+import desktop_mac
+import effects
+import effects_overlay
import gestures
import ignored_titles
import keyboard_layout
import notch_beam
import previews
+import diagram
+import motion
from notch_beam import NotchBeam
from notch_island import NotchIsland
from bridge import _GestureEventView
@@ -35,6 +41,7 @@ from key_codes import KEY_NAME_TO_CODE
import link_state
import login_item
import pages
+import updates
import protocol
import pairing
from settings_store import (
@@ -42,7 +49,6 @@ from settings_store import (
SettingsStore,
config_to_raw,
editable_default_config,
- migrate_legacy_config,
)
import theme
from wake import WakingController, lookup_mac
@@ -112,8 +118,8 @@ def configure_logging():
pass
# The handlers go on the root logger, not "Beamer": the shared modules --
# receiver, return_edge, pairing -- log under their own names, and with
- # the handlers on "Beamer" everything the PC's input did on this Mac went
- # nowhere, which left the 23-09-2026 stranded mouse with no record here.
+ # the handlers on "Beamer" everything the PC's input did on this Mac would
+ # go nowhere, leaving a stranded mouse with no record to diagnose it by.
root = logging.getLogger()
root.setLevel(logging.INFO)
root.handlers.clear()
@@ -329,12 +335,29 @@ def notch_x_range():
return None
+def menu_bar_height(display):
+ """The height in points of the menu bar across the top of `display`, a Quartz (left, top,
+ right, bottom), or 0 where it has none or hides itself: the gap between the screen's top and
+ its visible frame's, which the Dock never takes."""
+ screens = AppKit.NSScreen.screens()
+ if not screens or display is None:
+ return 0.0
+ left, top, _right, _bottom = display
+ primary_height = screens[0].frame().size.height
+ for screen in screens:
+ frame, visible = screen.frame(), screen.visibleFrame()
+ screen_top = frame.origin.y + frame.size.height
+ if abs(frame.origin.x - left) < 1 and abs(primary_height - screen_top - top) < 1:
+ return max(0.0, screen_top - (visible.origin.y + visible.size.height))
+ return 0.0
+
+
def full_screen_app():
"""The frontmost app's name while it is full screen, else None.
The signal that works is Accessibility's `AXFullScreen` on the frontmost app's focused
window. Beamer already holds Accessibility for its event tap, so this costs no new
- permission. Measured 10-09-2026 against Chrome driven by the OS's own Enter Full Screen
+ permission. Verified against Chrome driven by the OS's own Enter Full Screen
shortcut: False windowed, True full screen, False again on leaving.
⚠ Three plausible signals were measured and do NOT work, so nobody should try them again:
@@ -428,15 +451,16 @@ class Haptics:
self.performer = None
self.logger.exception("haptic feedback unavailable")
- def tick(self, feel="medium"):
- """`feel` is crossing.haptic_feel: light, medium or firm, macOS's three patterns."""
- self._perform({
- "light": AppKit.NSHapticFeedbackPatternGeneric,
- "firm": AppKit.NSHapticFeedbackPatternLevelChange,
- }.get(feel, AppKit.NSHapticFeedbackPatternAlignment))
+ def tick(self):
+ """One click of the push. macOS offers three patterns that differ in meaning, not
+ strength, and no intensity at all; level change is the one for discrete steps of pressure.
+ Nothing is felt unless a finger is on the trackpad at that moment."""
+ self._perform(AppKit.NSHapticFeedbackPatternLevelChange)
def thud(self):
+ """The breakthrough: two ticks close together, the one way to tell it from a step."""
self._perform(AppKit.NSHapticFeedbackPatternLevelChange)
+ AppHelper.callLater(0.06, self._perform, AppKit.NSHapticFeedbackPatternLevelChange)
def _perform(self, pattern):
if self.performer is None:
@@ -462,9 +486,16 @@ class EdgeGlow:
then redraws at 30Hz until both the pressure and the flash have faded, since nothing
arrives from the tap once the push stops. Any failure disables the glow for the run."""
+ dark_appearance = staticmethod(notch_beam.dark_appearance)
+
BAND_MAX = 18.0
FLASH_SECONDS = 0.18
PREVIEW_SECONDS = 0.6
+ # How far a corner's light reaches along each of its two walls.
+ CORNER_ARM = 200.0
+ # Over how much of its length a strip shorter than its display's edge, a third of it, fades in and
+ # out at each end, rather than stopping dead where the strip does.
+ TAPER = 72.0
def __init__(self, controller, logger):
self.controller = controller
@@ -472,6 +503,9 @@ class EdgeGlow:
self.panel = None
self.fill = None
self.comet = None
+ # A corner's second wall, and each wall's fade along it, used only in a corner.
+ self.side = None
+ self.masks = None
self.visible = False
self.disabled = False
self.mac_edge = None
@@ -482,6 +516,8 @@ class EdgeGlow:
self.drawn_at = None
self.preview_level = 0.0
self.preview_until = 0.0
+ # The pressure of a push home while the PC drives, which the Mac's own engine never sees.
+ self.level_now = None
self.timer = rumps.Timer(self._tick, 1 / 30)
def update(self, kind, step):
@@ -495,8 +531,36 @@ class EdgeGlow:
return
elif not self.visible:
self.centre = -notch_beam.EDGE_COMET / 2.0
+ self.level_now = None
self.mac_edge = step.mac_edge
- self.region = step.region
+ self.region = effects_overlay.strip_on_display(step.region, step.pin,
+ self.controller._current_desktop_bounds())
+ self._draw()
+ except Exception:
+ self._fail()
+
+ def driven(self, edge, pressure, crossed, cursor, corner=None):
+ """The PC is driving this Mac and pushing at the way home through `edge`, or into `corner`,
+ the pointer at `cursor`. The receiver reports pressure per movement, so it drains here at
+ the engine's own rate, as the PC's glow drains the Mac's push through it."""
+ if self.disabled:
+ return
+ try:
+ now = time.monotonic()
+ box = self.controller._current_desktop_bounds()
+ if crossed:
+ self.flash_at = now
+ self.finish = 1.0
+ self.level_now = lambda: 0.0
+ else:
+ if not self.visible:
+ self.centre = -notch_beam.EDGE_COMET / 2.0
+ level = float(pressure)
+ self.level_now = lambda: max(0.0, level - (time.monotonic() - now) / crossing.DECAY_S)
+ self.mac_edge = edge
+ display = effects_overlay.display_at(cursor, box)
+ self.region = (effects_overlay.corner_box(corner, display) if corner is not None
+ else crossing.CrossingEngine._strip(edge, display))
self._draw()
except Exception:
self._fail()
@@ -539,19 +603,20 @@ class EdgeGlow:
self.drawn_at = now
feel = self.controller.cfg.crossing
beam = feel["glow_style"] == "beam"
- level = self.controller.crossing_pressure_now()
+ pace = effects.pace(feel.get("effect_length"))
+ level = (self.level_now or self.controller.crossing_pressure_now)()
if now < self.preview_until:
level = max(level, self.preview_level)
flash = 0.0
if self.flash_at is not None:
- flash = max(0.0, 1.0 - (now - self.flash_at) / self.FLASH_SECONDS)
+ flash = max(0.0, 1.0 - (now - self.flash_at) / (self.FLASH_SECONDS * pace))
if flash <= 0.0:
self.flash_at = None
comet = notch_beam.EDGE_COMET
if self.finish > 0.0:
# Run on off the end of the edge instead of stopping, and never wrap back to the start.
- self.centre = min(1.0 + comet, self.centre + elapsed / notch_beam.EDGE_FINISH_TRAVERSE_S)
- self.finish = max(0.0, self.finish - elapsed / notch_beam.EDGE_FINISH_S)
+ self.centre = min(1.0 + comet, self.centre + elapsed / (notch_beam.EDGE_FINISH_TRAVERSE_S * pace))
+ self.finish = max(0.0, self.finish - elapsed / (notch_beam.EDGE_FINISH_S * pace))
elif level > 0.0:
self.centre += elapsed / notch_beam.edge_traverse_seconds(level)
if self.centre > 1.0 + comet / 2.0:
@@ -565,6 +630,15 @@ class EdgeGlow:
self._ensure_panel()
strength = max(level, flash, lingering)
band = 3.0 + 3.0 * strength if beam else 2.0 + self.BAND_MAX * strength
+ if self._corner() is not None:
+ self._draw_corner(feel, beam, band, level, flash, strength)
+ return
+ if self.side is not None:
+ self.side.setHidden_(True)
+ if self.mac_edge == "top":
+ x, y, width, height = self.region
+ band = self._top_band(band, beam, effects_overlay.display_at(
+ (x + width / 2.0, y + height / 2.0), self.controller._current_desktop_bounds()))
self.panel.setFrame_display_(self._band_frame(band), False)
# Colour runs along the edge: top to bottom on a side, left to right along the top or bottom.
start, end = ((0.5, 1.0), (0.5, 0.0)) if self.mac_edge in ("left", "right") else ((0.0, 0.5), (1.0, 0.5))
@@ -576,16 +650,24 @@ class EdgeGlow:
layer.setFrame_(bounds)
layer.setStartPoint_(start)
layer.setEndPoint_(end)
- self.fill.setColors_(notch_beam.palette_colours(feel["glow_colour"]))
+ self.fill.setColors_(notch_beam.palette_colours(feel["glow_colour"], dark=self.dark_appearance()))
+ fade = self._taper()
+ ends = (lambda at: 1.0) if fade is None else (lambda at: min(1.0, at / fade, (1.0 - at) / fade))
if beam:
stops = [index / 24 for index in range(25)]
self.comet.setLocations_(stops)
self.comet.setColors_([
- AppKit.NSColor.colorWithWhite_alpha_(1.0, notch_beam.edge_comet_alpha(at, self.centre, flash)).CGColor()
+ AppKit.NSColor.colorWithWhite_alpha_(
+ 1.0, notch_beam.edge_comet_alpha(at, self.centre, flash) * ends(at)).CGColor()
for at in stops
])
self.fill.setMask_(self.comet)
self.fill.setOpacity_(min(1.0, strength))
+ elif fade is not None:
+ self.comet.setLocations_([0.0, fade, 1.0 - fade, 1.0])
+ self.comet.setColors_([AppKit.NSColor.colorWithWhite_alpha_(1.0, a).CGColor() for a in (0.0, 1.0, 1.0, 0.0)])
+ self.fill.setMask_(self.comet)
+ self.fill.setOpacity_(min(1.0, 0.3 + 0.7 * level + 0.6 * flash))
else:
self.fill.setMask_(None)
self.fill.setOpacity_(min(1.0, 0.3 + 0.7 * level + 0.6 * flash))
@@ -597,20 +679,108 @@ class EdgeGlow:
if not getattr(self.timer, "is_alive", lambda: False)():
self.timer.start()
+ def _taper(self):
+ """The fraction of the strip each end fades over when it is shorter than its display's edge,
+ as a third of it is, else None."""
+ box = self.controller._current_desktop_bounds()
+ if box is None or self.region is None:
+ return None
+ x, y, width, height = self.region
+ left, top, right, bottom = effects_overlay.display_at((x + width / 2.0, y + height / 2.0), box)
+ length, full = (height, bottom - top) if self.mac_edge in ("left", "right") else (width, right - left)
+ if length <= 0 or length >= full - 2:
+ return None
+ return min(0.25, self.TAPER / length)
+
+ def _corner(self):
+ """(corner name, the display's (left, top, right, bottom)) for a push into a corner's box,
+ else None."""
+ x, y, width, height = self.region
+ if width > crossing.CORNER_PX or height > crossing.CORNER_PX:
+ return None
+ box = self.controller._current_desktop_bounds()
+ if box is None:
+ return None
+ display = effects_overlay.display_at((x + width / 2.0, y + height / 2.0), box)
+ return effects_overlay.corner_name(self.region, display), display
+
+ def _top_band(self, band, beam, display):
+ """How deep the glow reaches down from the top of `display`. Over a menu bar it is scaled
+ to fill the bar at full strength: the bar is about twice the band, so at the band's own
+ depth it lit only the bar's top half, under the status items and the clock, and a corner's
+ top arm read as a faint stripe beside the full side arm. The beam is a line and stays one."""
+ bar = menu_bar_height(display)
+ full = 2.0 + self.BAND_MAX
+ if beam or bar <= full:
+ return band
+ return band * bar / full
+
+ def _draw_corner(self, feel, beam, band, level, flash, strength):
+ """The band along both of the corner's walls, brightest where they meet and fading out along
+ each, so it reads as the corner rather than two edges; the beam's comet runs in along the top
+ or bottom wall and out along the side. One gradient layer per wall, each masked by its fade."""
+ name, (left, top, right, bottom) = self._corner()
+ vertical, horizontal = name.split("_")
+ arm = min(self.CORNER_ARM, right - left, bottom - top)
+ x = left if horizontal == "left" else right - arm
+ y = top if vertical == "top" else bottom - arm
+ primary_height = AppKit.NSScreen.screens()[0].frame().size.height
+ self.panel.setFrame_display_(AppKit.NSMakeRect(x, primary_height - (y + arm), arm, arm), False)
+ view = self.panel.contentView()
+ if self.side is None:
+ self.side = Quartz.CAGradientLayer.layer()
+ view.layer().addSublayer_(self.side)
+ self.masks = (Quartz.CAGradientLayer.layer(), Quartz.CAGradientLayer.layer())
+ colours = notch_beam.palette_colours(feel["glow_colour"], dark=self.dark_appearance())
+ stops = [index / 24 for index in range(25)]
+ fade = lambda u: max(0.0, 1.0 - u) ** 1.4
+ # AppKit's layer space runs up from the bottom; u runs from the corner outward.
+ at_top = vertical == "top"
+ across = self._top_band(band, beam, (left, top, right, bottom)) if at_top else band
+ walls = (
+ (self.fill, self.masks[0], ((0.0, arm - across) if at_top else (0.0, 0.0), (arm, across)),
+ ((1.0, 0.5), (0.0, 0.5)) if horizontal == "right" else ((0.0, 0.5), (1.0, 0.5)),
+ lambda u: 0.5 * (1.0 - u)),
+ (self.side, self.masks[1], ((arm - band, 0.0) if horizontal == "right" else (0.0, 0.0), (band, arm)),
+ ((0.5, 1.0), (0.5, 0.0)) if at_top else ((0.5, 0.0), (0.5, 1.0)),
+ lambda u: 0.5 + 0.5 * u),
+ )
+ Quartz.CATransaction.begin()
+ Quartz.CATransaction.setDisableActions_(True)
+ try:
+ for layer, mask, frame, (start, end), path in walls:
+ layer.setHidden_(False)
+ layer.setFrame_(frame)
+ layer.setStartPoint_(start)
+ layer.setEndPoint_(end)
+ layer.setColors_(colours)
+ mask.setFrame_(((0.0, 0.0), frame[1]))
+ mask.setStartPoint_(start)
+ mask.setEndPoint_(end)
+ mask.setLocations_(stops)
+ mask.setColors_([
+ AppKit.NSColor.colorWithWhite_alpha_(
+ 1.0, fade(u) * (notch_beam.edge_comet_alpha(path(u), self.centre, flash) if beam else 1.0)
+ ).CGColor()
+ for u in stops
+ ])
+ layer.setMask_(mask)
+ layer.setOpacity_(min(1.0, strength) if beam else min(1.0, 0.3 + 0.7 * level + 0.6 * flash))
+ finally:
+ Quartz.CATransaction.commit()
+ if not self.visible:
+ self.panel.orderFrontRegardless()
+ self.visible = True
+ if not getattr(self.timer, "is_alive", lambda: False)():
+ self.timer.start()
+
def _band_frame(self, band):
"""The band grows inward from the strip the engine reported. Quartz rects are top-left
origin and AppKit frames bottom-left; the flip is about the primary screen's height,
which is exact for every arrangement because every screen is placed relative to it."""
x, y, width, height = self.region
edge = self.mac_edge
- if width <= crossing.CORNER_PX and height <= crossing.CORNER_PX:
- # A corner box: grow it inward on both axes.
- size = crossing.CORNER_PX + band
- top = self.controller._current_desktop_bounds()[1]
- x = x if edge == "left" else x + width - size
- y = y if y <= top else y + height - size
- width = height = size
- elif edge == "right":
+ if edge == "right":
x, width = x + width - band, band
elif edge == "left":
width = band
@@ -758,6 +928,8 @@ class ControlWindow(AppKit.NSObject):
self.controller = controller
self.settings_store = settings_store
self.logger = logger
+ # Before anything is built: every control takes its colours from the palette in use.
+ theme.set_dark(theme.wants_dark(controller.cfg.appearance, theme.system_dark()))
# Set by TrayApp once it exists: the listener for the PC's input, and
# the second way an arrangement changed here can reach the PC.
self.windows_input = None
@@ -769,6 +941,7 @@ class ControlWindow(AppKit.NSObject):
self.granted_at_launch = accessibility_granted() and input_monitoring_granted()
# Set by TrayApp: the beacon listener whose PCs the Pair module lists.
self.discovery = None
+ self.update_checker = None
self._pcs = []
self._pcs_key = None
self.chosen_pc = None
@@ -798,23 +971,26 @@ class ControlWindow(AppKit.NSObject):
self.window.setReleasedWhenClosed_(False)
self.window.setDelegate_(self)
self.window.setContentMinSize_(AppKit.NSMakeSize(*theme.MIN_WINDOW))
- # Vernier is dark only: the window pins to the palette rather than following the Mac's
- # appearance, and the transparent title bar takes the window's own ground.
- self.window.setAppearance_(AppKit.NSAppearance.appearanceNamed_(AppKit.NSAppearanceNameDarkAqua))
+ # The window always carries the palette's own appearance, never nil: the title bar's
+ # buttons and text then match the palette whatever the Mac is set to, and the transparent
+ # title bar takes the window's ground.
+ self.window.setAppearance_(theme.appearance_named(theme.is_dark()))
self.window.setBackgroundColor_(theme.colour("ground"))
self.window.setTitlebarAppearsTransparent_(True)
self.window.center()
content = self.window.contentView()
content.setWantsLayer_(True)
- content.layer().setBackgroundColor_(theme.colour("ground").CGColor())
+ theme.tint(content.layer(), background="ground")
+ self.appearance_watch = theme.AppearanceWatch.alloc().initWithCallback_(lambda: self._apply_appearance())
top = widgets.hairline()
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",
+ # Words rather than the address, which wraps mid-path at the sidebar's narrowest; the
+ # address is in the tooltip.
+ footer_text=f"Beamer {VERSION}\nBeamer's website",
+ footer_label="Open Beamer's website, kalkmancode.co.uk/beamer",
on_footer=self._open_beamer_site,
)
divider = widgets.box("rule")
@@ -860,12 +1036,11 @@ class ControlWindow(AppKit.NSObject):
"crossing": self._crossing_page,
"design": self._design_page,
"keyboard": self._keyboard_page,
- "pairing": self._pairing_page,
"connection": self._connection_page,
"permissions": self._permissions_page,
}
for key, name, _symbol, purpose in pages.PAGES:
- scroll, body = self._page(name, purpose)
+ scroll, body = self._page(name, purpose, pages.SCOPE.get(key))
host.addSubview_(scroll)
widgets.pin(scroll, host)
scroll.setHidden_(True)
@@ -887,15 +1062,13 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _apply_width(self, width):
- """Two layouts, not a continuous reflow. Wide, the Overview's two controls sit side by
- side and Pairing puts the PC list beside the code; narrow, both stack and the large
- figures step down a size."""
+ """Two layouts, not a continuous reflow. Wide, Pairing puts the PC list beside the code;
+ narrow, it stacks and the large figures step down a size."""
wide = width >= WIDE_WIDTH
if wide == self.wide:
return
self.wide = wide
narrow = not wide
- self.daily.arrange([[(0, 1), (1, 1)]] if wide else [[(0, 1)], [(1, 1)]], 2 if wide else 1)
top, leading, bottom, trailing = theme.PAGE_PADDING_NARROW if narrow else theme.PAGE_PADDING
for constraints in self.page_paddings:
for constraint, constant in zip(constraints, (top, leading, bottom, trailing)):
@@ -903,7 +1076,7 @@ class ControlWindow(AppKit.NSObject):
for title in self.page_titles:
title.set(size=theme.PAGE_TITLE_NARROW if narrow else theme.PAGE_TITLE)
self.state_word.set(size=theme.TYPE["status_word_narrow" if narrow else "status_word"])
- for readout in (self.round_trip, self.resistance_readout, self.peer):
+ for readout in (self.round_trip, self.peer):
readout.set_narrow(narrow)
numeral = theme.TYPE["numeral_narrow" if narrow else "numeral"]
self.resistance_numeral.set(size=numeral)
@@ -927,10 +1100,12 @@ 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._say(pages.footer(key))
+ # Both recorders listen application-wide; left armed, they would take the first key typed on
+ # another page.
+ if key != "crossing":
self.key_recorder.cancel()
+ if key != "keyboard":
self.ignored_recorder.cancel()
self._run_previews()
@@ -947,6 +1122,7 @@ class ControlWindow(AppKit.NSObject):
if self.page == "design" and self.window.isVisible() and self.glow_box.value:
self.previews.start()
else:
+ self.tile_hover.stop()
self.previews.stop()
def showPage_(self, sender):
@@ -956,6 +1132,8 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _load(self, raw):
self.host_field.setStringValue_(str(raw["host"]))
+ self.host_secret.setStringValue_(str(raw["host"]))
+ self._show_host_field()
self.port_field.setStringValue_(str(raw["port"]))
self.token_field.setStringValue_(str(raw["auth_token"]))
self.token_plain.setStringValue_(str(raw["auth_token"]))
@@ -966,21 +1144,33 @@ class ControlWindow(AppKit.NSObject):
self.style_select.value = raw["trigger_style"]
self.double_tap_ruler.value = raw["double_tap_ms"]
self.double_tap_numeral.set(str(raw["double_tap_ms"]))
+ self.pointer_ruler.value = round(raw["pointer_speed"] * 100)
+ self.scroll_ruler.value = round(raw["scroll_speed"] * 100)
+ self.pointer_numeral.set(str(self.pointer_ruler.value))
+ self.scroll_numeral.set(str(self.scroll_ruler.value))
+ self.reverse_scroll_box.value = raw["reverse_scroll"]
+ self.appearance_select.value = raw["appearance"]
+ self._apply_appearance(raw["appearance"])
+ self.updates_switch.value = raw["check_updates"]
self.modifier_select.value = raw["key_map"] if isinstance(raw["key_map"], str) else "custom"
crossing_raw = raw["crossing"]
for name, tile in self.method_boxes.items():
tile.value = name in crossing_raw["methods"]
+ for name, tile in self.part_boxes.items():
+ tile.value = name in crossing_raw["edge_parts"]
self.edge_select.value = crossing_raw["edge"]
self.corner_select.value = crossing_raw["corner"]
self.resistance_ruler.value = crossing_raw["resistance_px"]
self.haptics_box.value = crossing_raw["haptics"]
self.glow_box.value = crossing_raw["glow"]
+ self.landing_box.value = crossing_raw["shortcut_arrival"]
+ self.switch_style_select.value = crossing_raw["shortcut_arrival_style"]
self.dragging_box.value = crossing_raw["block_while_dragging"]
self.notch_style_select.value = crossing_raw["notch_style"]
self.notch_after_select.value = crossing_raw["notch_after_ms"]
- self.tick_feel_select.value = crossing_raw["haptic_feel"]
self.tick_steps_select.value = crossing_raw["haptic_steps"]
self.glow_style_select.value = crossing_raw["glow_style"]
+ self.length_select.value = crossing_raw.get("effect_length", "normal")
self.glow_colour_select.value = crossing_raw["glow_colour"]
self._reflect()
@@ -988,21 +1178,90 @@ class ControlWindow(AppKit.NSObject):
def _reflect(self, *_ignored):
"""Enables each control only when the setting it edits is in play, and keeps the figures
beside the rulers in step with them."""
- self.edge_select.set_enabled(self.method_boxes["edge"].value)
- self.corner_select.set_enabled(self.method_boxes["corner"].value)
+ methods = [name for name, tile in self.method_boxes.items() if tile.value]
+ rows = pages.crossing_rows(methods)
+ for key, view in (("edge", self.edge_row), ("parts", self.parts_row), ("corner", self.corner_row),
+ ("dragging", self.dragging_box.view), ("resistance", self.resistance_module.view),
+ ("shortcut", self.shortcut_module.view)):
+ motion.set_hidden(view, not rows[key])
+ if not rows["shortcut"]:
+ # Hidden, an armed recorder would still take the next key typed anywhere on the page.
+ self.key_recorder.cancel()
+ for name, label in pages.part_names(self.edge_select.value).items():
+ self.part_boxes[name].name.set(label)
notch = self.method_boxes["notch"]
notch.set_enabled(self.has_notch)
+ self._show_arrangement(methods)
+ motion.set_hidden(self.edge_note.view, not pages.notch_or_corner_only(methods))
haptics, glow = self.haptics_box.value, self.glow_box.value
- for control in (self.tick_feel_select, self.tick_steps_select, self.try_button):
+ for control in (self.tick_steps_select, self.try_button):
control.set_enabled(haptics)
- for control in (self.notch_style_select, self.notch_after_select, self.glow_style_select, self.glow_colour_select):
- control.set_enabled(glow)
+ # Off, the look of crossing cannot apply, so its modules go rather than sit faded a screen
+ # each, and the landing plays through the same animations; the note under the switch
+ # says crossing still works.
+ for view in (self.landing_row, self.style_module.view, self.colour_module.view):
+ motion.set_hidden(view, not glow)
+ style = self.glow_style_select.value
+ # Without the effects, today's glow and notch styles draw whatever is chosen.
+ notch_applies = pages.notch_style_applies(style) or not self.effects_ready
+ if not self._place_chosen:
+ # Until a place is picked here, the tiles show where the pointer actually crosses.
+ self.place = pages.preview_place(methods)
+ self.effect_method_select.value = self.place
+ place = self.place
+ switching = glow and self.landing_box.value
+ motion.set_hidden(self.style_for_row, not switching)
+ mode = self.style_for_select.value if switching else "crossing"
+ # One set of tiles gives way before the other comes in; both at once would double the
+ # page's height for the length of the fade.
+ showing, leaving = (
+ (self.switch_styles_box, self.crossing_styles_box) if mode == "switch"
+ else (self.crossing_styles_box, self.switch_styles_box)
+ )
+ if not motion.heading(leaving):
+ motion.set_hidden(leaving, True, done=lambda: motion.set_hidden(showing, False))
+ elif not motion.moving(leaving):
+ motion.set_hidden(showing, False)
+ motion.set_hidden(self.effect_method_view, mode == "switch")
+ motion.set_hidden(self.place_note.view, mode == "switch" or not self.place_note_text(style, place, methods))
+ self.place_note.set(self.place_note_text(style, place, methods))
+ motion.set_hidden(self.notch_row, not (mode == "crossing" and place == "notch" and notch_applies))
+ for stack, still, screens in self.classic_pictures:
+ stack.show(screens.get(self.notch_style_select.value, screens["beam"]) if place == "notch" else still)
+ colour = self.glow_colour_select.value
+ # Every still redraws, cross-fading, for a new colour, place or length.
+ look = (colour, place, self.length_select.value)
+ if self._look is not None and look != self._look:
+ for still in self.effect_stills:
+ motion.cross_fade(still)
+ self._look = look
+ if mode == "switch":
+ choice = self.switch_style_select.value or "match"
+ fx = effects.switch_effect(choice, style or "glow")
+ prefix = "Same as crossing: " if choice == "match" else ""
+ self.effect_name.set(f"{prefix}{fx.name}")
+ else:
+ fx = effects.preview_effect(style) if self.effects_ready else effects.CLASSIC.get(style)
+ if fx is not None:
+ self.effect_name.set(f"{fx.name}, {pages.INTENSITIES.get(fx.intensity, fx.intensity).lower()}")
+ motion.set_hidden(self.chosen_box, fx is None)
+ if fx is not None:
+ self.effect_blurb.set(fx.blurb)
+ # Drawing every still is tens of milliseconds, so only what they show redraws them: the
+ # colour, the place, the length, the palette, and for Same as crossing the crossing style.
+ stills = (colour, style, place, self.length_select.value, theme.is_dark())
+ if stills != self._stills:
+ self._stills = stills
+ for still in self.effect_stills:
+ still.setNeedsDisplay_(True)
+ self.previews.repaint()
self.tick_note.set(
{
- "quarters": "A tick at a quarter, half and three quarters of the push, then a firmer one as the pointer goes through.",
- "halves": "One tick halfway through the push, then a firmer one as the pointer goes through.",
- "breakthrough": "Nothing on the way in, then one firm tick as the pointer goes through.",
+ "quarters": "A tick at a quarter, half and three quarters of the push, then a double tick as the pointer goes through.",
+ "halves": "One tick halfway through the push, then a double tick as the pointer goes through.",
+ "breakthrough": "Nothing on the way in, then a double tick as the pointer goes through.",
}.get(self.tick_steps_select.value, "")
+ + " macOS plays them only while a finger is on the trackpad, so press and hold Try it."
if haptics
else "Off: the trackpad stays still while you push."
)
@@ -1010,7 +1269,6 @@ class ControlWindow(AppKit.NSObject):
self.notch_note.set(
f"Once the pointer is through to Windows the notch keeps playing for {after:g} seconds, so the "
"animation finishes instead of cutting off."
- + ("" if self.has_notch else " There is no notch at the top of the desktop right now, so nothing plays there.")
)
self._run_previews()
notch_range = self.controller.notch_range
@@ -1020,8 +1278,7 @@ class ControlWindow(AppKit.NSObject):
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)
+ motion.set_hidden(self.double_tap_head, hold)
self.style_hint.set(
"Input is on Windows for as long as the key is held."
if hold
@@ -1029,21 +1286,35 @@ class ControlWindow(AppKit.NSObject):
)
resistance = self.resistance_ruler.value
self.resistance_numeral.set(str(resistance))
- self.resistance_readout.value.set(str(resistance))
- self.resistance_scale.fraction = min(1.0, max(0.0, resistance / 500.0))
- self.resistance_scale.setNeedsDisplay_(True)
+ self.push_strip.show(resistance / 500.0, link_state.peer_name(self.controller.cfg))
self.resistance_hint.set(
"Switches the moment the pointer touches the edge."
if resistance == 0
- else f"How far to push past the edge before it gives. It applies as you drag, and lights the {self.edge_select.value} edge so you can see the size of it."
+ else "How far to push past the edge before it gives. It applies as you drag, and lights the "
+ f"{self.edge_select.value} edge of this screen so you can feel the size of it."
)
- if self._preview_flashes == 0:
- self._place_preview(theme.PREVIEW_REST)
self.modifier_note.set({
- "semantic": "Semantic: Command sends Control, Control sends the Windows key.",
- "positional": "Positional: Command sends the Windows key.",
+ "semantic": "Command arrives on Windows as Control, so Command-C copies there too, and Control arrives as the Windows key.",
+ "positional": "Each key arrives as the key in its place, so Command arrives as the Windows key.",
}.get(self.modifier_select.value, "Custom: the key map in config.json is kept as it is."))
+ @objc.python_method
+ def _show_arrangement(self, methods):
+ cfg = self.controller.cfg
+ key = widgets.key_title(self.key_recorder.value)
+ held = self.style_select.value == "hold"
+ side = self.edge_select.value or "right"
+ pc = link_state.peer_name(cfg)
+ where = {"left": "to the left of", "right": "to the right of", "top": "above", "bottom": "below"}[side]
+ sentence = self._ways_in_sentence()
+ self.ways_note.set(sentence + "." if sentence else "No way in is switched on. Choose one below.")
+ self.arrangement_diagram.show(
+ side, methods, [name for name, tile in self.part_boxes.items() if tile.value],
+ self.corner_select.value or "top_right", widgets.key_cap(self.key_recorder.value), pc,
+ self.has_notch, f"{pc} is {where} this Mac. {sentence + '.' if sentence else 'No way in is on.'}",
+ key_how="hold" if held else "double-tap",
+ )
+
@objc.python_method
def _preview_resistance(self, value):
# Applied to the live engine at once, so the edge can be felt mid-drag; the saved setting
@@ -1052,17 +1323,21 @@ class ControlWindow(AppKit.NSObject):
self._changed()
if self.preview is not None and self.glow_box.value:
self.preview(self.edge_select.value, min(1.0, value / 500.0))
- self._flash_preview(min(1.0, value / 500.0))
@objc.python_method
def _show_peer(self):
cfg = self.controller.cfg
- self.peer.value.set(link_state.peer_name(cfg))
+ self.peer.value.set(self._shown(link_state.peer_name(cfg)))
if not cfg.host:
self.peer_footer.set("Not paired")
else:
# The port does not fit a third of the status module at the narrow grid.
- self.peer_footer.set(f"{cfg.host}:{cfg.port}" if self.wide else cfg.host)
+ self.peer_footer.set(self._shown(f"{cfg.host}:{cfg.port}" if self.wide else cfg.host))
+
+ @objc.python_method
+ def _shown(self, text):
+ """`text` as the window may show it: with Hide addresses on, no address in it."""
+ return pages.redact(text, self.controller.cfg.hide_addresses)
@objc.python_method
def _flash_preview(self, level):
@@ -1117,6 +1392,7 @@ class ControlWindow(AppKit.NSObject):
self.key_recorder.cancel()
self.ignored_recorder.cancel()
if self.previews is not None:
+ self.tile_hover.stop()
self.previews.stop()
@objc.python_method
@@ -1134,9 +1410,10 @@ class ControlWindow(AppKit.NSObject):
return widgets.hug(figure.view), figure
@objc.python_method
- def _page(self, title, purpose):
+ def _page(self, title, purpose, scope=None):
"""One page: a vertical scroller holding the title, the sentence saying what the page is
- for, then the modules the builder adds to the returned body. Returns (scroll, body)."""
+ for, `scope` saying whose settings they are where that needs saying, then the modules the
+ builder adds to the returned body. Returns (scroll, body)."""
scroll = AppKit.NSScrollView.alloc().init()
scroll.setTranslatesAutoresizingMaskIntoConstraints_(False)
scroll.setDrawsBackground_(False)
@@ -1171,19 +1448,27 @@ class ControlWindow(AppKit.NSObject):
purpose_label = widgets.Label(purpose, theme.TYPE["body"], ink="ink_2", wrap=True)
purpose_label.view.widthAnchor().constraintLessThanOrEqualToConstant_(theme.READING_WIDTH).setActive_(True)
widgets.add(header, purpose_label.view)
+ if scope is not None:
+ # ink_3, not signal: signal means something is happening, and on the light palette a
+ # line of it reads as a link.
+ scope_label = widgets.Label(scope, theme.TYPE["note"], ink="ink_3", wrap=True)
+ scope_label.view.widthAnchor().constraintLessThanOrEqualToConstant_(theme.READING_WIDTH).setActive_(True)
+ widgets.add(header, scope_label.view)
widgets.add(body, header)
body.setCustomSpacing_afterView_(32, header)
return scroll, body
@objc.python_method
def _overview_page(self, body):
+ # Pairing leads until there is a PC, since nothing else here works without one; once
+ # paired it is a quiet block further down with the one way to change it.
+ widgets.add(body, self._pair_module().view)
widgets.add(body, self._status_module().view)
- self.daily = widgets.Rack(
- [self._keyboard_module(), self._pause_module()], bottom_rule=False, gap=theme.MODULE_GAP, fill=None
- )
- widgets.add(body, self.daily.view)
+ widgets.add(body, self._keyboard_module().view)
widgets.add(body, self._directions_module().view)
+ widgets.add(body, self._paired_module().view)
widgets.add(body, self._login_module().view)
+ widgets.add(body, self._updates_module().view)
@objc.python_method
def _directions_module(self):
@@ -1218,6 +1503,7 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _login_module(self):
module = widgets.Module(spacing=10)
+ module.add(widgets.eyebrow("At login"))
self.login_switch = widgets.Switch("Start Beamer when you log in", on_change=self._set_login)
module.add(self.login_switch.view)
self.login_note = widgets.note()
@@ -1225,6 +1511,48 @@ class ControlWindow(AppKit.NSObject):
self._show_login_state()
return module
+ @objc.python_method
+ def _updates_module(self):
+ module = widgets.Module(spacing=10)
+ module.add(widgets.eyebrow("Updates"))
+ self.updates_switch = widgets.Switch("Check for updates", on_change=self._set_check_updates)
+ self.updates_switch.value = self.controller.cfg.check_updates
+ module.add(self.updates_switch.view)
+ module.add(widgets.note(
+ "Asks GitHub once a day whether there is a newer Beamer. Nothing is sent but the request itself."
+ ).view)
+ self.update_button = widgets.Button("Download", self, "downloadUpdate:", style="primary", full_width=True)
+ self.update_button.view.setHidden_(True)
+ module.add(self.update_button.view)
+ self.update_url = None
+ return module
+
+ @objc.python_method
+ def _set_check_updates(self, on):
+ try:
+ cfg = self.settings_store.save(config_to_raw(replace(self.controller.cfg, check_updates=bool(on))))
+ except SettingsError as exc:
+ self.logger.warning("update checking not saved: %s", exc)
+ self.updates_switch.value = self.controller.cfg.check_updates
+ return
+ self.controller.update_config(cfg)
+ if on and self.update_checker is not None:
+ self.update_checker.check_now()
+ if not on:
+ self.show_update(None)
+
+ @objc.python_method
+ def show_update(self, found):
+ """`found` is (version, url) for a newer release, or None."""
+ self.update_url = found[1] if found else None
+ if found:
+ self.update_button.set_title(f"Download Beamer {found[0]}")
+ motion.set_hidden(self.update_button.view, found is None)
+
+ def downloadUpdate_(self, _sender):
+ if self.update_url:
+ AppKit.NSWorkspace.sharedWorkspace().openURL_(AppKit.NSURL.URLWithString_(self.update_url))
+
@objc.python_method
def _show_login_state(self, refused=None):
try:
@@ -1252,25 +1580,105 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _crossing_page(self, body):
- for module in (self._ways_module(), self._resistance_module()):
+ # The shortcut's module is built first: the ways' tiles name its key.
+ self.shortcut_module = self._shortcut_module()
+ self.resistance_module = self._resistance_module()
+ for module in (self._ways_module(), self.resistance_module, self.shortcut_module):
widgets.add(body, module.view)
@objc.python_method
def _design_page(self, body):
- self.previews = previews.PreviewLoop(self.controller)
- for module in (self._on_screen_module(), self._notch_module(), self._edge_module(), self._trackpad_module()):
+ self.previews = previews.PreviewLoop(self.controller, body)
+ self.tile_hover = previews.TileHover(self.previews)
+ self.effect_stills = []
+ self.classic_pictures = []
+ self._stills = None
+ # A bundle missing the effects' modules still gets a working Design page, with today's
+ # styles and colours only; the overlay logs the failure and today's glow draws everything.
+ self.effects_ready = pages.effects_load_error() is None
+ self._look = None
+ self._place_chosen = False
+ self.style_module = self._edge_module()
+ self.colour_module = self._colour_module()
+ for module in (self._on_screen_module(), self.style_module, self.colour_module,
+ self._trackpad_module(), self._appearance_module()):
widgets.add(body, module.view)
+ @objc.python_method
+ def _appearance_module(self):
+ """The settings window's own palette. Last on the page: it is chosen once, and the modules
+ above are what the page is for."""
+ module = widgets.Module()
+ module.add(widgets.eyebrow("Appearance"))
+ self.appearance_select = widgets.Segmented(
+ [("system", "System"), ("light", "Light"), ("dark", "Dark")], on_change=self._appearance_chosen
+ )
+ module.add(widgets.field_row("This window", self.appearance_select.view)[0])
+ module.add(widgets.note("System follows your Mac's light or dark setting.").view)
+ return module
+
+ @objc.python_method
+ def _appearance_chosen(self, *_ignored):
+ # At once, not after _changed's pause for the settings to settle: the choice is the change.
+ self._apply_appearance(self.appearance_select.value)
+ self._changed()
+
+ @objc.python_method
+ def _apply_appearance(self, choice=None):
+ """Brings the window to the palette the appearance setting and the Mac ask for, cross-faded
+ while it is on screen. Called for the setting and whenever the Mac switches."""
+ choice = choice or self.appearance_select.value or self.controller.cfg.appearance
+ dark = theme.wants_dark(choice, theme.system_dark())
+ if dark == theme.is_dark():
+ return
+ content = self.window.contentView()
+ motion.cross_fade(content)
+ Quartz.CATransaction.begin()
+ Quartz.CATransaction.setDisableActions_(True)
+ theme.set_dark(dark)
+ self.window.setAppearance_(theme.appearance_named(dark))
+ theme.repaint(content)
+ Quartz.CATransaction.commit()
+ if self.previews is not None:
+ # The renderers take the palette as they draw, which a held still does not do again.
+ self.previews.repaint()
+
@objc.python_method
def _keyboard_page(self, body):
- widgets.add(body, self._shortcut_module().view)
- widgets.add(body, self._ignored_module().view)
+ # Modifier keys first: chosen once, while the list below grows as keys are added.
widgets.add(body, self._modifier_module().view)
+ widgets.add(body, self._ignored_module().view)
+ widgets.add(body, self._speed_module().view)
@objc.python_method
- def _pairing_page(self, body):
- widgets.add(body, self._paired_module().view)
- widgets.add(body, self._pair_module().view)
+ def _speed_module(self):
+ """How the PC's mouse feels on this Mac: the PC sends what its own acceleration made of the
+ hand's movement, and this Mac's settings decide the rest."""
+ module = widgets.Module()
+ figure, self.pointer_numeral = self._numeral("%")
+ module.add(self._head("The PC's pointer here", figure))
+ self.pointer_ruler = widgets.Ruler(
+ 25, 400, (25, 100, 200, 300, 400), step=5, minor=25, on_change=self._speed_moved,
+ title="Pointer speed", arrow_step=25,
+ )
+ module.add(self.pointer_ruler.view)
+ module.add(widgets.note("Pointer speed for the PC's mouse or trackpad while it drives this Mac.").view)
+ figure, self.scroll_numeral = self._numeral("%")
+ module.add(self._head("Scrolling", figure))
+ self.scroll_ruler = widgets.Ruler(
+ 25, 400, (25, 100, 200, 300, 400), step=5, minor=25, on_change=self._speed_moved,
+ title="Scroll speed", arrow_step=25,
+ )
+ module.add(self.scroll_ruler.view)
+ self.reverse_scroll_box = widgets.Switch("Reverse the PC's scrolling", on_change=self._changed)
+ module.add(self.reverse_scroll_box.view)
+ return module
+
+ @objc.python_method
+ def _speed_moved(self, _value=None):
+ self.pointer_numeral.set(str(self.pointer_ruler.value))
+ self.scroll_numeral.set(str(self.scroll_ruler.value))
+ self._changed()
@objc.python_method
def _connection_page(self, body):
@@ -1298,59 +1706,47 @@ class ControlWindow(AppKit.NSObject):
self.state_detail.view.heightAnchor().constraintGreaterThanOrEqualToConstant_(36).setActive_(True)
module.add(self.state_detail.view)
self.spark = widgets.size(widgets.flipped(widgets.Spark), height=14)
- self.round_trip = widgets.Readout("Round trip", "ms", self.spark)
- self.resistance_scale = widgets.size(widgets.flipped(widgets.Scale), height=14)
- self.resistance_readout = widgets.Readout("Resistance", "px", self.resistance_scale)
+ # The time a move takes to reach the PC and be answered, while input is there.
+ self.round_trip = widgets.Readout("Delay", "ms", self.spark)
self.peer_footer = widgets.Label("", theme.TYPE["small"], mono=True, ink="ink_3")
widgets.squeeze(self.peer_footer.view)
- self.peer = widgets.Readout("Peer", "", self.peer_footer.view, sizes=(theme.PEER_SIZE, theme.PEER_SIZE_NARROW))
- module.add(widgets.grid([self.round_trip.view, self.resistance_readout.view, self.peer.view], 3))
+ self.peer = widgets.Readout("PC", "", self.peer_footer.view, sizes=(theme.PEER_SIZE, theme.PEER_SIZE_NARROW))
+ module.add(widgets.grid([self.round_trip.view, self.peer.view], 2))
return module
@objc.python_method
def _keyboard_module(self):
- module = widgets.Module(spacing=14)
+ """Sending input by hand and pausing the edge, together as on the PC. Where input is now is
+ the status word above; a MAC / WINDOWS indicator here only said it twice."""
+ module = widgets.Module(spacing=12)
module.add(widgets.eyebrow("Keyboard and pointer"))
- self.selector = widgets.Selector()
- module.add(self.selector.view)
self.toggle_button = widgets.Button(
"Send input to Windows", self, "toggleRedirect:", style="primary", scale="big", full_width=True
)
module.add(self.toggle_button.view)
- return module
-
- @objc.python_method
- def _pause_module(self):
- module = widgets.Module(spacing=14)
- module.add(widgets.eyebrow("Pointer crossing"))
+ self.pause_row = widgets.stack(spacing=8)
self.pause_button = widgets.Button("Pause crossing", self, "togglePause:", full_width=True)
- module.add(self.pause_button.view)
+ widgets.add(self.pause_row, self.pause_button.view)
self.crossing_state = widgets.note()
- module.add(self.crossing_state.view)
+ widgets.add(self.pause_row, self.crossing_state.view)
+ module.add(self.pause_row)
+ module.body.setCustomSpacing_afterView_(14, self.toggle_button.view)
return module
@objc.python_method
def _resistance_module(self):
module = widgets.Module()
- figure, self.resistance_numeral = self._numeral("px of push")
+ figure, self.resistance_numeral = self._numeral("px")
module.add(self._head("Resistance", figure))
+ self.push_strip = diagram.PushStrip.alloc().init().setup()
+ module.add(self.push_strip)
self.resistance_ruler = widgets.Ruler(
- 0, 500, (0, 100, 200, 300, 400, 500), step=1, minor=25, on_change=self._preview_resistance
+ 0, 500, (0, 100, 200, 300, 400, 500), step=1, minor=25, on_change=self._preview_resistance,
+ title="Resistance", arrow_step=10,
)
module.add(self.resistance_ruler.view)
- line = widgets.stack(vertical=False, spacing=10)
- line.setAlignment_(AppKit.NSLayoutAttributeTop)
- screen = widgets.size(widgets.box("ground", "edge", 3), 46, 30)
- screen.layer().setMasksToBounds_(True)
- self.preview_glow = Quartz.CAGradientLayer.layer()
- self.preview_glow.setColors_([
- theme.colour("signal").colorWithAlphaComponent_(0).CGColor(), theme.colour("signal").CGColor(),
- ])
- screen.layer().addSublayer_(self.preview_glow)
- line.addArrangedSubview_(screen)
self.resistance_hint = widgets.note()
- line.addArrangedSubview_(self.resistance_hint.view)
- module.add(line)
+ module.add(self.resistance_hint.view)
return module
@objc.python_method
@@ -1359,17 +1755,37 @@ class ControlWindow(AppKit.NSObject):
module.add(widgets.eyebrow("Ways in"))
self.ways_note = widgets.note()
module.add(self.ways_note.view)
+ self.arrangement_diagram = diagram.ArrangementDiagram.alloc().init().setup()
+ module.add(self.arrangement_diagram)
+ module.body.setCustomSpacing_afterView_(16, self.arrangement_diagram)
+ # The pointer's ways first, the shortcut on its own row above its settings.
+ ways = (
+ ("edge", "Edge", "One whole side"),
+ ("part", "Part of the edge", "Only the thirds you pick"),
+ ("corner", "Corner", "Push diagonally into a corner"),
+ ("notch", "Notch", ""),
+ ("shortcut", "Shortcut", ""),
+ )
self.method_boxes = {
- "shortcut": widgets.WayTile("Shortcut", on_change=self._changed),
- "edge": widgets.WayTile("Edge", "One whole outer edge", on_change=self._changed),
- "corner": widgets.WayTile("Corner", f"{crossing.CORNER_PX:g} pt box, diagonal push", on_change=self._changed),
- "notch": widgets.WayTile("Notch", on_change=self._changed),
+ way: widgets.WayTile(title, detail, on_change=lambda on, way=way: self._way_toggled(way, on))
+ for way, title, detail in ways
}
module.add(widgets.grid([tile.view for tile in self.method_boxes.values()], 2))
+ # The values are the side of this Mac the PC is on, which is also the edge that crosses.
self.edge_select = widgets.Segmented(
- [("left", "Left"), ("right", "Right"), ("top", "Top"), ("bottom", "Bottom")], on_change=self._changed
+ [("left", "Left"), ("right", "Right"), ("top", "Above"), ("bottom", "Below")], on_change=self._changed
)
- module.add(widgets.field_row("Edge", self.edge_select.view)[0])
+ self.edge_row = widgets.field_row("Where the PC is", self.edge_select.view)[0]
+ module.add(self.edge_row)
+ self.edge_note = widgets.note(pages.NOTCH_OR_CORNER_NOTE)
+ self.edge_note.view.setHidden_(True)
+ module.add(self.edge_note.view)
+ self.part_boxes = {
+ part: widgets.WayTile(part.capitalize(), on_change=lambda on, part=part: self._part_toggled(part, on))
+ for part in return_edge.PARTS
+ }
+ self.parts_row = widgets.field_row("Parts", widgets.grid([tile.view for tile in self.part_boxes.values()], 3))[0]
+ module.add(self.parts_row)
self.corner_select = widgets.Segmented(
[
("top_left", "Top left"),
@@ -1380,26 +1796,54 @@ class ControlWindow(AppKit.NSObject):
columns=2,
on_change=self._changed,
)
- module.add(widgets.field_row("Corner", self.corner_select.view)[0])
- self.dragging_box = widgets.Switch("Never while dragging", on_change=self._changed)
+ self.corner_row = widgets.field_row("Corner", self.corner_select.view)[0]
+ module.add(self.corner_row)
+ self.dragging_box = widgets.Switch("Don't cross while dragging", on_change=self._changed)
module.add(self.dragging_box.view)
return module
+ @objc.python_method
+ def _way_toggled(self, way, on):
+ methods = pages.toggle_way([name for name, tile in self.method_boxes.items() if tile.value], way, on)
+ for name, tile in self.method_boxes.items():
+ tile.value = name in methods
+ self._changed()
+
+ @objc.python_method
+ def _part_toggled(self, part, on):
+ # The tile has already flipped itself; the last-third rule needs the thirds from before.
+ before = [name for name, tile in self.part_boxes.items() if (not on if name == part else tile.value)]
+ parts = pages.toggle_part(before, part, on)
+ for name, tile in self.part_boxes.items():
+ tile.value = name in parts
+ self._changed()
+
@objc.python_method
def _shortcut_module(self):
module = widgets.Module()
- self.double_tap_head, self.double_tap_numeral = self._numeral("ms between taps")
- module.add(self._head("Shortcut", self.double_tap_head))
+ module.add(widgets.eyebrow("Shortcut"))
self.key_recorder = widgets.KeyRecorder("alt_r", on_change=self._changed)
module.add(self.key_recorder.view)
self.style_select = widgets.Segmented([("double_tap", "Double-tap"), ("hold", "Hold")], on_change=self._changed)
- module.add(widgets.field_row("Trigger style", self.style_select.view)[0])
+ module.add(widgets.field_row("How you press it", self.style_select.view)[0])
+ # The figure sits on the ruler's own line, so it reads as the ruler's value rather than as
+ # a heading for the whole module, and the two hide together under Hold.
+ self.double_tap_head = widgets.stack(spacing=6)
+ caption = widgets.stack(vertical=False, spacing=12)
+ caption.setAlignment_(AppKit.NSLayoutAttributeLastBaseline)
+ caption.addArrangedSubview_(widgets.hug(widgets.label("Time between taps", theme.TYPE["note"], ink="ink_2"),
+ AppKit.NSLayoutPriorityDefaultLow))
+ figure, self.double_tap_numeral = self._numeral("ms")
+ caption.addArrangedSubview_(figure)
+ widgets.add(self.double_tap_head, caption)
# The stored window runs 50 to 2000 ms, but only about 150 to 600 is useful, so the ruler
# shows 50 to 1000 on a square-root scale; a stored value past 1000 pins the thumb.
self.double_tap_ruler = widgets.Ruler(
- 50, 1000, (50, 150, 300, 600, 1000), step=10, scale="sqrt", minor=20, on_change=self._double_tap_moved
+ 50, 1000, (50, 150, 300, 600, 1000), step=10, scale="sqrt", minor=20, on_change=self._double_tap_moved,
+ title="Time between taps",
)
- module.add(self.double_tap_ruler.view)
+ widgets.add(self.double_tap_head, self.double_tap_ruler.view)
+ module.add(self.double_tap_head)
self.style_hint = widgets.note()
module.add(self.style_hint.view)
return module
@@ -1423,6 +1867,7 @@ class ControlWindow(AppKit.NSObject):
module.add(self.ignored_recorder.view)
self.ignored_status = widgets.note()
module.add(self.ignored_status.view)
+ self.ignored_status.view.setHidden_(True)
self._render_ignored()
return module
@@ -1439,34 +1884,39 @@ class ControlWindow(AppKit.NSObject):
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_word = widgets.Label("Remove", theme.TYPE["small"], ink="ink_2")
remove.addSubview_(remove_word.view)
- widgets.pin(remove_word.view, remove, (4, 8, 4, 8))
+ widgets.pin(remove_word.view, remove, (7, 10, 7, 10))
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.pin(line, chip, (2, 12, 2, 2))
widgets.add(self.ignored_list, chip)
self.ignored_empty.view.setHidden_(bool(self.ignored_entries))
+ @objc.python_method
+ def _ignored_said(self, message):
+ self.ignored_status.set(message)
+ motion.set_hidden(self.ignored_status.view, not message)
+
@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.")
+ self._ignored_said("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._ignored_said("")
self._render_ignored()
self._changed()
@objc.python_method
def _remove_ignored(self, entry):
self.ignored_entries.remove(entry)
- self.ignored_status.set("")
+ self._ignored_said("")
self._render_ignored()
self._changed()
@@ -1477,9 +1927,17 @@ class ControlWindow(AppKit.NSObject):
self.glow_box = widgets.Switch("Animate crossings on this Mac", on_change=self._changed)
module.add(self.glow_box.view)
module.add(widgets.note(
- "Lights the notch or the edge as you push toward Windows. Switched off, crossing still "
- "works; you feel it rather than see it. Windows sets how its own edge looks."
+ "Lights the edge, the corner or the notch as you push toward Windows. Switched off, crossing "
+ "still works; you feel it rather than see it. Windows sets how its own edge looks."
).view)
+ self.landing_box = widgets.Switch("Show where the pointer lands", on_change=self._changed)
+ self.landing_row = widgets.stack(spacing=8)
+ widgets.add(self.landing_row, self.landing_box.view)
+ widgets.add(self.landing_row, widgets.note(
+ "When the shortcut or the menu brings input to this Mac, an animation plays around the "
+ "pointer. Choose it under Style, for Shortcut and menu."
+ ).view)
+ module.add(self.landing_row)
return module
@objc.python_method
@@ -1494,47 +1952,159 @@ class ControlWindow(AppKit.NSObject):
else:
renderer = previews.hosted_notch(base)(feed, self.logger, screen)
update = previews.notch_update(renderer)
- self.previews.add(feed, renderer, update)
+ self.previews.add(feed, renderer, update, screen)
return value, title, detail, screen
@objc.python_method
- def _notch_module(self):
- module = widgets.Module()
- module.add(widgets.eyebrow("Notch"))
+ def _notch_row(self):
+ """The notch's own styles, which play at the notch in place of Glow and Beam: under Show at,
+ shown while it is at the notch. Named apart from Classic Beam, which is the edge's line."""
+ row = widgets.stack(spacing=12)
+ widgets.add(row, widgets.label("Notch style", theme.TYPE["note"], 600, ink="ink_2"))
notch = previews.notch_size()
self.notch_style_select = widgets.ChoiceTiles(
[
- self._preview_tile(NotchBeam, "beam", "Beam", "A line of colour runs round the notch, faster the harder you push.", notch),
+ self._preview_tile(NotchBeam, "beam", "Outline", "A line of colour runs round the notch, faster the harder you push.", notch),
self._preview_tile(NotchIsland, "island", "Island", "The notch grows as you push, with a meter inside, and flashes as you go through.", notch),
],
on_change=self._changed,
)
- module.add(self.notch_style_select.view)
+ self._hover(self.notch_style_select)
+ widgets.add(row, self.notch_style_select.view)
self.notch_after_select = widgets.Segmented(
[(600, "0.6 s"), (1200, "1.2 s"), (2000, "2 s"), (3000, "3 s")], on_change=self._changed
)
- module.add(widgets.field_row("Keep animating", self.notch_after_select.view)[0])
+ widgets.add(row, widgets.field_row("Keep animating", self.notch_after_select.view)[0])
self.notch_note = widgets.note()
- module.add(self.notch_note.view)
- return module
+ widgets.add(row, self.notch_note.view)
+ return row
@objc.python_method
def _edge_module(self):
+ """Every style, grouped as effects.DIRECTIONS groups them: today's Glow and Beam first with
+ stills like the rest, then each direction's quiet, medium and showpiece effect; every tile shows
+ its style at the place chosen above them, and plays while the pointer is over it."""
module = widgets.Module()
- module.add(widgets.eyebrow("Edge and corner"))
- self.glow_style_select = widgets.ChoiceTiles(
- [
- self._preview_tile(EdgeGlow, "glow", "Glow", "A band of light that deepens the harder you push.", None, glow_style="glow"),
- self._preview_tile(EdgeGlow, "beam", "Beam", "A thin line with a comet of light running along it.", None, glow_style="beam"),
- ],
- on_change=self._changed,
- )
- module.add(self.glow_style_select.view)
- self.glow_colour_select = widgets.Swatches(
- [(name, name.capitalize()) for name in crossing.GLOW_COLOURS], on_change=self._changed
+ module.add(widgets.eyebrow("Style"))
+ self.style_for_select = widgets.Segmented(
+ [("crossing", "Crossing"), ("switch", "Shortcut and menu")], on_change=self._changed
)
- module.add(widgets.field_row("Colour", self.glow_colour_select.view)[0])
- module.add(widgets.note("The notch's Beam style uses this colour too. Island keeps Beamer's own cyan.").view)
+ self.style_for_select.value = "crossing"
+ self.style_for_row = widgets.field_row("Style for", self.style_for_select.view)[0]
+ module.add(self.style_for_row)
+ # Where every tile below plays its style: never switched off by the style, and what differs
+ # there is said beneath it.
+ self.effect_method_select = widgets.Segmented(previews.STAGE_METHODS, on_change=self._place_picked)
+ self.effect_method_select.value = self.place = "edge"
+ self.effect_method_view = widgets.field_row("Show at", self.effect_method_select.view)[0]
+ module.add(self.effect_method_view)
+ self.place_note = widgets.note()
+ module.add(self.place_note.view)
+ module.body.setCustomSpacing_afterView_(6, self.effect_method_view)
+ self.notch_row = self._notch_row()
+ module.add(self.notch_row)
+ module.body.setCustomSpacing_afterView_(22, self.notch_row)
+ colour = lambda: self.glow_colour_select.value or "signal"
+ place = lambda: self.place
+ pace = lambda: effects.pace(self.length_select.value)
+ # The two sets of tiles, one per mode; only the chosen mode's shows.
+ self.crossing_styles_box = widgets.stack(spacing=0)
+ rows = []
+ for group, choices in pages.style_groups(self.effects_ready):
+ # Glow and Beam as stills of the same scene as the effects, so every tile reads alike.
+ tiles = [(value, title, detail, previews.effect_still(value, colour, self.logger, place=place, pace=pace))
+ for value, title, detail in choices]
+ self.effect_stills.extend(tile[3] for tile in tiles)
+ if group == pages.TODAY:
+ # At the notch Glow and Beam do not draw: the notch style plays instead, so there
+ # their tiles show it, played by its own renderer as its tiles are.
+ notch = previews.notch_size()
+ stacked = []
+ for value, title, detail, still in tiles:
+ screens = {style: self._preview_tile(base, style, "", "", notch)[3]
+ for style, base in (("beam", NotchBeam), ("island", NotchIsland))}
+ stack = previews.TileStack.alloc().init().setup([still, *screens.values()])
+ self.classic_pictures.append((stack, still, screens))
+ stacked.append((value, title, detail, stack))
+ tiles = stacked
+ rows.append(self._style_group(self.crossing_styles_box, group, tiles))
+ module.add(self.crossing_styles_box)
+ self.glow_style_select = widgets.Linked(rows, on_change=self._changed, host=self.crossing_styles_box)
+ self.switch_styles_box = widgets.stack(spacing=0)
+ rows = []
+ for group, choices in pages.switch_style_groups(self.effects_ready):
+ tiles = []
+ for value, title, detail in choices:
+ fx = lambda value=value: effects.switch_effect(value, self.glow_style_select.value or "glow")
+ tiles.append((value, title, detail, previews.switch_still(fx, colour, self.logger, pace=pace)))
+ self.effect_stills.extend(tile[3] for tile in tiles)
+ rows.append(self._style_group(self.switch_styles_box, group, tiles))
+ widgets.add(self.switch_styles_box, widgets.note(
+ "What plays around the pointer when the shortcut or the menu brings input to this Mac. "
+ "Same as crossing follows the style you chose for crossing, with a ring for Glow and Beam."
+ ).view)
+ module.add(self.switch_styles_box)
+ self.switch_style_select = widgets.Linked(rows, on_change=self._changed, host=self.switch_styles_box)
+ # The chosen style's name and what it does, under the tiles that chose it.
+ self.chosen_box = widgets.stack(spacing=6)
+ self.effect_name = widgets.Label("", theme.TYPE["body"], 600)
+ widgets.add(self.chosen_box, self.effect_name.view)
+ self.effect_blurb = widgets.note()
+ widgets.add(self.chosen_box, self.effect_blurb.view)
+ module.add(self.chosen_box)
+ module.body.setCustomSpacing_afterView_(18, self.chosen_box)
+ # Every style and every switch plays at this length, so it follows the tiles either way.
+ self.length_select = widgets.Segmented(effects.LENGTHS, on_change=self._changed)
+ module.add(widgets.field_row("Length", self.length_select.view)[0])
+ module.add(widgets.note(
+ "How long each animation takes to play through once the pointer crosses, and to land."
+ ).view)
+ return module
+
+ @objc.python_method
+ def place_note_text(self, style, place, methods):
+ return pages.place_note(style if self.effects_ready else "glow", place, methods, self.has_notch)
+
+ @objc.python_method
+ def _place_picked(self, place):
+ """Every tile shows its style at `place`."""
+ self._place_chosen = True
+ self.place = place
+ self._reflect()
+
+ @objc.python_method
+ def _hover(self, choices):
+ """Each tile of `choices` plays its preview while the pointer is over it."""
+ for (_value, tile, _name), preview in zip(choices.tiles, choices.previews):
+ self.tile_hover.track(tile, preview)
+
+ @objc.python_method
+ def _style_group(self, box, group, tiles):
+ heading = widgets.label(group, theme.TYPE["note"], 600, ink="ink_2")
+ widgets.add(box, heading)
+ row = widgets.ChoiceTiles(tiles, columns=3)
+ self._hover(row)
+ widgets.add(box, row.view)
+ box.setCustomSpacing_afterView_(8, heading)
+ box.setCustomSpacing_afterView_(22, row.view)
+ return row
+
+ @objc.python_method
+ def _colour_module(self):
+ module = widgets.Module()
+ module.add(widgets.eyebrow("Colour"))
+ rows = []
+ for group, choices in pages.colour_groups(crossing.GLOW_COLOURS, self.effects_ready):
+ if group != pages.TODAY:
+ choices = [(value, title, effects_overlay.palette(value)) for value, title in choices]
+ heading = module.add(widgets.label(group, theme.TYPE["note"], 600, ink="ink_2"))
+ module.body.setCustomSpacing_afterView_(8, heading)
+ row = widgets.Swatches(choices, columns=len(crossing.GLOW_COLOURS))
+ module.add(row.view)
+ module.body.setCustomSpacing_afterView_(18, row.view)
+ rows.append(row)
+ self.glow_colour_select = widgets.Linked(rows, on_change=self._changed, host=module.body)
+ module.add(widgets.note("Any colour works with any style. The notch's Outline uses it too; Island keeps Beamer's own cyan.").view)
return module
@objc.python_method
@@ -1543,34 +2113,40 @@ class ControlWindow(AppKit.NSObject):
module.add(widgets.eyebrow("Trackpad"))
self.haptics_box = widgets.Switch("Tick as the push builds", on_change=self._changed)
module.add(self.haptics_box.view)
- strength = widgets.stack(vertical=False, spacing=10)
- self.tick_feel_select = widgets.Segmented(
- [("light", "Light"), ("medium", "Medium"), ("firm", "Firm")], on_change=self._changed
- )
- strength.addArrangedSubview_(widgets.hug(self.tick_feel_select.view, AppKit.NSLayoutPriorityDefaultLow))
- self.try_button = widgets.Button("Try it", self, "tryTick:", scale="small")
- strength.addArrangedSubview_(self.try_button.view)
- module.add(widgets.field_row("Strength", strength)[0])
self.tick_steps_select = widgets.Segmented(
[("quarters", "Every quarter"), ("halves", "Halfway"), ("breakthrough", "Only when through")],
on_change=self._changed,
)
module.add(widgets.field_row("Ticks at", self.tick_steps_select.view)[0])
+ # On the press, not the release: macOS plays nothing once the finger has left the trackpad.
+ self.try_button = widgets.Button("Try it", self, "tryTick:", scale="small")
+ self.try_button.view.sendActionOn_(AppKit.NSEventMaskLeftMouseDown)
+ feel = widgets.stack(vertical=False, spacing=10)
+ feel.addArrangedSubview_(self.try_button.view)
+ feel.addArrangedSubview_(widgets.hug(widgets.box(), AppKit.NSLayoutPriorityDefaultLow))
+ module.add(widgets.field_row("Feel it", feel)[0])
self.tick_note = widgets.note()
module.add(self.tick_note.view)
return module
def tryTick_(self, _sender):
- if self.haptics is not None:
- self.haptics.tick(self.tick_feel_select.value)
+ """A whole push in half a second, the ticks the chosen steps give and then the
+ breakthrough, for as long as the finger stays on the trackpad."""
+ if self.haptics is None:
+ return
+ ticks = {"quarters": 3, "halves": 1}.get(self.tick_steps_select.value, 0)
+ for index in range(ticks):
+ AppHelper.callLater(0.12 * index, self.haptics.tick)
+ AppHelper.callLater(0.12 * ticks + 0.08, self.haptics.thud)
@objc.python_method
def _modifier_module(self):
module = widgets.Module()
module.add(widgets.eyebrow("Modifier keys"))
self.modifier_select = widgets.Segmented(
- [("semantic", "Semantic"), ("positional", "Positional")], on_change=self._changed
+ [("semantic", "Same shortcuts"), ("positional", "Same positions")], on_change=self._changed
)
+ self.modifier_select.view.setAccessibilityLabel_("Modifier keys")
module.add(self.modifier_select.view)
self.modifier_note = widgets.note()
module.add(self.modifier_note.view)
@@ -1600,6 +2176,11 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _pair_module(self):
module = widgets.Module()
+ module.add(widgets.eyebrow("Pair with your PC"))
+ module.add(widgets.note(
+ "Open Beamer on the PC and press Pair a Mac. Then choose the PC here and type the "
+ "six-digit code it shows. You only do this once."
+ ).view)
self.pair_grid = widgets.stack(spacing=20)
self.pair_grid.setAlignment_(AppKit.NSLayoutAttributeTop)
found = widgets.stack(spacing=8)
@@ -1611,6 +2192,30 @@ class ControlWindow(AppKit.NSObject):
widgets.add(found, self.pc_frame)
self.pc_empty = widgets.note()
widgets.add(found, self.pc_empty.view)
+ # For a PC no broadcast reaches: asked by its address, it answers with its beacon and
+ # joins the list above, and pairing carries on with its code as usual.
+ # As dots while addresses are hidden, as the PC's address on Connection is.
+ find_box, self.find_field = widgets.field()
+ find_secret_box, self.find_secret = widgets.field(secure=True)
+ find_secret_box.setHidden_(True)
+ self.find_boxes = (find_box, find_secret_box)
+ for control in (self.find_field, self.find_secret):
+ control.setPlaceholderAttributedString_(widgets.attributed("PC's address", theme.TYPE["small"], ink="ink_3", mono=True))
+ control.setAccessibilityLabel_("Address of a PC that is not listed")
+ control.setTarget_(self)
+ control.setAction_("findPC:")
+ find_line = widgets.stack(vertical=False, spacing=8)
+ for box in self.find_boxes:
+ find_line.addArrangedSubview_(widgets.hug(box, AppKit.NSLayoutPriorityDefaultLow))
+ find_line.addArrangedSubview_(widgets.Button("Find", self, "findPC:").view)
+ find_caption = widgets.label("PC not listed? Type its address.", theme.TYPE["note"], ink="ink_2")
+ widgets.add(found, find_caption)
+ found.setCustomSpacing_afterView_(14, self.pc_empty.view)
+ found.setCustomSpacing_afterView_(14, self.pc_frame)
+ widgets.add(found, find_line)
+ self.find_status = widgets.note()
+ widgets.add(found, self.find_status.view)
+ self.find_status.view.setHidden_(True)
code = widgets.stack(spacing=8)
widgets.add(code, widgets.eyebrow("Code shown on the PC"))
self.code_boxes = widgets.CodeBoxes(pairing.CODE_DIGITS, self.confirmPair_)
@@ -1619,7 +2224,7 @@ class ControlWindow(AppKit.NSObject):
line.setAlignment_(AppKit.NSLayoutAttributeTop)
self.pair_status = widgets.note()
line.addArrangedSubview_(self.pair_status.view)
- self.confirm_button = widgets.Button("Pair", self, "confirmPair:", scale="small")
+ self.confirm_button = widgets.Button("Pair", self, "confirmPair:", style="primary")
line.addArrangedSubview_(self.confirm_button.view)
widgets.add(code, line)
self.pair_grid.addArrangedSubview_(found)
@@ -1634,10 +2239,25 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _connection_module(self):
module = widgets.Module(spacing=10)
+ self.hide_switch = widgets.Switch("Hide addresses", on_change=self._set_hide_addresses)
+ module.add(self.hide_switch.view)
+ module.add(widgets.note(
+ "Hides every IP and hardware address in this window and its menu."
+ ).view)
host_box, self.host_field = widgets.field()
- module.add(widgets.field_row("Windows address", host_box)[0])
+ secret_box, self.host_secret = widgets.field(secure=True)
+ secret_box.setHidden_(True)
+ self.host_boxes = (host_box, secret_box)
+ host_line = widgets.stack(vertical=False, spacing=0)
+ for box in self.host_boxes:
+ host_line.addArrangedSubview_(box)
+ widgets.hug(box, AppKit.NSLayoutPriorityDefaultLow)
+ module.add(widgets.field_row("PC's address", host_line)[0])
+ for control in (self.host_field, self.host_secret):
+ control.setAccessibilityLabel_("PC's address")
port_box, self.port_field = widgets.field()
module.add(widgets.field_row("Port", port_box)[0])
+ self.port_field.setAccessibilityLabel_("Port")
token_box, self.token_field = widgets.field(secure=True)
plain_box, self.token_plain = widgets.field()
plain_box.setHidden_(True)
@@ -1650,6 +2270,8 @@ class ControlWindow(AppKit.NSObject):
for box in self.token_boxes:
widgets.hug(box, AppKit.NSLayoutPriorityDefaultLow)
module.add(widgets.field_row("Shared token", token_line)[0])
+ for control in (self.token_field, self.token_plain):
+ control.setAccessibilityLabel_("Shared token")
self.wake_state = widgets.Label("", theme.TYPE["small"], mono=True)
module.add(widgets.field_row("Wake-on-LAN", self.wake_state.view)[0])
self.wake_hint = widgets.note()
@@ -1657,51 +2279,61 @@ class ControlWindow(AppKit.NSObject):
module.add(widgets.hairline())
line = widgets.stack(vertical=False, spacing=12)
line.addArrangedSubview_(widgets.note("A new address, port or token takes effect when you connect.").view)
- line.addArrangedSubview_(widgets.Button("Connect", self, "connect:", style="primary", scale="small").view)
+ line.addArrangedSubview_(widgets.Button("Connect", self, "connect:", style="primary").view)
module.add(line)
return module
@objc.python_method
def _access_module(self):
module = widgets.Module(spacing=10)
- self.access_status, self.access_button = self._permission_row(module, "Accessibility", "requestAccessibility:")
+ self.access_status, self.access_button = self._permission_row(
+ module, "Accessibility", "Lets Beamer move this Mac's pointer and type on it when the PC drives.",
+ "requestAccessibility:",
+ )
module.add(widgets.hairline())
- self.input_status, self.input_button = self._permission_row(module, "Input Monitoring", "requestInputMonitoring:")
+ self.input_status, self.input_button = self._permission_row(
+ module, "Input Monitoring", "Lets Beamer read this keyboard and trackpad, to send them to the PC.",
+ "requestInputMonitoring:",
+ )
self.capture_status = widgets.note()
- line = widgets.stack(vertical=False, spacing=12)
- line.addArrangedSubview_(widgets.hug(self.capture_status.view, AppKit.NSLayoutPriorityDefaultLow))
- self.relaunch_button = widgets.Button("Relaunch Beamer", self, "relaunch:", style="primary", scale="small")
+ module.add(self.capture_status.view)
+ self.relaunch_button = widgets.Button("Relaunch Beamer", self, "relaunch:", style="primary", full_width=True)
self.relaunch_button.view.setHidden_(True)
- line.addArrangedSubview_(self.relaunch_button.view)
- module.add(line)
+ module.add(self.relaunch_button.view)
return module
@objc.python_method
- def _permission_row(self, module, name, action):
+ def _permission_row(self, module, name, purpose, action):
line = widgets.stack(vertical=False, spacing=10)
+ line.setAlignment_(AppKit.NSLayoutAttributeCenterY)
words = widgets.stack(spacing=4)
widgets.add(words, widgets.Label(name, theme.TYPE["body"], 600).view)
+ widgets.add(words, widgets.note(purpose).view)
status = widgets.Label("Required", theme.TYPE["small"], mono=True, ink="amber", tracking=theme.STATE_TRACKING, upper=True)
widgets.add(words, status.view)
line.addArrangedSubview_(widgets.hug(words, AppKit.NSLayoutPriorityDefaultLow))
- button = widgets.Button("Grant", self, action, scale="small")
+ button = widgets.Button("Grant", self, action)
line.addArrangedSubview_(button.view)
module.add(line)
return status, button
@objc.python_method
def _ways_in_sentence(self):
- cfg = self.controller.cfg
- key = widgets.key_title(cfg.trigger_key)
- methods = set(cfg.crossing["methods"])
+ # Read from the controls, not the saved config, which lands a moment after a change: the
+ # sentence and the drawing's description would otherwise be one change behind.
+ key = widgets.key_title(self.key_recorder.value)
+ methods = {name for name, tile in self.method_boxes.items() if tile.value}
+ edge = self.edge_select.value or "right"
parts = []
if "shortcut" in methods:
- parts.append(f"{'Hold' if cfg.trigger_style == 'hold' else 'Double-tap'} {key}")
+ parts.append(f"{'Hold' if self.style_select.value == 'hold' else 'Double-tap'} {key}")
ways = []
if "edge" in methods:
- ways.append(f"the {cfg.crossing['edge']} edge")
+ ways.append(f"the {edge} edge")
+ elif "part" in methods:
+ ways.append(pages.parts_phrase(edge, [name for name, tile in self.part_boxes.items() if tile.value]))
if "corner" in methods:
- ways.append(f"the {cfg.crossing['corner'].replace('_', ' ')} corner")
+ ways.append(f"the {(self.corner_select.value or 'top_right').replace('_', ' ')} corner")
if "notch" in methods:
ways.append("the notch")
if ways:
@@ -1715,9 +2347,7 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _commit(self):
bar = widgets.box("ground")
- self.message_label = widgets.note(
- "Changes apply as you make them. Closing this window keeps Beamer running in the menu bar."
- )
+ self.message_label = widgets.note(pages.footer(None))
line = widgets.stack(vertical=False, spacing=16)
line.addArrangedSubview_(self.message_label.view)
bar.addSubview_(line)
@@ -1734,6 +2364,8 @@ class ControlWindow(AppKit.NSObject):
self.page if self.opened else None, accessibility_granted(), input_monitoring_granted()
))
self.opened = True
+ # Closed, the window stopped refreshing; bring it up to date before it is seen.
+ self.refresh()
self.window.makeKeyAndOrderFront_(None)
AppKit.NSApp.activateIgnoringOtherApps_(True)
self._run_previews()
@@ -1742,6 +2374,39 @@ class ControlWindow(AppKit.NSObject):
def _token(self):
return (self.token_plain if self.token_boxes[0].isHidden() else self.token_field).stringValue()
+ @objc.python_method
+ def _set_hide_addresses(self, on):
+ try:
+ cfg = self.settings_store.save(config_to_raw(replace(self.controller.cfg, hide_addresses=bool(on))))
+ except SettingsError as exc:
+ self.logger.warning("Hide addresses not saved: %s", exc)
+ return
+ self.controller.update_config(cfg)
+ self._show_host_field()
+ self._pcs_key = None
+ self.refresh()
+
+ @objc.python_method
+ def _show_host_field(self):
+ """The address fields as dots while addresses are hidden, still editable."""
+ hide = self.controller.cfg.hide_addresses
+ for (plain_box, secret_box), plain, secret in ((self.host_boxes, self.host_field, self.host_secret),
+ (self.find_boxes, self.find_field, self.find_secret)):
+ if hide == plain_box.isHidden():
+ continue
+ if hide:
+ secret.setStringValue_(plain.stringValue())
+ else:
+ plain.setStringValue_(secret.stringValue())
+ plain_box.setHidden_(hide)
+ secret_box.setHidden_(not hide)
+ if self.hide_switch.value != hide:
+ self.hide_switch.value = hide
+
+ @objc.python_method
+ def _host_text(self):
+ return (self.host_secret if self.controller.cfg.hide_addresses else self.host_field).stringValue()
+
def showToken_(self, _sender):
secure_box, plain_box = self.token_boxes
showing = plain_box.isHidden()
@@ -1758,7 +2423,7 @@ class ControlWindow(AppKit.NSObject):
waits for the button rather than applying as it is typed."""
raw = config_to_raw(self.controller.cfg)
try:
- raw["host"] = self.host_field.stringValue().strip()
+ raw["host"] = self._host_text().strip()
raw["port"] = int(self.port_field.stringValue().strip())
raw["auth_token"] = self._token()
if raw["host"] != self.controller.cfg.host:
@@ -1781,21 +2446,30 @@ class ControlWindow(AppKit.NSObject):
raw["ignored_inputs"] = list(self.ignored_entries)
raw["trigger_style"] = self.style_select.value
raw["double_tap_ms"] = self.double_tap_ruler.value
+ raw["pointer_speed"] = self.pointer_ruler.value / 100
+ raw["scroll_speed"] = self.scroll_ruler.value / 100
+ raw["reverse_scroll"] = self.reverse_scroll_box.value
+ raw["appearance"] = self.appearance_select.value or "system"
if self.modifier_select.value in config_module.KEY_MAP_STYLES:
raw["key_map"] = self.modifier_select.value
raw["crossing"] = {
"methods": [name for name, tile in self.method_boxes.items() if tile.value],
+ "edge_parts": [name for name, tile in self.part_boxes.items() if tile.value] or ["middle"],
"edge": self.edge_select.value,
"corner": self.corner_select.value,
"resistance_px": self.resistance_ruler.value,
"haptics": self.haptics_box.value,
"glow": self.glow_box.value,
+ "shortcut_arrival": self.landing_box.value,
+ "shortcut_arrival_style": self.switch_style_select.value or "match",
"notch_style": self.notch_style_select.value,
"notch_after_ms": self.notch_after_select.value,
- "haptic_feel": self.tick_feel_select.value,
+ # Kept so a saved file stays valid; macOS has no strength to choose.
+ "haptic_feel": self.controller.cfg.crossing.get("haptic_feel", "medium"),
"haptic_steps": self.tick_steps_select.value,
"glow_style": self.glow_style_select.value,
"glow_colour": self.glow_colour_select.value,
+ "effect_length": self.length_select.value or "normal",
"block_while_dragging": self.dragging_box.value,
"arrangement_set_at": self.controller.cfg.crossing.get("arrangement_set_at", 0),
}
@@ -1814,6 +2488,9 @@ class ControlWindow(AppKit.NSObject):
# the other way it can be reached, and either may be the one that is
# up. Both are best-effort and say so by returning False.
self.controller.apply_settings(cfg)
+ if self.previews is not None:
+ # The tiles' renderers read the colour from the applied settings, which land only now.
+ self.previews.repaint()
if moved and self.windows_input is not None:
self.windows_input.send_arrangement(
cfg.crossing["edge"], cfg.crossing.get("arrangement_set_at", 0)
@@ -1904,10 +2581,10 @@ class ControlWindow(AppKit.NSObject):
refused = state.key == "token"
repairing = getattr(self, "_repairing", False)
peer = link_state.peer_name(cfg)
- self.paired_module.view.setHidden_(not paired)
- self.pair_module.view.setHidden_(paired and not refused and not repairing)
+ motion.set_hidden(self.paired_module.view, not paired)
+ motion.set_hidden(self.pair_module.view, paired and not refused and not repairing)
self.paired_name.set(peer)
- self.paired_address.set(f"{cfg.host} · port {cfg.port}")
+ self.paired_address.set(self._shown(f"{cfg.host} · port {cfg.port}"))
if refused:
self.paired_note.set(f"{peer} refused this Mac's token. Pair again below with the code it shows.", ink="fault")
elif state.key in ("mac", "windows", "paused", "full_screen", "unlocking"):
@@ -1933,6 +2610,7 @@ class ControlWindow(AppKit.NSObject):
return
self._pcs_key = key
self._pcs = pcs
+ self._find_answered(pcs)
for view in list(self.pc_list.arrangedSubviews()):
self.pc_list.removeArrangedSubview_(view)
view.removeFromSuperview()
@@ -1942,7 +2620,7 @@ class ControlWindow(AppKit.NSObject):
role=AppKit.NSAccessibilityRadioButtonRole)
row.ring_inset = 1.0
showing = pc["pair_id"] is not None
- row.setAccessibilityLabel_(f"{pc['name']}, {pc['address']}" + (", showing a code" if showing else ""))
+ row.setAccessibilityLabel_(self._shown(f"{pc['name']}, {pc['address']}") + (", showing a code" if showing else ""))
row.setToolTip_(f"Port {pc['port']}" + (", showing a code" if showing else ""))
line = widgets.stack(vertical=False, spacing=9)
led = widgets.LED()
@@ -1950,7 +2628,7 @@ class ControlWindow(AppKit.NSObject):
line.addArrangedSubview_(led.view)
name = widgets.Label(pc["name"], theme.TYPE["note"], 600 if picked else 400)
line.addArrangedSubview_(widgets.hug(widgets.squeeze(name.view), AppKit.NSLayoutPriorityDefaultLow))
- line.addArrangedSubview_(widgets.Label(pc["address"], theme.TYPE["small"], mono=True, ink="ink_3").view)
+ line.addArrangedSubview_(widgets.Label(self._shown(pc["address"]), theme.TYPE["small"], mono=True, ink="ink_3").view)
row.addSubview_(line)
widgets.pin(line, row, (7, 10, 7, 10))
widgets.add(self.pc_list, row)
@@ -1959,7 +2637,7 @@ class ControlWindow(AppKit.NSObject):
else:
self.pc_empty.set(
"Looking for PCs running Beamer. Open it on the PC and it appears here; across a VPN or "
- "on guest Wi-Fi it cannot, so enter its address and a shared token on Connection instead.",
+ "on guest Wi-Fi it may not, so type its address below.",
ink="ink_2",
)
self.pc_frame.setHidden_(not pcs)
@@ -1977,12 +2655,51 @@ class ControlWindow(AppKit.NSObject):
self.code_boxes.clear()
self.code_boxes.view.setAccessibilityLabel_(f"Code shown on {self.chosen_pc['name']}")
if self.chosen_pc["pair_id"] is None:
- self._say_pairing(f"{self.chosen_pc['name']} is not showing a code yet. Press Pair a Mac on it first.")
+ self._say_pairing(f"{self.chosen_pc['name']} is not showing a code yet. Start pairing in Beamer on it first.")
else:
self._say_pairing("Six digits, as shown on the PC.")
self._refresh_pcs()
self.code_boxes.focus(self.window)
+ def findPC_(self, _sender):
+ host = (self.find_secret if self.controller.cfg.hide_addresses else self.find_field).stringValue().strip()
+ if self.discovery is None:
+ return
+ self.discovery.find(host)
+ self._find_serial = getattr(self, "_find_serial", 0) + 1
+ serial = self._find_serial
+ # Discovery only logs an address it cannot resolve, so the page watches for the PC
+ # itself: a PC new to the list since the ask, or one at the typed address, is the answer.
+ self._finding = {"host": host, "known": {pc["address"] for pc in self._pcs}, "serial": serial} if host else None
+ self._said_find(self._shown(f"Asking {host}…") if host else "")
+ if host:
+ AppHelper.callLater(6.0, lambda: self._find_timed_out(serial))
+
+ @objc.python_method
+ def _said_find(self, message, ink="ink_2"):
+ self.find_status.set(message, ink=ink)
+ motion.set_hidden(self.find_status.view, not message)
+
+ @objc.python_method
+ def _find_answered(self, pcs):
+ finding = getattr(self, "_finding", None)
+ if finding is None:
+ return
+ found = next((pc for pc in pcs if pc["address"] == finding["host"] or pc["address"] not in finding["known"]), None)
+ if found is not None:
+ self._finding = None
+ self._said_find(f"Found {found['name']}. Choose it in the list.", "signal")
+
+ @objc.python_method
+ def _find_timed_out(self, serial):
+ finding = getattr(self, "_finding", None)
+ if finding is not None and finding["serial"] == serial:
+ self._said_find(
+ self._shown(f"No answer from {finding['host']} yet. Check the address, and that Beamer is open on the PC; "
+ "this Mac keeps asking."),
+ "amber",
+ )
+
def confirmPair_(self, _sender):
pc = self.chosen_pc
if pc is None or self._pairing or self.discovery is None:
@@ -1994,7 +2711,7 @@ class ControlWindow(AppKit.NSObject):
# The list may have refreshed since the row was chosen; pair with the PC's latest beacon.
current = next((entry for entry in self._pcs if entry["address"] == pc["address"]), pc)
if current["pair_id"] is None:
- self._say_pairing(f"{current['name']} is not showing a code. Press Pair a Mac on it, then try again.", "fault")
+ self._say_pairing(f"{current['name']} is not showing a code. Start pairing in Beamer on it, then try again.", "fault")
return
self._pairing = True
self.confirm_button.set_enabled(False)
@@ -2021,9 +2738,9 @@ class ControlWindow(AppKit.NSObject):
if isinstance(result, pairing.PairingError):
reason = str(result)
if reason == pairing.ERROR_NOT_PAIRING:
- self._say_pairing(f"{name} is not showing a code. Press Pair a Mac on it, then try again.", "fault")
+ self._say_pairing(f"{name} is not showing a code. Start pairing in Beamer on it, then try again.", "fault")
elif reason == pairing.ERROR_REFUSED:
- self._say_pairing("That code was not accepted, and the PC has cancelled it. Press Pair a Mac there for a fresh one.", "fault")
+ self._say_pairing("That code was not accepted, and the PC has cancelled it. Start pairing there again for a fresh one.", "fault")
elif reason == "no_answer":
self._say_pairing(f"{name} did not answer. Check both machines are on the same network, then try again.", "fault")
else:
@@ -2059,24 +2776,39 @@ class ControlWindow(AppKit.NSObject):
self.logger.warning("hardware address not saved: %s", exc)
@objc.python_method
- def _crossing_state_sentence(self):
+ def _crossing_state_args(self):
controller = self.controller
- if not controller.crossing.armed:
- return "Only the shortcut is switched on; there is nothing to pause."
- if controller.crossing_paused:
- return "Paused. Edges, corners and the notch do nothing until you resume; the shortcut still works."
- if controller.full_screen_app is not None:
- return (
- f"Off while {controller.full_screen_app} is full screen, so the pointer stays put at "
- "the edges; the shortcut still works."
- )
- return "On. Pause it to lean on an edge without switching."
+ cfg = controller.cfg
+ return (
+ bool(cfg.host and cfg.auth_token), cfg.send_to_windows, controller.connected,
+ controller.crossing.armed, controller.crossing_paused, controller.full_screen_app,
+ )
+
+ @objc.python_method
+ def _crossing_state_sentence(self):
+ return pages.crossing_state_sentence(*self._crossing_state_args())
@objc.python_method
def _permission(self, status, button, granted):
status.set("Granted" if granted else "Required", ink="signal" if granted else "amber")
- button.set_title("Granted" if granted else "Grant")
- button.set_enabled(not granted)
+ # Granted, the state says so; a dead "Granted" button beside it only said it twice.
+ motion.set_hidden(button.view, granted)
+
+ @objc.python_method
+ def retry_capture(self, access=None, listening=None):
+ """Start input capture once both grants are in. The one part of refresh that must run
+ while the window is closed; the rest redraws what nobody can see."""
+ controller = self.controller
+ if controller.input_ready:
+ return
+ now = time.monotonic()
+ if now - self.last_capture_attempt < CAPTURE_RETRY_INTERVAL_SECONDS:
+ return
+ if access is None:
+ access, listening = accessibility_granted(), input_monitoring_granted()
+ if access and listening:
+ self.last_capture_attempt = now
+ controller.start_input_capture()
@objc.python_method
def refresh(self):
@@ -2086,11 +2818,7 @@ class ControlWindow(AppKit.NSObject):
listening = input_monitoring_granted()
self._permission(self.access_status, self.access_button, access)
self._permission(self.input_status, self.input_button, listening)
- if access and listening and not controller.input_ready:
- now = time.monotonic()
- if now - self.last_capture_attempt >= CAPTURE_RETRY_INTERVAL_SECONDS:
- self.last_capture_attempt = now
- controller.start_input_capture()
+ self.retry_capture(access, listening)
needs_relaunch = access and listening and not self.granted_at_launch
self.relaunch_button.view.setHidden_(not needs_relaunch)
if needs_relaunch:
@@ -2111,12 +2839,14 @@ class ControlWindow(AppKit.NSObject):
self.ways_note.set(sentence + "." if sentence else "No way in is switched on. Choose one below.")
state = link_state.describe(controller)
self._refresh_paired(state)
- self.sidebar.set_link(state, link_state.peer_name(controller.cfg))
+ self.sidebar.set_link(state, self._shown(link_state.peer_name(controller.cfg)))
self.sidebar.set_dots(pages.dots(access, listening, state.key))
self.link_led.set(state.led, state.blink)
self.link_tag.set(state.tag)
+ if (state.word, state.tone) != (self.state_word.text, self.state_word.ink):
+ motion.cross_fade(self.state_word.view)
self.state_word.set(state.word, ink=state.tone)
- self.state_detail.set(state.detail)
+ self.state_detail.set(self._shown(state.detail))
round_trip = controller.round_trip_ms
if controller.redirecting:
@@ -2134,13 +2864,19 @@ class ControlWindow(AppKit.NSObject):
self.pause_button.set_title("Resume crossing" if controller.crossing_paused else "Pause crossing")
self.pause_button.set_style("primary" if controller.crossing_paused else "plain")
- self.pause_button.set_enabled(controller.crossing.armed)
- self.crossing_state.set(self._crossing_state_sentence())
+ # With only the shortcut on there is no edge to pause, so there is no button either.
+ args = self._crossing_state_args()
+ blocked = pages.crossing_state_blocked(*args[:3])
+ self.pause_button.view.setHidden_(not controller.crossing.armed)
+ motion.set_hidden(self.pause_row, not (controller.crossing.armed or blocked))
+ sentence = pages.crossing_state_sentence(*args)
+ if sentence != self.crossing_state.text:
+ motion.cross_fade(self.crossing_state.view)
+ self.crossing_state.set(sentence)
has_notch = controller.notch_range is not None
if has_notch != self.has_notch:
self.has_notch = has_notch
self._reflect()
- self.selector.set("windows" if controller.redirecting else "mac")
if controller.redirecting:
self.toggle_button.set_title("Return input to Mac")
elif controller.waking:
@@ -2156,7 +2892,7 @@ class ControlWindow(AppKit.NSObject):
and (controller.connected or controller.can_wake)
)
mac = cfg.mac_address
- self.wake_state.set(mac if mac else "Not yet learned", ink="ink" if mac else "ink_3")
+ self.wake_state.set(self._shown(mac) if mac else "Not yet learned", ink="ink" if mac else "ink_3")
self.wake_hint.set(
"Crossing to the PC while it sleeps sends a wake-up packet and waits for it."
if mac
@@ -2231,6 +2967,7 @@ class TrayApp(rumps.App):
self.edge_glow = EdgeGlow(controller, logger)
self.notch_island = NotchIsland(controller, logger)
self.notch_beam = NotchBeam(controller, logger)
+ self.effects_overlay = effects_overlay.EffectsOverlay(controller, logger)
self.haptics = Haptics(logger)
self.control_window.preview = self.edge_glow.preview
self.control_window.haptics = self.haptics
@@ -2241,14 +2978,29 @@ class TrayApp(rumps.App):
# The other direction, listening from the moment Beamer opens: the PC
# may want to send its own keyboard here before this Mac has ever
# crossed the other way.
- self.windows_input = WindowsInput(controller, logger, arrangement_callback=self._arrangement)
+ self.windows_input = WindowsInput(
+ controller,
+ logger,
+ arrangement_callback=self._arrangement,
+ pressure_callback=self._driven_pressure,
+ arrival_callback=self._driven_arrival,
+ )
self.control_window.windows_input = self.windows_input
self.windows_input.sync(controller.cfg)
self.discovery = pairing.Discovery(logger=logger)
self.control_window.discovery = self.discovery
self.discovery.start()
+ # A PC that changed address is followed by its beacon; bridge sets cfg.host, this saves it.
+ controller.discovery = self.discovery
+ controller.on_host_learned = lambda host: AppHelper.callAfter(self.control_window._persist_mac, None)
+ self.update_checker = updates.Checker(
+ VERSION, lambda: self.controller.cfg.check_updates,
+ lambda found: AppHelper.callAfter(self._update_found, found), logger=logger,
+ )
+ self.control_window.update_checker = self.update_checker
self._notch_failed = False
- header = rumps.MenuItem(f"Beamer {VERSION}", callback=None)
+ self.header_item = header = rumps.MenuItem(f"Beamer {VERSION}", callback=None)
+ self.update_url = None
self.status_item = rumps.MenuItem("Starting", callback=None)
self.toggle_item = rumps.MenuItem("Send input to Windows", callback=self.toggle_redirect)
self.pause_item = rumps.MenuItem("Pause crossing", callback=self.toggle_pause)
@@ -2271,6 +3023,7 @@ class TrayApp(rumps.App):
rumps.separator,
rumps.MenuItem("Settings…", callback=self.open_window),
rumps.MenuItem("Reload configuration", callback=self.reload_config),
+ rumps.MenuItem("Open log folder", callback=self.open_log_folder),
rumps.separator,
rumps.MenuItem("About Beamer", callback=self.show_about),
rumps.MenuItem("Quit Beamer", callback=self.quit_app),
@@ -2285,6 +3038,26 @@ class TrayApp(rumps.App):
self.status_timer.start()
self.startup_timer.start()
self.full_screen_timer.start()
+ self.update_checker.start()
+
+ def _update_found(self, found):
+ """On the main thread. The version line in the menu becomes the way to the download."""
+ self.update_url = found[1] if found else None
+ if found:
+ self.header_item.title = f"Beamer {found[0]} is available…"
+ self.header_item.set_callback(self.open_update)
+ else:
+ self.header_item.title = f"Beamer {VERSION}"
+ self.header_item.set_callback(None)
+ self.control_window.show_update(found)
+
+ def open_update(self, _sender):
+ if self.update_url:
+ AppKit.NSWorkspace.sharedWorkspace().openURL_(AppKit.NSURL.URLWithString_(self.update_url))
+
+ def open_log_folder(self, _sender):
+ LOG_DIRECTORY.mkdir(parents=True, exist_ok=True, mode=0o700)
+ AppKit.NSWorkspace.sharedWorkspace().openURL_(AppKit.NSURL.fileURLWithPath_(str(LOG_DIRECTORY)))
def _arrangement(self, mac_edge, set_at):
"""An arrangement from the PC, over either link, applied on the main
@@ -2311,7 +3084,10 @@ class TrayApp(rumps.App):
def refresh_status(self, _timer):
self.windows_input.sync(self.controller.cfg)
self.measure_notch()
- self.control_window.refresh()
+ if self.control_window.window.isVisible():
+ self.control_window.refresh()
+ else:
+ self.control_window.retry_capture()
self.gesture_overlay.sync()
controller = self.controller
held = controller.crossing.armed and (controller.crossing_paused or controller.full_screen_app is not None)
@@ -2366,6 +3142,10 @@ class TrayApp(rumps.App):
self.logger.warning("direction not saved: %s", exc)
self.notify_user("Beamer", f"Could not save the change: {exc}")
return
+ if not cfg.send_to_windows and self.controller.redirecting:
+ # Input comes home by this switch, and shows where the pointer is as any switch does;
+ # update_config would bring it home too, silently, as it does for a new address.
+ self.controller.set_redirecting(False)
self.controller.update_config(cfg)
self.windows_input.sync(cfg)
self.logger.info("directions: this Mac drives Windows %s, Windows drives this Mac %s",
@@ -2380,8 +3160,9 @@ class TrayApp(rumps.App):
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))
+ # The controller first: the window's address fields read Hide addresses from it.
self.controller.update_config(cfg)
+ self.control_window._load(config_to_raw(cfg))
self.notify_user("Configuration reloaded", "Beamer is using the config on disk.")
def show_about(self, _sender):
@@ -2421,22 +3202,87 @@ class TrayApp(rumps.App):
def _crossing_feedback_main(self, kind, step):
try:
+ if kind == "home":
+ self._show_landing(step.pin[0], step.pin[1])
+ return
feel = self.controller.cfg.crossing
+ if kind == "arrive" and step.pin is not None and not self.effects_overlay.wanted(feel):
+ self.effects_overlay.crossed_in()
if feel["haptics"]:
if kind == "tick":
if crossing.tick_fires(feel["haptic_steps"], step.pressure):
- self.haptics.tick(feel["haptic_feel"])
+ self.haptics.tick()
elif kind in ("cross", "arrive"):
self.haptics.thud()
if feel["glow"]:
- if step.via == "notch":
+ drawn = False
+ if self.effects_overlay.wanted(feel):
+ # A crossing effect draws edge, corner and notch alike; the notch style is not used.
+ if kind == "arrive":
+ if step.pin is not None and step.mac_edge is not None:
+ self.effects_overlay.arrival("edge", step.pin[0], step.pin[1], step.mac_edge)
+ else:
+ self.effects_overlay.departure(kind, step)
+ # An effect that failed on this very event has turned itself off: today's glow
+ # draws it instead, so a breakthrough is never lost.
+ drawn = not self.effects_overlay.disabled
+ if not drawn and step.via == "notch":
notch = self.notch_beam if feel["notch_style"] == "beam" else self.notch_island
notch.update(kind)
- else:
+ elif not drawn:
self.edge_glow.update(kind, step)
except Exception:
self.logger.exception("crossing feedback failed")
+ def _driven_pressure(self, edge, pressure, crossed, part=None):
+ """The receiver's return edge while the PC drives this Mac, off its session thread: the push
+ home plays the departure effect. Today's glow never drew this direction."""
+ # Read here, beside the pressure it goes with: by the time the main thread runs, the
+ # receiver may have warped the pointer again.
+ try:
+ cursor = desktop_mac.cursor_position()
+ except Exception:
+ self.logger.exception("could not read the pointer for the return edge")
+ return
+ AppHelper.callAfter(self._driven_pressure_main, edge, pressure, crossed, cursor, part)
+
+ def _driven_pressure_main(self, edge, pressure, crossed, cursor, part=None):
+ """`part` names the corner when the way home is one, so it plays its corner form."""
+ corner = part if part in return_edge.CORNERS else None
+ try:
+ feel = self.controller.cfg.crossing
+ if self.effects_overlay.wanted(feel):
+ self.effects_overlay.return_push(edge, pressure, crossed, cursor, corner)
+ elif feel["glow"]:
+ self.edge_glow.driven(edge, pressure, crossed, cursor, corner)
+ except Exception:
+ self.logger.exception("return edge feedback failed")
+
+ def _driven_arrival(self, edge, x, y):
+ """The PC's input has just come to this Mac: placed at `edge` by a crossing, or left where
+ it was by a switch, when `edge` is None."""
+ AppHelper.callAfter(self._driven_arrival_main, edge, x, y)
+
+ def _driven_arrival_main(self, edge, x, y):
+ try:
+ if edge is None:
+ self._show_landing(x, y)
+ elif self.effects_overlay.wanted(self.controller.cfg.crossing):
+ self.effects_overlay.arrival("edge", x, y, edge)
+ else:
+ self.effects_overlay.crossed_in()
+ except Exception:
+ self.logger.exception("arrival feedback failed")
+
+ def _show_landing(self, x, y):
+ """Input came to this Mac by a switch rather than a crossing, and the pointer is at (x, y)
+ in Quartz points: show where, if the Design page says to."""
+ try:
+ if self.effects_overlay.wanted_switch(self.controller.cfg.crossing):
+ self.effects_overlay.switched(x, y)
+ except Exception:
+ self.logger.exception("switch feedback failed")
+
def notify_user(self, title, message):
"""Wired to controller.on_user_alert, which fires on the event-tap and
connection threads. AppKit is main-thread only, so the work hops
@@ -2458,6 +3304,7 @@ class TrayApp(rumps.App):
def quit_app(self, _sender=None):
self.status_timer.stop()
+ self.update_checker.stop()
self.discovery.stop()
self.windows_input.stop()
self.controller.stop()
@@ -2488,13 +3335,14 @@ def main(argv=None):
# Which faces actually carried the window: the only way to tell the bundled copies failed to
# register is to say what was used instead.
logger.info("type: %s / %s", theme.sans(), theme.mono())
- if args.config is None:
- migrate_legacy_config()
settings_store = SettingsStore(args.config)
try:
cfg = settings_store.load()
except SettingsError as exc:
- logger.warning("settings not loaded: %s", exc)
+ if Path(settings_store.path).exists():
+ logger.warning("settings not loaded: %s", exc)
+ else:
+ logger.info("first run: no settings yet, starting from the defaults")
cfg = editable_default_config()
controller = WakingController(cfg, logger=logger)
app = TrayApp(controller, settings_store, logger, hidden=args.hidden)
diff --git a/mac_app/link_state.py b/mac_app/link_state.py
index 0387c6a..272623f 100644
--- a/mac_app/link_state.py
+++ b/mac_app/link_state.py
@@ -76,7 +76,7 @@ def describe(controller) -> LinkState:
via = " through the macOS 27 tunnel" if tunnel else ""
return LinkState("mac", INK, "On Mac", linked, f"Connected to {peer}{via}.", SIGNAL)
if not (cfg.host and cfg.auth_token):
- return LinkState("unpaired", AMBER, "Not paired", "Setup", "Pair with a PC on the Pairing page and Beamer connects on its own.", AMBER)
+ return LinkState("unpaired", AMBER, "Not paired", "Setup", "Pair with a PC on Overview and Beamer connects on its own.", AMBER)
address = f"{cfg.host} port {cfg.port}"
if status == AUTH_FAILED_STATUS:
return LinkState("token", FAULT, "Token mismatch", "Refused", f"{peer} refused this Mac's shared token. Pair again to write a fresh one.", FAULT)
diff --git a/mac_app/motion.py b/mac_app/motion.py
new file mode 100644
index 0000000..5d35f6a
--- /dev/null
+++ b/mac_app/motion.py
@@ -0,0 +1,150 @@
+"""The settings window's motion: short, eased changes that show what a setting did, and none at all
+under Reduce Motion or while the window is not on screen, when a change lands at once."""
+
+from __future__ import annotations
+
+import AppKit
+import Quartz
+import objc
+
+DURATION = 0.2
+# Hiding runs as a fade and then the collapse, each this long, so the row has gone before the rows
+# under it close the gap over where it was.
+FADE_OUT = 0.1
+
+_serials: dict = {}
+
+
+def reduced():
+ try:
+ return bool(AppKit.NSWorkspace.sharedWorkspace().accessibilityDisplayShouldReduceMotion())
+ except Exception:
+ return False
+
+
+def live(view):
+ """Whether a change to `view` should move: its window is on screen and motion is not reduced."""
+ window = view.window() if view is not None else None
+ return window is not None and bool(window.isVisible()) and not reduced()
+
+
+def timing():
+ return Quartz.CAMediaTimingFunction.functionWithControlPoints____(0.16, 1.0, 0.3, 1.0)
+
+
+def transaction(animate, duration=DURATION):
+ """Opens a CATransaction for layer changes: eased over `duration`, or with actions off so the
+ change lands at once. Close it with Quartz.CATransaction.commit()."""
+ Quartz.CATransaction.begin()
+ if animate:
+ Quartz.CATransaction.setAnimationDuration_(duration)
+ Quartz.CATransaction.setAnimationTimingFunction_(timing())
+ else:
+ Quartz.CATransaction.setDisableActions_(True)
+
+
+def _group(duration, changes, done=None):
+ def run(context):
+ context.setDuration_(duration)
+ context.setTimingFunction_(timing())
+ context.setAllowsImplicitAnimation_(True)
+ changes()
+
+ AppKit.NSAnimationContext.runAnimationGroup_completionHandler_(run, done)
+
+
+def _relayout(view):
+ window = view.window()
+ if window is not None:
+ window.contentView().layoutSubtreeIfNeeded()
+
+
+def heading(view):
+ """Whether `view` is hidden, or is on its way to being: during a hide the view is still shown
+ for its fade, so isHidden() reads False until the fade is over."""
+ target = _serials.get(objc.pyobjc_id(view), (0, None))[1]
+ return bool(view.isHidden()) if target is None else target
+
+
+def moving(view):
+ return _serials.get(objc.pyobjc_id(view), (0, None))[1] is not None
+
+
+def set_hidden(view, hidden, done=None):
+ """Shows or hides a row of a stack view. Moving, a row fades and the rows below slide to close
+ or open its space, so the page does not jump under the pointer. `done` runs once a hide has
+ collapsed, or at once when there is nothing to move."""
+ hidden = bool(hidden)
+ key = objc.pyobjc_id(view)
+ serial, target = _serials.get(key, (0, None))
+ # Called again for where it is already going, as the window's refresh does several times a
+ # second, it leaves a move in flight alone.
+ if target == hidden or (target is None and bool(view.isHidden()) == hidden):
+ if done is not None and target is None:
+ done()
+ return
+ serial += 1
+ _serials[key] = (serial, hidden)
+
+ def settled():
+ if _serials.get(key, (None,))[0] == serial:
+ _serials[key] = (serial, None)
+
+ if not live(view):
+ view.setHidden_(hidden)
+ view.setAlphaValue_(1.0)
+ settled()
+ if done is not None:
+ done()
+ return
+ if hidden:
+ def collapsed():
+ if _serials.get(key, (None,))[0] == serial:
+ view.setAlphaValue_(1.0)
+ settled()
+ if done is not None:
+ done()
+
+ def collapse():
+ if _serials.get(key, (None,))[0] != serial:
+ return
+ _group(DURATION, lambda: (view.setHidden_(True), _relayout(view)), collapsed)
+
+ _group(FADE_OUT, lambda: view.animator().setAlphaValue_(0.0), collapse)
+ return
+ def reveal():
+ view.setHidden_(False)
+ view.setAlphaValue_(1.0)
+ _relayout(view)
+
+ _group(DURATION, reveal, settled)
+ layer = view.layer()
+ if layer is not None:
+ # Laid out for the first time, a row slides in from wherever it last sat and grows its
+ # insides out of a corner. It stays clear while the rows below open its space, and fades
+ # in once it has all but landed, so only the opening is seen.
+ fade = Quartz.CAKeyframeAnimation.animationWithKeyPath_("opacity")
+ fade.setValues_([0.0, 0.0, 1.0])
+ fade.setKeyTimes_([0.0, 0.5, 1.0])
+ fade.setDuration_(DURATION * 1.5)
+ fade.setTimingFunctions_([timing(), timing()])
+ layer.addAnimation_forKey_(fade, "reveal")
+
+
+def cross_fade(view):
+ """Cross-fades whatever `view` draws next with what it draws now: call it just before the change."""
+ if not live(view) or view.layer() is None:
+ return
+ fade = Quartz.CATransition.animation()
+ fade.setType_(Quartz.kCATransitionFade)
+ fade.setDuration_(DURATION)
+ fade.setTimingFunction_(timing())
+ view.layer().addAnimation_forKey_(fade, "cross-fade")
+
+
+def fade_paint(view, changes):
+ """Runs `changes` to a view's layer colours so the old colours fade into the new."""
+ if not live(view):
+ changes()
+ return
+ _group(DURATION * 0.75, changes)
diff --git a/mac_app/no_unlock.py b/mac_app/no_unlock.py
index 79869be..2765fdd 100644
--- a/mac_app/no_unlock.py
+++ b/mac_app/no_unlock.py
@@ -1,6 +1,7 @@
"""The Mac has no lock-screen unlock, and the receiver is written to expect
one. `is_locked` answering None is how it says "no idea, carry on" -- the same
-answer the Windows module gives when Room Deck's provider is absent.
+answer the Windows module gives when its external unlock credential provider
+is absent.
A Mac at its own lock screen simply does not receive the PC's input; macOS
gives no application a way to type on it, exactly as Windows gives none for
diff --git a/mac_app/notch_beam.py b/mac_app/notch_beam.py
index e309a50..d4cc7ac 100644
--- a/mac_app/notch_beam.py
+++ b/mac_app/notch_beam.py
@@ -16,7 +16,7 @@ The comet moves by distance along the path (strokeStart and strokeEnd), in at th
out at the right, with the notch itself hiding the way back. The package turns a conic mask instead,
and on a card that is fine; on this tab, far wider than it is deep, it was not: half of every turn
pointed up into the camera cutout, which has no pixels, the short sides lit all at once as the sweep
-crossed them, and the long bottom shrank the comet to a spot. Recorded 15-09-2026 as flashing.
+crossed them, and the long bottom shrank the comet to a spot: the net effect reads as flashing.
Movement is integrated on the frame timer rather than left to a CABasicAnimation, because its speed
follows pressure and retiming a running animation jumps. Reduce Motion parks the comet mid-border.
@@ -29,6 +29,7 @@ import time
import AppKit
import Quartz
+import effects
import tokens
from notch_island import (
NOTCH_FALLBACK_HEIGHT,
@@ -70,10 +71,29 @@ EDGE_FINISH_S = 0.6
EDGE_FINISH_TRAVERSE_S = 0.35
-def palette_colours(name, closed=False):
- """CGColors for one of tokens.PALETTES, a lone colour repeated so a gradient has two stops, and
- with `closed` ending on the first colour so a conic ring has no seam."""
- values = list(tokens.PALETTES.get(name, tokens.PALETTES["signal"]))
+def palette_values(name):
+ """The hex colours of a glow_colour setting: one of tokens.PALETTES, else a crossing-effects
+ pack, which any style may use, else Beamer's own signal."""
+ if name in tokens.PALETTES:
+ return list(tokens.PALETTES[name])
+ try:
+ found = effects.pack(name) if name in effects.PACK_IDS else None
+ except Exception:
+ # The effects' modules failed to load; the overlay has already said so.
+ found = None
+ return list(found[1]) if found is not None else list(tokens.PALETTES["signal"])
+
+
+def dark_appearance():
+ style = AppKit.NSUserDefaults.standardUserDefaults().stringForKey_("AppleInterfaceStyle")
+ return str(style or "").lower() == "dark"
+
+
+def palette_colours(name, closed=False, dark=False):
+ """CGColors for a glow_colour setting (see palette_values), a lone colour repeated so a gradient has two stops, and
+ with `closed` ending on the first colour so a conic ring has no seam. `dark` lifts the darkest colours as the
+ crossing effects do on a dark appearance, where the Ink packs all but vanish."""
+ values = effects.legible(palette_values(name), dark)
if len(values) == 1:
values *= 2
if closed:
@@ -135,6 +155,8 @@ def _rgb(red, green, blue, alpha=1.0):
class NotchBeam(NotchIsland):
+ dark_appearance = staticmethod(dark_appearance)
+
def __init__(self, controller, logger):
super().__init__(controller, logger)
self.strength = 0.0
@@ -196,11 +218,11 @@ class NotchBeam(NotchIsland):
# in from the near shoulder, a new flash on the way out.
self.position = (self.position + LAP * elapsed / turn_seconds(self.strength)) % LAP
spans = comet_segments(self.position)
- colour = self.controller.cfg.crossing["glow_colour"]
+ colour = (self.controller.cfg.crossing["glow_colour"], self.dark_appearance())
with _no_actions():
if colour != self.painted:
for gradient in self.gradients:
- gradient.setColors_(palette_colours(colour, closed=True))
+ gradient.setColors_(palette_colours(colour[0], closed=True, dark=colour[1]))
self.painted = colour
for segments in self.comets:
for layer, (start, end) in zip(segments, spans):
diff --git a/mac_app/notch_island.py b/mac_app/notch_island.py
index c9db26e..21a54cc 100644
--- a/mac_app/notch_island.py
+++ b/mac_app/notch_island.py
@@ -4,13 +4,12 @@ The edge glow cannot do this job. It draws a band inward from the strip being pu
strip sits in the top 32pt of a notched screen, where the display has no pixels at all: the band
topped out at 20pt, so every frame of it was drawn behind the camera housing and nobody ever saw it.
-So the notch grows instead, drawn to the Vernier design (docs/designs/claude-2-vernier.html). A black
-shape with the notch's own concave shoulders sits over the cutout, invisible at rest. Pressure
-springs it wider and down past the cutout; a signal-coloured rim and glow trace its lower outline,
-and once it is deep enough a four-segment meter and the percentage appear inside it. Each trackpad
-tick gives the width a small velocity kick, so the tick is seen as well as felt. Breakthrough plays
-as its own fixed sequence, see `breakthrough_phase`. Everything that glows or reads is masked to
-below the cutout.
+So the notch grows instead, drawn to the Vernier design. A black shape with the notch's own concave
+shoulders sits over the cutout, invisible at rest. Pressure springs it wider and down past the
+cutout; a signal-coloured rim and glow trace its lower outline, and once it is deep enough a
+four-segment meter and the percentage appear inside it. Each trackpad tick gives the width a small
+velocity kick, so the tick is seen as well as felt. Breakthrough plays as its own fixed sequence,
+see `breakthrough_phase`. Everything that glows or reads is masked to below the cutout.
Core Animation does the motion: every pressure change retargets a CASpringAnimation on the shape's
path from its presentation value, so a push that wavers never jumps. Reduce Motion replaces growth
@@ -139,7 +138,7 @@ class NotchIsland:
while the pointer is still pinned at the notch, the highest recent pressure is held for
GRACE_S instead. That includes a slow push, whose pressure drains to nothing between every
pair of events: reading the engine's pin, which it drops each time, showed and hid the
- notch several times a second, a strobe recorded 15-09-2026. Moving off the notch still lets
+ notch several times a second, which strobes. Moving off the notch still lets
go at once, since the engine stops touching."""
if not getattr(getattr(self.controller, "crossing", None), "touching", False):
self.held, self.held_at = level, now
@@ -398,7 +397,7 @@ class NotchIsland:
view.setWantsLayer_(True)
panel.setContentView_(view)
- # Top-left origin inside the island, so every path below reads like the mock's SVG. The
+ # Top-left origin inside the island, so every path below reads like the design's SVG. The
# window server puts a window on whole points, so the stage is offset by whatever that
# rounding moved: the island asked for 88.5pt from x 689.5 and got 89 from x 689, which
# anchored at the bottom left a one-pixel row of wallpaper above the black.
diff --git a/mac_app/pages.py b/mac_app/pages.py
index c858e49..74670a9 100644
--- a/mac_app/pages.py
+++ b/mac_app/pages.py
@@ -1,29 +1,50 @@
"""The control window's pages, which one opens first, and which carry a dot in the sidebar.
-Pure, so the rules are tested without AppKit.
+Pure, so the rules are tested without AppKit. The Design page's groups of styles and colours live here
+for the same reason.
"""
from __future__ import annotations
-# (key, name, SF Symbol, what the page is for), in sidebar order; Cmd+1 is the first.
+import re
+
+import effects
+
+# (key, name, SF Symbol, what the page is for), in sidebar order, which is the order a new Mac is
+# set up in after the Overview; Cmd+1 is the first.
PAGES = (
("overview", "Overview", "gauge.with.needle",
- "Where input is, whether the link is up, and the controls you reach for every day."),
+ "Where input is, whether the link is up, and the controls you reach for every day. Pair with a "
+ "PC here first."),
+ ("permissions", "Permissions", "lock.shield",
+ "macOS must allow Beamer to read this keyboard and trackpad before it can send them anywhere."),
("crossing", "Crossing", "cursorarrow.motionlines",
- "How the pointer passes from this Mac to Windows, and how hard the edge pushes back first."),
- ("design", "Design", "paintpalette",
- "How crossing looks and feels on this Mac: the notch, the edge and the trackpad. Every change applies as you make it."),
+ "Choose how the pointer or a key moves input to Windows, and how hard the edge pushes back first."),
("keyboard", "Keyboard", "keyboard",
- "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."),
+ "How this Mac's modifier keys arrive on Windows, which keys and buttons stay on this Mac, and "
+ "how fast the PC's pointer moves here. The switch key is on the Crossing page."),
+ ("design", "Design", "paintpalette",
+ "How crossing looks and feels on this Mac: the edge, the corner, the notch and the trackpad."),
("connection", "Connection", "network",
"Where the PC is and the token this Mac proves itself with. Pairing fills these in."),
- ("permissions", "Permissions", "lock.shield",
- "macOS must allow Beamer to read this keyboard and trackpad before it can send them anywhere."),
)
KEYS = tuple(page[0] for page in PAGES)
+# Under the purpose on the pages whose settings are this Mac's alone, so nobody looks for the PC's
+# on the Mac: each app sets only its own machine, and the PC's are in Beamer on the PC.
+SCOPE = {
+ "crossing": "For this Mac only; the PC keeps its own. Only which side the PC is on is shared. This Mac's "
+ "resistance is also what its pointer meets at the PC's edge on the way back.",
+ "design": "For this Mac's screen only; the PC keeps its own.",
+ "keyboard": "For this Mac's keyboard only; the PC keeps its own.",
+}
+# The window's footer, and the pages where its first sentence would be untrue.
+FOOTER_APPLIES = "Changes apply as you make them."
+FOOTER_RUNNING = "Closing this window keeps Beamer running in the menu bar."
+EXPLICIT_PAGES = ("connection",)
+
+
+def footer(page):
+ return FOOTER_RUNNING if page in EXPLICIT_PAGES else f"{FOOTER_APPLIES} {FOOTER_RUNNING}"
def opening_page(last, accessibility, input_monitoring):
@@ -40,7 +61,7 @@ def dots(accessibility, input_monitoring, link_key):
if not (accessibility and input_monitoring):
marks["permissions"] = "amber"
if link_key == "token":
- marks["pairing"] = "fault"
+ marks["overview"] = "fault"
return marks
@@ -48,3 +69,259 @@ def step(current, direction):
"""The page an arrow key moves to, stopping at either end of the list."""
index = KEYS.index(current) if current in KEYS else 0
return KEYS[min(max(index + direction, 0), len(KEYS) - 1)]
+
+
+# The Design page's styles and colours. The classic Glow and Beam come first and stay the default;
+# the crossing effects follow in effects.DIRECTIONS order, each direction a row of quiet, medium
+# and showpiece, and its three colour packs a row of swatches.
+TODAY = "Classic"
+TODAY_STYLES = (
+ ("glow", "Glow", "A band of light that deepens the harder you push."),
+ ("beam", "Beam", "A thin line with a comet of light running along it."),
+)
+INTENSITIES = {"quiet": "Quiet", "medium": "Medium", "showpiece": "Showpiece", "classic": "Classic"}
+
+
+def effects_load_error():
+ """None when every crossing effect loads, else the exception: the Design page then offers only
+ today's styles and colours rather than failing to build."""
+ try:
+ effects._load()
+ except Exception as exc:
+ return exc
+ return None
+
+
+def style_groups(with_effects=True):
+ """[(group, [(style id, name, detail)])] for the style tiles."""
+ # Glow and Beam's detail is their kind, as an effect's is its intensity; what they do is said
+ # under the preview.
+ groups = [(TODAY, [(value, name, INTENSITIES["classic"]) for value, name, _blurb in TODAY_STYLES])]
+ for _module, direction, effect_ids, _packs in effects.DIRECTIONS if with_effects else ():
+ row = []
+ for effect_id in effect_ids:
+ fx = effects.effect(effect_id)
+ row.append((effect_id, fx.name, INTENSITIES.get(fx.intensity, fx.intensity.capitalize())))
+ groups.append((direction, row))
+ return groups
+
+
+SIMPLE = "Simple"
+
+
+def switch_style_groups(with_effects=True):
+ """[(group, [(value, name, detail)])] for the style tiles in Switch mode: what a switch plays,
+ effects.SWITCH_STYLES, with the effects grouped as the crossing's are."""
+ simple = [("match", "Same as crossing", "Plays the crossing style"), ("locator", "Ring", "Closes onto the pointer")]
+ return [(SIMPLE, simple)] + style_groups(with_effects)[1:]
+
+
+def colour_groups(today_colours, with_effects=True):
+ """[(group, [(colour id, name)])] for the swatches; `today_colours` is crossing.GLOW_COLOURS."""
+ groups = [(TODAY, [(name, name.capitalize()) for name in today_colours])]
+ for _module, direction, _effects, pack_ids in effects.DIRECTIONS if with_effects else ():
+ groups.append((direction, [(pack_id, effects.pack(pack_id)[0]) for pack_id in pack_ids]))
+ return groups
+
+
+def notch_style_applies(style):
+ """A crossing effect draws the notch itself, so the notch style only matters under Glow and Beam."""
+ return style not in effects.EFFECT_IDS
+
+
+def part_names(edge):
+ """The names of return_edge.PARTS along `edge`, as the page shows them: top to bottom on a side
+ edge, left to right along the top or bottom."""
+ if edge in ("left", "right"):
+ return {"start": "Top", "middle": "Middle", "end": "Bottom"}
+ return {"start": "Left", "middle": "Middle", "end": "Right"}
+
+
+def parts_phrase(edge, parts):
+ """The chosen thirds in a sentence: "the top and middle of the right edge"."""
+ names = part_names(edge)
+ # No third, or none known, is never saved, but a sentence must not be what fails on it.
+ chosen = [names[part].lower() for part in ("start", "middle", "end") if part in parts] or ["middle"]
+ joined = chosen[0] if len(chosen) == 1 else ", ".join(chosen[:-1]) + " and " + chosen[-1]
+ return f"the {joined} of the {edge} edge"
+
+
+# The ways in, in the Crossing page's order.
+WAYS = ("shortcut", "edge", "part", "corner", "notch")
+_EXCLUSIVE = {"edge": "part", "part": "edge"}
+
+
+def toggle_way(methods, way, on):
+ """The ways in after `way` is switched on or off. Edge and Part of the edge exclude each other:
+ the whole edge already includes any part of it."""
+ chosen = set(methods) - {way}
+ if on:
+ chosen = (chosen | {way}) - {_EXCLUSIVE.get(way)}
+ return [name for name in WAYS if name in chosen]
+
+
+def toggle_part(parts, part, on):
+ """The thirds after `part` is ticked or unticked. The last one cannot be unticked: no thirds
+ would be a way in that never crosses; switching Part of the edge off is how to have none."""
+ chosen = set(parts) | {part} if on else set(parts) - {part}
+ if not chosen:
+ chosen = set(parts)
+ return [name for name in ("start", "middle", "end") if name in chosen]
+
+
+# The Crossing page's diagram: this Mac's screen at 16:10 and the PC's at 16:9, a gap between.
+DIAGRAM_THIS = (120.0, 75.0)
+DIAGRAM_OTHER = (112.0, 63.0)
+DIAGRAM_GAP = 10.0
+MARK = 3.0
+CORNER_MARK = 12.0
+
+
+def arrangement(width, height, side):
+ """Where the two screens sit in a diagram `width` by `height`, top left at the origin: (this,
+ other) as (x, y, w, h), the pair centred with the other screen on `side` of this one."""
+ tw, th = DIAGRAM_THIS
+ ow, oh = DIAGRAM_OTHER
+ if side in ("left", "right"):
+ left = (width - (tw + DIAGRAM_GAP + ow)) / 2
+ this_x = left + ow + DIAGRAM_GAP if side == "left" else left
+ other_x = left if side == "left" else left + tw + DIAGRAM_GAP
+ return (this_x, (height - th) / 2, tw, th), (other_x, (height - oh) / 2, ow, oh)
+ top = (height - (th + DIAGRAM_GAP + oh)) / 2
+ this_y = top + oh + DIAGRAM_GAP if side == "top" else top
+ other_y = top if side == "top" else top + th + DIAGRAM_GAP
+ return ((width - tw) / 2, this_y, tw, th), ((width - ow) / 2, other_y, ow, oh)
+
+
+def side_mark(screen, side):
+ """The strip of `screen` along `side` that lights for the Edge way."""
+ x, y, w, h = screen
+ return {
+ "left": (x, y, MARK, h),
+ "right": (x + w - MARK, y, MARK, h),
+ "top": (x, y, w, MARK),
+ "bottom": (x, y + h - MARK, w, MARK),
+ }[side]
+
+
+def third_marks(screen, side, gap=2.0):
+ """The three thirds of the side strip, start to end as return_edge.PARTS runs: top to bottom
+ on a side edge, left to right along the top or bottom."""
+ x, y, w, h = side_mark(screen, side)
+ if side in ("left", "right"):
+ length = (h - 2 * gap) / 3
+ return {part: (x, y + index * (length + gap), w, length) for index, part in enumerate(("start", "middle", "end"))}
+ length = (w - 2 * gap) / 3
+ return {part: (x + index * (length + gap), y, length, h) for index, part in enumerate(("start", "middle", "end"))}
+
+
+def corner_mark(screen, corner):
+ x, y, w, h = screen
+ size = CORNER_MARK
+ vertical, horizontal = corner.split("_")
+ return (x if horizontal == "left" else x + w - size, y if vertical == "top" else y + h - size, size, size)
+
+
+def notch_mark(screen):
+ x, y, w, _h = screen
+ width = round(w * 0.2)
+ return (x + (w - width) / 2, y, width, 6.0)
+
+
+def crossing_state_sentence(paired, sending, connected, armed, paused, full_screen_app):
+ """The Crossing page's line under Pause: why nothing can cross, first match wins, and only then
+ whether crossing is on, held or paused."""
+ if not paired:
+ return "Not paired yet, so no edge or shortcut moves input until you pair with a PC above."
+ if not sending:
+ return "This Mac drives Windows is off, so edges and the shortcut do nothing."
+ if not connected:
+ return "Not connected to the PC, so edges and the shortcut do nothing yet."
+ if not armed:
+ return "Only the shortcut is switched on; there is nothing to pause."
+ if paused:
+ return "Paused. Edges, corners and the notch do nothing until you resume; the shortcut still works."
+ if full_screen_app is not None:
+ return (
+ f"Off while {full_screen_app} is full screen, so the pointer stays put at "
+ "the edges; the shortcut still works."
+ )
+ return "On. Pause it to lean on an edge without switching."
+
+
+def crossing_state_blocked(paired, sending, connected):
+ """Whether crossing_state_sentence is giving a reason nothing can cross."""
+ return not (paired and sending and connected)
+
+
+PLACES = {"edge": "the edge", "corner": "a corner", "notch": "the notch"}
+
+
+def preview_place(methods):
+ """Where the Design page's preview opens: the first of the pointer's ways in it can show, Part of
+ the edge shown as the edge, or the edge when the only way in is the shortcut."""
+ chosen = set(methods)
+ for place, ways in (("edge", {"edge", "part"}), ("corner", {"corner"}), ("notch", {"notch"})):
+ if chosen & ways:
+ return place
+ return "edge"
+
+
+def place_note(style, place, methods, has_notch):
+ """The line under the preview's Edge / Corner / Notch switch: why nothing would cross there, or
+ how the chosen style plays there; empty when there is nothing to add."""
+ if place == "notch" and not has_notch:
+ return "This Mac has no notch, so this only shows how it would look."
+ ways = {"edge": {"edge", "part"}, "corner": {"corner"}, "notch": {"notch"}}[place]
+ off = not set(methods) & ways
+ if off:
+ lead = f"{PLACES[place].capitalize()} is not one of your ways in, so this only shows how it would look. "
+ lead += "Turn it on under Crossing."
+ else:
+ lead = ""
+ if place != "notch":
+ return lead
+ if notch_style_applies(style):
+ return (lead + " " if lead else "") + "At the notch, Glow and Beam do not draw: the notch style you choose here plays instead, and their tiles show it."
+ name = effects.effect(style).name if effects.effect(style) is not None else "The effect"
+ return (lead + " " if lead else "") + f"{name} draws its own form round the notch."
+
+
+def notch_or_corner_only(methods):
+ """The pointer's only ways in are the notch and/or a corner, so input arrives by their own side
+ and Where the PC is does not steer it."""
+ chosen = set(methods)
+ return bool(chosen & {"notch", "corner"}) and not chosen & {"edge", "part"}
+
+
+NOTCH_OR_CORNER_NOTE = (
+ "With only the notch or a corner on, input arrives by the notch's or corner's own side, so this "
+ "choice does nothing on this Mac; your PC's own push still follows it."
+)
+
+
+def crossing_rows(methods):
+ """Which of the Crossing page's rows and modules show for these ways. The rest are hidden, not
+ dimmed, and reappear the moment a way that uses them is chosen."""
+ chosen = set(methods)
+ pointer = bool(chosen & {"edge", "part", "corner", "notch"})
+ return {
+ # Where the PC sits, which every way in uses: a crossing arrives by it, and with only the
+ # shortcut on it is still the PC's edge that leads back here.
+ "edge": True,
+ "parts": "part" in chosen,
+ "corner": "corner" in chosen,
+ "dragging": pointer,
+ "resistance": pointer,
+ "shortcut": "shortcut" in chosen,
+ }
+
+
+# An IPv4 address or a hardware address, anywhere in a line of text.
+_ADDRESS = re.compile(r"\b(?:\d{1,3}(?:\.\d{1,3}){3}|[0-9A-Fa-f]{2}(?:[:-][0-9A-Fa-f]{2}){5})\b")
+HIDDEN = "•••"
+
+
+def redact(text, hide):
+ """`text` with every address in it replaced when `hide` is on."""
+ return _ADDRESS.sub(HIDDEN, text) if hide and text else text
diff --git a/mac_app/pairing.py b/mac_app/pairing.py
index dfd7925..f733d84 100644
--- a/mac_app/pairing.py
+++ b/mac_app/pairing.py
@@ -12,6 +12,9 @@ Both proofs are HMACs keyed from the six-digit code (scrypt, salted with the pai
the transcript, so each side shows the other that it knows the code. The shared token is
HKDF over the X25519 secret: an eavesdropper who records every datagram cannot derive it.
+Where no broadcast reaches the Mac (another subnet, a VPN), the Mac asks a typed address for its
+beacon with a `find` datagram, and pairing continues exactly as above.
+
What this protects against, and what it does not:
- The token never crosses the wire, and neither does the code. The beacon carries nothing a
@@ -65,6 +68,9 @@ PAIR_ATTEMPTS = 3
MSG_BEACON = "beacon"
MSG_PAIR_REQUEST = "pair_request"
MSG_PAIR_REPLY = "pair_reply"
+# The Mac asking one address for its beacon, for a PC that no broadcast reaches (another subnet,
+# a VPN). The answer is the beacon every listener already hears, so it discloses nothing new.
+MSG_FIND = "find"
ERROR_NOT_PAIRING = "not_pairing"
ERROR_REFUSED = "refused"
@@ -296,11 +302,11 @@ def broadcast_targets(port: int) -> list:
broadcast as a backstop.
⚠ 255.255.255.255 alone is not enough and this is not theoretical: it leaves by the default
- route only, so a PC with a second interface — a Hyper-V vEthernet switch is the common case,
- and the owner's rig has one — announces on whichever the routing table prefers and may never
- reach the LAN the Mac is on. Measured 10-09-2026: the PC beaconed steadily while no beacon
- reached the Mac at all, and the Mac then paired against a stale id from an older beacon that
- had got through, which is what produced `not_pairing`.
+ route only, so a PC with a second interface — a Hyper-V vEthernet switch is the common case —
+ announces on whichever the routing table prefers and may never reach the LAN the Mac is on.
+ Seen in practice: the PC beaconed steadily while no beacon reached the Mac at all, and the Mac
+ then paired against a stale id from an older beacon that had got through, which is what
+ produced `not_pairing`.
The per-interface directed broadcast assumes a /24, because the stdlib exposes no netmask.
A wrong guess costs one datagram that goes nowhere; the limited broadcast is still sent, so
@@ -390,6 +396,11 @@ class Announcer:
self.host.active
return self.host.outcome
+ def _beacon(self) -> bytes:
+ with self._lock:
+ pair_id = self.host.pair_id if self.host.active else None
+ return encode(beacon_msg(self.name, self.port_getter(), pair_id))
+
def _run(self) -> None:
try:
sock = _udp_socket(self.bind_port)
@@ -399,14 +410,13 @@ class Announcer:
return
self.error = None
next_beacon = 0.0
+ answered = {}
try:
while not self._stop.is_set():
now = time.monotonic()
if now >= next_beacon:
next_beacon = now + BEACON_INTERVAL_SECONDS
- with self._lock:
- pair_id = self.host.pair_id if self.host.active else None
- beacon = encode(beacon_msg(self.name, self.port_getter(), pair_id))
+ beacon = self._beacon()
delivered = 0
# Only a caller asking for the limited broadcast wants the per-interface
# fan-out; a named address is honoured exactly, which keeps the tests off
@@ -441,6 +451,17 @@ class Announcer:
message = decode(data)
if message is None:
continue
+ if message.get("type") == MSG_FIND:
+ # At most one answer per address per interval, so the port is no amplifier.
+ if now - answered.get(address[0], -BEACON_INTERVAL_SECONDS) >= BEACON_INTERVAL_SECONDS / 4:
+ if len(answered) > 256:
+ answered.clear()
+ answered[address[0]] = now
+ try:
+ sock.sendto(self._beacon(), address)
+ except OSError as exc:
+ self.logger.warning("beacon to %s not sent: %s", address[0], exc)
+ continue
with self._lock:
reply = self.host.handle(message)
paired, self.host.paired = self.host.paired, None
@@ -476,8 +497,36 @@ class Discovery:
self._stop = threading.Event()
self._thread = None
self._sock = None
+ self._finding = None
+ self._find_serial = 0
+ self._next_find = 0.0
self.error = None
+ def find(self, host: str, port: int = PAIRING_PORT) -> None:
+ """Ask `host` for its beacon, for a PC no broadcast reaches, and keep asking while
+ discovery runs so it stays listed. Returns at once; the PC appears in pcs() when it
+ answers. An empty host stops asking."""
+ host = (host or "").strip()
+ with self._lock:
+ self._find_serial += 1
+ serial = self._find_serial
+ self._finding = None
+ self._next_find = 0.0
+ if host:
+ # A name can take seconds to resolve, and this loop also carries the pairing replies.
+ threading.Thread(target=self._resolve, args=(host, int(port), serial),
+ name="Beamer-find", daemon=True).start()
+
+ def _resolve(self, host: str, port: int, serial: int) -> None:
+ try:
+ address = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_DGRAM)[0][4][0]
+ except (OSError, IndexError) as exc:
+ self.logger.warning("could not resolve %s: %s", host, exc)
+ return
+ with self._lock:
+ if serial == self._find_serial:
+ self._finding = (address, port)
+
def start(self) -> None:
if self._thread is not None:
return
@@ -545,6 +594,7 @@ class Discovery:
self._sock = sock
try:
while not self._stop.is_set():
+ self._send_find(sock)
try:
data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)
except socket.timeout:
@@ -572,6 +622,17 @@ class Discovery:
self._sock = None
sock.close()
+ def _send_find(self, sock) -> None:
+ with self._lock:
+ target = self._finding
+ if target is None or self.clock() < self._next_find:
+ return
+ self._next_find = self.clock() + BEACON_INTERVAL_SECONDS
+ try:
+ sock.sendto(encode({"type": MSG_FIND}), target)
+ except OSError as exc:
+ self.logger.warning("could not ask %s for its beacon: %s", target[0], exc)
+
def _note_beacon(self, message: dict, address) -> None:
name = message.get("name")
port = message.get("port")
diff --git a/mac_app/previews.py b/mac_app/previews.py
index 1cc3c64..25cb959 100644
--- a/mac_app/previews.py
+++ b/mac_app/previews.py
@@ -1,11 +1,13 @@
"""Live previews for the Design page: the notch and edge animations, played in the settings window by
-the very classes that draw them on screen, so a preview cannot drift from the real thing.
+the very classes that draw them on screen, so a preview cannot drift from the real thing. The crossing
+effects' previews at the end of the file do the same through effects_overlay's replay.
Each renderer is hosted in a view rather than a screen-level panel. Only where it draws, and how it
is shown and hidden, is redirected; everything else runs as it does on screen. PreviewFeed stands in
for the controller: the live settings, so a change shows at once, with a scripted push instead of a
trackpad. The script builds pressure, goes through, keeps animating for the chosen time and rests,
-on a loop, and PreviewLoop only runs it while the Design page is showing.
+on a loop. PreviewLoop plays a notch tile only while the pointer is over it, and only while the Design
+page is showing.
Main thread only. A failing preview disables itself as the real renderer does; nothing depends on it.
"""
@@ -16,9 +18,12 @@ import types
import AppKit
import Quartz
import objc
-import rumps
import crossing
+import effects
+import effects_overlay
+import motion
+import notch_beam
import notch_island
import theme
@@ -70,6 +75,11 @@ class PreviewFeed:
def crossing_pressure_now(self):
return self.level
+ def _current_desktop_bounds(self):
+ """A preview draws in its own small scene, not on the desktop, so there are no displays
+ to cut its band to."""
+ return None
+
class _Panel:
"""The panel calls the renderers make, answered by a view in the settings window."""
@@ -99,6 +109,9 @@ def hosted_notch(base):
"""NotchBeam or NotchIsland, drawing into a PreviewScreen instead of over the notch."""
class HostedNotch(base):
+ # On the window's screen, not the desktop: the window's palette decides which variant draws.
+ dark_appearance = staticmethod(theme.is_dark)
+
def __init__(self, feed, logger, screen):
super().__init__(feed, logger)
self.screen = screen
@@ -126,6 +139,9 @@ def hosted_edge(base):
"""The app's EdgeGlow, drawing its band along the right side of a PreviewScreen."""
class HostedEdge(base):
+ # On the window's screen, not the desktop: the window's palette decides which variant draws.
+ dark_appearance = staticmethod(theme.is_dark)
+
def __init__(self, feed, logger, screen):
super().__init__(feed, logger)
self.screen = screen
@@ -166,9 +182,9 @@ class PreviewScreen(AppKit.NSView):
layer.setCornerRadius_(theme.RADIUS["field"])
layer.setMasksToBounds_(True)
layer.setBorderWidth_(1)
- layer.setBorderColor_(theme.colour("rule").CGColor())
+ theme.tint(layer, border="rule")
self.ground = Quartz.CAGradientLayer.layer()
- self.ground.setColors_([theme.colour("edge").CGColor(), theme.colour("well").CGColor()])
+ theme.tint(self.ground, colours=["edge", "well"])
self.ground.setStartPoint_((0.5, 1.0))
self.ground.setEndPoint_((0.5, 0.0))
layer.addSublayer_(self.ground)
@@ -216,60 +232,293 @@ class PreviewScreen(AppKit.NSView):
Quartz.CATransaction.commit()
+FRAME_RATE = 60
+HOVER_INTENT_S = 0.1
+
+
+class _Fire(AppKit.NSObject):
+ def fire_(self, _sender):
+ self.callback()
+
+
+def on_screen(view):
+ """Whether any of `view` can be seen: in a window on screen and not covered, not hidden, and not
+ scrolled out of its page."""
+ window = view.window()
+ if window is None or not window.isVisible() or view.isHiddenOrHasHiddenAncestor():
+ return False
+ if not window.occlusionState() & AppKit.NSWindowOcclusionStateVisible:
+ return False
+ visible = view.visibleRect()
+ return visible.size.width > 0 and visible.size.height > 0
+
+
+class FrameClock:
+ """Calls `callback()` once a frame, timed to `view`'s display at up to FRAME_RATE where macOS
+ offers a view's display link (14 and later), else by a timer. Either runs in the common run loop
+ modes, as a default-mode timer, rumps.Timer's, stops dead while the page scrolls or a slider is
+ dragged and then jumps."""
+
+ def __init__(self, view, callback):
+ self.view = view
+ self.callback = callback
+ self.source = None
+
+ def start(self):
+ if self.source is not None:
+ return
+ target = _Fire.alloc().init()
+ target.callback = self.callback
+ runloop = AppKit.NSRunLoop.mainRunLoop()
+ if self.view.window() is not None and hasattr(self.view, "displayLinkWithTarget_selector_"):
+ link = self.view.displayLinkWithTarget_selector_(target, "fire:")
+ # 60 on a 120Hz panel lands every other refresh, evenly, where a timer beats against it.
+ link.setPreferredFrameRateRange_(Quartz.CAFrameRateRangeMake(30, FRAME_RATE, FRAME_RATE))
+ link.addToRunLoop_forMode_(runloop, AppKit.NSRunLoopCommonModes)
+ self.source = link
+ else:
+ timer = AppKit.NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
+ 1.0 / FRAME_RATE, target, "fire:", None, True
+ )
+ runloop.addTimer_forMode_(timer, AppKit.NSRunLoopCommonModes)
+ self.source = timer
+
+ def stop(self):
+ source, self.source = self.source, None
+ if source is not None:
+ source.invalidate()
+
+ def is_alive(self):
+ return self.source is not None
+
+
class PreviewLoop:
- """Plays every preview on the page from one clock, and only while it is wanted."""
+ """Plays the page's hosted renderers from one clock: the tile the pointer is over, else the
+ tiles set `resting`. Every other tile holds a still, the push part way in, and a tile that starts
+ playing goes on from that push rather than from nothing."""
- def __init__(self, controller):
+ HOLD = 0.7
+
+ def __init__(self, controller, host=None):
+ """`host` is a view on screen whenever the loop runs, the page itself, to time it by: a
+ view's display link stops while the view is hidden, as a tile's is in the other mode."""
self.controller = controller
self.players = []
- self.started_at = None
- self.phase = None
- self.quarter = 0
- self.timer = rumps.Timer(self._tick, 1 / 30)
+ self.running = False
+ self.resting = ()
+ self.hovered = None
+ self.hovered_at = 0.0
+ self.clock = None if host is None else FrameClock(host, self._tick)
- def add(self, feed, renderer, update):
+ def add(self, feed, renderer, update, screen):
"""`update(kind, pressure)` passes an event to `renderer` the way the app's crossing
- feedback would."""
- self.players.append((feed, renderer, update))
+ feedback would. The renderer's own timer is swapped for a FrameClock on `screen`."""
+ renderer.timer = FrameClock(screen, lambda: renderer._tick(None))
+ self.players.append(types.SimpleNamespace(feed=feed, renderer=renderer, update=update, screen=screen,
+ started_at=None, phase=None, quarter=0))
+ if self.clock is None:
+ self.clock = FrameClock(screen, self._tick)
+
+ def owns(self, view):
+ return any(player.screen is view for player in self.players)
+
+ def set_resting(self, screens):
+ self.resting = tuple(screens)
+
+ def hover(self, view):
+ """`view` is the preview of the tile under the pointer, one of this loop's or not, or None."""
+ self.hovered = view
+ self.hovered_at = time.monotonic()
def start(self):
- if self.started_at is not None:
+ if self.running:
return
- self.started_at = time.monotonic()
- self.phase = None
- self.quarter = 0
- self.timer.start()
+ self.running = True
+ self.repaint()
+ if self.clock is not None:
+ self.clock.start()
def stop(self):
- if self.started_at is None:
+ if not self.running:
return
- self.started_at = None
- self.timer.stop()
- for feed, renderer, _update in self.players:
- feed.level = 0.0
- feed.crossing.touching = False
+ self.running = False
+ if self.clock is not None:
+ self.clock.stop()
+ for player in self.players:
+ player.started_at = None
+ player.feed.level = 0.0
+ player.feed.crossing.touching = False
try:
- renderer._hide()
- renderer.timer.stop()
+ player.renderer._hide()
+ player.renderer.timer.stop()
except Exception:
pass
- def _tick(self, _timer):
- if self.started_at is None:
+ def repaint(self):
+ """Draws every tile that is not playing again, as a colour or palette change needs."""
+ for player in self.players:
+ if player.started_at is None:
+ self._hold(player)
+
+ def _wanted(self, player):
+ # A pointer only passing over, or any under Reduce Motion, leaves the resting tile playing.
+ if (self.hovered is not None and time.monotonic() - self.hovered_at >= HOVER_INTENT_S
+ and not effects_overlay.reduce_motion()):
+ return player.screen is self.hovered
+ return player.screen in self.resting
+
+ def _hold(self, player):
+ feed, renderer = player.feed, player.renderer
+ feed.level = self.HOLD
+ feed.crossing.touching = True
+ try:
+ # Left mid-breakthrough, a renderer would freeze its flash, halo and run-off into the
+ # still and snap to the end of the crossing when it next played.
+ for name, value in (("cross_at", None), ("halo_at", None), ("flash_at", None), ("flare", 0.0),
+ ("kick", 0.0), ("held", 0.0), ("finish", 0.0)):
+ if hasattr(renderer, name):
+ setattr(renderer, name, value)
+ player.update("pressure", self.HOLD)
+ # Drawn once and left: a moving light part way along, at full strength rather than
+ # easing up to it from nothing.
+ if hasattr(renderer, "finish"):
+ renderer.centre = 0.5
+ if hasattr(renderer, "cross_travel"):
+ renderer.position = notch_beam.LAP * 0.3
+ renderer.strength = self.HOLD
+ if hasattr(renderer, "drawn_at"):
+ renderer.drawn_at = None
+ renderer._draw()
+ renderer.timer.stop()
+ except Exception:
+ pass
+
+ def _tick(self):
+ if not self.running:
return
+ now = time.monotonic()
after = self.controller.cfg.crossing["notch_after_ms"] / 1000.0
- level, phase = preview_frame(time.monotonic() - self.started_at, after)
- quarter = min(3, int(4 * level)) if phase == "push" else 0
- crossed = phase == "after" and self.phase == "push"
- ticked = quarter > self.quarter
- self.phase, self.quarter = phase, quarter
- for feed, _renderer, update in self.players:
- feed.level = level
- feed.crossing.touching = phase == "push"
+ for player in self.players:
+ playing = self._wanted(player) and on_screen(player.screen)
+ if not playing:
+ if player.started_at is not None:
+ player.started_at = None
+ motion.cross_fade(player.screen)
+ self._hold(player)
+ continue
+ if player.started_at is None:
+ # Where the script's push reaches the held still's pressure.
+ player.started_at = now - PUSH_S * self.HOLD ** (1 / 1.6)
+ player.phase, player.quarter = "push", min(3, int(4 * self.HOLD))
+ level, phase = preview_frame(now - player.started_at, after)
+ quarter = min(3, int(4 * level)) if phase == "push" else 0
+ crossed = phase == "after" and player.phase == "push"
+ ticked = quarter > player.quarter
+ player.phase, player.quarter = phase, quarter
+ player.feed.level = level
+ player.feed.crossing.touching = phase == "push"
if crossed:
- update("cross", 1.0)
+ player.update("cross", 1.0)
elif phase == "push" and level > 0.0:
- update("tick" if ticked else "pressure", level)
+ player.update("tick" if ticked else "pressure", level)
+
+
+class TileStack(AppKit.NSView):
+ """A tile's picture that is one of several views laid over each other, only one shown: Glow and
+ Beam's still, or at the notch, where the notch style plays in their place, that style's own
+ hosted preview."""
+
+ @objc.python_method
+ def setup(self, children, height=84):
+ self.setTranslatesAutoresizingMaskIntoConstraints_(False)
+ self.heightAnchor().constraintEqualToConstant_(height).setActive_(True)
+ self.children = list(children)
+ for child in self.children:
+ child.setTranslatesAutoresizingMaskIntoConstraints_(False)
+ self.addSubview_(child)
+ for a, b in ((child.leadingAnchor(), self.leadingAnchor()), (child.trailingAnchor(), self.trailingAnchor()),
+ (child.topAnchor(), self.topAnchor()), (child.bottomAnchor(), self.bottomAnchor())):
+ a.constraintEqualToAnchor_(b).setActive_(True)
+ self.shown = None
+ self.show(self.children[0])
+ return self
+
+ @objc.python_method
+ def show(self, child):
+ if child is self.shown:
+ return
+ if self.shown is not None:
+ motion.cross_fade(self)
+ self.shown = child
+ for other in self.children:
+ other.setHidden_(other is not child)
+
+ @objc.python_method
+ def current(self):
+ return self.shown
+
+
+class _HoverOwner(AppKit.NSObject):
+ def mouseEntered_(self, _event):
+ self.entered()
+
+ def mouseExited_(self, _event):
+ self.exited()
+
+
+class TileHover:
+ """The one tile under the pointer plays its animation and settles back to its still when the
+ pointer leaves; under Reduce Motion it keeps its still. A crossing effect's still plays on from
+ the frame it shows, so the tile starts without a jump."""
+
+ def __init__(self, loop):
+ self.loop = loop
+ self.owners = []
+ self.current = None
+ # What plays for the tile under the pointer: its preview, or the one a TileStack shows.
+ self.target = None
+ self.clock = None
+
+ def track(self, tile, preview):
+ owner = _HoverOwner.alloc().init()
+ owner.entered = lambda: self.enter(preview)
+ owner.exited = lambda: self.leave(preview)
+ options = (AppKit.NSTrackingMouseEnteredAndExited | AppKit.NSTrackingActiveInActiveApp
+ | AppKit.NSTrackingInVisibleRect)
+ tile.addTrackingArea_(AppKit.NSTrackingArea.alloc().initWithRect_options_owner_userInfo_(
+ AppKit.NSZeroRect, options, owner, None))
+ # A tracking area does not keep its owner.
+ self.owners.append(owner)
+
+ def enter(self, preview):
+ if self.current is preview:
+ return
+ self.stop()
+ self.current = preview
+ target = self.target = preview.current() if isinstance(preview, TileStack) else preview
+ self.loop.hover(target)
+ if self.loop.owns(target) or effects_overlay.reduce_motion():
+ return
+ # A pointer passing over on its way elsewhere leaves the tiles it crosses still.
+ target.playing_since = time.monotonic() + HOVER_INTENT_S
+ self.clock = FrameClock(target, lambda: target.setNeedsDisplay_(True))
+ self.clock.start()
+
+ def leave(self, preview):
+ if preview is self.current:
+ self.stop()
+
+ def stop(self):
+ preview, self.current, self.target = self.target, None, None
+ self.loop.hover(None)
+ if self.clock is not None:
+ self.clock.stop()
+ self.clock = None
+ if preview is not None and getattr(preview, "playing_since", None) is not None:
+ if time.monotonic() > preview.playing_since:
+ motion.cross_fade(preview)
+ preview.playing_since = None
+ preview.setNeedsDisplay_(True)
def edge_update(renderer):
@@ -279,3 +528,66 @@ def edge_update(renderer):
def notch_update(renderer):
return lambda kind, _level: renderer.update(kind)
+
+
+# The crossing effects' previews: effects.preview_scene drawn by effects_overlay.draw_scene, the same
+# replay the overlay uses on screen. Every tile shows one still frame at the place the page's Show at
+# chooses, and plays on from it while TileHover says the pointer is over it; nothing else animates.
+# The still is part way into the push, where every style shows.
+STILL_AT_S = 1.7
+# The part of the scene a tile shows at each place, centred on where the pointer pushes so the
+# departure fills the tile: the Mac's right-hand side, the gap and the PC's left edge; the Mac's
+# top right corner with room above it; the notch and the Mac's screen under it, where the forms play.
+STILL_CROPS = {"edge": (620.0, 142.0, 240.0, 120.0), "corner": (680.0, -50.0, 240.0, 120.0),
+ "notch": (220.0, 470.0, 360.0, 180.0)}
+STAGE_METHODS = (("edge", "Edge"), ("corner", "Corner"), ("notch", "Notch"))
+SWITCH_STILL_CROP = (248.0, 138.0, 240.0, 120.0)
+SWITCH_STILL_AT_S = 0.6
+
+
+def _played(view, still_at):
+ """The time into its loop a tile draws: its still, or on from it while it plays."""
+ since = view.playing_since
+ return still_at if since is None else still_at + max(0.0, time.monotonic() - since)
+
+
+def effect_still(effect_id, colour, logger, height=84, place=lambda: "edge", pace=lambda: 1.0):
+ """A tile's still frame of `effect_id`, in whatever colour `colour()` names, at the place
+ `place()` names and the length `pace()` gives, when it draws."""
+ view = effects_overlay.EffectsCanvas.alloc().initWithFrame_(AppKit.NSMakeRect(0, 0, 1, 1))
+ view.setTranslatesAutoresizingMaskIntoConstraints_(False)
+ view.heightAnchor().constraintEqualToConstant_(height).setActive_(True)
+ view.setWantsLayer_(True)
+ view.layer().setCornerRadius_(theme.RADIUS["field"])
+ view.layer().setMasksToBounds_(True)
+ view.layer().setBorderWidth_(1)
+ theme.tint(view.layer(), border="rule")
+ view.logger = logger
+ view.playing_since = None
+
+ def paint(ctx, width, height):
+ fx = effects.preview_effect(effect_id)
+ dark = theme.is_dark()
+ where = place()
+ scene = effects.preview_scene(fx, _played(view, STILL_AT_S), where, effects_overlay.palette(colour()), dark=dark,
+ pace=pace())
+ # A small pointer, so the effect rather than the arrow is what a tile shows.
+ effects_overlay.draw_scene(Quartz, ctx, scene, width, height, where, dark, crop=STILL_CROPS[where], pointer=11.0)
+
+ view.painter = paint
+ return view
+
+
+def switch_still(fx, colour, logger, height=84, pace=lambda: 1.0):
+ """A tile's still frame of what a switch plays: `fx()` is the Effect, asked when it draws, since
+ Same as crossing follows the crossing style."""
+ view = effect_still(None, colour, logger, height)
+
+ def paint(ctx, width, height):
+ dark = theme.is_dark()
+ scene = effects.preview_switch_scene(fx(), _played(view, SWITCH_STILL_AT_S), effects_overlay.palette(colour()),
+ dark=dark, pace=pace())
+ effects_overlay.draw_scene(Quartz, ctx, scene, width, height, "switch", dark, crop=SWITCH_STILL_CROP, pointer=11.0)
+
+ view.painter = paint
+ return view
diff --git a/mac_app/protocol.py b/mac_app/protocol.py
index afe05b2..dc86bad 100644
--- a/mac_app/protocol.py
+++ b/mac_app/protocol.py
@@ -46,7 +46,7 @@ PROTOCOL_VERSION = 4
# handed out below 49152, so the port a user pairs on stays theirs.
DEFAULT_PORT = 24820
PAIRING_PORT = 24821
-# What DEFAULT_PORT was until 20-09-2026. A config still carrying it was never chosen by
+# What DEFAULT_PORT used to be. A config still carrying it was never chosen by
# anyone, so it is migrated rather than honoured; a port a user picked is left alone.
LEGACY_DEFAULT_PORT = 51820
# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing
@@ -58,7 +58,7 @@ KEY_INFO = b"beamy-input-channel"
CLIPBOARD_MAX_BYTES = 256 * 1024
# The clipboard goes out ahead of the focus message on every switch, sealed as one frame and
# buffered whole on both sides, so the image cap is a bound on how late the switch lands, not on
-# bandwidth. A full-screen grab of a 3456x2234 Retina display measured 2.9MB as PNG (09-09-2026);
+# bandwidth. A full-screen grab of a 3456x2234 Retina display measured 2.9MB as PNG;
# 8MB covers that with room for a busier desktop, and as a base64 frame (~10.7MB) it is about
# 0.1s on wired gigabit and half a second on decent Wi-Fi. Beyond it the text still goes.
CLIPBOARD_IMAGE_MAX_BYTES = 8 * 1024 * 1024
@@ -66,7 +66,7 @@ CLIPBOARD_IMAGE_PNG = "png"
# The largest sealed frame either end accepts. It must hold the biggest clipboard message -- an
# 8MB image is ~10.7MB as base64, beside up to 256KB of text -- because the clipboard also travels
# back on the reply stream. A 1MB cap there dropped the link on every return with a screenshot on
-# the clipboard (18-09-2026).
+# the clipboard.
MAX_FRAME_BYTES = 16 * 1024 * 1024
# The first frame each way is a hello or a welcome of a few dozen bytes. Anything larger before
# authentication is not a Beamer, so it is refused before it is read.
diff --git a/mac_app/receiver.py b/mac_app/receiver.py
index a64691c..cc7b14a 100644
--- a/mac_app/receiver.py
+++ b/mac_app/receiver.py
@@ -7,7 +7,7 @@ import sys
import threading
import time
from enum import Enum
-from typing import Callable, Optional
+from typing import Callable, Optional, Tuple
import return_edge as crossing
import protocol
@@ -72,7 +72,37 @@ class ProcessedSequence:
return self._latest
-def handle_message(message: dict, injector=None) -> bool:
+class InputScale:
+ """This machine's own speed for the pointer and scroll arriving from the peer. The peer sends
+ what its own acceleration made of the hand's movement, and this machine may accelerate it
+ again, so how fast it feels here is a setting here. Fractions carry over between messages, so
+ a slow movement at a low speed still moves. `reverse` turns the peer's scroll round."""
+
+ MIN, MAX = 0.25, 4.0
+
+ def __init__(self, pointer: float = 1.0, scroll: float = 1.0, reverse: bool = False) -> None:
+ self.pointer = min(self.MAX, max(self.MIN, float(pointer)))
+ self.scroll = min(self.MAX, max(self.MIN, float(scroll)))
+ self.reverse = bool(reverse)
+ self._carry = [0.0, 0.0]
+
+ def move(self, dx: int, dy: int) -> Tuple[int, int]:
+ if self.pointer == 1.0:
+ return dx, dy
+ x = dx * self.pointer + self._carry[0]
+ y = dy * self.pointer + self._carry[1]
+ whole_x, whole_y = int(x), int(y)
+ self._carry = [x - whole_x, y - whole_y]
+ return whole_x, whole_y
+
+ def wheel(self, dy, dx):
+ if self.scroll == 1.0 and not self.reverse:
+ return dy, dx
+ sign = -1.0 if self.reverse else 1.0
+ return dy * self.scroll * sign, dx * self.scroll * sign
+
+
+def handle_message(message: dict, injector=None, scale: Optional[InputScale] = None) -> bool:
"""Inject one input event. `injector` defaults to the real input_injector
module, imported lazily here (not at module load) so receiver.py stays
importable — and its non-injection logic testable — on a machine without
@@ -92,13 +122,21 @@ def handle_message(message: dict, injector=None) -> bool:
elif message_type == protocol.MSG_KEYUP:
injector.inject_key(data["key"], down=False)
elif message_type == protocol.MSG_MOUSEMOVE:
- injector.inject_mouse_move(int(data["dx"]), int(data["dy"]))
+ dx, dy = int(data["dx"]), int(data["dy"])
+ if scale is not None and (dx or dy):
+ dx, dy = scale.move(dx, dy)
+ if not (dx or dy):
+ return True
+ injector.inject_mouse_move(dx, dy)
elif message_type == protocol.MSG_MOUSEDOWN:
injector.inject_mouse_button(data["button"], down=True)
elif message_type == protocol.MSG_MOUSEUP:
injector.inject_mouse_button(data["button"], down=False)
elif message_type == protocol.MSG_SCROLL:
- injector.inject_scroll(data["dy"], data.get("dx", 0), data.get("mode", "line"))
+ dy, dx = data["dy"], data.get("dx", 0)
+ if scale is not None:
+ dy, dx = scale.wheel(dy, dx)
+ injector.inject_scroll(dy, dx, data.get("mode", "line"))
elif message_type == protocol.MSG_GESTURE:
injector.inject_gesture(data["name"])
else:
@@ -114,11 +152,12 @@ class ReceiverServer:
clipboard=None,
unlock=None,
desktop=None,
- pressure_callback: Optional[Callable[[str, float, bool], None]] = None,
+ pressure_callback: Optional[Callable[[str, float, bool, Optional[str]], None]] = None,
injector=None,
focus_callback: Optional[Callable[[str], None]] = None,
peer_callback: Optional[Callable[[str, Optional[str], Optional[int]], None]] = None,
arrangement_callback: Optional[Callable[[str, int], None]] = None,
+ arrival_callback: Optional[Callable[[str, int, int], None]] = None,
self_name: str = "PC",
peer_name: str = "Mac",
self_target: str = "windows",
@@ -136,6 +175,18 @@ class ReceiverServer:
# taken it back, because the peer fails open on its side and the
# message saying so never reaches a dead socket.
self._injector = injector
+ # This machine's speed for the peer's pointer and scroll; the owner replaces it when its
+ # settings change. Read once per message on the session thread.
+ self.input_scale: Optional[InputScale] = None
+ # Whether this machine's edges are held (Pause crossing, a full-screen app). A hold is
+ # about this screen, so it stops the peer's pointer going home through it as well as this
+ # machine's own; the peer's shortcut still switches. Read on the session thread.
+ self.edges_held: Callable[[], bool] = lambda: False
+ # `return_model(edge, resistance)` builds the way home the peer named from this machine's
+ # own ways in: the whole edge, only its chosen thirds, its corner, or None for no way home
+ # by the pointer. The edges on a screen follow that machine's settings, whoever's pointer
+ # pushes; without an owner's answer the whole edge is armed.
+ self.return_model: Optional[Callable[[str, int], Optional[crossing.ReturnEdge]]] = None
self._focus_callback = focus_callback
self._peer_driving = False
# `peer_callback(host, return_edge, resistance_px)` fires once per
@@ -149,6 +200,13 @@ class ReceiverServer:
# change it, so this is how the change arrives at the end that did not
# make it.
self._arrangement_callback = arrangement_callback
+ # `arrival_callback(edge, x, y)` fires on the session thread each time
+ # a crossing lands the pointer here, with the edge it came in by and
+ # where it was placed, in the desktop module's coordinates, and with
+ # edge None and wherever the pointer is when input comes here by a
+ # switch instead. It is how the owner plays its arrival effect; the
+ # owner marshals it.
+ self._arrival_callback = arrival_callback
self._self_name = self_name
self._peer_name = peer_name
self._self_target = self_target
@@ -156,13 +214,20 @@ class ReceiverServer:
self._status_callback = status_callback
# `desktop` defaults to the real desktop_win module, imported lazily for
# the same reason as `clipboard` below. `pressure_callback(edge,
- # pressure, crossed)` is called on the session thread as the pointer
- # is pushed against the return edge; the GUI marshals it to the glow.
+ # pressure, crossed, part)` is called on the session thread as the
+ # pointer is pushed against the return edge, `part` the third or corner
+ # pushed when the way home is only those; the GUI marshals it to the glow.
self._desktop = desktop
self._pressure_callback = pressure_callback
# The way home. Armed by every focus{target:"windows"} the Mac sends,
# which carries the return edge and resistance, and None until then.
self._return_edge: Optional[crossing.ReturnEdge] = None
+ # The edge and resistance that focus named, kept so a settings change can rebuild the way
+ # home (`rearm_return`) without waiting for the next focus.
+ self._named_return: Optional[tuple] = None
+ # Held while the session thread feeds the way home and while a settings change rebuilds it,
+ # so a rebuild never revives a way home that was just pushed through or handed back.
+ self._return_lock = threading.RLock()
# `unlock` defaults to the real unlock_win module, imported lazily for
# the same reason as `clipboard` below.
self._unlock = unlock
@@ -299,8 +364,8 @@ class ReceiverServer:
# TIME_WAIT. On Windows the same option means something else: a
# second bind on a port another listener holds succeeds, and the
# two split the Mac's connections between them, so the held-port
- # wait below never fired for a zombie Beamer (rig, 22-09-2026).
- # Windows does not need it for TIME_WAIT, so it does without.
+ # wait below never fired for a zombie Beamer. Windows does not
+ # need it for TIME_WAIT, so it does without.
if sys.platform != "win32":
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
@@ -399,6 +464,7 @@ class ReceiverServer:
if handshake is None:
return
session, version, hello = handshake
+ self._clipboard_module().forget_sync()
if version != protocol.PROTOCOL_VERSION:
LOGGER.warning(
@@ -502,7 +568,7 @@ class ReceiverServer:
sequence.record(message)
continue
try:
- processed = handle_message(message, self._injector)
+ processed = handle_message(message, self._injector, self.input_scale)
except Exception:
LOGGER.exception("Input event from %s could not be injected", peer)
now = time.monotonic()
@@ -648,15 +714,25 @@ class ReceiverServer:
a return edge is armed; True means the move was consumed — the pointer
was held at the edge, or it broke through and the Mac has been asked
to take input back — and must not be injected."""
- model = self._return_edge
- if model is None or not model.armed:
- return False
data = message.get("data")
if not isinstance(data, dict):
return False
try:
- desktop = self._desktop_module()
- outcome = model.feed(desktop.monitors(), desktop.cursor_position(), float(data["dx"]), float(data["dy"]))
+ with self._return_lock:
+ model = self._return_edge
+ if model is None or not model.armed or self.edges_held():
+ return False
+ desktop = self._desktop_module()
+ monitors, pointer = desktop.monitors(), desktop.cursor_position()
+ outcome = model.feed(monitors, pointer, float(data["dx"]), float(data["dy"]))
+ if outcome.action == crossing.CROSS:
+ self._named_return = None
+ # Which third or corner is being pushed, so the owner lights only that.
+ part = None
+ if isinstance(model, crossing.PartEdge):
+ part = crossing.part_of(crossing.display_fraction(monitors, model.edge, pointer))
+ elif isinstance(model, crossing.CornerPush):
+ part = model.corner
if outcome.action == crossing.HOLD:
desktop.set_cursor_position(*outcome.position)
elif outcome.action == crossing.CROSS:
@@ -666,11 +742,11 @@ class ReceiverServer:
# Logged once, not at 100Hz: the return edge is dropped until the
# Mac's next switch re-arms it, and input keeps flowing normally.
LOGGER.exception("Return edge failed; crossing back is off until the next switch")
- self._return_edge = None
+ self._drop_return()
return False
if outcome.action == crossing.PASS:
return False
- self._notify_pressure(model.edge, outcome.pressure, outcome.action == crossing.CROSS)
+ self._notify_pressure(model.edge, outcome.pressure, outcome.action == crossing.CROSS, part)
return True
def send_arrangement(self, mac_edge: str, set_at: int) -> bool:
@@ -688,17 +764,18 @@ class ReceiverServer:
def send_home(self) -> bool:
"""Send the peer's input back to it from this end, as its own return
edge would. The escape that does not depend on that edge: the owner
- calls it when someone here asks to switch while the peer is driving,
- which was refused outright until the 23-09-2026 afternoon a push
- through the edge never fired and the PC's mouse stayed on the Mac.
- The send runs on its own thread, because the callers are a hook and
- an event tap that must never block on a socket."""
+ calls it when someone here asks to switch while the peer is driving.
+ Earlier versions refused this outright, and a push through the edge
+ that failed to fire could then leave the peer's pointer stuck here
+ with no way back. The send runs on its own thread, because the
+ callers are a hook and an event tap that must never block on a
+ socket."""
with self._lock:
connection = self._client
session = self._session_for(connection)
if not self._peer_driving or connection is None or session is None:
return False
- self._return_edge = None
+ self._drop_return()
LOGGER.info("Switch asked for here; sending input home to the %s", self._peer_name)
threading.Thread(
target=self._send_message,
@@ -755,7 +832,7 @@ class ReceiverServer:
crosses in and back."""
if not self._peer_driving:
return
- self._return_edge = None
+ self._drop_return()
LOGGER.info("%s while its input was here; input returned to this %s", why, self._self_name)
self._release_peer_keys()
self._notify_focus(self._peer_target)
@@ -780,39 +857,88 @@ class ReceiverServer:
except Exception:
LOGGER.exception("Could not release the keys the %s was holding", self._peer_name)
- def _notify_pressure(self, edge: str, pressure: float, crossed: bool) -> None:
+ def _notify_pressure(self, edge: str, pressure: float, crossed: bool, part: Optional[str] = None) -> None:
if self._pressure_callback is None:
return
try:
- self._pressure_callback(edge, pressure, crossed)
+ self._pressure_callback(edge, pressure, crossed, part)
except Exception:
LOGGER.exception("Pressure callback failed")
+ def rearm_return(self) -> None:
+ """Rebuilds the way home from this machine's Crossing settings as they are now, for the
+ edge and resistance the peer last named, so a change applies while the peer's input is
+ here rather than at its next crossing. Nothing happens once that input has gone home, or
+ after the way home has been pushed through."""
+ with self._return_lock:
+ named = self._named_return
+ model = self._return_edge
+ if not self._peer_driving or named is None or (model is not None and not model.armed):
+ return
+ self._arm_return({"return_edge": named[0], "resistance_px": named[1]})
+
+ def _drop_return(self) -> None:
+ """The peer's visit is over, or its way home is spent: nothing may rebuild it."""
+ with self._return_lock:
+ self._return_edge = None
+ self._named_return = None
+
def _arm_return(self, data: dict) -> None:
"""Every switch to Windows says which edge leads home and how hard to
push; an older Mac that says neither gets no return edge, so nothing
it does not expect can fire."""
+ with self._return_lock:
+ self._build_return(data)
+
+ def _build_return(self, data: dict) -> None:
edge = data.get("return_edge")
if edge not in crossing.EDGES:
self._return_edge = None
+ self._named_return = None
return
resistance = data.get("resistance_px", crossing.DEFAULT_RESISTANCE_PX)
# json.loads accepts Infinity and NaN, and int() of either raises, which
# nothing above this catches: a bad number gets the default instead.
if isinstance(resistance, bool) or not isinstance(resistance, (int, float)) or not math.isfinite(resistance):
resistance = crossing.DEFAULT_RESISTANCE_PX
- self._return_edge = crossing.ReturnEdge(edge, int(resistance))
+ self._named_return = (edge, int(resistance))
+ if self.return_model is None:
+ self._return_edge = crossing.ReturnEdge(edge, int(resistance))
+ return
+ try:
+ self._return_edge = self.return_model(edge, int(resistance))
+ except Exception:
+ LOGGER.exception("Could not build the way home through the %s edge", edge)
+ self._return_edge = crossing.ReturnEdge(edge, int(resistance))
def _place_pointer(self, data: dict) -> None:
+ """A crossing names the edge and the fraction along it, and the pointer is placed there. A
+ switch by the shortcut or a menu names neither and leaves the pointer where it was, which
+ the arrival callback gets as edge None, so the owner can show where that is."""
edge = data.get("edge")
offset = data.get("offset")
if edge not in crossing.EDGES or isinstance(offset, bool) or not isinstance(offset, (int, float)):
+ if self._arrival_callback is None:
+ return
+ try:
+ x, y = self._desktop_module().cursor_position()
+ self._arrival_callback(None, x, y)
+ except Exception:
+ LOGGER.exception("Arrival callback for a switch failed")
return
try:
desktop = self._desktop_module()
- desktop.set_cursor_position(*crossing.arrival_position(desktop.monitors(), edge, offset))
+ x, y = crossing.arrival_position(desktop.monitors(), edge, offset)
+ desktop.set_cursor_position(x, y)
except Exception:
LOGGER.exception("Could not place the pointer at the %s edge on arrival", edge)
+ return
+ if self._arrival_callback is None:
+ return
+ try:
+ self._arrival_callback(edge, x, y)
+ except Exception:
+ LOGGER.exception("Arrival callback failed")
def _begin_unlock(self, peer: str, host: str) -> None:
"""Take the console off the lock screen, if it is on one, so the input
@@ -885,7 +1011,7 @@ class ReceiverServer:
# Released before the owner hears input is home: the Mac's tap
# comes back on at that notice, and a modifier still down would
# chord with the first local keystroke.
- self._return_edge = None
+ self._drop_return()
self._release_peer_keys()
self._notify_focus(target)
if target == self._self_target:
@@ -897,7 +1023,7 @@ class ReceiverServer:
return
clipboard = self._clipboard_module()
try:
- text, image = clipboard.get_contents()
+ text, image = clipboard.changed_contents()
except Exception:
LOGGER.exception("Failed to read the local clipboard for %s", peer)
return
diff --git a/mac_app/requirements-mac.txt b/mac_app/requirements-mac.txt
index a1df8f0..e95ef8f 100644
--- a/mac_app/requirements-mac.txt
+++ b/mac_app/requirements-mac.txt
@@ -4,3 +4,4 @@ pyobjc-framework-ApplicationServices==12.2.2
rumps==0.4.0
py2app==0.28.10
cryptography>=42
+dmgbuild==1.6.7
diff --git a/mac_app/return_edge.py b/mac_app/return_edge.py
index d565fdb..643b7b7 100644
--- a/mac_app/return_edge.py
+++ b/mac_app/return_edge.py
@@ -21,6 +21,18 @@ DECAY_SECONDS = 0.4
# 8 pixels, and the two boundaries are meant to feel like one.
CORNER_PX = 8
CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")
+# The thirds of an edge "Part of the edge" may use, top to bottom or left to right. Both machines'
+# engines read them through in_parts, so a third means the same stretch on each.
+PARTS = ("start", "middle", "end")
+
+
+def part_of(fraction: float) -> str:
+ """Which third of an edge `fraction` of the way along it falls in."""
+ return PARTS[min(2, max(0, int(fraction * 3)))]
+
+
+def in_parts(fraction: float, parts) -> bool:
+ return part_of(fraction) in parts
PASS = "pass"
HOLD = "hold"
@@ -78,6 +90,14 @@ def edge_offset(bounds: Rect, edge: str, pointer: Tuple[int, int]) -> float:
return _clamp((pointer[0] - bounds.x) / max(bounds.width, 1), 0.0, 1.0)
+def display_fraction(monitors: List[Rect], edge: str, pointer: Tuple[int, int]) -> float:
+ """Fraction along `edge` of the display the pointer is on, which is how Part of the edge
+ measures its thirds: against the bounding box, a short display beside a tall one could hold
+ none of the middle third. The bounding box when the pointer is on no display."""
+ home = next((m for m in monitors if _contains(m, pointer)), None) or union(monitors)
+ return edge_offset(home, edge, pointer)
+
+
def owning_monitor(monitors: List[Rect], edge: str) -> Rect:
"""The monitor that reaches the bounding box on `edge`; ties go to the
first enumerated, which on Windows is the primary."""
@@ -90,19 +110,40 @@ def owning_monitor(monitors: List[Rect], edge: str) -> Rect:
return max(monitors, key=lambda r: r.bottom)
+def landing_monitor(monitors: List[Rect], edge: str, along: float) -> Rect:
+ """The monitor a pointer arriving through `edge` at coordinate `along` (y for a side edge, x
+ for the top or bottom) lands on: of those spanning `along`, the outermost on that edge, so two
+ stacked monitors each take their own stretch of it; with none spanning it, a gap in a staggered
+ arrangement, the nearest. Ties go to the first enumerated, which on Windows is the primary."""
+ def span(r: Rect):
+ return (r.y, r.bottom) if edge in ("left", "right") else (r.x, r.right)
+
+ def outer(r: Rect):
+ return {"left": r.x, "right": -r.right, "top": r.y, "bottom": -r.bottom}[edge]
+
+ def distance(r: Rect):
+ low, high = span(r)
+ return max(low - along, along - (high - 1), 0)
+
+ return min(monitors, key=lambda r: (distance(r), outer(r)))
+
+
def arrival_position(monitors: List[Rect], edge: str, offset: float) -> Tuple[int, int]:
- """Where a pointer arriving at `edge`, `offset` of the way along it, lands.
- The fraction is applied against the whole bounding box, then clamped into
- the owning monitor so a staggered arrangement never lands it in a gap."""
+ """Where a pointer arriving at `edge`, `offset` of the way along it, lands. The fraction is
+ applied against the whole bounding box, then placed on the monitor `landing_monitor` picks, so
+ no arrangement lands it in a gap or on the wrong one of two monitors sharing the edge."""
bounds = union(monitors)
- owner = owning_monitor(monitors, edge)
offset = _clamp(float(offset), 0.0, 1.0)
if edge in ("left", "right"):
+ along = int(round(bounds.y + offset * bounds.height))
+ owner = landing_monitor(monitors, edge, along)
x = owner.x if edge == "left" else owner.right
- y = _clamp(int(round(bounds.y + offset * bounds.height)), owner.y, owner.bottom)
+ y = _clamp(along, owner.y, owner.bottom)
else:
+ along = int(round(bounds.x + offset * bounds.width))
+ owner = landing_monitor(monitors, edge, along)
y = owner.y if edge == "top" else owner.bottom
- x = _clamp(int(round(bounds.x + offset * bounds.width)), owner.x, owner.right)
+ x = _clamp(along, owner.x, owner.right)
return x, y
@@ -144,9 +185,9 @@ class ReturnEdge:
def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:
"""On a monitor, with no monitor one pixel beyond it: the pointer is
against a wall. Testing the bounding box instead made the edge of a
- shorter monitor in a staggered arrangement unreachable — on the rig,
- pushing down on the LG, whose bottom stops 204px above the ultrawide's,
- never went home."""
+ shorter monitor in a staggered arrangement unreachable — for example,
+ pushing down on a monitor whose bottom stops above its neighbour's
+ could never reach the edge."""
x, y = pointer
step_x, step_y = {"left": (-1, 0), "right": (1, 0), "top": (0, -1), "bottom": (0, 1)}[self.edge]
beyond = (x + step_x, y + step_y)
@@ -182,6 +223,35 @@ class ReturnEdge:
return Outcome(HOLD, self.pressure, position=position)
+class PartEdge(ReturnEdge):
+ """The edge, but only along the chosen thirds of it: the rest of the edge is a plain wall, so
+ a menu or a dock at one end can sit against it without the pointer ever crossing there. The
+ thirds are measured along the display the pointer is on, by `display_fraction`."""
+
+ def __init__(self, edge: str, parts, resistance_px: int = DEFAULT_RESISTANCE_PX, clock=time.monotonic) -> None:
+ super().__init__(edge, resistance_px, clock)
+ self.parts = frozenset(part for part in parts if part in PARTS)
+
+ def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:
+ return super()._at_edge(monitors, pointer) and in_parts(display_fraction(monitors, self.edge, pointer), self.parts)
+
+
+class SpanEdge(ReturnEdge):
+ """The edge, but only along a stretch of it, in the monitors' own coordinates: a Mac's notch,
+ a fixed stretch of its top edge rather than a third of it. `span()` gives (start, end) or None
+ and is read at every push, so a stretch measured late, or moved by a display change, applies
+ at once."""
+
+ def __init__(self, edge: str, span: Callable[[], Optional[Tuple[float, float]]], resistance_px: int = DEFAULT_RESISTANCE_PX, clock=time.monotonic) -> None:
+ super().__init__(edge, resistance_px, clock)
+ self.span = span
+
+ def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:
+ span = self.span()
+ along = pointer[0] if self.edge in ("top", "bottom") else pointer[1]
+ return span is not None and super()._at_edge(monitors, pointer) and span[0] <= along <= span[1]
+
+
class CornerPush(ReturnEdge):
"""The same pressure model gated to one corner, for a machine whose whole
edge is busy with something else. The push has to be diagonal: travel that
diff --git a/mac_app/settings_store.py b/mac_app/settings_store.py
index effe3ab..1aa541c 100644
--- a/mac_app/settings_store.py
+++ b/mac_app/settings_store.py
@@ -1,13 +1,14 @@
import json
import os
-import shutil
import tempfile
from dataclasses import replace
from pathlib import Path
import config as config_module
+import effects
import ignored
import protocol
+import return_edge
from crossing import CORNERS, EDGES, GLOW_COLOURS, GLOW_STYLES, HAPTIC_FEELS, HAPTIC_STEPS, METHODS, NOTCH_STYLES
from key_codes import KEY_NAME_TO_CODE
@@ -17,32 +18,6 @@ from wake import parse_mac
APP_SUPPORT_DIRECTORY = Path.home() / "Library" / "Application Support" / "Beamer"
DEFAULT_SETTINGS_PATH = APP_SUPPORT_DIRECTORY / "config.json"
-# The OpenKB-era directory, kept only as a migration source now the app is
-# Beamer.
-LEGACY_APP_SUPPORT_DIRECTORY = Path.home() / "Library" / "Application Support" / "OpenKB"
-LEGACY_SETTINGS_PATH = LEGACY_APP_SUPPORT_DIRECTORY / "config.json"
-
-
-def migrate_legacy_config():
- """Copy the OpenKB config.json into the new Beamer directory if Beamer has
- none yet. Never moves or deletes the old file, so a downgrade still finds
- it."""
- if DEFAULT_SETTINGS_PATH.exists() or not LEGACY_SETTINGS_PATH.exists():
- return False
- APP_SUPPORT_DIRECTORY.mkdir(parents=True, exist_ok=True, mode=0o700)
- try:
- os.chmod(APP_SUPPORT_DIRECTORY, 0o700)
- except OSError:
- pass
- # Copied beside, then renamed into place: a copy cut short would otherwise
- # leave a truncated config that shadows the intact old one for ever.
- staged = DEFAULT_SETTINGS_PATH.with_name(".config.migrating")
- shutil.copyfile(LEGACY_SETTINGS_PATH, staged)
- os.chmod(staged, 0o600)
- os.replace(staged, DEFAULT_SETTINGS_PATH)
- return True
-
-
class SettingsError(Exception):
pass
@@ -63,6 +38,12 @@ def editable_default_config():
mac_address="",
send_to_windows=True,
allow_windows_to_drive=True,
+ check_updates=True,
+ hide_addresses=False,
+ pointer_speed=1.0,
+ scroll_speed=1.0,
+ reverse_scroll=False,
+ appearance="system",
ignored_inputs=[],
)
@@ -80,11 +61,18 @@ def config_to_raw(cfg):
"crossing": {
**cfg.crossing,
"methods": list(cfg.crossing["methods"]),
+ "edge_parts": list(cfg.crossing["edge_parts"]),
},
"pc_name": cfg.pc_name,
"mac_address": cfg.mac_address,
"send_to_windows": cfg.send_to_windows,
"allow_windows_to_drive": cfg.allow_windows_to_drive,
+ "check_updates": cfg.check_updates,
+ "hide_addresses": cfg.hide_addresses,
+ "pointer_speed": cfg.pointer_speed,
+ "scroll_speed": cfg.scroll_speed,
+ "reverse_scroll": cfg.reverse_scroll,
+ "appearance": cfg.appearance,
"ignored_inputs": list(cfg.ignored_inputs),
}
@@ -106,8 +94,8 @@ class SettingsStore:
"""Move a config still on the old default port, and write the move down.
51820 sat inside the 49152-65535 range both operating systems hand out for
- themselves, so it was never a port anyone could rely on keeping -- WinNAT took it on
- the rig and the PC could not listen at all. Nobody chose that number, it was what the
+ themselves, so it was never a port anyone could rely on keeping -- WinNAT claimed it on
+ one PC and the app could not listen at all. Nobody chose that number, it was what the
app shipped with, so it moves; a port a user typed is theirs and is left alone.
"""
if cfg.port != protocol.LEGACY_DEFAULT_PORT:
@@ -178,10 +166,13 @@ class SettingsStore:
raise SettingsError("trigger_style must be double_tap or hold")
crossing = cfg.crossing
methods = crossing["methods"]
- if not isinstance(methods, list) or not set(methods) <= set(METHODS):
+ if not isinstance(methods, list) or not all(method in METHODS for method in methods):
raise SettingsError(f"crossing.methods must only contain: {', '.join(METHODS)}")
if crossing["edge"] not in EDGES:
raise SettingsError(f"crossing.edge must be one of: {', '.join(EDGES)}")
+ parts = crossing["edge_parts"]
+ if not isinstance(parts, list) or not parts or not all(part in return_edge.PARTS for part in parts):
+ raise SettingsError(f"crossing.edge_parts must be one or more of: {', '.join(return_edge.PARTS)}")
if crossing["corner"] not in CORNERS:
raise SettingsError(f"crossing.corner must be one of: {', '.join(CORNERS)}")
if isinstance(crossing["resistance_px"], bool) or not 0 <= crossing["resistance_px"] <= 500:
@@ -194,15 +185,24 @@ class SettingsStore:
choices = (
("haptic_feel", HAPTIC_FEELS),
("haptic_steps", HAPTIC_STEPS),
- ("glow_style", GLOW_STYLES),
- ("glow_colour", GLOW_COLOURS),
+ # Today's styles and colours, then every crossing effect and colour pack.
+ ("glow_style", GLOW_STYLES + effects.EFFECT_IDS),
+ ("glow_colour", GLOW_COLOURS + effects.PACK_IDS),
+ ("shortcut_arrival_style", effects.SWITCH_STYLES),
+ ("effect_length", tuple(value for value, _name in effects.LENGTHS)),
)
for name, allowed in choices:
if crossing[name] not in allowed:
raise SettingsError(f"crossing.{name} must be one of: {', '.join(allowed)}")
- for name in ("haptics", "glow", "block_while_dragging"):
+ for name in ("haptics", "glow", "block_while_dragging", "shortcut_arrival"):
if not isinstance(crossing[name], bool):
raise SettingsError(f"crossing.{name} must be true or false")
+ for name in ("pointer_speed", "scroll_speed"):
+ value = getattr(cfg, name)
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not 0.25 <= value <= 4.0:
+ raise SettingsError(f"{name} must be a number from 0.25 to 4")
+ if not isinstance(cfg.reverse_scroll, bool):
+ raise SettingsError("reverse_scroll must be true or false")
try:
ignored.validate(cfg.ignored_inputs)
except ValueError as exc:
diff --git a/mac_app/setup.py b/mac_app/setup.py
index 6ab0f59..070a1ee 100644
--- a/mac_app/setup.py
+++ b/mac_app/setup.py
@@ -22,6 +22,13 @@ setup(
"config",
"crossing",
"desktop_mac",
+ "effects",
+ "effects_overlay",
+ "fx_ink",
+ "fx_instrument",
+ "fx_membrane",
+ "fx_sparks",
+ "fx_warp",
"gestures",
"ignored",
"input_injector_mac",
@@ -63,7 +70,12 @@ setup(
# cryptography ships a compiled _rust extension plus cffi; py2app's own recipe pulls
# both in, but naming the package keeps its data files and submodules in the bundle.
"packages": ["rumps", "cryptography", "cffi"],
- "includes": ["objc", "AppKit", "ApplicationServices", "Quartz"],
+ # effects.py imports its fx_* modules by name at first use, which py2app's import scan
+ # cannot see, so they are named here or the bundle ships without a single effect.
+ "includes": [
+ "objc", "AppKit", "ApplicationServices", "Quartz",
+ "fx_ink", "fx_instrument", "fx_membrane", "fx_sparks", "fx_warp",
+ ],
"iconfile": "../Beamer.icns",
"plist": {
"CFBundleDisplayName": "Beamer",
diff --git a/mac_app/tests/test_appearance.py b/mac_app/tests/test_appearance.py
new file mode 100644
index 0000000..1a06b10
--- /dev/null
+++ b/mac_app/tests/test_appearance.py
@@ -0,0 +1,122 @@
+"""The settings window's light and dark palettes: the choice, the Mac's own setting and a live switch.
+
+The window is built for real, as tools/readme_shots_mac.py builds it, and never put on screen."""
+
+import json
+import logging
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+import AppKit # noqa: E402
+import Quartz # noqa: E402
+
+AppKit.NSApplication.sharedApplication()
+
+import kvm_bridge_app # noqa: E402
+import motion # noqa: E402
+import settings_store # noqa: E402
+import theme # noqa: E402
+import tokens # noqa: E402
+from wake import WakingController # noqa: E402
+
+
+def _hex(cg_colour):
+ red, green, blue = Quartz.CGColorGetComponents(cg_colour)[:3]
+ return "#" + "".join(f"{round(value * 255):02x}" for value in (red, green, blue))
+
+
+class ThemeTests(unittest.TestCase):
+ def tearDown(self):
+ theme.set_dark(True)
+
+ def test_wants_dark_keeps_a_choice_and_follows_the_system_otherwise(self):
+ self.assertTrue(theme.wants_dark("dark", False))
+ self.assertFalse(theme.wants_dark("light", True))
+ self.assertTrue(theme.wants_dark("system", True))
+ self.assertFalse(theme.wants_dark("system", False))
+
+ def test_a_tinted_layer_follows_a_switch_and_a_dynamic_colour_resolves_to_the_palette_in_use(self):
+ layer = Quartz.CALayer.layer()
+ theme.tint(layer, background="panel", border=("signal", 0.5))
+ theme.set_dark(False)
+ theme.retint(layer)
+ self.assertEqual(_hex(layer.backgroundColor()), tokens.PALETTE_LIGHT["panel"])
+ self.assertAlmostEqual(Quartz.CGColorGetAlpha(layer.borderColor()), 0.5, places=3)
+ ink = theme.colour("ink").colorUsingColorSpace_(AppKit.NSColorSpace.sRGBColorSpace())
+ self.assertEqual(_hex(ink.CGColor()), tokens.PALETTE_LIGHT["ink"])
+
+ def test_both_palettes_name_the_same_colours(self):
+ self.assertEqual(set(tokens.PALETTE), set(tokens.PALETTE_LIGHT))
+
+
+class WindowAppearanceTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.directory = tempfile.TemporaryDirectory()
+ path = Path(cls.directory.name) / "config.json"
+ raw = settings_store.config_to_raw(settings_store.editable_default_config())
+ raw.update(host="192.0.2.20", auth_token="synthetic", appearance="dark")
+ path.write_text(json.dumps(raw))
+ store = settings_store.SettingsStore(path)
+ logger = logging.getLogger("test-appearance")
+ with mock.patch.object(kvm_bridge_app, "accessibility_granted", return_value=True), \
+ mock.patch.object(kvm_bridge_app, "input_monitoring_granted", return_value=True):
+ cls.window = kvm_bridge_app.ControlWindow.alloc().initWithController_settingsStore_logger_(
+ WakingController(store.load(), logger=logger), store, logger
+ )
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.window.appearance_watch.stop()
+ theme.set_dark(True)
+ cls.directory.cleanup()
+
+ def setUp(self):
+ self.window._apply_appearance("dark")
+
+ def _ground(self):
+ return _hex(self.window.window.contentView().layer().backgroundColor())
+
+ def _appearance(self):
+ return self.window.window.appearance().name()
+
+ def test_choosing_light_repaints_the_window_and_its_title_bar(self):
+ self.assertEqual(self._ground(), tokens.PALETTE["ground"])
+ self.window._apply_appearance("light")
+ self.assertFalse(theme.is_dark())
+ self.assertEqual(self._ground(), tokens.PALETTE_LIGHT["ground"])
+ self.assertEqual(self._appearance(), AppKit.NSAppearanceNameAqua)
+ self.window._apply_appearance("dark")
+ self.assertEqual(self._ground(), tokens.PALETTE["ground"])
+ self.assertEqual(self._appearance(), AppKit.NSAppearanceNameDarkAqua)
+
+ def test_system_follows_the_mac_and_a_fixed_choice_does_not(self):
+ self.window.appearance_select.value = "system"
+ with mock.patch.object(theme, "system_dark", return_value=False):
+ self.window.appearance_watch.callback()
+ self.assertFalse(theme.is_dark())
+ self.window.appearance_select.value = "dark"
+ self.window._apply_appearance()
+ with mock.patch.object(theme, "system_dark", return_value=False):
+ self.window.appearance_watch.callback()
+ self.assertTrue(theme.is_dark())
+
+ def test_a_switch_on_screen_cross_fades(self):
+ with mock.patch.object(motion, "live", return_value=True):
+ self.window._apply_appearance("light")
+ # A CATransition is filed under "transition" whatever key it was added with.
+ self.assertIsNotNone(self.window.window.contentView().layer().animationForKey_("transition"))
+
+ def test_the_choice_is_saved(self):
+ self.window.appearance_select.value = "light"
+ self.window._apply_settings()
+ self.assertEqual(self.window.settings_store.load().appearance, "light")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.py
index 26e184f..650debf 100644
--- a/mac_app/tests/test_bridge.py
+++ b/mac_app/tests/test_bridge.py
@@ -237,6 +237,12 @@ class FakeClipboard:
def get_contents(self):
return self.text, self.image
+ def changed_contents(self):
+ return self.text, self.image
+
+ def forget_sync(self):
+ pass
+
def set_contents(self, text, image):
self.set_calls.append((text, image))
return True
@@ -692,7 +698,7 @@ class ControllerTests(unittest.TestCase):
)
def test_switching_while_receiving_sends_the_pcs_input_home(self):
- # 23-09-2026: the PC's mouse was on this Mac, its push back through
+ # Seen in practice: the PC's mouse was on this Mac, its push back through
# the edge never fired, and the menu's switch only said Windows was
# already driving. Switching now sends the PC's input home instead.
sent_home = []
@@ -827,7 +833,7 @@ class ControllerTests(unittest.TestCase):
# input local and leave the worker running for the next message.
self.controller.redirecting = True
self.controller.clipboard = types.SimpleNamespace(
- get_contents=lambda: (_ for _ in ()).throw(RuntimeError("synthetic clipboard failure"))
+ changed_contents=lambda: (_ for _ in ()).throw(RuntimeError("synthetic clipboard failure"))
)
self.controller.outbound.put_nowait({"type": "_local_clipboard", "data": {}})
self.controller.stop_event.clear()
@@ -929,8 +935,8 @@ class ControllerTests(unittest.TestCase):
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.
+ # Seen in practice: Windows stalled every app for 40s while it reconfigured its displays,
+ # and the Mac wrongly prompted to update a Beamer that was already current.
answering, silent = FakeSocket(), FakeSocket()
seed_receiver_reply(answering, protocol.welcome_msg())
sockets = iter([answering, silent])
@@ -1803,7 +1809,7 @@ class CrossingWiringTests(unittest.TestCase):
self.assertEqual(kinds.count("tick"), 3)
def test_this_macs_own_push_while_windows_drives_sends_the_pc_home_and_crosses(self):
- # The Mac half of 2f45c00: this Mac's trackpad could not push back while the PC drove it.
+ # Regression: this Mac's trackpad could not push back while the PC drove it.
sent_home = []
self.controller.receiving = True
self.controller.send_peer_home = lambda: sent_home.append(True) or True
@@ -1925,6 +1931,8 @@ class CrossingWiringTests(unittest.TestCase):
self.assertEqual(FakeQuartz.warp_calls, [(1725.0, 558.0)])
self.assertEqual([m["type"] for m in self._sent()], [protocol.MSG_FOCUS])
self.assertEqual(self.feedback[-1][0], "arrive")
+ # Where it landed, for the arrival effect.
+ self.assertEqual((self.feedback[-1][1].mac_edge, self.feedback[-1][1].pin), ("right", (1725.0, 558.0)))
def test_inbound_switch_without_a_position_still_returns_input(self):
self.controller.set_redirecting(True)
@@ -1932,6 +1940,45 @@ class CrossingWiringTests(unittest.TestCase):
self.controller._handle_inbound(protocol.switch_msg("mac"))
self.assertFalse(self.controller.redirecting)
self.assertEqual(FakeQuartz.warp_calls, [])
+ self.assertIsNone(self.feedback[-1][1].pin)
+
+ def _kinds(self):
+ return [kind for kind, _step in self.feedback]
+
+ def test_the_shortcut_home_reports_where_the_pointer_is(self):
+ self.controller.set_redirecting(True)
+ self.feedback.clear()
+ self.controller.set_redirecting(False)
+ self.assertEqual(self._kinds(), ["home"])
+ self.assertEqual(self.feedback[0][1].pin, FakeQuartz.cursor_pin_location)
+
+ def test_a_crossing_home_reports_only_its_own_arrival(self):
+ self.controller.set_redirecting(True)
+ self.feedback.clear()
+ self.controller._handle_inbound(protocol.switch_msg("mac", "right", 0.5))
+ self.assertEqual(self._kinds(), ["arrive"])
+
+ def test_the_pc_sending_input_home_by_its_switch_reports_it_once(self):
+ self.controller.set_redirecting(True)
+ self.feedback.clear()
+ self.controller._handle_inbound(protocol.switch_msg("mac"))
+ self.assertEqual(self._kinds().count("home"), 1)
+
+ def test_the_pc_taking_this_mac_over_is_not_a_switch_home(self):
+ self.controller.set_redirecting(True)
+ self.feedback.clear()
+ self.controller.set_receiving(True)
+ self.assertNotIn("home", self._kinds())
+
+ def test_a_dropped_link_shows_nothing(self):
+ self.controller.set_redirecting(True)
+ self.feedback.clear()
+ self.controller._connection_failed("Windows stopped responding")
+ self.assertEqual(self._kinds(), [])
+
+ def test_switching_home_while_already_home_shows_nothing(self):
+ self.controller.set_redirecting(False)
+ self.assertEqual(self._kinds(), [])
def test_inbound_switch_to_an_unknown_target_is_ignored(self):
self.controller.set_redirecting(True)
@@ -1977,7 +2024,7 @@ class CrossingWiringTests(unittest.TestCase):
self.assertEqual(controller._default_desktop_bounds(), (0.0, -300.0, 3648.0, 1117.0))
def test_a_sleeping_display_still_bounds_the_desktop(self):
- # 27-09-2026: the active list is empty while the display sleeps; the first push after
+ # Seen in practice: the active list is empty while the display sleeps; the first push after
# waking raised and turned crossing off until settings were next saved.
class SleepingQuartz(FakeQuartz):
@staticmethod
@@ -2107,5 +2154,61 @@ class RoundTripTests(unittest.TestCase):
self.assertIsNone(self.controller.round_trip_ms)
+class FollowingAMovedPcTests(unittest.TestCase):
+ """The PC's router hands it a new address; it still beacons under the name it paired with."""
+
+ OLD, NEW = "192.0.2.10", "192.0.2.77"
+
+ def make(self, reply_token="synthetic-token", beacons=None):
+ sock = FakeSocket()
+ seed_receiver_reply(sock, protocol.welcome_msg(), token=reply_token)
+ tried = []
+
+ def socket_factory(address, timeout):
+ tried.append(address[0])
+ if address[0] == self.OLD:
+ raise ConnectionRefusedError("nothing there now")
+ return sock
+
+ controller = KVMController(
+ dataclasses.replace(make_config(), pc_name="STUDIO-PC"),
+ logger=quiet_logger(),
+ quartz=FakeQuartz,
+ clock=FakeClock(),
+ socket_factory=socket_factory,
+ )
+ found = beacons if beacons is not None else [
+ {"name": "STUDIO-PC", "address": self.NEW, "port": 51820, "reply_port": 24821, "pair_id": None}]
+ controller.discovery = types.SimpleNamespace(pcs=lambda: found)
+ learned = []
+ controller.on_host_learned = learned.append
+ return controller, tried, learned
+
+ def test_it_follows_the_pc_and_saves_the_address_once_it_authenticates(self):
+ controller, tried, learned = self.make()
+ self.assertFalse(controller._connect_once())
+ controller._follow_the_pc()
+ self.assertEqual(tried, [self.OLD, self.NEW])
+ self.assertEqual(controller.cfg.host, self.NEW)
+ self.assertEqual(learned, [self.NEW])
+ self.assertIsNotNone(controller.sock)
+
+ def test_a_beacon_that_cannot_authenticate_changes_nothing(self):
+ controller, tried, learned = self.make(reply_token="an-impostors-token")
+ controller._connect_once()
+ controller._follow_the_pc()
+ self.assertEqual(tried, [self.OLD, self.NEW])
+ self.assertEqual(controller.cfg.host, self.OLD)
+ self.assertEqual(learned, [])
+
+ def test_another_pcs_beacon_is_ignored(self):
+ controller, tried, learned = self.make(beacons=[
+ {"name": "SOMEONE-ELSE", "address": self.NEW, "port": 51820, "reply_port": 24821, "pair_id": None}])
+ controller._connect_once()
+ controller._follow_the_pc()
+ self.assertEqual(tried, [self.OLD])
+ self.assertEqual(learned, [])
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/mac_app/tests/test_clipboard_mac.py b/mac_app/tests/test_clipboard_mac.py
index 3d94921..958ac9f 100644
--- a/mac_app/tests/test_clipboard_mac.py
+++ b/mac_app/tests/test_clipboard_mac.py
@@ -29,6 +29,10 @@ class FakePasteboard:
self.string = string
self.cleared = 0
self.written = []
+ self.count = 1
+
+ def changeCount(self):
+ return self.count
def stringForType_(self, kind):
return self.string
@@ -38,6 +42,7 @@ class FakePasteboard:
def clearContents(self):
self.cleared += 1
+ self.count += 1
def setString_forType_(self, text, kind):
self.written.append((kind, text))
@@ -94,5 +99,50 @@ class PasteboardImageTests(unittest.TestCase):
self.assertFalse(clipboard_mac.set_contents(None, None))
+
[email protected](clipboard_mac.AppKit is None, "AppKit is only available on macOS")
+class ChangedContentsTests(unittest.TestCase):
+ def setUp(self):
+ AppKit = clipboard_mac.AppKit
+ self.board = FakePasteboard(string="copied")
+ fake_appkit = type("FakeAppKit", (), {})()
+ fake_appkit.NSPasteboard = type("NSPasteboard", (), {"generalPasteboard": staticmethod(lambda: self.board)})
+ fake_appkit.NSData = AppKit.NSData
+ for name in ("NSPasteboardTypeString", "NSPasteboardTypePNG", "NSPasteboardTypeTIFF"):
+ setattr(fake_appkit, name, getattr(AppKit, name))
+ real = clipboard_mac.AppKit
+ clipboard_mac.AppKit = fake_appkit
+ clipboard_mac.forget_sync()
+ self.addCleanup(setattr, clipboard_mac, "AppKit", real)
+ self.addCleanup(clipboard_mac.forget_sync)
+
+ def test_an_unchanged_clipboard_is_sent_once(self):
+ self.assertEqual(clipboard_mac.changed_contents()[0], "copied")
+ self.assertEqual(clipboard_mac.changed_contents(), (None, None))
+
+ def test_a_new_copy_is_sent_again(self):
+ clipboard_mac.changed_contents()
+ self.board.count += 1
+ self.assertEqual(clipboard_mac.changed_contents()[0], "copied")
+
+ def test_what_the_peer_sent_is_not_sent_back(self):
+ clipboard_mac.set_contents("from the pc", None)
+ self.assertEqual(clipboard_mac.changed_contents(), (None, None))
+
+ def test_a_failed_read_does_not_hold_the_clipboard_back(self):
+ real = clipboard_mac.get_contents
+ clipboard_mac.get_contents = lambda: (None, None)
+ try:
+ self.assertEqual(clipboard_mac.changed_contents(), (None, None))
+ finally:
+ clipboard_mac.get_contents = real
+ self.assertEqual(clipboard_mac.changed_contents()[0], "copied")
+
+ def test_a_new_link_sends_it_again(self):
+ clipboard_mac.changed_contents()
+ clipboard_mac.forget_sync()
+ self.assertEqual(clipboard_mac.changed_contents()[0], "copied")
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/mac_app/tests/test_crossing.py b/mac_app/tests/test_crossing.py
index 2db78d7..21aa973 100644
--- a/mac_app/tests/test_crossing.py
+++ b/mac_app/tests/test_crossing.py
@@ -62,6 +62,11 @@ class ResistanceTests(unittest.TestCase):
self.assertGreater(second.pressure, first.pressure)
self.assertFalse(second.crossed)
+ def test_the_crossing_step_says_where_it_gave(self):
+ crossed = engine(resistance_px=0).feed(RIGHT_X, 420.0, 20, 0, BOUNDS, 1.0)
+ self.assertTrue(crossed.crossed)
+ self.assertEqual(crossed.pin, (RIGHT_X, 420.0))
+
def test_arriving_at_the_edge_counts_only_the_overshoot(self):
machine = engine()
machine.feed(1700.0, 500.0, 0, 0, BOUNDS, 1.0)
@@ -181,7 +186,9 @@ class BreakthroughTests(unittest.TestCase):
# `edge` stays "right" in config with the edge method off; it must not arm Windows' left.
self.assertEqual(engine(methods=("shortcut", "notch"), edge="right").home_edge(), "bottom")
self.assertEqual(engine(methods=("corner",), corner="top_left").home_edge(), "right")
- self.assertIsNone(engine(methods=("shortcut",)).home_edge())
+ # With only the shortcut on, the PC's edge facing this Mac still leads home.
+ self.assertEqual(engine(methods=("shortcut",), edge="right").home_edge(), "left")
+ self.assertEqual(engine(methods=("shortcut",), edge="top").home_edge(), "bottom")
def test_arrival_point_sits_just_inside_the_edge(self):
self.assertEqual(CrossingEngine.arrival_point("left", 0.5, BOUNDS), (2.0, 558.0))
@@ -285,5 +292,106 @@ class NotchTests(unittest.TestCase):
self.assertFalse(step.crossed)
+
+class PartOfTheEdgeTests(unittest.TestCase):
+ """Part of the edge: the chosen thirds of the edge cross, the rest is a plain wall."""
+
+ def test_only_the_chosen_thirds_cross(self):
+ # 1117 tall: the thirds break at about 372 and 745.
+ for y, crosses in ((100.0, False), (560.0, True), (1000.0, True)):
+ with self.subTest(y=y):
+ machine = engine(methods=("part",), parts=("middle", "end"))
+ self.assertEqual(push_right(machine, 20, y=y).crossed, crosses)
+
+ def test_the_glow_region_is_the_third_being_pushed(self):
+ machine = engine(methods=("part",), parts=("middle",))
+ step = drive(machine, RIGHT_X, 560.0, 20, 0, 2)
+ x, y, w, h = step.region
+ self.assertAlmostEqual((y, h), (1117 / 3, 1117 / 3), places=3)
+
+ def test_thirds_are_the_pointers_own_displays(self):
+ # A 1117-tall MacBook as the rightmost display, top-aligned beside a 1440-tall external:
+ # on the 1440 box its end third would start at 960, 157 points from its bottom.
+ displays = [(-2560, 0, 0, 1440), (0, 0, 1728, 1117)]
+ bounds = (-2560, 0, 1728, 1440)
+ machine = engine(methods=("part",), parts=("end",))
+ result = drive(machine, RIGHT_X, 800.0, 20, 0, 20, bounds=bounds)
+ self.assertFalse(result.crossed, "measured on the desktop box, 800 is the middle third")
+ machine = engine(methods=("part",), parts=("end",))
+ for index in range(20):
+ result = machine.feed(RIGHT_X, 800.0, 20, 0, bounds, 1.0 + index * 0.01, displays=displays)
+ if result.crossed:
+ break
+ self.assertTrue(result.crossed)
+
+ def test_it_is_the_way_home_as_the_edge_would_be(self):
+ self.assertEqual(engine(methods=("part",)).home_edge(), "left")
+ self.assertTrue(engine(methods=("part",)).armed)
+
+
+class MonitorLayoutTests(unittest.TestCase):
+ """Displays as (left, top, right, bottom) in Quartz points, the way the tap sees them."""
+
+ # A MacBook under a wider external: the MacBook's right edge stops short of the desktop's.
+ UNDER = [(0, 0, 2560, 1440), (416, 1440, 2144, 2557)]
+ UNDER_BOUNDS = (0, 0, 2560, 2557)
+
+ def feed_at(self, machine, x, y, dx, dy, displays, bounds, times=20):
+ result = None
+ for index in range(times):
+ result = machine.feed(x, y, dx, dy, bounds, 1.0 + index * 0.01, displays=displays)
+ if result.crossed:
+ break
+ return result
+
+ def test_a_shorter_displays_own_edge_is_a_wall_when_nothing_lies_beyond(self):
+ step = self.feed_at(engine(), 2143.0, 2000.0, 20, 0, self.UNDER, self.UNDER_BOUNDS)
+ self.assertTrue(step.crossed)
+
+ def test_an_edge_with_another_display_beyond_it_is_not(self):
+ side = [(0, 0, 1728, 1117), (1728, 0, 3648, 1080)]
+ step = self.feed_at(engine(), 1727.0, 500.0, 20, 0, side, (0, 0, 3648, 1117))
+ self.assertFalse(step.crossed)
+
+ def test_the_bottom_of_a_short_display_beside_a_tall_one_crosses(self):
+ tall_short = [(0, 0, 100, 300), (100, 0, 200, 100)]
+ step = self.feed_at(engine(edge="bottom"), 150.0, 99.0, 0, 20, tall_short, (0, 0, 200, 300))
+ self.assertTrue(step.crossed)
+
+ def test_part_of_the_edge_counts_its_thirds_on_the_pointers_display(self):
+ machine = engine(methods=("part",), parts=("middle",))
+ step = self.feed_at(machine, 2143.0, 1440 + 1117 / 2, 20, 0, self.UNDER, self.UNDER_BOUNDS)
+ self.assertTrue(step.crossed)
+ machine = engine(methods=("part",), parts=("middle",))
+ step = self.feed_at(machine, 2143.0, 1450.0, 20, 0, self.UNDER, self.UNDER_BOUNDS)
+ self.assertFalse(step.crossed)
+
+ def test_an_arrival_never_lands_in_a_gap(self):
+ staggered = [(0, 0, 1920, 1080), (1920, 0, 3200, 720)]
+ x, y = CrossingEngine.arrival_point("right", 0.9, (0, 0, 3200, 1080), displays=staggered)
+ self.assertTrue(any(d[0] <= x < d[2] and d[1] <= y < d[3] for d in staggered), (x, y))
+
+ def test_an_arrival_lands_on_whichever_of_two_stacked_displays_holds_it(self):
+ stacked = [(0, 0, 1512, 982), (0, 982, 1920, 2062)]
+ x, y = CrossingEngine.arrival_point("left", 0.9, (0, 0, 1920, 2062), displays=stacked)
+ self.assertEqual(x, 2.0)
+ self.assertGreater(y, 982)
+
+
+
+class CornerAndEdgeTests(unittest.TestCase):
+ def test_a_straight_push_in_the_corners_box_crosses_by_the_edge(self):
+ machine = engine(methods=("corner", "edge"), corner="top_right")
+ step = drive(machine, RIGHT_X, 3.0, 40, 0, 20)
+ self.assertTrue(step.crossed)
+ self.assertEqual(step.via, "edge")
+
+ def test_a_diagonal_push_there_is_still_the_corner(self):
+ machine = engine(methods=("corner", "edge"), corner="top_right")
+ step = drive(machine, RIGHT_X, 0.0, 30, -30, 20)
+ self.assertTrue(step.crossed)
+ self.assertEqual(step.via, "corner")
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/mac_app/tests/test_crossing_matrix.py b/mac_app/tests/test_crossing_matrix.py
new file mode 100644
index 0000000..2d636ce
--- /dev/null
+++ b/mac_app/tests/test_crossing_matrix.py
@@ -0,0 +1,467 @@
+"""Every way in on this Mac, on each arrangement and in each state, both directions, against the
+PC's own code over loopback. What each row proves, and which setting governs it, is written up in
+docs/crossing-matrix-28-09-2026.md."""
+
+import itertools
+import os
+import types
+import unittest
+
+from crossing import CORNERS, EDGES, OPPOSITE, CrossingEngine
+from settings_store import config_to_raw
+from test_bridge import FakeQuartz, crossing_config
+from two_machines import Duo, wait_for
+
+BOUNDS = (0, 0, 1728, 1117)
+NOTCH = (782.0, 946.0)
+THIRDS = {"start": 0.17, "middle": 0.5, "end": 0.83}
+
+
+def side_point(side, third):
+ f = THIRDS[third]
+ return {
+ "left": (0.0, f * 1116),
+ "right": (1727.0, f * 1116),
+ "top": (f * 1727, 0.0),
+ "bottom": (f * 1727, 1116.0),
+ }[side]
+
+
+def outward(side, n=30):
+ return {"left": (-n, 0), "right": (n, 0), "top": (0, -n), "bottom": (0, n)}[side]
+
+
+def corner_point(corner):
+ vertical, horizontal = corner.split("_")
+ return (0.0 if horizontal == "left" else 1727.0), (0.0 if vertical == "top" else 1116.0)
+
+
+def push_on_engine(engine, x, y, dx, dy):
+ """The Windows edge the push arrives at, or None when it never crosses."""
+ engine.reset()
+ now = 0.0
+ for _ in range(12):
+ now += 0.01
+ step = engine.feed(x, y, dx, dy, BOUNDS, now, notch_range=NOTCH)
+ if step.crossed:
+ return step
+ return None
+
+
+def probes():
+ """(name, x, y, dx, dy, kind, where, third) for a push at every side's three thirds, at each
+ corner diagonally and along each of its two sides, and at the notch."""
+ for side in EDGES:
+ for third in THIRDS:
+ x, y = side_point(side, third)
+ yield f"{side}/{third}", x, y, *outward(side), "edge", side, third
+ for corner in CORNERS:
+ vertical, horizontal = corner.split("_")
+ x, y = corner_point(corner)
+ yield f"{corner} diagonal", x, y, outward(horizontal)[0], outward(vertical)[1], "diagonal", corner, None
+ inset = 4 if vertical == "top" else -4
+ yield f"{corner} along {horizontal}", x, y + inset, *outward(horizontal), "straight", corner, horizontal
+ inset = 4 if horizontal == "left" else -4
+ yield f"{corner} along {vertical}", x + inset, y, *outward(vertical), "straight", corner, vertical
+ yield "notch", 850.0, 0.0, 0, -30, "notch", None, None
+
+
+def third_at_corner(corner, side):
+ vertical, horizontal = corner.split("_")
+ if side in ("left", "right"):
+ return "start" if vertical == "top" else "end"
+ return "start" if horizontal == "left" else "end"
+
+
+def expected(methods, edge, corner, parts, probe):
+ """The Windows edge a push arrives at, from the rules the Crossing page states: Edge is the
+ whole arrangement side, Part of the edge its chosen thirds, Corner its one corner and it leaves
+ by that corner's own horizontal side, the notch the top."""
+ _, _, _, _, _, kind, where, third = probe
+
+ def by_edge(side, part):
+ if side != edge:
+ return None
+ if "edge" in methods or ("part" in methods and part in parts):
+ return OPPOSITE[edge]
+ return None
+
+ if kind == "notch":
+ return OPPOSITE["top"] if "notch" in methods or by_edge("top", "middle") else None
+ if kind == "edge":
+ if where == "top" and third == "middle" and "notch" in methods:
+ return OPPOSITE["top"]
+ return by_edge(where, third)
+ vertical, horizontal = where.split("_")
+ if kind == "diagonal":
+ if "corner" in methods and where == corner:
+ return OPPOSITE[horizontal]
+ return by_edge(horizontal, third_at_corner(where, horizontal)) or by_edge(vertical, third_at_corner(where, vertical))
+ return by_edge(third, third_at_corner(where, third))
+
+
+def method_sets():
+ for shortcut, pointer, corner, notch in itertools.product((False, True), ("", "edge", "part"), (False, True), (False, True)):
+ methods = {name for name, on in (("shortcut", shortcut), (pointer, bool(pointer)), ("corner", corner), ("notch", notch)) if on and name}
+ if methods:
+ yield frozenset(methods)
+
+
+class MacWaysInTests(unittest.TestCase):
+ def test_every_way_crosses_where_it_says_and_nowhere_else(self):
+ for methods in method_sets():
+ for edge in EDGES:
+ for corner in CORNERS:
+ for parts in (("middle",), ("start", "end"), ("start", "middle", "end")):
+ engine = CrossingEngine(methods=methods, edge=edge, corner=corner, resistance_px=40, parts=parts)
+ for probe in probes():
+ step = push_on_engine(engine, *probe[1:5])
+ arrived = None if step is None else step.edge
+ with self.subTest(methods=sorted(methods), edge=edge, corner=corner, parts=parts, probe=probe[0]):
+ self.assertEqual(arrived, expected(methods, edge, corner, parts, probe))
+
+ def test_the_shortcut_alone_leaves_every_edge_a_wall(self):
+ engine = CrossingEngine(methods=("shortcut",), edge="right")
+ self.assertFalse(engine.armed)
+ for probe in probes():
+ self.assertIsNone(push_on_engine(engine, *probe[1:5]), probe[0])
+
+ def test_where_the_pointer_lands_is_the_far_edge_at_the_same_fraction(self):
+ for edge in EDGES:
+ for third, fraction in THIRDS.items():
+ engine = CrossingEngine(methods=("edge",), edge=edge, resistance_px=40)
+ x, y = side_point(edge, third)
+ step = push_on_engine(engine, x, y, *outward(edge))
+ self.assertEqual(step.edge, OPPOSITE[edge])
+ self.assertAlmostEqual(step.offset, fraction, places=2)
+
+
+class MacWayHomeNamedInTheHelloTests(unittest.TestCase):
+ """`home_edge` is the PC edge facing this Mac: what the hello tells the PC, and what a
+ shortcut switch arms as the PC's way home."""
+
+ def home(self, methods, edge="right", corner="top_right"):
+ return CrossingEngine(methods=methods, edge=edge, corner=corner).home_edge()
+
+ def test_the_arrangement_side_is_the_way_home_for_edge_part_and_shortcut(self):
+ for methods in (("edge",), ("part",), ("shortcut",), ("shortcut", "edge"), ("shortcut", "part"), ("edge", "corner")):
+ for edge in EDGES:
+ with self.subTest(methods=methods, edge=edge):
+ self.assertEqual(self.home(methods, edge), OPPOSITE[edge])
+
+ def test_the_notch_alone_names_the_pcs_bottom_edge_whatever_the_arrangement_says(self):
+ for edge in EDGES:
+ self.assertEqual(self.home(("notch",), edge), "bottom")
+ self.assertEqual(self.home(("notch", "shortcut"), edge), "bottom")
+
+ def test_a_corner_alone_names_the_side_of_the_corner_whatever_the_arrangement_says(self):
+ for edge in EDGES:
+ for corner in CORNERS:
+ self.assertEqual(self.home(("corner",), edge, corner), OPPOSITE[corner.split("_")[1]])
+
+ def test_with_the_edge_on_too_the_arrangement_wins_and_the_notch_and_corner_arrive_elsewhere(self):
+ # Pinned known gap (G6 in the report): the way home differs by how the pointer left.
+ engine = CrossingEngine(methods=("edge", "notch", "corner"), edge="right", corner="top_left", resistance_px=40)
+ self.assertEqual(engine.home_edge(), "left")
+ by_notch = push_on_engine(engine, 850.0, 0.0, 0, -30)
+ by_corner = push_on_engine(engine, 0.0, 0.0, -30, -30)
+ self.assertEqual((by_notch.edge, by_corner.edge), ("bottom", "right"))
+
+
+class ArrangementFromEitherSideTests(unittest.TestCase):
+ """The arrangement is one value both machines hold: which Mac edge leads to the PC. One that
+ arrives from the PC is applied by ControlWindow.apply_arrangement, the side that owns the
+ settings file."""
+
+ def setUp(self):
+ import tempfile
+
+ from kvm_bridge_app import ControlWindow
+ from settings_store import SettingsStore
+
+ self.dir = tempfile.TemporaryDirectory()
+ self.addCleanup(self.dir.cleanup)
+ self.apply = ControlWindow.apply_arrangement
+ self.store = SettingsStore(os.path.join(self.dir.name, "settings.json"))
+ self.logged = []
+
+ def window(self, edge="right", stamp=0):
+ cfg = crossing_config(edge=edge, arrangement_set_at=stamp)
+ self.store.save(config_to_raw(cfg))
+ cfg = self.store.load()
+ return types.SimpleNamespace(
+ controller=types.SimpleNamespace(cfg=cfg, crossing=None),
+ settings_store=self.store,
+ logger=types.SimpleNamespace(info=lambda *a: self.logged.append(a), exception=lambda *a: None),
+ refresh=lambda: None,
+ )
+
+ def test_a_newer_arrangement_from_the_pc_is_applied_with_its_stamp_and_arms_the_new_edge(self):
+ window = self.window("right", stamp=100)
+ self.apply(window, "left", 200)
+ self.assertEqual(window.controller.cfg.crossing["edge"], "left")
+ self.assertEqual(window.controller.cfg.crossing["arrangement_set_at"], 200)
+ self.assertEqual(window.controller.crossing.edge, "left")
+
+ def test_an_older_one_is_ignored(self):
+ window = self.window("right", stamp=200)
+ self.apply(window, "left", 100)
+ self.assertEqual(window.controller.cfg.crossing["edge"], "right")
+
+ def test_the_same_one_over_the_second_link_changes_nothing_and_logs_nothing(self):
+ window = self.window("left", stamp=300)
+ self.apply(window, "left", 300)
+ self.assertEqual(self.logged, [])
+
+ def test_two_different_arrangements_stamped_in_the_same_second_each_keep_their_own(self):
+ # Pinned known gap, not a rule: a tie-break would flip this.
+ # Nothing breaks the tie, so the machines stay apart until one is changed again; two
+ # people changing the same setting on two machines in one second is the only way in.
+ window = self.window("right", stamp=300)
+ self.apply(window, "left", 300)
+ self.assertEqual(window.controller.cfg.crossing["edge"], "right")
+
+
+class ArrangementOverTheLinksTests(unittest.TestCase):
+ def test_a_change_reaches_the_other_machine_over_either_link(self):
+ duo = Duo().listen()
+ self.addCleanup(duo.close)
+ duo.link_mac_to_pc()
+ duo.link_pc_to_mac()
+ # From the Mac: over its own link, and over the link the PC opened to it.
+ self.assertTrue(duo.mac.send_arrangement("left", 500))
+ self.assertTrue(duo.mac_server.send_arrangement("left", 500))
+ self.assertTrue(wait_for(lambda: len(duo.pc_arrangements) == 2), duo.pc_arrangements)
+ self.assertEqual(set(duo.pc_arrangements), {("left", 500)})
+ # From the PC, the same two ways.
+ self.assertTrue(duo.pc.send_arrangement("top", 600))
+ self.assertTrue(duo.pc_server.send_arrangement("top", 600))
+ self.assertTrue(wait_for(lambda: len(duo.mac_arrangements) == 2), duo.mac_arrangements)
+ self.assertEqual(set(duo.mac_arrangements), {("top", 600)})
+
+ def test_the_hello_carries_the_way_home_and_the_resistance_and_no_stamp(self):
+ duo = Duo(crossing={"methods": ["notch", "shortcut"], "edge": "top", "resistance_px": 96}).listen()
+ self.addCleanup(duo.close)
+ duo.link_mac_to_pc()
+ self.assertTrue(wait_for(lambda: duo.pc_peer))
+ self.assertEqual(duo.pc_peer[0][1:], ("bottom", 96))
+
+
+class WhatIsSharedTests(unittest.TestCase):
+ def test_the_crossing_page_shares_only_the_side_the_resistance_stays_each_machines_own(self):
+ import pages
+
+ line = pages.SCOPE["crossing"]
+ self.assertNotIn("Two are shared", line)
+ self.assertIn("Only which side the PC is on is shared", line)
+
+
+def pc_at_edge(duo, edge):
+ x, y = duo.pc_desktop.cursor
+ return {"left": x == 0, "right": x == 1919, "top": y == 0, "bottom": y == 1079}[edge]
+
+
+class MacToPcTests(unittest.TestCase):
+ """This Mac's own pointer out to the PC, and home again through the PC's edge while it drives."""
+
+ def duo(self, **crossing):
+ crossing.setdefault("resistance_px", 40)
+ duo = Duo(crossing=crossing).listen()
+ self.addCleanup(duo.close)
+ return duo
+
+ def cross(self, duo, edge):
+ x, y = side_point(edge, "middle")
+ self.assertTrue(duo.mac_push(x, y, *outward(edge)), "the push never crossed")
+ self.assertTrue(wait_for(lambda: duo.pc_server.return_edge is not None), "the PC was never armed")
+
+ def test_each_arrangement_crosses_to_the_opposite_edge_and_arms_that_edge_as_the_way_home(self):
+ for edge in EDGES:
+ with self.subTest(pc_is=edge):
+ duo = self.duo(edge=edge)
+ duo.link_mac_to_pc()
+ self.cross(duo, edge)
+ self.assertTrue(pc_at_edge(duo, OPPOSITE[edge]))
+ self.assertEqual(duo.pc_server.return_edge, OPPOSITE[edge])
+ duo.close()
+
+ def test_the_way_home_uses_the_resistance_this_mac_sends_with_the_switch(self):
+ # 77 is neither the default nor the PC's own 400: the PC's setting is never consulted.
+ duo = Duo(crossing={"resistance_px": 77}, pc={"crossing_resistance_px": 400}).listen()
+ self.addCleanup(duo.close)
+ duo.link_mac_to_pc()
+ self.cross(duo, "right")
+ self.assertEqual(duo.pc_server.return_resistance, 77)
+
+ def test_home_through_any_part_of_the_pcs_edge_whatever_the_pcs_own_ways_are(self):
+ pc = {"crossing_methods": ["corner"], "crossing_corner": "bottom_right", "mac_return_edge": "top"}
+ for third in THIRDS:
+ with self.subTest(third=third):
+ duo = Duo(crossing={"resistance_px": 40}, pc=pc).listen()
+ self.addCleanup(duo.close)
+ duo.link_mac_to_pc()
+ self.cross(duo, "right")
+ x, y = 0, int(THIRDS[third] * 1079)
+ duo.pc_desktop.cursor = (x, y)
+ for _ in range(6):
+ duo.mac_move(1727.0, 558.0, -30)
+ if not duo.mac.redirecting:
+ break
+ wait_for(lambda: False, 0.02)
+ self.assertTrue(wait_for(lambda: not duo.mac.redirecting), "the push through the PC's left edge never came home")
+ duo.close()
+
+ def test_a_push_along_the_way_home_is_the_pcs_edge_facing_this_mac_even_with_only_the_shortcut_on(self):
+ duo = self.duo(methods=["shortcut"], edge="top")
+ duo.link_mac_to_pc()
+ duo.mac.set_redirecting(True)
+ self.assertTrue(wait_for(lambda: duo.pc_server.return_edge == "bottom"))
+
+ def test_nothing_crosses_while_the_link_is_down_and_nothing_is_swallowed(self):
+ duo = self.duo(edge="right")
+ for _ in range(12):
+ event = {"location": (1727.0, 558.0), FakeQuartz.kCGMouseEventDeltaX: 30, FakeQuartz.kCGMouseEventDeltaY: 0}
+ self.assertIs(duo.mac._event_tap_callback(None, FakeQuartz.kCGEventMouseMoved, event, None), event)
+ self.assertFalse(duo.mac.redirecting)
+ self.assertEqual(FakeQuartz.warp_calls, [])
+
+ def test_this_macs_direction_switch_off_stops_every_way_out_but_not_the_way_back_by_shortcut(self):
+ duo = self.duo(edge="right")
+ duo.link_mac_to_pc()
+ duo.mac.cfg.send_to_windows = False
+ x, y = side_point("right", "middle")
+ self.assertFalse(duo.mac_push(x, y, 30))
+ self.assertFalse(duo.mac.set_redirecting(True))
+
+ def test_paused_and_full_screen_hold_the_mac_pointer_but_not_the_pc_pointer_coming_home(self):
+ for held in ("crossing_paused", "full_screen_app"):
+ with self.subTest(held=held):
+ duo = self.duo(edge="right")
+ duo.link_mac_to_pc()
+ self.cross(duo, "right")
+ setattr(duo.mac, held, True if held == "crossing_paused" else "Steam")
+ duo.pc_desktop.cursor = (0, 540)
+ for _ in range(6):
+ duo.mac_move(1727.0, 558.0, -30)
+ wait_for(lambda: False, 0.02)
+ if not duo.mac.redirecting:
+ break
+ self.assertTrue(wait_for(lambda: not duo.mac.redirecting), "the PC's edge stopped leading home while held")
+ duo.close()
+
+
+def mac_at_edge(duo, edge):
+ x, y = duo.mac_desktop.cursor
+ return {"left": x == 0, "right": x == 1727, "top": y == 0, "bottom": y == 1116}[edge]
+
+
+def pc_settings(edge, **more):
+ return dict(mac_return_edge=edge, crossing_methods=["edge"], **more)
+
+
+class PcToMacTests(unittest.TestCase):
+ """The PC's own mouse out to this Mac, and home again through this Mac's edge while the PC
+ drives."""
+
+ def duo(self, pc=None, **crossing):
+ crossing.setdefault("resistance_px", 40)
+ duo = Duo(crossing=crossing, pc=pc).listen()
+ self.addCleanup(duo.close)
+ return duo
+
+ def cross(self, duo, pc_edge):
+ x, y = {"left": (0, 540), "right": (1919, 540), "top": (960, 0), "bottom": (960, 1079)}[pc_edge]
+ self.assertTrue(duo.pc_push(x, y, *outward(pc_edge)), "the PC's push never crossed")
+ self.assertTrue(wait_for(lambda: duo.mac_server.return_edge is not None), "the Mac was never armed")
+
+ def test_each_arrangement_crosses_to_the_opposite_mac_edge_and_arms_it_as_the_way_home(self):
+ for edge in EDGES:
+ with self.subTest(mac_is=edge):
+ duo = self.duo(pc=pc_settings(edge, crossing_resistance_px=40))
+ duo.link_pc_to_mac()
+ self.cross(duo, edge)
+ self.assertTrue(wait_for(lambda: mac_at_edge(duo, OPPOSITE[edge])))
+ self.assertEqual(duo.mac_server.return_edge, OPPOSITE[edge])
+ duo.close()
+
+ def test_the_way_home_uses_the_resistance_the_pc_sends_with_the_switch(self):
+ duo = self.duo(pc=pc_settings("right", crossing_resistance_px=77, mac_resistance_px=5), resistance_px=400)
+ duo.link_pc_to_mac()
+ self.cross(duo, "right")
+ self.assertEqual(duo.mac_server.return_resistance, 77)
+
+ def test_home_through_this_macs_arrival_edge_whatever_this_macs_own_ways_and_arrangement_are(self):
+ for methods in (["notch"], ["corner"], ["part"], ["shortcut"]):
+ with self.subTest(macs_ways=methods):
+ duo = self.duo(pc=pc_settings("right", crossing_resistance_px=40), methods=methods, edge="top")
+ duo.link_pc_to_mac()
+ self.cross(duo, "right")
+ duo.mac_desktop.cursor = (0.0, 558.0)
+ for _ in range(6):
+ duo.pc.on_motion(-30, 0)
+ wait_for(lambda: False, 0.02)
+ if not duo.pc.redirecting:
+ break
+ self.assertTrue(wait_for(lambda: not duo.pc.redirecting), "the Mac's left edge never led home")
+ duo.close()
+
+ def test_a_pc_that_has_learned_no_edge_has_no_way_out_however_it_is_pushed(self):
+ duo = self.duo(pc=pc_settings("", crossing_resistance_px=40))
+ duo.link_pc_to_mac()
+ for edge in EDGES:
+ x, y = {"left": (0, 540), "right": (1919, 540), "top": (960, 0), "bottom": (960, 1079)}[edge]
+ self.assertFalse(duo.pc_push(x, y, *outward(edge)), edge)
+ self.assertFalse(duo.pc.redirecting)
+
+ def test_no_link_no_crossing_and_the_pc_says_nothing(self):
+ duo = self.duo(pc=pc_settings("right"))
+ self.assertFalse(duo.pc_push(1919, 540, 30))
+ self.assertFalse(duo.pc.redirecting)
+ self.assertEqual(duo.pc.status, "Not connected to the Mac")
+
+ def test_a_mac_that_is_not_listening_leaves_the_pc_with_no_link(self):
+ duo = Duo(pc=pc_settings("right"))
+ self.addCleanup(duo.close)
+ duo.pc.start(duo.pc_config)
+ self.assertFalse(wait_for(lambda: duo.pc.connected, 0.5))
+ self.assertFalse(duo.pc_push(1919, 540, 30))
+
+ def test_the_pcs_pause_and_full_screen_hold_its_own_edges(self):
+ for held in ("crossing_paused", "full_screen_app"):
+ with self.subTest(held=held):
+ duo = self.duo(pc=pc_settings("right"))
+ duo.link_pc_to_mac()
+ setattr(duo.pc, held, True if held == "crossing_paused" else "Steam")
+ self.assertFalse(duo.pc_push(1919, 540, 30))
+ duo.close()
+
+ def test_this_macs_own_pointer_can_take_input_back_only_with_its_own_link_to_the_pc_up(self):
+ # Pinned known gap (G7 in the report): the push back needs the Mac's own link.
+ duo = self.duo(pc=pc_settings("right", crossing_resistance_px=40), edge="right")
+ duo.link_pc_to_mac()
+ self.cross(duo, "right")
+ self.assertTrue(wait_for(lambda: duo.mac.receiving))
+ self.assertFalse(duo.mac_push(1727.0, 558.0, 30, times=6), "crossed with no link of its own")
+ self.assertTrue(duo.mac.receiving)
+ duo.link_mac_to_pc()
+ self.assertTrue(duo.mac_push(1727.0, 558.0, 30), "the Mac's pointer could not take input back")
+ self.assertTrue(wait_for(lambda: not duo.pc.redirecting))
+
+ def test_a_shortcut_while_the_other_machine_drives_only_sends_its_input_home(self):
+ duo = self.duo(pc=pc_settings("right"))
+ duo.link_pc_to_mac()
+ duo.link_mac_to_pc()
+ self.assertTrue(duo.pc.set_redirecting(True))
+ self.assertTrue(wait_for(lambda: duo.mac.receiving))
+ self.assertTrue(duo.mac.set_redirecting(True))
+ self.assertTrue(wait_for(lambda: not duo.pc.redirecting))
+ self.assertFalse(duo.mac.redirecting, "the shortcut also crossed this Mac's input, which only a push does")
+ self.assertTrue(duo.mac.set_redirecting(True))
+ self.assertTrue(wait_for(lambda: duo.pc_server.return_edge is not None))
+ self.assertTrue(duo.pc.set_redirecting(True))
+ self.assertTrue(wait_for(lambda: not duo.mac.redirecting))
+ self.assertFalse(duo.pc.redirecting)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_effect_fires.py b/mac_app/tests/test_effect_fires.py
new file mode 100644
index 0000000..02750ab
--- /dev/null
+++ b/mac_app/tests/test_effect_fires.py
@@ -0,0 +1,384 @@
+"""Traces every crossing-effect "move" from bridge.py's engine feedback to the call that actually
+reaches the effects overlay or a glow object, at the one hop that has no test today:
+kvm_bridge_app.py's routing between controller.on_crossing / the driven-edge callbacks and
+EffectsOverlay / EdgeGlow / NotchBeam / NotchIsland.
+
+bridge.py raising each crossing kind ("pressure", "tick", "cross", "arrive", "home") with the
+right Step fields (region, pin, via, mac_edge) is already proven by test_bridge.py's
+CrossingWiringTests and the switch_msg("mac", ...) tests around line 1920 -- not repeated here.
+This file starts from a Step already shaped the way bridge.py builds one, and checks where it
+lands."""
+
+import logging
+import unittest
+from types import SimpleNamespace
+from unittest import mock
+
+from PyObjCTools import AppHelper
+
+import crossing
+import desktop_mac
+from kvm_bridge_app import TrayApp
+
+
+def _feel(**overrides):
+ return dict(crossing.DEFAULT_CROSSING, **overrides)
+
+
+class _FakeTrayApp:
+ """Stand-in with just what the crossing-feedback and driven-edge methods read from self --
+ same pattern as test_notify_user_thread.py's _FakeTrayApp: bind the real unbound methods onto
+ a lightweight object instead of building a whole TrayApp, which needs a live NSStatusItem.
+ The overlay and glow objects are plain Mocks, so
+ these tests never touch effects.Player or draw anything."""
+
+ _crossing_feedback_main = TrayApp._crossing_feedback_main
+ _driven_pressure_main = TrayApp._driven_pressure_main
+ _driven_arrival_main = TrayApp._driven_arrival_main
+ _show_landing = TrayApp._show_landing
+ crossing_feedback = TrayApp.crossing_feedback
+ _driven_pressure = TrayApp._driven_pressure
+ _driven_arrival = TrayApp._driven_arrival
+
+ def __init__(self, feel):
+ self.logger = logging.getLogger("test-effect-fires")
+ self.controller = SimpleNamespace(cfg=SimpleNamespace(crossing=feel))
+ self.effects_overlay = mock.Mock()
+ self.effects_overlay.disabled = False
+ self.edge_glow = mock.Mock()
+ self.notch_beam = mock.Mock()
+ self.notch_island = mock.Mock()
+ self.haptics = mock.Mock()
+
+
+class MainThreadHopTest(unittest.TestCase):
+ """controller.on_crossing and the receiver's pressure/arrival callbacks fire off background
+ threads (the event tap, the ack thread, the receiver's session thread); every one of them
+ must hop to the main thread via AppHelper.callAfter before touching AppKit, the same
+ requirement test_notify_user_thread.py proves for notify_user."""
+
+ def test_crossing_feedback_hops_to_the_main_thread(self):
+ app = _FakeTrayApp(_feel())
+ step = crossing.Step(pressure=0.2)
+ with mock.patch.object(AppHelper, "callAfter") as call_after:
+ app.crossing_feedback("pressure", step)
+ call_after.assert_called_once_with(app._crossing_feedback_main, "pressure", step)
+
+ def test_driven_pressure_reads_the_cursor_then_hops_to_the_main_thread(self):
+ app = _FakeTrayApp(_feel())
+ with mock.patch.object(desktop_mac, "cursor_position", return_value=(5, 6)), mock.patch.object(
+ AppHelper, "callAfter"
+ ) as call_after:
+ app._driven_pressure("left", 0.3, False)
+ call_after.assert_called_once_with(app._driven_pressure_main, "left", 0.3, False, (5, 6), None)
+
+ def test_driven_arrival_hops_to_the_main_thread(self):
+ app = _FakeTrayApp(_feel())
+ with mock.patch.object(AppHelper, "callAfter") as call_after:
+ app._driven_arrival("left", 10.0, 20.0)
+ call_after.assert_called_once_with(app._driven_arrival_main, "left", 10.0, 20.0)
+
+
+class CrossingFeedbackDepartureTest(unittest.TestCase):
+ """The Mac's own pressure/tick/cross Steps, as bridge.py's _handle_local_mouse builds them."""
+
+ def test_pressure_reaches_the_effects_overlay_when_the_style_is_an_effect(self):
+ app = _FakeTrayApp(_feel(glow_style="rupture"))
+ app.effects_overlay.wanted.return_value = True
+ step = crossing.Step(pressure=0.4, hold=True, pin=(1727.0, 558.0), mac_edge="right",
+ region=(1727.0, 0.0, 1.0, 1117.0), via="edge")
+ app._crossing_feedback_main("pressure", step)
+ app.effects_overlay.departure.assert_called_once_with("pressure", step)
+ app.edge_glow.update.assert_not_called()
+ app.notch_beam.update.assert_not_called()
+
+ def test_pressure_reaches_edge_glow_when_the_style_is_glow(self):
+ app = _FakeTrayApp(_feel(glow_style="glow"))
+ app.effects_overlay.wanted.return_value = False
+ step = crossing.Step(pressure=0.4, hold=True, pin=(1727.0, 558.0), mac_edge="right",
+ region=(1727.0, 0.0, 1.0, 1117.0), via="edge")
+ app._crossing_feedback_main("pressure", step)
+ app.edge_glow.update.assert_called_once_with("pressure", step)
+ app.effects_overlay.departure.assert_not_called()
+
+ def test_tick_at_the_notch_reaches_notch_beam_not_edge_glow(self):
+ app = _FakeTrayApp(_feel(glow_style="beam", notch_style="beam"))
+ app.effects_overlay.wanted.return_value = False
+ step = crossing.Step(pressure=0.6, tick=True, pin=(700.0, 0.0), mac_edge="top",
+ region=(600.0, 0.0, 200.0, 1.0), via="notch")
+ app._crossing_feedback_main("tick", step)
+ app.notch_beam.update.assert_called_once_with("tick")
+ app.edge_glow.update.assert_not_called()
+
+ def test_tick_at_the_notch_reaches_notch_island_when_the_notch_style_is_island(self):
+ app = _FakeTrayApp(_feel(glow_style="beam", notch_style="island"))
+ app.effects_overlay.wanted.return_value = False
+ step = crossing.Step(pressure=0.6, tick=True, pin=(700.0, 0.0), mac_edge="top",
+ region=(600.0, 0.0, 200.0, 1.0), via="notch")
+ app._crossing_feedback_main("tick", step)
+ app.notch_island.update.assert_called_once_with("tick")
+ app.notch_beam.update.assert_not_called()
+
+ def test_cross_reaches_the_effects_overlay_when_the_style_is_an_effect(self):
+ app = _FakeTrayApp(_feel(glow_style="wormhole"))
+ app.effects_overlay.wanted.return_value = True
+ step = crossing.Step(pressure=1.0, crossed=True, pin=(1727.0, 558.0), edge="left", offset=0.5,
+ mac_edge="right", region=(1727.0, 0.0, 1.0, 1117.0), via="edge")
+ app._crossing_feedback_main("cross", step)
+ app.effects_overlay.departure.assert_called_once_with("cross", step)
+
+ def test_cross_reaches_edge_glow_when_the_style_is_glow(self):
+ app = _FakeTrayApp(_feel(glow_style="glow"))
+ app.effects_overlay.wanted.return_value = False
+ step = crossing.Step(pressure=1.0, crossed=True, pin=(1727.0, 558.0), edge="left", offset=0.5,
+ mac_edge="right", region=(1727.0, 0.0, 1.0, 1117.0), via="edge")
+ app._crossing_feedback_main("cross", step)
+ app.edge_glow.update.assert_called_once_with("cross", step)
+
+ def test_glow_switched_off_in_settings_draws_nothing(self):
+ app = _FakeTrayApp(_feel(glow=False, glow_style="glow"))
+ app.effects_overlay.wanted.return_value = False
+ step = crossing.Step(pressure=0.4, hold=True, pin=(1727.0, 558.0), mac_edge="right",
+ region=(1727.0, 0.0, 1.0, 1117.0), via="edge")
+ app._crossing_feedback_main("pressure", step)
+ app.edge_glow.update.assert_not_called()
+ app.effects_overlay.departure.assert_not_called()
+
+ def test_an_effect_that_disables_itself_this_event_falls_back_to_the_glow(self):
+ """The comment above the glow branch in _crossing_feedback_main: an effect that failed on
+ this very event has turned itself off, so today's glow draws instead and a breakthrough is
+ never lost. effects_overlay.disabled flipping True is what the real overlay's _guard does
+ on a drawing failure; simulated here by setting it directly on the mock."""
+ app = _FakeTrayApp(_feel(glow_style="rupture"))
+ app.effects_overlay.wanted.return_value = True
+ app.effects_overlay.disabled = True
+ step = crossing.Step(pressure=1.0, crossed=True, pin=(1727.0, 558.0), edge="left", offset=0.5,
+ mac_edge="right", region=(1727.0, 0.0, 1.0, 1117.0), via="edge")
+ app._crossing_feedback_main("cross", step)
+ app.effects_overlay.departure.assert_called_once_with("cross", step)
+ app.edge_glow.update.assert_called_once_with("cross", step)
+
+
+class CrossingFeedbackArrivalTest(unittest.TestCase):
+ """The Mac's own "arrive" Step, as bridge.py's _handle_switch builds it when Windows' switch
+ reply names a crossing edge (not a plain shortcut switch, which is "home", tested below)."""
+
+ def test_a_crossing_arrival_reaches_the_effects_overlay_when_the_style_is_an_effect(self):
+ app = _FakeTrayApp(_feel(glow_style="rupture"))
+ app.effects_overlay.wanted.return_value = True
+ step = crossing.Step(mac_edge="right", pin=(1727.0, 558.0))
+ app._crossing_feedback_main("arrive", step)
+ app.effects_overlay.arrival.assert_called_once_with("edge", 1727.0, 558.0, "right")
+ app.effects_overlay.crossed_in.assert_not_called()
+
+ def test_a_crossing_arrival_under_glow_calls_crossed_in_and_the_edge_glow(self):
+ """Glow and Beam are edge styles with no arrival: EdgeGlow.update ignores "arrive", and
+ crossed_in only makes a waiting switch arrival give way to the crossing."""
+ app = _FakeTrayApp(_feel(glow_style="glow"))
+ app.effects_overlay.wanted.return_value = False
+ step = crossing.Step(mac_edge="right", pin=(1727.0, 558.0))
+ app._crossing_feedback_main("arrive", step)
+ app.effects_overlay.crossed_in.assert_called_once()
+ app.effects_overlay.arrival.assert_not_called()
+ app.edge_glow.update.assert_called_once_with("arrive", step)
+
+
+class HomeArrivalTest(unittest.TestCase):
+ """kind "home": input came back by the shortcut, the menu, or set_redirecting(False), and
+ _crossing_feedback_main routes it through _show_landing rather than the glow/effect branch
+ the other kinds share."""
+
+ def test_home_shows_where_the_pointer_landed_when_the_switch_locator_is_on(self):
+ app = _FakeTrayApp(_feel(shortcut_arrival=True))
+ app.effects_overlay.wanted_switch.return_value = True
+ step = crossing.Step(pin=(400.0, 300.0))
+ app._crossing_feedback_main("home", step)
+ app.effects_overlay.switched.assert_called_once_with(400.0, 300.0)
+
+ def test_home_does_nothing_when_the_switch_locator_is_off(self):
+ app = _FakeTrayApp(_feel(shortcut_arrival=False))
+ app.effects_overlay.wanted_switch.return_value = False
+ step = crossing.Step(pin=(400.0, 300.0))
+ app._crossing_feedback_main("home", step)
+ app.effects_overlay.switched.assert_not_called()
+
+
+class DrivenReturnEdgeTest(unittest.TestCase):
+ """The PC-driven return edge: receiver.py's pressure_callback and arrival_callback, wired in
+ kvm_bridge_app.py's TrayApp.__init__ as WindowsInput(pressure_callback=self._driven_pressure,
+ arrival_callback=self._driven_arrival), land here after the main-thread hop proved above."""
+
+ def test_a_return_push_reaches_the_effects_overlay_when_wanted(self):
+ app = _FakeTrayApp(_feel(glow_style="rupture"))
+ app.effects_overlay.wanted.return_value = True
+ app._driven_pressure_main("left", 0.5, False, (10.0, 20.0))
+ app.effects_overlay.return_push.assert_called_once_with("left", 0.5, False, (10.0, 20.0), None)
+
+ def test_a_return_push_lights_the_edge_glow_under_glow(self):
+ app = _FakeTrayApp(_feel(glow_style="glow"))
+ app.effects_overlay.wanted.return_value = False
+ app._driven_pressure_main("left", 0.5, False, (10.0, 20.0))
+ app.effects_overlay.return_push.assert_not_called()
+ app.edge_glow.driven.assert_called_once_with("left", 0.5, False, (10.0, 20.0), None)
+
+ def test_a_way_home_through_a_corner_plays_its_corner_form(self):
+ for style, wanted, target in (("rupture", True, "return_push"), ("glow", False, "driven")):
+ app = _FakeTrayApp(_feel(glow_style=style))
+ app.effects_overlay.wanted.return_value = wanted
+ app._driven_pressure_main("top", 0.5, False, (10.0, 20.0), "top_left")
+ owner = app.effects_overlay if wanted else app.edge_glow
+ getattr(owner, target).assert_called_once_with("top", 0.5, False, (10.0, 20.0), "top_left")
+
+ def test_a_third_of_the_edge_plays_as_the_edge(self):
+ app = _FakeTrayApp(_feel(glow_style="glow"))
+ app.effects_overlay.wanted.return_value = False
+ app._driven_pressure_main("left", 0.5, False, (10.0, 20.0), "middle")
+ app.edge_glow.driven.assert_called_once_with("left", 0.5, False, (10.0, 20.0), None)
+
+ def test_a_driven_crossing_reaches_the_effects_overlay_when_wanted(self):
+ app = _FakeTrayApp(_feel(glow_style="rupture"))
+ app.effects_overlay.wanted.return_value = True
+ app._driven_arrival_main("left", 10.0, 20.0)
+ app.effects_overlay.arrival.assert_called_once_with("edge", 10.0, 20.0, "left")
+
+ def test_a_driven_crossing_under_glow_only_calls_crossed_in(self):
+ """Glow and Beam have no arrival; the crossing only makes a waiting switch give way."""
+ app = _FakeTrayApp(_feel(glow_style="beam"))
+ app.effects_overlay.wanted.return_value = False
+ app._driven_arrival_main("left", 10.0, 20.0)
+ app.effects_overlay.crossed_in.assert_called_once()
+ app.effects_overlay.arrival.assert_not_called()
+ app.edge_glow.update.assert_not_called()
+
+ def test_a_driven_switch_with_no_edge_shows_where_the_pointer_landed(self):
+ """edge=None is the receiver's _place_pointer telling the arrival callback the PC's input
+ came home by a switch rather than a crossing -- routed through _show_landing exactly like
+ the "home" kind above."""
+ app = _FakeTrayApp(_feel(shortcut_arrival=True))
+ app.effects_overlay.wanted_switch.return_value = True
+ app._driven_arrival_main(None, 10.0, 20.0)
+ app.effects_overlay.switched.assert_called_once_with(10.0, 20.0)
+
+
+if __name__ == "__main__":
+ unittest.main()
+
+
+class EdgeGlowDrawTest(unittest.TestCase):
+ """The real glow drawn through a push and its breakthrough, at an edge and in a corner, at every
+ length: a failure here turns the glow off for the run, which no fake would show."""
+
+ def test_a_push_and_its_breakthrough_draw_without_failing(self):
+ import AppKit
+
+ from kvm_bridge_app import EdgeGlow
+
+ AppKit.NSApplication.sharedApplication()
+ for style in ("glow", "beam"):
+ for length in ("short", "normal", "long"):
+ for region in ((1727.0, 0.0, 1.0, 1117.0), (1720.0, 1109.0, 8.0, 8.0)):
+ with self.subTest(style=style, length=length, region=region):
+ controller = SimpleNamespace(
+ cfg=SimpleNamespace(crossing=dict(crossing.DEFAULT_CROSSING, glow_style=style,
+ effect_length=length)),
+ crossing_pressure_now=lambda: 0.6,
+ _current_desktop_bounds=lambda: (0.0, 0.0, 1728.0, 1117.0),
+ )
+ glow = EdgeGlow(controller, logging.getLogger("test"))
+ glow.timer = mock.Mock()
+ step = crossing.Step(pressure=0.6, pin=(1727.0, 1116.0), mac_edge="right", region=region)
+ with mock.patch.object(desktop_mac, "monitors", return_value=[]):
+ glow.update("pressure", step)
+ glow.update("cross", step)
+ glow._draw()
+ self.assertFalse(glow.disabled)
+ glow._hide()
+
+
+class MenuBarArmTest(unittest.TestCase):
+ """Toby, 28-09-2026: the Mac's Glow corner was lopsided, the top arm a faint stripe inside the
+ menu bar beside a full side arm. Both arms measured the same 18.5pt on film, half the 37pt bar."""
+
+ BOUNDS = (0.0, 0.0, 1728.0, 1117.0)
+
+ def _glow(self, style, region, edge):
+ import AppKit
+
+ from kvm_bridge_app import EdgeGlow
+
+ AppKit.NSApplication.sharedApplication()
+ controller = SimpleNamespace(
+ cfg=SimpleNamespace(crossing=dict(crossing.DEFAULT_CROSSING, glow_style=style)),
+ crossing_pressure_now=lambda: 1.0,
+ _current_desktop_bounds=lambda: self.BOUNDS,
+ )
+ glow = EdgeGlow(controller, logging.getLogger("test"))
+ glow.timer = mock.Mock()
+ glow._ensure_panel()
+ # Already visible, so drawing never orders the panel onto the real screen.
+ glow.visible = True
+ glow.mac_edge, glow.region = edge, region
+ return glow
+
+ def _draw(self, glow, bar):
+ with mock.patch.object(desktop_mac, "monitors", return_value=[]), \
+ mock.patch("kvm_bridge_app.menu_bar_height", return_value=bar):
+ glow._draw()
+ self.assertFalse(glow.disabled)
+
+ def test_a_top_corners_arm_fills_the_menu_bar_as_the_side_arm_fills_its_band(self):
+ glow = self._glow("glow", (1720.0, 0.0, 8.0, 8.0), "right")
+ self._draw(glow, 37.0)
+ side = 2.0 + glow.BAND_MAX
+ self.assertAlmostEqual(glow.fill.frame().size.height, 37.0)
+ self.assertAlmostEqual(glow.side.frame().size.width, side)
+ # Still hung from the top of the screen.
+ self.assertAlmostEqual(glow.fill.frame().origin.y + 37.0, glow.CORNER_ARM)
+ glow._hide()
+
+ def test_a_bottom_corner_a_hidden_menu_bar_and_the_beam_are_unchanged(self):
+ for style, region, bar in (("glow", (1720.0, 1109.0, 8.0, 8.0), 37.0),
+ ("glow", (1720.0, 0.0, 8.0, 8.0), 0.0),
+ ("beam", (1720.0, 0.0, 8.0, 8.0), 37.0)):
+ with self.subTest(style=style, region=region, bar=bar):
+ glow = self._glow(style, region, "right")
+ self._draw(glow, bar)
+ self.assertAlmostEqual(glow.fill.frame().size.height, glow.side.frame().size.width)
+ glow._hide()
+
+ def test_the_top_edge_fills_the_menu_bar_too(self):
+ glow = self._glow("glow", (0.0, 0.0, 1728.0, 1.0), "top")
+ self._draw(glow, 37.0)
+ self.assertAlmostEqual(glow.panel.frame().size.height, 37.0)
+ glow._hide()
+
+ def test_the_menu_bar_is_read_from_the_screen_the_display_is(self):
+ import kvm_bridge_app
+
+ def rect(x, y, w, h):
+ return SimpleNamespace(origin=SimpleNamespace(x=x, y=y), size=SimpleNamespace(width=w, height=h))
+
+ built_in = SimpleNamespace(frame=lambda: rect(0, 0, 1728, 1117), visibleFrame=lambda: rect(0, 60, 1728, 1020))
+ # Above the built-in display, its top 1080pt higher in AppKit and at -1080 in Quartz.
+ external = SimpleNamespace(frame=lambda: rect(0, 1117, 1920, 1080), visibleFrame=lambda: rect(0, 1117, 1920, 1080))
+ fake = SimpleNamespace(NSScreen=SimpleNamespace(screens=lambda: [built_in, external]))
+ with mock.patch.object(kvm_bridge_app, "AppKit", fake):
+ self.assertAlmostEqual(kvm_bridge_app.menu_bar_height((0.0, 0.0, 1728.0, 1117.0)), 37.0)
+ self.assertAlmostEqual(kvm_bridge_app.menu_bar_height((0.0, -1080.0, 1920.0, 0.0)), 0.0)
+ self.assertAlmostEqual(kvm_bridge_app.menu_bar_height((5000.0, 0.0, 6000.0, 900.0)), 0.0)
+ self.assertAlmostEqual(kvm_bridge_app.menu_bar_height(None), 0.0)
+
+
+class ThirdEndsTest(unittest.TestCase):
+ def test_a_third_of_the_edge_fades_at_its_ends_and_the_whole_edge_does_not(self):
+ from kvm_bridge_app import EdgeGlow
+
+ controller = SimpleNamespace(cfg=SimpleNamespace(crossing=dict(crossing.DEFAULT_CROSSING)),
+ _current_desktop_bounds=lambda: (0.0, 0.0, 1728.0, 1117.0))
+ glow = EdgeGlow(controller, logging.getLogger("test"))
+ glow.mac_edge = "right"
+ with mock.patch.object(desktop_mac, "monitors", return_value=[]):
+ glow.region = (1727.0, 372.0, 1.0, 373.0)
+ self.assertAlmostEqual(glow._taper(), 72.0 / 373.0)
+ glow.region = (1727.0, 0.0, 1.0, 1117.0)
+ self.assertIsNone(glow._taper())
diff --git a/mac_app/tests/test_effect_layouts.py b/mac_app/tests/test_effect_layouts.py
new file mode 100644
index 0000000..db83623
--- /dev/null
+++ b/mac_app/tests/test_effect_layouts.py
@@ -0,0 +1,322 @@
+"""Every effect on one display of many: monitor layouts side by side, stacked, staggered, left of or
+above the primary, portrait, mixed sizes and three displays. Each move plays on the display the
+pointer is on and no other, framed as that display alone, and lands where the pointer lands.
+Byte-identical in mac_app and win_app."""
+
+import colorsys
+import unittest
+from types import SimpleNamespace
+
+import effects
+
+PALETTE = ["#ff7828", "#ff3264", "#ffb43c"]
+NOTCH = {"x": 771.5, "y": 0.0, "w": 185.0, "h": 32.0, "r": 10.0}
+
+# Desktop-relative (x, y, w, h), as both overlays hand them to the Player. The first display is the
+# one with the notch, at the top middle of it.
+LAYOUTS = {
+ "one": [(0.0, 0.0, 1728.0, 1117.0)],
+ "side by side": [(0.0, 0.0, 1728.0, 1117.0), (1728.0, 0.0, 2560.0, 1440.0)],
+ "stacked": [(416.0, 1440.0, 1728.0, 1117.0), (0.0, 0.0, 2560.0, 1440.0)],
+ "staggered": [(0.0, 400.0, 1728.0, 1117.0), (1728.0, 0.0, 1920.0, 1080.0)],
+ "left of the primary": [(1920.0, 0.0, 1728.0, 1117.0), (0.0, 300.0, 1920.0, 1080.0)],
+ "portrait": [(0.0, 300.0, 1728.0, 1117.0), (1728.0, 0.0, 1080.0, 1920.0)],
+ "three": [(1920.0, 200.0, 1728.0, 1117.0), (0.0, 0.0, 1920.0, 1080.0), (3648.0, 0.0, 1280.0, 1024.0)],
+ "150% beside 100%": [(0.0, 0.0, 2560.0, 1440.0), (2560.0, 0.0, 1706.67, 960.0)],
+}
+
+
+def box(displays):
+ return (max(x + w for x, _y, w, _h in displays), max(y + h for _x, y, _w, h in displays))
+
+
+def notch_on(displays):
+ x, y, _w, _h = displays[0]
+ return dict(NOTCH, x=x + NOTCH["x"], y=y)
+
+
+def edge_region(display, edge, desktop=None):
+ """The engine's strip for `edge` of `display`; `desktop` stretches it along the whole box, as
+ the Mac's engine measures an edge."""
+ x, y, w, h = display
+ if desktop is not None and edge in ("left", "right"):
+ y, h = 0.0, desktop[1]
+ if desktop is not None and edge in ("top", "bottom"):
+ x, w = 0.0, desktop[0]
+ strips = {"left": (x, y, 1.0, h), "right": (x + w - 1.0, y, 1.0, h), "top": (x, y, w, 1.0), "bottom": (x, y + h - 1.0, w, 1.0)}
+ rx, ry, rw, rh = strips[edge]
+ return {"kind": "edge", "edge": edge, "x": rx, "y": ry, "w": rw, "h": rh}
+
+
+def corner_region(display, corner):
+ x, y, w, h = display
+ vertical, horizontal = corner.split("_")
+ return {"kind": "corner", "edge": horizontal, "corner": corner, "x": x if horizontal == "left" else x + w - 8.0,
+ "y": y if vertical == "top" else y + h - 8.0, "w": 8.0, "h": 8.0}
+
+
+def corner_point(display, corner):
+ x, y, w, h = display
+ vertical, horizontal = corner.split("_")
+ return (x if horizontal == "left" else x + w - 1.0, y if vertical == "top" else y + h - 1.0)
+
+
+def moves(display, desktop, first):
+ """(name, a function that feeds a Player at `now`) for every move on `display`."""
+ x, y, w, h = display
+ out = []
+ for edge in ("left", "right", "top", "bottom"):
+ region = edge_region(display, edge, desktop)
+ own = edge_region(display, edge)
+ for along in (0.0, 0.5, 1.0):
+ at = (own["x"] + own["w"] * along if edge in ("top", "bottom") else own["x"],
+ own["y"] + own["h"] * along if edge in ("left", "right") else own["y"])
+ at = (min(at[0], x + w - 1.0), min(at[1], y + h - 1.0))
+ out.append((f"push {edge} {along}", lambda p, now, region=region, at=at: p.push(now, "edge", region, at, 0.6, 2, display=display)))
+ out.append((f"cross {edge} {along}", lambda p, now, region=region, at=at: (p.push(now, "edge", region, at, 1.0, display=display), p.cross(now))))
+ out.append((f"arrive {edge} {along}", lambda p, now, at=at, edge=edge: p.arrive(now, "edge", at, edge, display)))
+ third = dict(own)
+ if edge in ("left", "right"):
+ third.update(y=y + 2.0 * h / 3.0, h=h / 3.0)
+ at = (own["x"], y + 5.0 * h / 6.0)
+ else:
+ third.update(x=x + 2.0 * w / 3.0, w=w / 3.0)
+ at = (x + 5.0 * w / 6.0, own["y"])
+ out.append((f"part {edge}", lambda p, now, third=third, at=at: p.push(now, "edge", third, at, 0.6, 2, display=display)))
+ for corner in ("top_left", "top_right", "bottom_left", "bottom_right"):
+ region, at = corner_region(display, corner), corner_point(display, corner)
+ out.append((f"corner {corner}", lambda p, now, region=region, at=at: (p.push(now, "corner", region, at, 1.0, display=display), p.cross(now))))
+ out.append((f"switch near {corner}", lambda p, now, at=at: p.switched(now - effects.SWITCH_SETTLE_S, at, "left", None, display)))
+ if first:
+ region = {"kind": "notch", "edge": "top", "x": x + NOTCH["x"], "y": y, "w": NOTCH["w"], "h": 1.0}
+ at = (x + NOTCH["x"] + NOTCH["w"] / 2.0, y)
+ out.append(("notch", lambda p, now, region=region, at=at: (p.push(now, "notch", region, at, 1.0, display=display), p.cross(now))))
+ out.append(("arrive under the notch", lambda p, now, at=(x + w / 2.0, y + 2.0): p.arrive(now, "edge", at, "top", display)))
+ return out
+
+
+def inside(box_, display):
+ x, y, w, h = display
+ return box_[0] >= x and box_[1] >= y and box_[2] <= x + w and box_[3] <= y + h
+
+
+class EveryLayoutTests(unittest.TestCase):
+ def test_every_move_draws_only_on_the_pointers_display(self):
+ styles = [effects.effect(effect_id) for effect_id in effects.EFFECT_IDS] + [effects.LOCATOR]
+ for layout, displays in LAYOUTS.items():
+ desktop = box(displays)
+ notch = notch_on(displays)
+ for index, display in enumerate(displays):
+ edge = (display[0], display[1], display[0] + display[2], display[1] + display[3])
+ for name, feed in moves(display, desktop, index == 0):
+ for fx in styles:
+ if fx is effects.LOCATOR and not name.startswith("switch"):
+ continue
+ with self.subTest(layout=layout, display=index, move=name, effect=fx.id):
+ player = effects.Player()
+ feed(player, 10.0)
+ drawn = 0
+ for step in (0, 14, 35):
+ for pen in player.frames(10.0 + step / 60.0, fx, (desktop[0], desktop[1], "mac"),
+ PALETTE, False, True, notch):
+ drawn += 1
+ self.assertEqual(pen.clip, edge)
+ self.assertTrue(inside(pen.bounds, display), pen.bounds)
+ self.assertGreater(drawn, 0)
+
+ def test_an_effect_is_framed_as_its_display_alone(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append((s.screen.w, s.screen.h, s.point.x, s.point.y, s.edge)), 0.0, 0.5)
+ player = effects.Player()
+ player.arrive(0.0, "edge", (1730.0, 500.0), "left", (1728.0, 0.0, 1920.0, 1080.0))
+ player.frames(0.1, fx, (3648.0, 1517.0, "mac"), PALETTE, False, True)
+ self.assertEqual(seen, [(1920.0, 1080.0, 2.0, 500.0, "left")])
+
+ def test_an_edge_strip_along_the_whole_desktop_is_cut_to_the_display(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: seen.append(vars(s.region)),
+ lambda pen, s: None, 0.5, 0.0)
+ player = effects.Player()
+ display = (1728.0, 0.0, 1920.0, 1080.0)
+ player.push(0.0, "edge", {"kind": "edge", "edge": "right", "x": 3647.0, "y": 0.0, "w": 1.0, "h": 1517.0},
+ (3647.0, 500.0), 0.5, display=display)
+ player.frames(0.0, fx, (3648.0, 1517.0, "mac"), PALETTE, False, True)
+ self.assertEqual((seen[0]["x"], seen[0]["y"], seen[0]["h"]), (1919.0, 0.0, 1080.0))
+
+ def test_the_notch_is_only_seen_on_its_own_display(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append(getattr(s, "notch", None)), 0.0, 0.5)
+ displays = LAYOUTS["left of the primary"]
+ for display in displays:
+ player = effects.Player()
+ player.arrive(0.0, "edge", (display[0] + display[2] / 2.0, display[1] + 2.0), "top", display)
+ player.frames(0.1, fx, (3648.0, 1380.0, "mac"), PALETTE, False, True, notch_on(displays))
+ self.assertEqual((seen[0].x, seen[0].y), (NOTCH["x"], 0.0))
+ self.assertIsNone(seen[1])
+
+
+class AuditFindingTests(unittest.TestCase):
+ def test_a_departure_carries_no_tick_from_its_push(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: seen.append(s.tick), lambda pen, s: None, 0.5, 0.0)
+ player = effects.Player()
+ region = edge_region((0.0, 0.0, 1728.0, 1117.0), "right")
+ player.push(0.0, "edge", region, (1727.0, 500.0), 0.8, 3)
+ player.frames(0.01, fx, (1728.0, 1117.0, "mac"), PALETTE, False, True)
+ player.cross(0.02)
+ player.frames(0.05, fx, (1728.0, 1117.0, "mac"), PALETTE, False, True)
+ self.assertEqual((seen[0].index, seen[1]), (3, None))
+
+ def test_a_push_draining_between_events_stays_on_its_display(self):
+ player = effects.Player()
+ display = (1728.0, 0.0, 1920.0, 1080.0)
+ region = edge_region(display, "right")
+ player.push(0.0, "edge", region, (3647.0, 500.0), 0.6, display=display)
+ player.push(0.1, "edge", region, (3647.0, 500.0), 0.4)
+ self.assertEqual(player.depart["display"], display)
+
+ def test_a_gauge_switch_near_a_corner_draws_no_corner_register(self):
+ def ops(at):
+ s = effects.state(1728.0, 1117.0, "mac", "switch", PALETTE, point=effects.point(*at),
+ edge=effects.nearest_edge(at[0], at[1], 1728.0, 1117.0), since=0.2)
+ return len(effects.draw(effects.effect("gauge"), "arrive", s).ops)
+ self.assertEqual(ops((5.0, 5.0)), ops((800.0, 500.0)))
+
+
+class LegibleColourTests(unittest.TestCase):
+ @staticmethod
+ def lightness(colour):
+ r, g, b, _a = effects.parse_colour(colour)
+ return colorsys.rgb_to_hls(r, g, b)[1]
+
+ def test_dark_colours_are_lifted_on_dark_and_keep_their_hue(self):
+ ink = effects.pack("indigo_ink")[1]
+ lifted = effects.legible(ink, True, effects.effect("flint"))
+ self.assertTrue(all(self.lightness(c) >= effects.DARK_FLOOR - 0.01 for c in lifted))
+ before = colorsys.rgb_to_hls(*effects.parse_colour(ink[0])[:3])[0]
+ after = colorsys.rgb_to_hls(*effects.parse_colour(lifted[0])[:3])[0]
+ self.assertAlmostEqual(before, after, delta=0.02)
+ self.assertEqual(lifted[-1], ink[-1])
+
+ def test_pale_colours_come_down_on_light_only_for_effects_that_draw_them_as_given(self):
+ pearl = effects.pack("pearl")[1]
+ for effect_id in ("hyperdrive", "capillary"):
+ drawn = effects.legible(pearl, False, effects.effect(effect_id))
+ self.assertTrue(all(self.lightness(c) <= effects.LIGHT_CEILING + 0.01 for c in drawn))
+ for effect_id in ("film", "flint", "gauge"):
+ self.assertEqual(effects.legible(pearl, False, effects.effect(effect_id)), list(pearl))
+
+
+class DisplayForTests(unittest.TestCase):
+ DISPLAYS = LAYOUTS["staggered"]
+
+ def test_a_point_on_a_display_stays_where_it_is(self):
+ self.assertEqual(effects.display_for((1800.0, 20.0), self.DISPLAYS), (self.DISPLAYS[1], (1800.0, 20.0)))
+
+ def test_a_point_on_no_display_lands_on_the_nearest(self):
+ # Above the shorter display, where an arrival along the staggered desktop's top edge lands.
+ display, at = effects.display_for((500.0, 2.0), self.DISPLAYS)
+ self.assertEqual((display, at), (self.DISPLAYS[0], (500.0, 400.0)))
+
+ def test_the_far_edge_is_inside(self):
+ display, at = effects.display_for((5000.0, 5000.0), self.DISPLAYS)
+ self.assertEqual((display, at), (self.DISPLAYS[1], (3647.0, 1079.0)))
+
+
+class InkCornerTests(unittest.TestCase):
+ def test_every_corner_draws_on_screen(self):
+ w, h = 1728.0, 1117.0
+ for effect_id in ("capillary", "viscous_drop", "sumi_bloom"):
+ for corner in ("top_left", "top_right", "bottom_left", "bottom_right"):
+ for reduced in (False, True):
+ with self.subTest(effect=effect_id, corner=corner, reduced=reduced):
+ display = (0.0, 0.0, w, h)
+ region = corner_region(display, corner)
+ s = effects.state(w, h, "mac", "corner", PALETTE, reduced=reduced, region=SimpleNamespace(**region),
+ point=effects.point(*corner_point(display, corner)), along=0.0, pressure=0.8,
+ tick=None, since=None)
+ pen = effects.draw(effects.effect(effect_id), "depart", s)
+ points = [(seg[-2], seg[-1]) for op in pen.ops for seg in op[1] if len(seg) > 1]
+ on = [p for p in points if -1.0 <= p[0] <= w + 1.0 and -1.0 <= p[1] <= h + 1.0]
+ self.assertGreater(len(on) / len(points), 0.9)
+
+
+class CornerSideTests(unittest.TestCase):
+ def test_a_corner_draws_the_same_whichever_of_its_sides_leads_to_the_other_machine(self):
+ # The region's edge is the side the other machine is on: the corner's horizontal side on
+ # a machine beside it, its vertical side on one above or below.
+ w, h = 2560.0, 1440.0
+ display = (0.0, 0.0, w, h)
+ for effect_id in effects.EFFECT_IDS:
+ for corner in ("top_left", "top_right", "bottom_left", "bottom_right"):
+ sizes = []
+ for side in corner.split("_"):
+ region = dict(corner_region(display, corner), edge=side)
+ s = effects.state(w, h, "windows", "corner", PALETTE, region=SimpleNamespace(**region),
+ point=effects.point(*corner_point(display, corner)), along=0.0, pressure=0.8,
+ tick=None, since=None)
+ b = effects.draw(effects.effect(effect_id), "depart", s).bounds
+ sizes.append((round(min(b[2], w) - max(b[0], 0.0)), round(min(b[3], h) - max(b[1], 0.0))))
+ with self.subTest(effect=effect_id, corner=corner):
+ self.assertEqual(sizes[0], sizes[1])
+
+
+class ClassicPreviewTests(unittest.TestCase):
+ def test_glow_and_beam_play_at_every_place_the_preview_shows(self):
+ for style in ("glow", "beam"):
+ fx = effects.preview_effect(style)
+ for method in ("edge", "corner"):
+ with self.subTest(style=style, method=method):
+ pushing = effects.preview_scene(fx, 1.8, method, PALETTE)
+ through = effects.preview_scene(fx, 2.3, method, PALETTE)
+ self.assertTrue(pushing["pens"])
+ self.assertTrue(through["pens"])
+ # The Mac's notch style plays at the notch instead.
+ self.assertFalse(effects.preview_scene(fx, 1.8, "notch", PALETTE)["pens"])
+
+ def test_a_corner_lights_both_its_walls_on_the_mac_screen(self):
+ fx = effects.preview_effect("glow")
+ pen = effects.preview_scene(fx, 2.0, "corner", PALETTE)["pens"][0]
+ w, h = effects.PREVIEW_SCREEN
+ self.assertLess(pen.bounds[0], w - effects.CLASSIC_ARM + 10)
+ self.assertGreater(pen.bounds[3], effects.CLASSIC_ARM - 10)
+ self.assertLessEqual(pen.bounds[2], w + 4)
+
+ def test_only_the_styles_have_a_preview(self):
+ self.assertIsNone(effects.preview_effect("nonsense"))
+ self.assertEqual(effects.preview_effect("flint").id, "flint")
+
+
+class LengthTests(unittest.TestCase):
+ def test_a_longer_length_plays_the_crossing_and_the_landing_for_longer(self):
+ fx = effects.effect("rupture")
+ region = {"kind": "edge", "edge": "right", "x": 1727.0, "y": 0.0, "w": 1.0, "h": 1117.0}
+ lasted = {}
+ for length in ("short", "normal", "long"):
+ player = effects.Player(effects.pace(length))
+ player.push(0.0, "edge", region, (1727.0, 500.0), 0.9)
+ player.cross(0.0)
+ player.arrive(0.0, "edge", (1.0, 500.0), "left")
+ t = 0.0
+ while player.frames(t, fx, (1728.0, 1117.0, "mac"), PALETTE, False, True) and t < 5.0:
+ t += 1 / 60
+ lasted[length] = t
+ self.assertLess(lasted["short"], lasted["normal"])
+ self.assertLess(lasted["normal"], lasted["long"])
+ self.assertAlmostEqual(lasted["long"] / lasted["normal"], 1.5, delta=0.1)
+
+ def test_the_push_follows_the_hand_whatever_the_length(self):
+ fx = effects.effect("flint")
+ region = {"kind": "edge", "edge": "right", "x": 1727.0, "y": 0.0, "w": 1.0, "h": 1117.0}
+ drawn = []
+ for length in ("short", "long"):
+ player = effects.Player(effects.pace(length))
+ player.push(0.0, "edge", region, (1727.0, 500.0), 0.6)
+ drawn.append(player.frames(0.2, fx, (1728.0, 1117.0, "mac"), PALETTE, False, True)[0].bounds)
+ self.assertEqual(drawn[0], drawn[1])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_effects_overlay.py b/mac_app/tests/test_effects_overlay.py
new file mode 100644
index 0000000..75bd8be
--- /dev/null
+++ b/mac_app/tests/test_effects_overlay.py
@@ -0,0 +1,773 @@
+import importlib
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+import crossing
+import effects
+import effects_overlay
+from return_edge import Rect
+
+
+class FakeCG:
+ """A recording stand-in for the Quartz module: every CGContext* call effects_overlay.replay
+ makes is logged, and a real graphics-state stack tracks alpha and blend mode across
+ Save/Restore, so a test can prove each op's state is undone by the end of it. No
+ CGContextDrawConicGradient here, so a conic paint falls back to _conic_wedges; ConicFakeCG
+ below adds it back for the direct-call path."""
+
+ kCGColorSpaceSRGB = "sRGB"
+ kCGBlendModeNormal = "normal"
+ kCGBlendModePlusLighter = "plusLighter"
+ kCGBlendModeCopy = "copy"
+ kCGLineCapButt = "cap-butt"
+ kCGLineCapRound = "cap-round"
+ kCGLineCapSquare = "cap-square"
+ kCGLineJoinMiter = "join-miter"
+ kCGLineJoinRound = "join-round"
+ kCGLineJoinBevel = "join-bevel"
+ kCGGradientDrawsBeforeStartLocation = 1
+ kCGGradientDrawsAfterEndLocation = 2
+
+ BASE_STATE = {"alpha": 1.0, "blend": kCGBlendModeNormal}
+
+ def __init__(self, clip_box=((0.0, 0.0), (1440.0, 900.0))):
+ self.calls = []
+ self.gradients = []
+ self.restored_states = []
+ self.state = dict(self.BASE_STATE)
+ self._stack = []
+ self._clip_box = clip_box
+
+ def _log(self, name, *args):
+ self.calls.append((name, args))
+
+ def names(self):
+ return [name for name, _args in self.calls]
+
+ # -- state --
+
+ def CGContextSaveGState(self, ctx):
+ self._log("CGContextSaveGState")
+ self._stack.append(dict(self.state))
+
+ def CGContextRestoreGState(self, ctx):
+ self._log("CGContextRestoreGState")
+ self.state = self._stack.pop()
+ self.restored_states.append(dict(self.state))
+
+ def CGContextSetAlpha(self, ctx, alpha):
+ self._log("CGContextSetAlpha", alpha)
+ self.state["alpha"] = alpha
+
+ def CGContextSetBlendMode(self, ctx, mode):
+ self._log("CGContextSetBlendMode", mode)
+ self.state["blend"] = mode
+
+ def CGContextBeginTransparencyLayer(self, ctx, info):
+ self._log("CGContextBeginTransparencyLayer")
+ self._stack.append(dict(self.state))
+
+ def CGContextEndTransparencyLayer(self, ctx):
+ self._log("CGContextEndTransparencyLayer")
+ self.state = self._stack.pop()
+
+ # -- path --
+
+ def CGContextBeginPath(self, ctx):
+ self._log("CGContextBeginPath")
+
+ def CGContextMoveToPoint(self, ctx, x, y):
+ self._log("CGContextMoveToPoint", x, y)
+
+ def CGContextAddLineToPoint(self, ctx, x, y):
+ self._log("CGContextAddLineToPoint", x, y)
+
+ def CGContextAddQuadCurveToPoint(self, ctx, cx, cy, x, y):
+ self._log("CGContextAddQuadCurveToPoint", cx, cy, x, y)
+
+ def CGContextAddCurveToPoint(self, ctx, c1x, c1y, c2x, c2y, x, y):
+ self._log("CGContextAddCurveToPoint", c1x, c1y, c2x, c2y, x, y)
+
+ def CGContextClosePath(self, ctx):
+ self._log("CGContextClosePath")
+
+ # -- stroke setup --
+
+ def CGContextSetLineWidth(self, ctx, width):
+ self._log("CGContextSetLineWidth", width)
+
+ def CGContextSetLineCap(self, ctx, cap):
+ self._log("CGContextSetLineCap", cap)
+
+ def CGContextSetLineJoin(self, ctx, join):
+ self._log("CGContextSetLineJoin", join)
+
+ def CGContextReplacePathWithStrokedPath(self, ctx):
+ self._log("CGContextReplacePathWithStrokedPath")
+
+ # -- solid colour --
+
+ def CGContextSetRGBFillColor(self, ctx, r, g, b, a):
+ self._log("CGContextSetRGBFillColor", r, g, b, a)
+
+ def CGContextSetRGBStrokeColor(self, ctx, r, g, b, a):
+ self._log("CGContextSetRGBStrokeColor", r, g, b, a)
+
+ def CGContextFillPath(self, ctx):
+ self._log("CGContextFillPath")
+
+ def CGContextEOFillPath(self, ctx):
+ self._log("CGContextEOFillPath")
+
+ def CGContextStrokePath(self, ctx):
+ self._log("CGContextStrokePath")
+
+ def CGContextClip(self, ctx):
+ self._log("CGContextClip")
+
+ def CGContextClipToRect(self, ctx, rect):
+ self._log("CGContextClipToRect", rect)
+
+ def CGContextEOClip(self, ctx):
+ self._log("CGContextEOClip")
+
+ # -- gradients --
+
+ def CGGradientCreateWithColorComponents(self, space, components, locations, count):
+ gradient = {"space": space, "components": list(components), "locations": list(locations), "count": count}
+ self.gradients.append(gradient)
+ self._log("CGGradientCreateWithColorComponents", gradient)
+ return gradient
+
+ def CGContextDrawLinearGradient(self, ctx, gradient, start, end, options):
+ self._log("CGContextDrawLinearGradient", gradient, start, end, options)
+
+ def CGContextDrawRadialGradient(self, ctx, gradient, start, start_r, end, end_r, options):
+ self._log("CGContextDrawRadialGradient", gradient, start, start_r, end, end_r, options)
+
+ def CGContextGetClipBoundingBox(self, ctx):
+ self._log("CGContextGetClipBoundingBox")
+ return self._clip_box
+
+ # -- misc, used by draw_scene / not by replay but harmless to have --
+
+ def CGColorSpaceCreateWithName(self, name):
+ return ("colourspace", name)
+
+
+class ConicFakeCG(FakeCG):
+ """The same recorder, with CGContextDrawConicGradient present, so replay takes the direct path
+ instead of the 72-wedge fallback."""
+
+ def CGContextDrawConicGradient(self, ctx, gradient, centre, angle):
+ self._log("CGContextDrawConicGradient", gradient, centre, angle)
+
+
+CTX = "the-context"
+
+
+def _square_pen(fill=None, stroke=None, rule="nonzero"):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(10.0, 0.0)
+ pen.lineTo(10.0, 10.0)
+ pen.lineTo(0.0, 10.0)
+ pen.closePath()
+ if fill is not None:
+ pen.fillStyle = fill
+ pen.fill(rule)
+ if stroke is not None:
+ pen.strokeStyle = stroke
+ pen.stroke()
+ return pen
+
+
+class ColourFillTest(unittest.TestCase):
+ def test_nonzero_fill_sets_colour_and_fills(self):
+ pen = _square_pen(fill="#ff0000")
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ self.assertIn(("CGContextSetRGBFillColor", (1.0, 0.0, 0.0, 1.0)), cg.calls)
+ self.assertIn("CGContextFillPath", cg.names())
+ self.assertNotIn("CGContextEOFillPath", cg.names())
+
+ def test_evenodd_fill_uses_the_eo_variant(self):
+ pen = _square_pen(fill="#00ff00", rule="evenodd")
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ self.assertIn("CGContextEOFillPath", cg.names())
+ self.assertNotIn("CGContextFillPath", cg.names())
+
+
+class ColourStrokeTest(unittest.TestCase):
+ def test_stroke_sets_width_cap_join_and_colour(self):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(10.0, 0.0)
+ pen.strokeStyle = "#0000ff"
+ pen.lineWidth = 3.0
+ pen.lineCap = "round"
+ pen.lineJoin = "bevel"
+ pen.stroke()
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ self.assertIn(("CGContextSetLineWidth", (3.0,)), cg.calls)
+ self.assertIn(("CGContextSetLineCap", (cg.kCGLineCapRound,)), cg.calls)
+ self.assertIn(("CGContextSetLineJoin", (cg.kCGLineJoinBevel,)), cg.calls)
+ self.assertIn(("CGContextSetRGBStrokeColor", (0.0, 0.0, 1.0, 1.0)), cg.calls)
+ names = cg.names()
+ self.assertLess(names.index("CGContextSetRGBStrokeColor"), names.index("CGContextStrokePath"))
+
+ def test_every_cap_and_join_maps_to_its_cg_constant(self):
+ for canvas_cap, cg_name in effects_overlay._CAPS.items():
+ for canvas_join, join_name in effects_overlay._JOINS.items():
+ with self.subTest(cap=canvas_cap, join=canvas_join):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(5.0, 0.0)
+ pen.strokeStyle = "#fff"
+ pen.lineCap = canvas_cap
+ pen.lineJoin = canvas_join
+ pen.stroke()
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ self.assertIn(("CGContextSetLineCap", (getattr(cg, cg_name),)), cg.calls)
+ self.assertIn(("CGContextSetLineJoin", (getattr(cg, join_name),)), cg.calls)
+
+
+class GradientFillTest(unittest.TestCase):
+ def test_nonzero_gradient_fill_clips_then_draws(self):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(10.0, 0.0)
+ pen.lineTo(10.0, 10.0)
+ pen.closePath()
+ gradient = pen.createLinearGradient(0.0, 0.0, 10.0, 0.0)
+ gradient.addColorStop(0.0, "#000000")
+ gradient.addColorStop(1.0, "#ffffff")
+ pen.fillStyle = gradient
+ pen.fill()
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ names = cg.names()
+ self.assertIn("CGContextClip", names)
+ self.assertNotIn("CGContextEOClip", names)
+ self.assertIn("CGContextDrawLinearGradient", names)
+ self.assertLess(names.index("CGContextClip"), names.index("CGContextDrawLinearGradient"))
+
+ def test_evenodd_gradient_fill_clips_with_the_eo_variant(self):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(10.0, 0.0)
+ pen.lineTo(10.0, 10.0)
+ pen.closePath()
+ gradient = pen.createLinearGradient(0.0, 0.0, 10.0, 0.0)
+ gradient.addColorStop(0.0, "#000000")
+ gradient.addColorStop(1.0, "#ffffff")
+ pen.fillStyle = gradient
+ pen.fill("evenodd")
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ names = cg.names()
+ self.assertIn("CGContextEOClip", names)
+ self.assertNotIn("CGContextClip", names)
+
+
+class GradientStrokeTest(unittest.TestCase):
+ def test_gradient_stroke_replaces_path_then_clips_then_draws(self):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(10.0, 0.0)
+ gradient = pen.createLinearGradient(0.0, 0.0, 10.0, 0.0)
+ gradient.addColorStop(0.0, "#000000")
+ gradient.addColorStop(1.0, "#ffffff")
+ pen.strokeStyle = gradient
+ pen.lineWidth = 2.0
+ pen.stroke()
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ names = cg.names()
+ for required in ("CGContextReplacePathWithStrokedPath", "CGContextClip", "CGContextDrawLinearGradient"):
+ self.assertIn(required, names)
+ self.assertLess(names.index("CGContextReplacePathWithStrokedPath"), names.index("CGContextClip"))
+ self.assertLess(names.index("CGContextClip"), names.index("CGContextDrawLinearGradient"))
+ self.assertNotIn("CGContextStrokePath", names)
+
+
+class PathVerbTest(unittest.TestCase):
+ def test_every_verb_maps_to_its_cg_call_with_the_right_numbers(self):
+ pen = effects.Pen()
+ pen.moveTo(1.0, 2.0)
+ pen.lineTo(3.0, 4.0)
+ pen.quadraticCurveTo(5.0, 6.0, 7.0, 8.0)
+ pen.bezierCurveTo(9.0, 10.0, 11.0, 12.0, 13.0, 14.0)
+ pen.closePath()
+ pen.fillStyle = "#fff"
+ pen.fill()
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ self.assertIn(("CGContextMoveToPoint", (1.0, 2.0)), cg.calls)
+ self.assertIn(("CGContextAddLineToPoint", (3.0, 4.0)), cg.calls)
+ self.assertIn(("CGContextAddQuadCurveToPoint", (5.0, 6.0, 7.0, 8.0)), cg.calls)
+ self.assertIn(("CGContextAddCurveToPoint", (9.0, 10.0, 11.0, 12.0, 13.0, 14.0)), cg.calls)
+ self.assertIn(("CGContextClosePath", ()), cg.calls)
+
+
+class PaintKindTest(unittest.TestCase):
+ def test_rgba_colour(self):
+ pen = _square_pen(fill="rgba(255, 0, 0, 0.5)")
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ self.assertIn(("CGContextSetRGBFillColor", (1.0, 0.0, 0.0, 0.5)), cg.calls)
+
+ def test_linear_gradient_passes_its_endpoints_and_extends_both_ways(self):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(10.0, 0.0)
+ pen.lineTo(10.0, 10.0)
+ pen.closePath()
+ gradient = pen.createLinearGradient(1.0, 2.0, 8.0, 9.0)
+ gradient.addColorStop(0.0, "#000000")
+ gradient.addColorStop(1.0, "#ffffff")
+ pen.fillStyle = gradient
+ pen.fill()
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ extend = cg.kCGGradientDrawsBeforeStartLocation | cg.kCGGradientDrawsAfterEndLocation
+ calls = [args for name, args in cg.calls if name == "CGContextDrawLinearGradient"]
+ self.assertEqual(len(calls), 1)
+ _made, start, end, options = calls[0]
+ self.assertEqual(start, (1.0, 2.0))
+ self.assertEqual(end, (8.0, 9.0))
+ self.assertEqual(options, extend)
+
+ def test_radial_gradient_passes_both_circles(self):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(10.0, 0.0)
+ pen.lineTo(10.0, 10.0)
+ pen.closePath()
+ gradient = pen.createRadialGradient(1.0, 2.0, 3.0, 8.0, 9.0, 20.0)
+ gradient.addColorStop(0.0, "#000000")
+ gradient.addColorStop(1.0, "#ffffff")
+ pen.fillStyle = gradient
+ pen.fill()
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ extend = cg.kCGGradientDrawsBeforeStartLocation | cg.kCGGradientDrawsAfterEndLocation
+ calls = [args for name, args in cg.calls if name == "CGContextDrawRadialGradient"]
+ self.assertEqual(len(calls), 1)
+ _made, start, start_r, end, end_r, options = calls[0]
+ self.assertEqual(start, (1.0, 2.0))
+ self.assertEqual(start_r, 3.0)
+ self.assertEqual(end, (8.0, 9.0))
+ self.assertEqual(end_r, 20.0)
+ self.assertEqual(options, extend)
+
+ def _conic_pen(self):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(10.0, 0.0)
+ pen.lineTo(10.0, 10.0)
+ pen.closePath()
+ gradient = pen.createConicGradient(0.75, 4.0, 5.0)
+ gradient.addColorStop(0.0, "#ff0000")
+ gradient.addColorStop(1.0, "#0000ff")
+ pen.fillStyle = gradient
+ pen.fill()
+ return pen
+
+ def test_conic_gradient_draws_directly_when_the_fake_offers_it(self):
+ pen = self._conic_pen()
+ cg = ConicFakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ calls = [args for name, args in cg.calls if name == "CGContextDrawConicGradient"]
+ self.assertEqual(len(calls), 1)
+ _made, centre, angle = calls[0]
+ self.assertEqual(centre, (4.0, 5.0))
+ self.assertEqual(angle, 0.75)
+ self.assertNotIn("CGContextGetClipBoundingBox", cg.names())
+
+ def test_conic_gradient_falls_back_to_72_wedges_without_the_real_call(self):
+ pen = self._conic_pen()
+ cg = FakeCG(clip_box=((0.0, 0.0), (20.0, 20.0)))
+ effects_overlay.replay(cg, CTX, [pen])
+ names = cg.names()
+ self.assertNotIn("CGContextDrawConicGradient", names)
+ self.assertIn("CGContextGetClipBoundingBox", names)
+ wedge_fills = [name for name in names if name == "CGContextFillPath"]
+ self.assertEqual(len(wedge_fills), effects_overlay.CONIC_WEDGES)
+ # Overlapping wedges are copied inside one layer, so a translucent stop never doubles.
+ begin, end = names.index("CGContextBeginTransparencyLayer"), names.index("CGContextEndTransparencyLayer")
+ self.assertLess(begin, names.index("CGContextFillPath"))
+ self.assertGreater(end, len(names) - 1 - names[::-1].index("CGContextFillPath"))
+ self.assertIn(("CGContextSetBlendMode", ("copy",)), cg.calls[begin:end])
+
+
+class StateRestoreTest(unittest.TestCase):
+ def test_each_op_is_bracketed_and_state_returns_to_base_afterwards(self):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(10.0, 0.0)
+ pen.lineTo(10.0, 10.0)
+ pen.closePath()
+ pen.globalCompositeOperation = "lighter"
+ pen.globalAlpha = 0.3
+ pen.fillStyle = "#ff0000"
+ pen.fill()
+ pen.beginPath()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(5.0, 0.0)
+ pen.lineTo(5.0, 5.0)
+ pen.closePath()
+ pen.globalCompositeOperation = "source-over"
+ pen.globalAlpha = 1.0
+ pen.fillStyle = "#0000ff"
+ pen.fill()
+
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+
+ self.assertEqual(cg.calls.count(("CGContextSaveGState", ())), 2)
+ self.assertEqual(cg.calls.count(("CGContextRestoreGState", ())), 2)
+ self.assertIn(("CGContextSetAlpha", (0.3,)), cg.calls)
+ self.assertIn(("CGContextSetAlpha", (1.0,)), cg.calls)
+ self.assertIn(("CGContextSetBlendMode", (cg.kCGBlendModePlusLighter,)), cg.calls)
+ self.assertIn(("CGContextSetBlendMode", (cg.kCGBlendModeNormal,)), cg.calls)
+ # Every RestoreGState left the fake back at the untouched base state.
+ for restored in cg.restored_states:
+ self.assertEqual(restored, cg.BASE_STATE)
+ self.assertEqual(cg.state, cg.BASE_STATE)
+
+
+class GradientStopsTest(unittest.TestCase):
+ def test_stops_are_sorted_by_offset(self):
+ gradient = effects.Gradient("linear", (0.0, 0.0, 1.0, 0.0))
+ gradient.addColorStop(1.0, "#ff0000")
+ gradient.addColorStop(0.0, "#0000ff")
+ stops = effects_overlay._stops(gradient)
+ self.assertEqual([offset for offset, _rgba in stops], [0.0, 1.0])
+ self.assertEqual(stops[0][1], (0.0, 0.0, 1.0, 1.0))
+ self.assertEqual(stops[1][1], (1.0, 0.0, 0.0, 1.0))
+
+ def test_a_single_stop_becomes_flat_colour_at_both_ends(self):
+ gradient = effects.Gradient("linear", (0.0, 0.0, 1.0, 0.0))
+ gradient.addColorStop(0.5, "#00ff00")
+ stops = effects_overlay._stops(gradient)
+ self.assertEqual(stops, [(0.0, (0.0, 1.0, 0.0, 1.0)), (1.0, (0.0, 1.0, 0.0, 1.0))])
+
+ def test_an_empty_gradient_draws_nothing(self):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(10.0, 0.0)
+ pen.lineTo(10.0, 10.0)
+ pen.closePath()
+ gradient = pen.createLinearGradient(0.0, 0.0, 10.0, 0.0)
+ pen.fillStyle = gradient
+ pen.fill()
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ self.assertEqual(cg.gradients, [])
+ self.assertNotIn("CGContextDrawLinearGradient", cg.names())
+
+ def test_one_gradient_build_per_pen_object_even_when_two_ops_share_it(self):
+ pen = effects.Pen()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(10.0, 0.0)
+ pen.lineTo(10.0, 10.0)
+ pen.closePath()
+ gradient = pen.createLinearGradient(0.0, 0.0, 10.0, 0.0)
+ gradient.addColorStop(0.0, "#000000")
+ gradient.addColorStop(1.0, "#ffffff")
+ pen.fillStyle = gradient
+ pen.fill()
+ pen.beginPath()
+ pen.moveTo(0.0, 0.0)
+ pen.lineTo(5.0, 0.0)
+ pen.strokeStyle = gradient
+ pen.lineWidth = 1.0
+ pen.stroke()
+
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, [pen])
+ self.assertEqual(len(cg.gradients), 1)
+
+
+class RegionGeometryTest(unittest.TestCase):
+ def test_corner_name_top_right(self):
+ box = (0.0, 0.0, 1440.0, 900.0)
+ region = (1432.0, 0.0, 8.0, 8.0)
+ self.assertEqual(effects_overlay.corner_name(region, box), "top_right")
+
+ def test_corner_name_bottom_left(self):
+ box = (0.0, 0.0, 1440.0, 900.0)
+ region = (0.0, 892.0, 8.0, 8.0)
+ self.assertEqual(effects_overlay.corner_name(region, box), "bottom_left")
+
+ def test_region_of_corner_is_relative_to_the_box_top_left(self):
+ found = effects_overlay.region_of("corner", "right", (1432.0, 0.0, 8.0, 8.0), (0.0, 0.0, 1440.0, 900.0))
+ self.assertEqual(found, {
+ "kind": "corner", "edge": "right", "x": 1432.0, "y": 0.0, "w": 8.0, "h": 8.0, "corner": "top_right",
+ })
+
+ def test_region_of_corner_with_a_non_zero_origin_box(self):
+ box = (-1920.0, -200.0, 1440.0, 900.0)
+ region = (1432.0, -200.0, 8.0, 8.0)
+ found = effects_overlay.region_of("corner", "right", region, box)
+ self.assertEqual(found["kind"], "corner")
+ self.assertEqual(found["edge"], "right")
+ self.assertEqual(found["corner"], "top_right")
+ self.assertEqual(found["x"], 1432.0 - (-1920.0))
+ self.assertEqual(found["y"], -200.0 - (-200.0))
+ self.assertEqual(found["w"], 8.0)
+ self.assertEqual(found["h"], 8.0)
+
+ def test_region_of_edge_has_no_corner_key(self):
+ found = effects_overlay.region_of("edge", "right", (1439.0, 0.0, 1.0, 900.0), (0.0, 0.0, 1440.0, 900.0))
+ self.assertNotIn("corner", found)
+
+
+# Which fx_*.py module each of effects.EFFECT_IDS lives in, from effects.DIRECTIONS.
+_MODULE_FOR_EFFECT = {
+ effect_id: module_name
+ for module_name, _name, effect_ids, _packs in effects.DIRECTIONS
+ for effect_id in effect_ids
+}
+
+
+class DisplayClipTest(unittest.TestCase):
+ def test_a_pen_that_names_its_display_is_drawn_inside_it(self):
+ pen = effects.Pen()
+ pen.fillRect(0, 0, 50, 50)
+ pen.clip = (10.0, 20.0, 110.0, 220.0)
+ cg = FakeCG()
+ effects_overlay.replay(cg, "ctx", [pen])
+ clip = [args for name, args in cg.calls if name == "CGContextClipToRect"]
+ self.assertEqual(clip, [(((10.0, 20.0), (100.0, 200.0)),)])
+ self.assertEqual(cg.state, FakeCG.BASE_STATE)
+
+
+class EdgeGlowDisplayTest(unittest.TestCase):
+ """Glow and Beam's band on the pointer's own display, and on the push home while the PC drives."""
+
+ DISPLAYS = [Rect(0, 0, 1728, 1117), Rect(0, -1440, 2560, 1440)]
+ BOX = (0.0, -1440.0, 2560.0, 1117.0)
+
+ def setUp(self):
+ mock.patch.object(effects_overlay.desktop_mac, "monitors", return_value=self.DISPLAYS).start()
+ self.addCleanup(mock.patch.stopall)
+
+ def test_a_strip_along_the_whole_desktop_is_cut_to_the_pointers_display(self):
+ # Stacked, the external above: the desktop's left edge runs down both displays.
+ strip = (0.0, -1440.0, 1.0, 2557.0)
+ self.assertEqual(effects_overlay.strip_on_display(strip, (0.0, 500.0), self.BOX), (0.0, 0.0, 1.0, 1117.0))
+ self.assertEqual(effects_overlay.strip_on_display(strip, None, self.BOX), strip)
+
+ def glow(self):
+ import kvm_bridge_app
+ controller = SimpleNamespace(_current_desktop_bounds=lambda: self.BOX, crossing_pressure_now=lambda: 0.0)
+ glow = kvm_bridge_app.EdgeGlow(controller, mock.Mock())
+ glow._draw = mock.Mock()
+ return glow
+
+ def test_the_push_home_while_the_pc_drives_lights_the_band_and_drains(self):
+ glow = self.glow()
+ glow.driven("left", 0.6, False, (0.0, 500.0))
+ self.assertEqual((glow.mac_edge, glow.region), ("left", (0, 0, 1, 1117)))
+ self.assertAlmostEqual(glow.level_now(), 0.6, places=1)
+ glow.driven("left", 1.0, True, (0.0, 500.0))
+ self.assertEqual(glow.level_now(), 0.0)
+ self.assertIsNotNone(glow.flash_at)
+
+ def test_the_macs_own_push_uses_the_engines_pressure_again(self):
+ glow = self.glow()
+ glow.driven("left", 0.6, False, (0.0, 500.0))
+ glow.update("pressure", crossing.Step(pressure=0.3, pin=(0.0, -700.0), mac_edge="left",
+ region=(0.0, -1440.0, 1.0, 2557.0), via="edge"))
+ self.assertIsNone(glow.level_now)
+ self.assertEqual(glow.region, (0.0, -1440.0, 1.0, 1440.0))
+
+
+class RealEffectIntegrationTest(unittest.TestCase):
+ def test_every_landed_effect_replays_its_preview_scene_without_error(self):
+ """The fx_*.py modules land one at a time (module docstring); an id whose OWN module is
+ not here yet is skipped rather than failed. Landed ids are not caught here: if
+ effects.effect() itself errors for a module that does exist, that is a real bug to see,
+ not something to swallow as a skip."""
+ drew_something = False
+ checked_any = False
+ for effect_id in effects.EFFECT_IDS:
+ module_name = _MODULE_FOR_EFFECT[effect_id]
+ with self.subTest(effect=effect_id, module=module_name):
+ try:
+ importlib.import_module(module_name)
+ except ImportError:
+ continue
+ fx = effects.effect(effect_id)
+ if fx is None:
+ continue
+ checked_any = True
+ for t in (1.2, 2.5):
+ scene = effects.preview_scene(fx, t, "edge", ["#5fd4f4", "#ff7828"])
+ cg = FakeCG()
+ effects_overlay.replay(cg, CTX, scene["pens"])
+ if any(pen.ops for pen in scene["pens"]):
+ drew_something = True
+ if not checked_any:
+ self.skipTest("no fx_*.py module has landed yet")
+ self.assertTrue(drew_something, "no landed effect's preview scene drew any op")
+
+
+def AppKit_rect(x, y, w, h):
+ return SimpleNamespace(origin=SimpleNamespace(x=x, y=y), size=SimpleNamespace(width=w, height=h))
+
+
+class _Controller:
+ def __init__(self, style="rupture"):
+ self.cfg = SimpleNamespace(crossing=dict(crossing.DEFAULT_CROSSING, glow_style=style, glow_colour="neon"))
+ self.level = 0.0
+
+ def _current_desktop_bounds(self):
+ return (-100.0, -50.0, 1340.0, 850.0)
+
+ def crossing_pressure_now(self):
+ return self.level
+
+
+class OverlayFeedTest(unittest.TestCase):
+ """What the app's events do to the Player, without a window: events only move it on and start
+ the timer, and each lands where the pointer is."""
+
+ def setUp(self):
+ self.overlay = effects_overlay.EffectsOverlay(_Controller(), mock.Mock())
+ self.overlay.timer = mock.Mock()
+ self.overlay.timer.is_alive.return_value = False
+ self.overlay._notch = mock.Mock(return_value=None)
+ self.monitors = mock.patch.object(effects_overlay.desktop_mac, "monitors",
+ return_value=[Rect(-100, -50, 1440, 900)]).start()
+ self.draw = mock.patch.object(self.overlay, "_draw").start()
+ self.addCleanup(mock.patch.stopall)
+
+ def test_an_event_starts_the_timer_and_never_draws_itself(self):
+ region = (1339.0, -50.0, 1.0, 900.0)
+ step = crossing.Step(pressure=0.3, hold=True, pin=(1339.0, 400.0), mac_edge="right", region=region, via="edge")
+ for _ in range(50):
+ self.overlay.departure("pressure", step)
+ self.draw.assert_not_called()
+ self.overlay.timer.start.assert_called()
+ self.assertFalse(self.overlay.disabled)
+ self.assertEqual(self.overlay.player.depart["at"], (1439.0, 450.0))
+
+ def test_crossing_on_the_first_event_starts_where_it_gave(self):
+ step = crossing.Step(pressure=1.0, crossed=True, pin=(1339.0, 700.0), mac_edge="right",
+ region=(1339.0, -50.0, 1.0, 900.0), via="edge")
+ self.overlay.departure("cross", step)
+ self.assertEqual(self.overlay.player.depart["at"], (1439.0, 750.0))
+ self.assertIsNotNone(self.overlay.player.depart["crossed_at"])
+
+ def test_a_notch_push_with_no_notch_plays_as_the_top_edge(self):
+ step = crossing.Step(pressure=0.5, hold=True, pin=(700.0, -50.0), mac_edge="top",
+ region=(600.0, -50.0, 200.0, 1.0), via="notch")
+ self.overlay.departure("pressure", step)
+ self.assertEqual(self.overlay.player.depart["method"], "edge")
+ self.assertEqual(self.overlay.player.depart["region"]["kind"], "edge")
+
+ def test_the_way_home_runs_along_the_pointers_own_display(self):
+ displays = [Rect(0, 0, 1440, 900), Rect(1440, -300, 2560, 1440)]
+ with mock.patch.object(effects_overlay.desktop_mac, "monitors", return_value=displays):
+ self.overlay.return_push("left", 0.4, False, (0, 500))
+ region = self.overlay.player.depart["region"]
+ # The box starts at (-100, -50); the Mac's own display is 0..900 tall, not the box's height.
+ self.assertEqual((region["x"], region["y"], region["h"]), (100.0, 50.0, 900.0))
+
+ def test_a_way_home_through_a_corner_plays_the_corner_form_there(self):
+ with mock.patch.object(effects_overlay.desktop_mac, "monitors", return_value=[Rect(-100, -50, 1440, 900)]):
+ self.overlay.return_push("top", 0.4, False, (1339, -50), "top_right")
+ depart = self.overlay.player.depart
+ self.assertEqual((depart["method"], depart["region"]["kind"], depart["region"]["corner"]),
+ ("corner", "corner", "top_right"))
+ self.assertEqual((depart["region"]["x"], depart["region"]["y"], depart["region"]["w"]), (1432.0, 0.0, 8.0))
+
+ def test_each_event_plays_on_the_display_under_the_pointer(self):
+ # A display left of and below the primary's top, so its Quartz points are negative.
+ self.monitors.return_value = [Rect(0, 0, 1728, 1117), Rect(-1920, 300, 1920, 1080)]
+ self.overlay.controller._current_desktop_bounds = lambda: (-1920.0, 0.0, 1728.0, 1380.0)
+ self.overlay.arrival("edge", -1000.0, 800.0, "left")
+ arrival = self.overlay.player.arrival
+ self.assertEqual((arrival["display"], arrival["at"]), ((0.0, 300.0, 1920.0, 1080.0), (920.0, 800.0)))
+
+ def test_a_switch_is_oriented_by_its_own_display(self):
+ self.monitors.return_value = [Rect(0, 0, 1728, 1117), Rect(1728, 0, 2560, 1440)]
+ self.overlay.controller._current_desktop_bounds = lambda: (0.0, 0.0, 4288.0, 1440.0)
+ self.overlay.switched(1740.0, 700.0)
+ # Near the second display's left edge, though in the middle of the whole desktop.
+ self.assertEqual(self.overlay.player.arrival["edge"], "left")
+
+ def test_the_timer_stops_and_the_panels_hide_once_nothing_plays(self):
+ self.overlay.arrival("edge", 10.0, 400.0, "left")
+ panel = mock.Mock()
+ self.overlay.panels = {0: (panel, mock.Mock())}
+ self.overlay.player.arrival["started"] -= 5.0
+ effects_overlay.EffectsOverlay._draw(self.overlay)
+ panel.orderOut_.assert_called_once()
+ self.overlay.timer.stop.assert_called_once()
+ self.assertIsNone(self.overlay.fx)
+
+ def test_a_display_unplugged_mid_effect_shows_nothing_and_the_effect_still_ends(self):
+ self.monitors.return_value = [Rect(0, 0, 1728, 1117), Rect(1728, 0, 2560, 1440)]
+ self.overlay.controller._current_desktop_bounds = lambda: (0.0, 0.0, 4288.0, 1440.0)
+ self.overlay.arrival("edge", 1730.0, 700.0, "left")
+ # Only the built-in display is left, in AppKit's bottom-left coordinates.
+ builtin = SimpleNamespace(frame=lambda: AppKit_rect(0.0, 0.0, 1728.0, 1117.0))
+ panel = mock.Mock()
+ self.overlay._panel = mock.Mock(return_value=(panel, mock.Mock()))
+ appkit = SimpleNamespace(NSScreen=SimpleNamespace(screens=lambda: [builtin]))
+ with mock.patch.object(effects_overlay, "AppKit", appkit):
+ effects_overlay.EffectsOverlay._draw(self.overlay)
+ self.overlay._panel.assert_not_called()
+ self.overlay.player.arrival["started"] -= 5.0
+ effects_overlay.EffectsOverlay._draw(self.overlay)
+ self.overlay.timer.stop.assert_called_once()
+
+ def test_a_switch_plays_the_chosen_effect_where_the_pointer_is(self):
+ self.overlay.switched(200.0, 150.0)
+ self.assertEqual(self.overlay.fx.id, "rupture")
+ arrival = self.overlay.player.arrival
+ self.assertEqual((arrival["method"], arrival["at"], arrival["switch"]), ("switch", (300.0, 200.0), True))
+ self.overlay.timer.start.assert_called()
+
+ def test_a_switch_with_glow_or_beam_plays_the_locator(self):
+ for style in ("glow", "beam"):
+ with self.subTest(style=style):
+ overlay = effects_overlay.EffectsOverlay(_Controller(style), mock.Mock())
+ overlay.timer = mock.Mock()
+ overlay.timer.is_alive.return_value = False
+ overlay._notch = mock.Mock(return_value=None)
+ overlay.switched(200.0, 150.0)
+ self.assertIs(overlay.fx, effects.LOCATOR)
+ self.assertFalse(overlay.wanted(overlay.controller.cfg.crossing))
+ self.assertTrue(overlay.wanted_switch(overlay.controller.cfg.crossing))
+
+ def test_a_switch_is_wanted_only_with_both_switches_on(self):
+ feel = dict(crossing.DEFAULT_CROSSING)
+ self.assertTrue(self.overlay.wanted_switch(feel))
+ self.assertFalse(self.overlay.wanted_switch(dict(feel, shortcut_arrival=False)))
+ self.assertFalse(self.overlay.wanted_switch(dict(feel, glow=False)))
+
+ def test_effects_that_cannot_load_are_off_from_the_start(self):
+ logger = mock.Mock()
+ with mock.patch.object(effects, "_load", side_effect=ModuleNotFoundError("fx_membrane")):
+ overlay = effects_overlay.EffectsOverlay(_Controller(), logger)
+ self.assertTrue(overlay.disabled)
+ self.assertFalse(overlay.wanted(_Controller().cfg.crossing))
+ logger.exception.assert_called_once()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_gestures.py b/mac_app/tests/test_gestures.py
index a75f3cf..7d2be86 100644
--- a/mac_app/tests/test_gestures.py
+++ b/mac_app/tests/test_gestures.py
@@ -168,7 +168,7 @@ class FakeDockFields:
class DockSwipeClassifierTests(unittest.TestCase):
- """Signs as measured on macOS 26.6.2 (docs/gestures-scope-06-09-2026.md)."""
+ """Signs as measured on macOS 26.6.2."""
def setUp(self):
self.classifier = DockSwipeClassifier(macos_major=26)
diff --git a/mac_app/tests/test_hide_addresses_window.py b/mac_app/tests/test_hide_addresses_window.py
new file mode 100644
index 0000000..1caa023
--- /dev/null
+++ b/mac_app/tests/test_hide_addresses_window.py
@@ -0,0 +1,79 @@
+"""Hide addresses in the real settings window: the pairing card's typed address and what it says
+about it. Built as tools/readme_shots_mac.py builds it, never put on screen, starting no network."""
+
+import json
+import logging
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+import AppKit # noqa: E402
+
+AppKit.NSApplication.sharedApplication()
+
+import kvm_bridge_app # noqa: E402
+import settings_store # noqa: E402
+from wake import WakingController # noqa: E402
+
+
+class HideAddressesWindowTests(unittest.TestCase):
+ """Codex, the final pass on 28-09-2026: the address typed under "PC not listed?" stayed plain,
+ the no-answer message repeated it, and a found PC's screen-reader label carried its address."""
+
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ path = Path(self.directory.name) / "config.json"
+ raw = settings_store.config_to_raw(settings_store.editable_default_config())
+ raw.update(host="192.0.2.20", auth_token="synthetic", hide_addresses=True)
+ path.write_text(json.dumps(raw))
+ store = settings_store.SettingsStore(path)
+ logger = logging.getLogger("test-hide-addresses")
+ with mock.patch.object(kvm_bridge_app, "accessibility_granted", return_value=True), \
+ mock.patch.object(kvm_bridge_app, "input_monitoring_granted", return_value=True):
+ self.window = kvm_bridge_app.ControlWindow.alloc().initWithController_settingsStore_logger_(
+ WakingController(store.load(), logger=logger), store, logger
+ )
+ self.window.discovery = mock.Mock(pcs=mock.Mock(return_value=[]))
+
+ def tearDown(self):
+ self.window.appearance_watch.stop()
+ self.directory.cleanup()
+
+ def test_the_typed_address_is_dots_and_is_never_said_back(self):
+ plain_box, secret_box = self.window.find_boxes
+ self.assertTrue(plain_box.isHidden())
+ self.assertFalse(secret_box.isHidden())
+ self.window.find_secret.setStringValue_("192.0.2.10")
+ with mock.patch.object(kvm_bridge_app.AppHelper, "callLater"):
+ self.window.findPC_(None)
+ self.window.discovery.find.assert_called_once_with("192.0.2.10")
+ self.window._find_timed_out(self.window._find_serial)
+ self.assertNotIn("192.0.2.10", self.window.find_status.view.stringValue())
+
+ def test_switching_it_off_shows_the_typed_address_again(self):
+ self.window.find_secret.setStringValue_("192.0.2.10")
+ self.window._set_hide_addresses(False)
+ self.assertEqual(self.window.find_field.stringValue(), "192.0.2.10")
+ self.assertFalse(self.window.find_boxes[0].isHidden())
+
+
+class ReloadTests(unittest.TestCase):
+ def test_a_reload_sets_the_controller_before_the_window_reads_it(self):
+ # Codex, 28-09-2026: the window was filled before the controller had the reloaded config,
+ # so both address fields followed the old Hide addresses.
+ calls = []
+ tray = mock.Mock()
+ tray.settings_store.load.return_value = "cfg"
+ tray.controller.update_config.side_effect = lambda cfg: calls.append("controller")
+ tray.control_window._load.side_effect = lambda raw: calls.append("window")
+ with mock.patch.object(kvm_bridge_app, "config_to_raw", return_value={}):
+ kvm_bridge_app.TrayApp.reload_config(tray, None)
+ self.assertEqual(calls, ["controller", "window"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_keyboard_layout.py b/mac_app/tests/test_keyboard_layout.py
index 43392e8..21fdce7 100644
--- a/mac_app/tests/test_keyboard_layout.py
+++ b/mac_app/tests/test_keyboard_layout.py
@@ -1,7 +1,7 @@
"""Keys follow this Mac's own layout in both directions. UK and US share letter positions, so every
test here uses a layout that moves them: German swaps Y and Z and puts ü where US has [, and French
puts A where US has Q. The tables are what UCKeyTranslate reads from macOS's own German and French
-layouts (checked 27-09-2026); the last class reads them from the system to prove that."""
+layouts; the last class reads them from the system to prove that."""
import ctypes
import sys
diff --git a/mac_app/tests/test_pages.py b/mac_app/tests/test_pages.py
index 2095eb6..21d3422 100644
--- a/mac_app/tests/test_pages.py
+++ b/mac_app/tests/test_pages.py
@@ -4,15 +4,20 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import effects
import pages
class PagesTest(unittest.TestCase):
def test_order(self):
self.assertEqual(
- pages.KEYS, ("overview", "crossing", "design", "keyboard", "pairing", "connection", "permissions")
+ pages.KEYS, ("overview", "permissions", "crossing", "keyboard", "design", "connection")
)
+ def test_the_footer_does_not_claim_connection_applies_as_you_type(self):
+ self.assertTrue(pages.footer("design").startswith("Changes apply as you make them."))
+ self.assertEqual(pages.footer("connection"), pages.FOOTER_RUNNING)
+
def test_first_open(self):
self.assertEqual(pages.opening_page(None, True, True), "overview")
self.assertEqual(pages.opening_page(None, False, True), "permissions")
@@ -25,15 +30,180 @@ class PagesTest(unittest.TestCase):
def test_dots(self):
self.assertEqual(pages.dots(True, True, "mac"), {})
self.assertEqual(pages.dots(True, False, "mac"), {"permissions": "amber"})
- self.assertEqual(pages.dots(True, True, "token"), {"pairing": "fault"})
- self.assertEqual(pages.dots(False, False, "token"), {"permissions": "amber", "pairing": "fault"})
+ self.assertEqual(pages.dots(True, True, "token"), {"overview": "fault"})
+ self.assertEqual(pages.dots(False, False, "token"), {"permissions": "amber", "overview": "fault"})
self.assertEqual(pages.dots(True, True, "unreachable"), {})
def test_step_stops_at_the_ends(self):
self.assertEqual(pages.step("overview", -1), "overview")
- self.assertEqual(pages.step("overview", 1), "crossing")
- self.assertEqual(pages.step("permissions", 1), "permissions")
- self.assertEqual(pages.step("pairing", -1), "keyboard")
+ self.assertEqual(pages.step("overview", 1), "permissions")
+ self.assertEqual(pages.step("connection", 1), "connection")
+ self.assertEqual(pages.step("keyboard", -1), "crossing")
+
+
+class DiagramTest(unittest.TestCase):
+ def test_the_other_screen_sits_on_the_chosen_side_with_the_pair_centred(self):
+ for side in ("left", "right", "top", "bottom"):
+ with self.subTest(side=side):
+ (tx, ty, tw, th), (ox, oy, ow, oh) = pages.arrangement(400, 158, side)
+ if side == "right":
+ self.assertEqual(ox, tx + tw + pages.DIAGRAM_GAP)
+ elif side == "left":
+ self.assertEqual(ox + ow + pages.DIAGRAM_GAP, tx)
+ elif side == "top":
+ self.assertEqual(oy + oh + pages.DIAGRAM_GAP, ty)
+ else:
+ self.assertEqual(oy, ty + th + pages.DIAGRAM_GAP)
+ left, right = min(tx, ox), max(tx + tw, ox + ow)
+ top, bottom = min(ty, oy), max(ty + th, oy + oh)
+ self.assertAlmostEqual(left + right, 400)
+ self.assertAlmostEqual(top + bottom, 158)
+ self.assertGreaterEqual(top, 0)
+
+ def test_the_thirds_run_start_to_end_along_the_side_strip(self):
+ screen = (0, 0, 104, 65)
+ thirds = pages.third_marks(screen, "right")
+ self.assertEqual([frame[0] for frame in thirds.values()], [101] * 3)
+ self.assertLess(thirds["start"][1], thirds["middle"][1])
+ self.assertAlmostEqual(thirds["end"][1] + thirds["end"][3], 65)
+ along_top = pages.third_marks(screen, "top")
+ self.assertLess(along_top["start"][0], along_top["end"][0])
+
+ def test_the_corner_mark_sits_in_its_corner(self):
+ self.assertEqual(pages.corner_mark((10, 20, 104, 65), "bottom_right"), (102, 73, 12, 12))
+ self.assertEqual(pages.corner_mark((10, 20, 104, 65), "top_left"), (10, 20, 12, 12))
+
+
+class DesignChoicesTest(unittest.TestCase):
+ def test_styles_are_today_then_each_direction_quiet_medium_showpiece(self):
+ import effects
+
+ groups = pages.style_groups()
+ self.assertEqual([group for group, _ in groups], ["Classic", "Membrane", "Sparks", "Instrument"])
+ self.assertEqual([value for value, _title, _detail in groups[0][1]], ["glow", "beam"])
+ for group, choices in groups[1:]:
+ with self.subTest(group=group):
+ self.assertEqual([detail for _value, _title, detail in choices], ["Quiet", "Medium", "Showpiece"])
+ values = [value for _group, choices in groups[1:] for value, _title, _detail in choices]
+ self.assertEqual(tuple(values), effects.EFFECT_IDS)
+ self.assertEqual(groups[1][1][0][:2], ("skin", "Skin"))
+
+ def test_colours_are_today_then_each_direction_three_packs(self):
+ import crossing
+ import effects
+
+ groups = pages.colour_groups(crossing.GLOW_COLOURS)
+ self.assertEqual(groups[0], ("Classic", [(name, name.capitalize()) for name in crossing.GLOW_COLOURS]))
+ self.assertEqual([group for group, _ in groups[1:]], ["Membrane", "Sparks", "Instrument"])
+ self.assertEqual(tuple(value for _group, choices in groups[1:] for value, _title in choices), effects.PACK_IDS)
+ self.assertIn(("sodium", "Sodium"), groups[3][1])
+
+ def test_without_the_effects_only_today_is_offered(self):
+ import crossing
+
+ self.assertIsNone(pages.effects_load_error())
+ self.assertEqual([group for group, _ in pages.style_groups(False)], ["Classic"])
+ self.assertEqual([group for group, _ in pages.colour_groups(crossing.GLOW_COLOURS, False)], ["Classic"])
+ from unittest import mock
+ import effects
+
+ with mock.patch.object(effects, "_load", side_effect=ModuleNotFoundError("fx_ink")):
+ self.assertIsInstance(pages.effects_load_error(), ModuleNotFoundError)
+
+ def test_the_preview_opens_where_the_pointer_crosses(self):
+ self.assertEqual(pages.preview_place(["shortcut", "corner"]), "corner")
+ self.assertEqual(pages.preview_place(["notch"]), "notch")
+ self.assertEqual(pages.preview_place(["part", "corner"]), "edge")
+ self.assertEqual(pages.preview_place(["shortcut"]), "edge")
+
+ def test_every_place_plays_every_style_and_says_why_when_it_differs(self):
+ self.assertEqual(pages.place_note("glow", "corner", ["corner"], True), "")
+ self.assertEqual(pages.place_note("flint", "edge", ["edge"], True), "")
+ self.assertIn("not one of your ways in", pages.place_note("glow", "corner", ["edge"], True))
+ self.assertIn("notch style you choose here plays instead", pages.place_note("beam", "notch", ["notch"], True))
+ self.assertIn("Flint draws its own form", pages.place_note("flint", "notch", ["notch"], True))
+ self.assertIn("no notch", pages.place_note("glow", "notch", ["notch"], False))
+
+ def test_glow_and_beam_tiles_read_as_the_effects_do(self):
+ today = pages.style_groups()[0][1]
+ self.assertEqual([detail for _value, _name, detail in today], ["Classic", "Classic"])
+
+ def test_the_notch_style_only_matters_under_glow_and_beam(self):
+ self.assertTrue(pages.notch_style_applies("glow"))
+ self.assertTrue(pages.notch_style_applies("beam"))
+ self.assertFalse(pages.notch_style_applies("rupture"))
+ self.assertFalse(pages.notch_style_applies("discharge"))
+
+
+
+class CrossingPageRulesTests(unittest.TestCase):
+ def test_edge_and_part_of_the_edge_exclude_each_other(self):
+ self.assertEqual(pages.toggle_way(["shortcut", "edge"], "part", True), ["shortcut", "part"])
+ self.assertEqual(pages.toggle_way(["part", "corner"], "edge", True), ["edge", "corner"])
+ self.assertEqual(pages.toggle_way(["edge", "corner"], "corner", False), ["edge"])
+
+ def test_the_last_third_cannot_be_unticked(self):
+ self.assertEqual(pages.toggle_part(["middle"], "middle", False), ["middle"])
+ self.assertEqual(pages.toggle_part(["start", "middle"], "start", False), ["middle"])
+ self.assertEqual(pages.toggle_part(["middle"], "end", True), ["middle", "end"])
+
+ def test_rows_follow_the_ways(self):
+ self.assertEqual(pages.crossing_rows(["shortcut"]),
+ {"edge": True, "parts": False, "corner": False, "dragging": False,
+ "resistance": False, "shortcut": True})
+ rows = pages.crossing_rows(["part"])
+ self.assertTrue(rows["edge"] and rows["parts"] and rows["resistance"])
+ self.assertFalse(rows["shortcut"] or rows["corner"])
+ self.assertTrue(pages.crossing_rows(["corner"])["edge"])
+ self.assertTrue(pages.crossing_rows(["notch"])["resistance"])
+ # Where the PC sits shows whatever the ways: the PC's edge facing this Mac always leads here.
+ self.assertTrue(pages.crossing_rows(["notch"])["edge"])
+
+ def test_the_switch_tiles_offer_every_switch_style_once(self):
+ offered = [value for _group, choices in pages.switch_style_groups() for value, _name, _detail in choices]
+ self.assertEqual(sorted(offered), sorted(effects.SWITCH_STYLES))
+ self.assertEqual(pages.switch_style_groups()[0][0], pages.SIMPLE)
+
+ def test_parts_are_named_along_the_edge(self):
+ self.assertEqual(pages.part_names("right")["start"], "Top")
+ self.assertEqual(pages.part_names("top")["end"], "Right")
+ self.assertEqual(pages.parts_phrase("left", ["start", "middle"]), "the top and middle of the left edge")
+ self.assertEqual(pages.parts_phrase("top", []), "the middle of the top edge")
+ self.assertEqual(pages.parts_phrase("top", ["sideways"]), "the middle of the top edge")
+
+ def test_the_crossing_line_gives_the_first_reason_nothing_can_cross(self):
+ line = pages.crossing_state_sentence
+ self.assertTrue(line(False, False, False, True, False, None).startswith("Not paired yet"))
+ self.assertTrue(line(True, False, False, True, False, None).startswith("This Mac drives Windows is off"))
+ self.assertTrue(line(True, True, False, True, False, None).startswith("Not connected to the PC"))
+ self.assertEqual(line(True, True, True, False, False, None), "Only the shortcut is switched on; there is nothing to pause.")
+ self.assertTrue(line(True, True, True, True, True, None).startswith("Paused."))
+ self.assertTrue(line(True, True, True, True, False, "Keynote").startswith("Off while Keynote is full screen"))
+ self.assertEqual(line(True, True, True, True, False, None), "On. Pause it to lean on an edge without switching.")
+
+ def test_a_reason_shows_even_when_only_the_shortcut_is_on(self):
+ self.assertTrue(pages.crossing_state_blocked(False, True, True))
+ self.assertTrue(pages.crossing_state_blocked(True, False, True))
+ self.assertTrue(pages.crossing_state_blocked(True, True, False))
+ self.assertFalse(pages.crossing_state_blocked(True, True, True))
+
+ def test_the_notch_and_corner_note_shows_only_when_they_are_the_pointer_ways(self):
+ self.assertTrue(pages.notch_or_corner_only(["notch", "shortcut"]))
+ self.assertTrue(pages.notch_or_corner_only(["corner"]))
+ self.assertTrue(pages.notch_or_corner_only(["corner", "notch"]))
+ self.assertFalse(pages.notch_or_corner_only(["notch", "edge"]))
+ self.assertFalse(pages.notch_or_corner_only(["corner", "part"]))
+ self.assertFalse(pages.notch_or_corner_only(["shortcut"]))
+
+
+
+class RedactTests(unittest.TestCase):
+ def test_hides_ip_and_hardware_addresses_only_when_asked(self):
+ line = "Desktop PC at 192.168.1.20:24820, woken by 02:1A:2B:3C:0D:4E"
+ self.assertEqual(pages.redact(line, False), line)
+ self.assertEqual(pages.redact(line, True), "Desktop PC at •••:24820, woken by •••")
+ self.assertEqual(pages.redact("port 24820 and version 1.4.0", True), "port 24820 and version 1.4.0")
+ self.assertEqual(pages.redact("", True), "")
if __name__ == "__main__":
diff --git a/mac_app/tests/test_pairing.py b/mac_app/tests/test_pairing.py
index 1c06a48..43668ee 100644
--- a/mac_app/tests/test_pairing.py
+++ b/mac_app/tests/test_pairing.py
@@ -2,8 +2,10 @@ import filecmp
import logging
import os
import socket
+import threading
import time
import unittest
+from unittest import mock
import pairing
from pairing import Announcer, Discovery, PairingClient, PairingHost, beacon_msg, encode
@@ -122,5 +124,63 @@ class LoopbackTests(unittest.TestCase):
self.assertEqual(str(caught.exception), pairing.ERROR_NOT_PAIRING)
+class FindTests(unittest.TestCase):
+ """A PC whose beacons never reach the Mac, found by its address instead."""
+
+ def setUp(self):
+ self.pc_port = free_udp_port()
+ self.mac_port = free_udp_port()
+ self.paired = []
+ self.announcer = Announcer(
+ lambda: 51820,
+ lambda token, name, address: self.paired.append((token, name, address)),
+ logger=quiet_logger(),
+ bind_port=self.pc_port,
+ announce_to=("127.0.0.1", free_udp_port()),
+ name="FAR-PC",
+ )
+ self.discovery = Discovery(logger=quiet_logger(), bind_port=self.mac_port)
+ self.discovery.start()
+ self.announcer.start()
+ self.addCleanup(self.announcer.stop)
+ self.addCleanup(self.discovery.stop)
+
+ def test_a_pc_no_beacon_reaches_is_found_by_address_and_pairs(self):
+ self.assertFalse(wait_until(lambda: self.discovery.pcs(), timeout=0.6))
+ self.discovery.find("127.0.0.1", self.pc_port)
+ self.assertTrue(wait_until(lambda: self.discovery.pcs()))
+ self.assertEqual(self.discovery.pcs()[0]["name"], "FAR-PC")
+ code = self.announcer.begin_pairing()
+ self.assertTrue(wait_until(lambda: self.discovery.pcs()[0]["pair_id"] is not None, timeout=4.0))
+ token = self.discovery.pair(self.discovery.pcs()[0], code, name="Far Mac")
+ self.assertTrue(wait_until(lambda: self.paired))
+ self.assertEqual(self.paired[0], (token, "Far Mac", "127.0.0.1"))
+
+ def test_an_empty_address_stops_asking(self):
+ self.discovery.find("127.0.0.1", self.pc_port)
+ self.assertTrue(wait_until(lambda: self.discovery._finding))
+ self.discovery.find(" ")
+ self.assertIsNone(self.discovery._finding)
+
+ def test_a_name_that_never_resolves_does_not_hold_up_beacons(self):
+ resolving = threading.Event()
+ real = socket.getaddrinfo
+
+ def slow(host, *args, **kwargs):
+ if host == "slow.invalid":
+ resolving.set()
+ time.sleep(3.0)
+ raise socket.gaierror("no such name")
+ return real(host, *args, **kwargs)
+
+ with mock.patch.object(pairing.socket, "getaddrinfo", slow):
+ self.discovery.find("slow.invalid")
+ self.assertTrue(resolving.wait(1.0))
+ sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ self.addCleanup(sender.close)
+ sender.sendto(pairing.encode(pairing.beacon_msg("NEAR-PC", 51820)), ("127.0.0.1", self.mac_port))
+ self.assertTrue(wait_until(lambda: self.discovery.pcs(), timeout=1.0))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/mac_app/tests/test_previews.py b/mac_app/tests/test_previews.py
index 984501e..1b43377 100644
--- a/mac_app/tests/test_previews.py
+++ b/mac_app/tests/test_previews.py
@@ -21,5 +21,95 @@ class PreviewFrameTest(unittest.TestCase):
self.assertEqual(previews.preview_frame(cycle + 0.1, 3.0)[1], "push")
+
+class HostedGlowTest(unittest.TestCase):
+ def test_the_design_pages_glow_preview_survives_a_push(self):
+ # A preview's feed has no desktop; the glow once asked it for one and switched itself off.
+ import logging
+ import types
+
+ import config
+ import crossing
+ import kvm_bridge_app
+
+ feed = previews.PreviewFeed(types.SimpleNamespace(cfg=config.Config(
+ host="192.0.2.10", port=24820, auth_token="synthetic-token", crossing=dict(config.DEFAULT_CROSSING))))
+ glow = kvm_bridge_app.EdgeGlow(feed, logging.getLogger("test-previews"))
+ glow._draw = lambda: None
+ step = crossing.Step(pressure=0.4, pin=(799.0, 200.0), mac_edge="right", region=(799, 0, 1, 450), via="edge")
+ glow.update("pressure", step)
+ self.assertFalse(glow.disabled)
+ self.assertEqual(glow.region, (799, 0, 1, 450))
+
+
+class TileHoverTest(unittest.TestCase):
+ """The page's tiles hold stills; the one the pointer is over plays, alone, from its still."""
+
+ def setUp(self):
+ from unittest import mock
+
+ self.patches = [mock.patch.object(previews, "on_screen", lambda view: True),
+ mock.patch.object(previews.effects_overlay, "reduce_motion", lambda: False)]
+ for patch in self.patches:
+ patch.start()
+ controller = mock.Mock()
+ controller.cfg.crossing = {"notch_after_ms": 1200}
+ self.loop = previews.PreviewLoop(controller)
+ self.screens = [mock.Mock(**{"window.return_value": None}) for _ in range(2)]
+ for screen in self.screens:
+ feed = mock.Mock(level=0.0)
+ renderer = mock.Mock(spec=["_draw", "_hide", "_tick", "timer"])
+ self.loop.add(feed, renderer, mock.Mock(), screen)
+ self.loop.running = True
+
+ def tearDown(self):
+ for patch in self.patches:
+ patch.stop()
+
+ def playing(self):
+ return [player.started_at is not None for player in self.loop.players]
+
+ def test_only_the_resting_tile_plays_until_one_is_hovered(self):
+ self.loop.set_resting([self.screens[0]])
+ self.loop._tick()
+ self.assertEqual(self.playing(), [True, False])
+ self.loop.hover(self.screens[1])
+ self.loop.hovered_at -= previews.HOVER_INTENT_S
+ self.loop._tick()
+ self.assertEqual(self.playing(), [False, True])
+
+ def test_a_pointer_passing_over_starts_nothing(self):
+ self.loop.hover(self.screens[1])
+ self.loop._tick()
+ self.assertEqual(self.playing(), [False, False])
+
+ def test_a_tile_plays_on_from_its_held_push(self):
+ self.loop.set_resting([self.screens[0]])
+ self.loop._tick()
+ self.assertAlmostEqual(self.loop.players[0].feed.level, previews.PreviewLoop.HOLD, places=2)
+
+ def test_a_tile_left_mid_breakthrough_holds_a_clean_still(self):
+ renderer = self.loop.players[0].renderer
+ renderer.cross_at, renderer.flare = 12.0, 0.8
+ renderer.mock_add_spec(["_draw", "_hide", "_tick", "timer", "cross_at", "flare"])
+ renderer.cross_at, renderer.flare = 12.0, 0.8
+ self.loop._hold(self.loop.players[0])
+ self.assertEqual((renderer.cross_at, renderer.flare), (None, 0.0))
+
+ def test_a_pointer_passing_over_leaves_the_resting_tile_playing(self):
+ self.loop.set_resting([self.screens[0]])
+ self.loop._tick()
+ self.loop.hover(self.screens[1])
+ self.loop._tick()
+ self.assertEqual(self.playing(), [True, False])
+
+ def test_reduce_motion_keeps_the_hovered_tile_still(self):
+ with __import__("unittest").mock.patch.object(previews.effects_overlay, "reduce_motion", lambda: True):
+ self.loop.hover(self.screens[1])
+ self.loop.hovered_at -= previews.HOVER_INTENT_S
+ self.loop._tick()
+ self.assertEqual(self.playing(), [False, False])
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/mac_app/tests/test_settings_store.py b/mac_app/tests/test_settings_store.py
index 8123fa2..0dd544e 100644
--- a/mac_app/tests/test_settings_store.py
+++ b/mac_app/tests/test_settings_store.py
@@ -8,7 +8,7 @@ from unittest import mock
import config as config_module
import protocol
import settings_store
-from settings_store import SettingsError, SettingsStore, config_to_raw, migrate_legacy_config
+from settings_store import SettingsError, SettingsStore, config_to_raw
class SettingsStoreTests(unittest.TestCase):
@@ -47,6 +47,31 @@ class SettingsStoreTests(unittest.TestCase):
self.assertTrue(loaded.allow_windows_to_drive)
self.assertFalse(store.load().send_to_windows)
+ def test_appearance_defaults_to_system_and_each_choice_round_trips(self):
+ with tempfile.TemporaryDirectory() as directory:
+ store = SettingsStore(Path(directory) / "config.json")
+ self.assertEqual(store.save(self.valid_raw()).appearance, "system")
+ for choice in ("light", "dark", "system"):
+ raw = config_to_raw(store.load())
+ raw["appearance"] = choice
+ store.save(raw)
+ self.assertEqual(store.load().appearance, choice)
+ raw = config_to_raw(store.load())
+ raw["appearance"] = "sepia"
+ self.assertEqual(store.save(raw).appearance, "system")
+
+ def test_a_hand_edited_appearance_loads_as_system(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "config.json"
+ path.write_text(json.dumps({**self.valid_raw(), "appearance": "sepia"}), encoding="utf-8")
+ self.assertEqual(config_module.load_config(str(path)).appearance, "system")
+
+ def test_appearances_match_the_shared_tokens(self):
+ import sys
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+ import tokens
+ self.assertEqual(config_module.APPEARANCES, tokens.APPEARANCES)
+
def test_legacy_positional_key_map_is_replaced_by_the_semantic_default(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "config.json"
@@ -92,6 +117,50 @@ class SettingsStoreTests(unittest.TestCase):
self.assertEqual(loaded.crossing, config_module.DEFAULT_CROSSING)
self.assertIsNot(loaded.crossing, config_module.DEFAULT_CROSSING)
+ def test_showing_where_the_pointer_lands_is_on_for_an_old_config_and_round_trips_off(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "config.json"
+ raw = self.valid_raw()
+ raw["crossing"] = {"edge": "left", "glow_style": "rupture"}
+ path.write_text(json.dumps(raw), encoding="utf-8")
+ store = SettingsStore(path)
+ loaded = store.load()
+ self.assertTrue(loaded.crossing["shortcut_arrival"])
+ raw = config_to_raw(loaded)
+ raw["crossing"]["shortcut_arrival"] = False
+ store.save(raw)
+ self.assertFalse(store.load().crossing["shortcut_arrival"])
+ self.assertEqual(store.load().crossing["shortcut_arrival_style"], "match")
+ raw["crossing"]["shortcut_arrival_style"] = "discharge"
+ store.save(raw)
+ self.assertEqual(store.load().crossing["shortcut_arrival_style"], "discharge")
+ self.assertEqual(store.load().crossing["glow_style"], "rupture")
+
+ def test_the_length_defaults_to_normal_and_round_trips(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "config.json"
+ raw = config_to_raw(settings_store.editable_default_config())
+ path.write_text(json.dumps(raw))
+ store = SettingsStore(path)
+ self.assertEqual(store.load().crossing["effect_length"], "normal")
+ raw["crossing"]["effect_length"] = "short"
+ store.save(raw)
+ self.assertEqual(store.load().crossing["effect_length"], "short")
+ raw["crossing"]["effect_length"] = "forever"
+ with self.assertRaises(SettingsError):
+ store.save(raw)
+
+ def test_a_saved_warp_choice_reads_as_its_stand_in(self):
+ # Warp is offered nowhere for now; a Mac that chose it keeps working.
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "config.json"
+ raw = config_to_raw(settings_store.editable_default_config())
+ raw["crossing"].update(glow_style="hyperdrive", glow_colour="vaporwave", shortcut_arrival_style="light_slit")
+ path.write_text(json.dumps(raw))
+ crossing = SettingsStore(path).load().crossing
+ self.assertEqual((crossing["glow_style"], crossing["glow_colour"], crossing["shortcut_arrival_style"]),
+ ("glow", "colourful", "match"))
+
def test_partial_crossing_object_keeps_the_other_defaults(self):
with tempfile.TemporaryDirectory() as directory:
raw = self.valid_raw()
@@ -112,6 +181,15 @@ class SettingsStoreTests(unittest.TestCase):
({"resistance_px": 501}, "crossing.resistance_px"),
({"resistance_px": -1}, "crossing.resistance_px"),
({"glow": "yes"}, "crossing.glow"),
+ ({"shortcut_arrival": "yes"}, "crossing.shortcut_arrival"),
+ ({"edge_parts": []}, "crossing.edge_parts"),
+ ({"edge_parts": ["side"]}, "crossing.edge_parts"),
+ ({"edge_parts": "middle"}, "crossing.edge_parts"),
+ ({"edge_parts": [["middle"]]}, "crossing.edge_parts"),
+ ({"edge_parts": [{}]}, "crossing.edge_parts"),
+ ({"methods": [["edge"]]}, "crossing.methods"),
+ ({"methods": ["part", "sideways"]}, "crossing.methods"),
+ ({"shortcut_arrival_style": "sparkle"}, "crossing.shortcut_arrival_style"),
({"notch_style": "sparkle"}, "crossing.notch_style"),
({"notch_after_ms": 50}, "crossing.notch_after_ms"),
({"notch_after_ms": 1.5}, "crossing.notch_after_ms"),
@@ -129,6 +207,39 @@ class SettingsStoreTests(unittest.TestCase):
SettingsStore(Path(directory) / "config.json").save(raw)
self.assertIn(field, str(caught.exception))
+ def test_every_crossing_effect_and_colour_pack_round_trips(self):
+ import effects
+
+ pairs = [(style, "signal") for style in effects.EFFECT_IDS]
+ pairs += [(style, colour) for style in ("glow", "beam") for colour in effects.PACK_IDS]
+ pairs += list(zip(effects.EFFECT_IDS, effects.PACK_IDS))
+ with tempfile.TemporaryDirectory() as directory:
+ store = SettingsStore(Path(directory) / "config.json")
+ for style, colour in pairs:
+ with self.subTest(style=style, colour=colour):
+ raw = self.valid_raw()
+ raw["crossing"] = {"glow_style": style, "glow_colour": colour}
+ store.save(raw)
+ loaded = store.load()
+ self.assertEqual((loaded.crossing["glow_style"], loaded.crossing["glow_colour"]), (style, colour))
+
+ def test_rejects_a_direction_or_a_pack_where_a_style_goes(self):
+ cases = [
+ ({"glow_style": "membrane"}, "crossing.glow_style"),
+ ({"glow_style": "Skin"}, "crossing.glow_style"),
+ ({"glow_style": "neon"}, "crossing.glow_style"),
+ ({"glow_colour": "rupture"}, "crossing.glow_colour"),
+ ({"glow_colour": "atmosphere"}, "crossing.glow_colour"),
+ ]
+ with tempfile.TemporaryDirectory() as directory:
+ for crossing, field in cases:
+ with self.subTest(crossing=crossing):
+ raw = self.valid_raw()
+ raw["crossing"] = crossing
+ with self.assertRaises(SettingsError) as caught:
+ SettingsStore(Path(directory) / "config.json").save(raw)
+ self.assertIn(field, str(caught.exception))
+
def test_rejects_unknown_trigger_style(self):
with tempfile.TemporaryDirectory() as directory:
raw = self.valid_raw()
@@ -151,47 +262,6 @@ class SettingsStoreTests(unittest.TestCase):
with self.assertRaises(SettingsError):
SettingsStore(path).save(raw)
- def test_migrate_legacy_config_copies_without_touching_the_old_file(self):
- with tempfile.TemporaryDirectory() as directory:
- legacy_dir = Path(directory) / "OpenKB"
- legacy_dir.mkdir()
- legacy_path = legacy_dir / "config.json"
- legacy_path.write_text(json.dumps(self.valid_raw()), encoding="utf-8")
- os.chmod(legacy_path, 0o600)
- new_dir = Path(directory) / "Beamer"
- new_path = new_dir / "config.json"
- with mock.patch.multiple(
- settings_store,
- LEGACY_APP_SUPPORT_DIRECTORY=legacy_dir,
- LEGACY_SETTINGS_PATH=legacy_path,
- APP_SUPPORT_DIRECTORY=new_dir,
- DEFAULT_SETTINGS_PATH=new_path,
- ):
- self.assertTrue(migrate_legacy_config())
- self.assertTrue(legacy_path.exists())
- self.assertEqual(
- json.loads(new_path.read_text(encoding="utf-8")),
- json.loads(legacy_path.read_text(encoding="utf-8")),
- )
- self.assertEqual(new_path.stat().st_mode & 0o777, 0o600)
- # A second run must not overwrite the now-existing new config.
- new_path.write_text(json.dumps({"changed": True}), encoding="utf-8")
- self.assertFalse(migrate_legacy_config())
- self.assertEqual(json.loads(new_path.read_text(encoding="utf-8")), {"changed": True})
-
- def test_migrate_legacy_config_is_a_noop_with_no_legacy_file(self):
- with tempfile.TemporaryDirectory() as directory:
- legacy_dir = Path(directory) / "OpenKB"
- new_dir = Path(directory) / "Beamer"
- with mock.patch.multiple(
- settings_store,
- LEGACY_APP_SUPPORT_DIRECTORY=legacy_dir,
- LEGACY_SETTINGS_PATH=legacy_dir / "config.json",
- APP_SUPPORT_DIRECTORY=new_dir,
- DEFAULT_SETTINGS_PATH=new_dir / "config.json",
- ):
- self.assertFalse(migrate_legacy_config())
- self.assertFalse(new_dir.exists())
if __name__ == "__main__":
diff --git a/mac_app/tests/test_shared_copies.py b/mac_app/tests/test_shared_copies.py
index 6fb648c..ec5e1ad 100644
--- a/mac_app/tests/test_shared_copies.py
+++ b/mac_app/tests/test_shared_copies.py
@@ -1,6 +1,7 @@
"""The files both apps share are kept byte-identical, not merely similar.
-`ignored.py`, `pairing.py`, `protocol.py`, `receiver.py`, `return_edge.py` and `wol.py` each exist once in mac_app
+`effects.py` and its `fx_*.py`, `ignored.py`, `pairing.py`, `protocol.py`, `receiver.py`, `return_edge.py`
+and `wol.py` each exist once in mac_app
and once in win_app because neither app can import across the other's
directory -- both are packaged as self-contained bundles. Everything
platform-shaped in them is injected at construction instead, so there is no
@@ -19,8 +20,11 @@ import unittest
_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))
-SHARED_MODULES = ("ignored.py", "pairing.py", "protocol.py", "receiver.py", "return_edge.py", "wol.py")
-SHARED_TESTS = ("test_ignored.py", "test_shared_copies.py")
+SHARED_MODULES = (
+ "effects.py", "fx_ink.py", "fx_instrument.py", "fx_membrane.py", "fx_sparks.py", "fx_warp.py",
+ "ignored.py", "pairing.py", "protocol.py", "receiver.py", "return_edge.py", "updates.py", "wol.py",
+)
+SHARED_TESTS = ("test_ignored.py", "test_shared_copies.py", "test_switch_arrival.py", "test_updates.py")
def _digest(path):
diff --git a/mac_app/tests/test_switch_arrival.py b/mac_app/tests/test_switch_arrival.py
new file mode 100644
index 0000000..532b99c
--- /dev/null
+++ b/mac_app/tests/test_switch_arrival.py
@@ -0,0 +1,189 @@
+"""What plays when input arrives by the shortcut, a menu or a switch rather than a crossing: the
+Player's switch arrival, the locator Glow and Beam get, and every effect's arrival away from an
+edge. Byte-identical in mac_app and win_app."""
+
+import math
+import unittest
+
+import effects
+
+SCREEN = (1728.0, 1117.0, "mac")
+MID = (700.0, 460.0)
+PALETTE = ["#ff7828", "#ff3264", "#ffb43c"]
+
+
+def frames(player, now, fx=None, reduced=False, dark=True):
+ return player.frames(now, fx or effects.LOCATOR, SCREEN, PALETTE, reduced, dark)
+
+
+def arrival_state(fx, since, reduced=False, dark=True, palette=PALETTE):
+ x, y = MID
+ edge = effects.nearest_edge(x, y, SCREEN[0], SCREEN[1])
+ return effects.state(SCREEN[0], SCREEN[1], "mac", "switch", palette, reduced=reduced, dark=dark,
+ point=effects.point(x, y), edge=edge, since=since)
+
+
+class PlayerSwitchTests(unittest.TestCase):
+ def test_a_switch_waits_for_the_settle_then_plays_at_the_pointer(self):
+ player = effects.Player()
+ player.switched(10.0, MID, "top")
+ self.assertEqual(frames(player, 10.0 + effects.SWITCH_SETTLE_S / 2), [])
+ self.assertTrue(player.busy)
+ pens = frames(player, 10.0 + effects.SWITCH_SETTLE_S + 0.1)
+ self.assertEqual(len(pens), 1)
+ left, top, right, bottom = pens[0].bounds
+ self.assertTrue(left < MID[0] < right and top < MID[1] < bottom)
+
+ def test_a_switch_plays_out_and_ends(self):
+ player = effects.Player()
+ player.switched(10.0, MID, "top")
+ self.assertEqual(frames(player, 10.0 + effects.SWITCH_SETTLE_S + 1.0), [])
+ self.assertFalse(player.busy)
+
+ def test_a_crossing_arriving_during_the_settle_is_the_one_that_plays(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append(s.method) or pen.fillRect(0, 0, 4, 4), 0.1, 0.5)
+ player = effects.Player()
+ player.switched(10.0, MID, "top")
+ player.arrive(10.05, "edge", (2.0, 300.0), "left")
+ for step in range(10):
+ frames(player, 10.05 + step * 0.05, fx)
+ self.assertEqual(set(seen), {"edge"})
+
+ def test_a_switch_just_after_a_crossing_arrival_gives_way_to_it(self):
+ player = effects.Player()
+ player.arrive(10.0, "edge", (2.0, 300.0), "left")
+ player.switched(10.0 + effects.SWITCH_SETTLE_S / 2, MID, "top")
+ self.assertFalse(player.arrival["switch"])
+ self.assertEqual(player.arrival["at"], (2.0, 300.0))
+
+ def test_a_crossing_drawn_elsewhere_still_cancels_a_waiting_switch(self):
+ # Glow and Beam draw a crossing themselves and never tell the Player about it.
+ player = effects.Player()
+ player.switched(10.0, MID, "top")
+ player.crossed_in(10.05)
+ self.assertEqual(frames(player, 10.0 + effects.SWITCH_SETTLE_S + 0.1), [])
+ self.assertFalse(player.busy)
+ player.switched(10.1, MID, "top")
+ self.assertIsNone(player.arrival)
+
+ def test_a_later_switch_replaces_an_old_crossing_arrival(self):
+ player = effects.Player()
+ player.arrive(10.0, "edge", (2.0, 300.0), "left")
+ player.switched(10.5, MID, "top")
+ self.assertTrue(player.arrival["switch"])
+ self.assertEqual(player.arrival["at"], MID)
+
+ def test_a_switch_is_not_told_about_the_notch(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append(getattr(s, "notch", None)), 0.1, 0.5)
+ player = effects.Player()
+ player.switched(10.0, (860.0, 40.0), "top")
+ notch = {"x": 771, "y": 0, "w": 185, "h": 32, "r": 10}
+ player.frames(10.0 + effects.SWITCH_SETTLE_S + 0.1, fx, SCREEN, PALETTE, False, True, notch)
+ self.assertEqual(seen, [None])
+
+
+class SwitchStyleTests(unittest.TestCase):
+ def test_same_as_crossing_follows_the_crossing_style(self):
+ self.assertIs(effects.switch_effect("match", "glow"), effects.LOCATOR)
+ self.assertIs(effects.switch_effect("match", "beam"), effects.LOCATOR)
+ self.assertEqual(effects.switch_effect("match", "rupture").id, "rupture")
+
+ def test_a_chosen_style_wins_over_the_crossing_style(self):
+ self.assertIs(effects.switch_effect("locator", "rupture"), effects.LOCATOR)
+ self.assertEqual(effects.switch_effect("discharge", "glow").id, "discharge")
+
+ def test_the_picker_offers_every_choice_once(self):
+ offered = [value for _title, items in effects.switch_style_groups() for value, _name in items]
+ self.assertEqual(sorted(offered), sorted(effects.SWITCH_STYLES))
+ self.assertEqual(offered[:2], ["match", "locator"])
+
+ def test_a_switch_plays_its_own_effect_beside_the_crossing_one(self):
+ seen = []
+ own = effects.Effect("own", "Own", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append("own") or pen.fillRect(0, 0, 4, 4), 0.1, 0.5)
+ crossing_fx = effects.Effect("crossing", "Crossing", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append("crossing"), 0.1, 0.5)
+ player = effects.Player()
+ player.switched(10.0, MID, "top", own)
+ frames(player, 10.0 + effects.SWITCH_SETTLE_S + 0.1, crossing_fx)
+ self.assertEqual(seen, ["own"])
+
+
+class SwitchPreviewTests(unittest.TestCase):
+ def test_the_loop_rests_then_plays_round_the_pointer(self):
+ for fx in (effects.LOCATOR, effects.effect("rupture")):
+ with self.subTest(fx=fx.id):
+ self.assertEqual(effects.preview_switch_scene(fx, 0.1, PALETTE)["pens"], [])
+ scene = effects.preview_switch_scene(fx, 0.55, PALETTE)
+ self.assertTrue(scene["pens"])
+ self.assertEqual(len(scene["screens"]), 1)
+ self.assertEqual(effects.preview_size("switch"), effects.PREVIEW_SCREEN)
+
+
+class NearestEdgeTests(unittest.TestCase):
+ def test_each_side(self):
+ self.assertEqual(effects.nearest_edge(10, 500, 1000, 1000), "left")
+ self.assertEqual(effects.nearest_edge(990, 500, 1000, 1000), "right")
+ self.assertEqual(effects.nearest_edge(500, 10, 1000, 1000), "top")
+ self.assertEqual(effects.nearest_edge(500, 990, 1000, 1000), "bottom")
+
+
+class LocatorTests(unittest.TestCase):
+ def _bounds(self, since, reduced):
+ pen = effects.draw(effects.LOCATOR, "arrive", arrival_state(effects.LOCATOR, since, reduced))
+ return None if pen is None else pen.bounds
+
+ def test_it_is_never_more_than_260pt_across(self):
+ for reduced in (False, True):
+ for step in range(0, 80):
+ box = self._bounds(step / 100.0, reduced)
+ if box is None:
+ continue
+ with self.subTest(since=step / 100.0, reduced=reduced):
+ # The Pen pads its bounds by the stroke and two points each side.
+ self.assertLessEqual(box[2] - box[0], 260.0 + 12.0)
+ self.assertLessEqual(box[3] - box[1], 260.0 + 12.0)
+
+ def test_it_closes_onto_the_pointer(self):
+ start, end = self._bounds(0.05, False), self._bounds(0.45, False)
+ self.assertGreater(start[2] - start[0], 3 * (end[2] - end[0]))
+ for box in (start, end):
+ self.assertAlmostEqual((box[0] + box[2]) / 2, MID[0], delta=1.0)
+ self.assertAlmostEqual((box[1] + box[3]) / 2, MID[1], delta=1.0)
+
+ def test_reduce_motion_holds_its_size(self):
+ early, late = self._bounds(0.15, True), self._bounds(0.4, True)
+ self.assertAlmostEqual(early[2] - early[0], late[2] - late[0], delta=0.5)
+
+ def test_it_is_over_within_0_8s(self):
+ self.assertLessEqual(effects.LOCATOR.arrive_seconds, 0.8)
+ self.assertIsNone(self._bounds(effects.LOCATOR.arrive_seconds + 0.06, False))
+
+ def test_one_colour_and_many_both_draw(self):
+ for palette in (["#5fd4f4"], PALETTE):
+ with self.subTest(palette=palette):
+ pen = effects.draw(effects.LOCATOR, "arrive", arrival_state(effects.LOCATOR, 0.2, palette=palette))
+ self.assertTrue(pen.ops)
+
+
+class EveryEffectAwayFromAnEdgeTests(unittest.TestCase):
+ def test_each_arrival_plays_round_the_pointer(self):
+ for effect_id in effects.EFFECT_IDS:
+ fx = effects.effect(effect_id)
+ for reduced in (False, True):
+ for dark in (True, False):
+ with self.subTest(effect=effect_id, reduced=reduced, dark=dark):
+ pen = effects.draw(fx, "arrive", arrival_state(fx, 0.12, reduced, dark))
+ self.assertIsNotNone(pen, "drew nothing")
+ left, top, right, bottom = pen.bounds
+ centre = ((left + right) / 2, (top + bottom) / 2)
+ # Centred on the pointer, not left at the nearest edge 460pt away.
+ self.assertLess(math.dist(centre, MID), 60.0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_update_config_redirecting.py b/mac_app/tests/test_update_config_redirecting.py
index 39b8280..7c66d19 100644
--- a/mac_app/tests/test_update_config_redirecting.py
+++ b/mac_app/tests/test_update_config_redirecting.py
@@ -5,9 +5,9 @@ from test_bridge import FakeClock, FakeQuartz, FakeSocket, crossing_config, quie
class UpdateConfigWhileRedirectingTests(unittest.TestCase):
- """mac-sender-1: update_config sets self.redirecting = False directly
- instead of going through set_redirecting(False), so it skips
- _set_cursor_follows_mouse(True) when settings are applied mid-redirect."""
+ """update_config sets self.redirecting = False directly instead of going
+ through set_redirecting(False), so it skips _set_cursor_follows_mouse(True)
+ when settings are applied mid-redirect."""
def setUp(self):
FakeQuartz.reset_cursor_spies()
diff --git a/mac_app/tests/test_updates.py b/mac_app/tests/test_updates.py
new file mode 100644
index 0000000..d41ddfb
--- /dev/null
+++ b/mac_app/tests/test_updates.py
@@ -0,0 +1,91 @@
+import json
+import os
+import sys
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import updates
+
+
+def release(tag, **extra):
+ return dict({"tag_name": tag, "html_url": f"https://github.com/kalkman-code/beamer/releases/tag/{tag}",
+ "draft": False, "prerelease": False}, **extra)
+
+
+class NewerReleaseTests(unittest.TestCase):
+ def test_a_patch_release_is_quiet_unless_its_notes_announce_it(self):
+ self.assertIsNone(updates.newer_release("1.4.0", release("v1.4.1", body="Small fixes.")))
+ self.assertIsNone(updates.newer_release("1.4.0", release("v1.4.1")))
+ self.assertIsNotNone(updates.newer_release("1.4.0", release("v1.4.1", body="Fixes a crash.\n<!-- announce -->")))
+
+ def test_a_quiet_patch_still_offers_the_minor_version_someone_is_behind(self):
+ self.assertIsNotNone(updates.newer_release("1.4.2", release("v1.5.1", body="Small fixes.")))
+ self.assertIsNotNone(updates.newer_release("1.9.0", release("v2.0.1")))
+
+ def test_a_newer_tag_is_offered_with_its_page(self):
+ self.assertEqual(updates.newer_release("1.3.3", release("v1.4.0")),
+ ("1.4.0", "https://github.com/kalkman-code/beamer/releases/tag/v1.4.0"))
+
+ def test_the_same_or_an_older_tag_is_not(self):
+ self.assertIsNone(updates.newer_release("1.4.0", release("v1.4.0")))
+ self.assertIsNone(updates.newer_release("1.4.0", release("v1.3.9")))
+
+ def test_versions_compare_as_numbers(self):
+ self.assertIsNotNone(updates.newer_release("1.9.0", release("v1.10.0")))
+ self.assertIsNone(updates.newer_release("1.4", release("v1.4.1")))
+
+ def test_drafts_prereleases_and_odd_tags_never_count(self):
+ self.assertIsNone(updates.newer_release("1.3.3", release("v2.0.0", prerelease=True)))
+ self.assertIsNone(updates.newer_release("1.3.3", release("v2.0.0", draft=True)))
+ self.assertIsNone(updates.newer_release("1.3.3", release("v2.0.0-beta")))
+ self.assertIsNone(updates.newer_release("1.3.3", {"message": "rate limited"}))
+ self.assertIsNone(updates.newer_release("1.3.3", ["not", "a", "dict"]))
+
+ def test_a_dev_build_is_never_told_to_update(self):
+ self.assertIsNone(updates.newer_release("dev", release("v9.0.0")))
+
+ def test_a_page_outside_the_project_is_replaced_by_the_releases_page(self):
+ found = updates.newer_release("1.3.3", release("v1.4.0", html_url="https://example.com/beamer.exe"))
+ self.assertEqual(found, ("1.4.0", updates.RELEASES_PAGE))
+
+
+class CheckerTests(unittest.TestCase):
+ def make(self, payload=None, enabled=True, error=None):
+ results = []
+
+ def fetcher():
+ if error:
+ raise error
+ return json.dumps(payload).encode("utf-8")
+
+ checker = updates.Checker("1.3.3", lambda: enabled, results.append, fetcher=fetcher,
+ logger=updates.logging.getLogger("test-updates"))
+ return checker, results
+
+ def test_reports_a_newer_release(self):
+ checker, results = self.make(release("v1.4.0"))
+ checker.check_once()
+ self.assertEqual(results, [("1.4.0", "https://github.com/kalkman-code/beamer/releases/tag/v1.4.0")])
+
+ def test_reports_none_when_current(self):
+ checker, results = self.make(release("v1.3.3"))
+ checker.check_once()
+ self.assertEqual(results, [None])
+
+ def test_switched_off_it_asks_nothing(self):
+ checker, results = self.make(error=AssertionError("fetched while switched off"), enabled=False)
+ checker.check_once()
+ self.assertEqual(results, [])
+
+ def test_a_failed_check_keeps_the_last_answer(self):
+ checker, results = self.make(release("v1.4.0"))
+ checker.check_once()
+ checker.fetcher = lambda: (_ for _ in ()).throw(OSError("offline"))
+ checker.check_once()
+ self.assertEqual(checker.latest[0], "1.4.0")
+ self.assertEqual(len(results), 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_wake.py b/mac_app/tests/test_wake.py
index 99425fb..cc1b2c3 100644
--- a/mac_app/tests/test_wake.py
+++ b/mac_app/tests/test_wake.py
@@ -1,5 +1,6 @@
import logging
import threading
+import types
import unittest
import config
@@ -11,7 +12,7 @@ from wake import NOT_WOKEN_STATUS, WAKING_STATUS, WakingController, mac_from_arp
WINDOWS_ARP = """
Interface: 192.168.1.5 --- 0x10
Internet Address Physical Address Type
- 192.168.1.1 a8-5e-45-1c-22-f0 dynamic
+ 192.168.1.1 02-00-00-00-00-01 dynamic
192.168.1.3 02-1a-2b-3c-0d-4e dynamic
192.168.1.30 00-11-22-33-44-55 dynamic
224.0.0.22 01-00-5e-00-00-16 static
@@ -169,5 +170,55 @@ class WakingControllerTests(unittest.TestCase):
self.assertFalse(self.controller.can_wake)
+class ComingHomeThroughTheAppsControllerTests(unittest.TestCase):
+ """The app runs WakingController, so every way home the base class takes must pass through it."""
+
+ def make(self):
+ def refuse(address, timeout):
+ raise OSError("unreachable")
+
+ controller = WakingController(make_config(), logger=quiet_logger(), quartz=FakeQuartz, clock=FakeClock(),
+ socket_factory=refuse)
+ controller.redirecting = True
+ return controller
+
+ def test_the_pc_sending_input_home_returns_it(self):
+ controller = self.make()
+ controller._handle_switch({"target": "mac"})
+ self.assertFalse(controller.redirecting)
+
+ def test_the_pc_taking_this_mac_over_ends_the_redirect(self):
+ controller = self.make()
+ controller.set_receiving(True)
+ self.assertFalse(controller.redirecting)
+ self.assertTrue(controller.receiving)
+
+
+class FollowingAMovedPcThroughTheAppsControllerTests(unittest.TestCase):
+ def test_the_app_controller_takes_the_new_address(self):
+ from test_bridge import FakeSocket, seed_receiver_reply
+ import protocol
+
+ sock = FakeSocket()
+ seed_receiver_reply(sock, protocol.welcome_msg())
+
+ def socket_factory(address, timeout):
+ if address[0] == "192.0.2.10":
+ raise ConnectionRefusedError("gone")
+ return sock
+
+ cfg = make_config()
+ cfg.pc_name = "STUDIO-PC"
+ controller = WakingController(cfg, logger=quiet_logger(), quartz=FakeQuartz, clock=FakeClock(),
+ socket_factory=socket_factory, mac_lookup=lambda host: None)
+ controller.discovery = types.SimpleNamespace(pcs=lambda: [
+ {"name": "STUDIO-PC", "address": "192.0.2.77", "port": cfg.port, "reply_port": 24821, "pair_id": None}])
+ learned = []
+ controller.on_host_learned = learned.append
+ self.assertFalse(controller._connect_once())
+ controller._follow_the_pc()
+ self.assertEqual(learned, ["192.0.2.77"])
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/mac_app/tests/test_way_home.py b/mac_app/tests/test_way_home.py
new file mode 100644
index 0000000..2606743
--- /dev/null
+++ b/mac_app/tests/test_way_home.py
@@ -0,0 +1,81 @@
+import os
+import sys
+import threading
+import unittest
+from types import SimpleNamespace
+from unittest import mock
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import return_edge
+from windows_input import WindowsInput
+
+
+def model(methods, parts=("middle",), corner="top_right", edge="right", notch_range=(656.0, 856.0)):
+ crossing = {"methods": list(methods), "edge_parts": list(parts), "corner": corner}
+ owner = SimpleNamespace(_controller=SimpleNamespace(cfg=SimpleNamespace(crossing=crossing), notch_range=notch_range))
+ return WindowsInput._return_model(owner, edge, 120)
+
+
+def crosses_at(armed, x):
+ """Whether a hard push up at `x` along the top of a 1512x982 display goes home."""
+ display = [return_edge.Rect(0, 0, 1512, 982)]
+ return any(armed.feed(display, (x, 0), 0, -40).action == return_edge.CROSS for _ in range(20))
+
+
+class WayHomeFollowsThisMacTests(unittest.TestCase):
+ """The PC's pointer comes home through this Mac's edge as this Mac's own settings say."""
+
+ def test_part_of_the_edge_arms_only_its_thirds(self):
+ armed = model(["part", "shortcut"], parts=("start",))
+ self.assertIsInstance(armed, return_edge.PartEdge)
+ self.assertEqual(armed.parts, frozenset({"start"}))
+
+ def test_the_whole_edge(self):
+ self.assertEqual(type(model(["edge"])), return_edge.ReturnEdge)
+
+ def test_the_notch_arms_only_the_notch(self):
+ # Toby, 28-09-2026: with only the notch and the shortcut on, the PC's pointer went home
+ # anywhere along the Mac's top edge.
+ self.assertTrue(crosses_at(model(["notch", "shortcut"], edge="top"), 756))
+ self.assertFalse(crosses_at(model(["notch", "shortcut"], edge="top"), 200))
+ self.assertFalse(crosses_at(model(["notch", "shortcut"], edge="top"), 1300))
+ self.assertIsNone(model(["notch", "shortcut"], edge="right"))
+
+ def test_the_notch_is_read_at_each_push(self):
+ # A focus that arrives before the first measurement, or across a display change, must not
+ # leave the pointer without its way home for the rest of the session.
+ controller = SimpleNamespace(cfg=SimpleNamespace(crossing={"methods": ["notch", "shortcut"]}), notch_range=None)
+ armed = WindowsInput._return_model(SimpleNamespace(_controller=controller), "top", 120)
+ self.assertFalse(crosses_at(armed, 756))
+ controller.notch_range = (656.0, 856.0)
+ self.assertTrue(crosses_at(armed, 756))
+
+ def test_the_whole_edge_still_wins_over_the_notch(self):
+ self.assertTrue(crosses_at(model(["edge", "notch"], edge="top"), 200))
+
+ def test_a_corner_on_that_edge(self):
+ self.assertIsInstance(model(["corner"], corner="top_right"), return_edge.CornerPush)
+ self.assertIsNone(model(["corner"], corner="top_left"))
+
+ def test_the_shortcut_alone_leaves_no_way_home_by_the_pointer(self):
+ self.assertIsNone(model(["shortcut"]))
+
+
+class CrossingChangesReachTheWayHomeTests(unittest.TestCase):
+ def test_a_change_to_the_ways_in_rebuilds_the_way_home_once(self):
+ # Toby, 28-09-2026: a change to Part of the edge applied only after crossing out and back.
+ owner = SimpleNamespace(server=mock.Mock(input_scale=None), _ways=None, _running_for=None, _lock=threading.RLock())
+ crossing = {"methods": ["part"], "edge_parts": ["start"], "corner": "top_right"}
+ cfg = SimpleNamespace(pointer_speed=1.0, scroll_speed=1.0, reverse_scroll=False,
+ allow_windows_to_drive=False, crossing=crossing)
+ WindowsInput.sync(owner, cfg)
+ WindowsInput.sync(owner, cfg)
+ self.assertEqual(owner.server.rearm_return.call_count, 1)
+ crossing["edge_parts"] = ["end"]
+ WindowsInput.sync(owner, cfg)
+ self.assertEqual(owner.server.rearm_return.call_count, 2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/two_machines.py b/mac_app/tests/two_machines.py
new file mode 100644
index 0000000..82cd4e8
--- /dev/null
+++ b/mac_app/tests/two_machines.py
@@ -0,0 +1,204 @@
+"""Both apps' real link code against each other over loopback, for the crossing matrix.
+
+The Mac is a real KVMController, driven through its event-tap callback with FakeQuartz; the PC is a
+real MacSender, driven through its hook entry points. Each machine also runs the shared
+ReceiverServer that the other one's link connects to, as it does in the apps. Only the platform
+edges are faked: the pointer, the injector, the clipboard and the display geometry.
+
+win_app's modules are put on the path after this app's, so the names both apps share resolve to the
+byte-identical copies and the PC's own (`sender`, `app_config`) resolve to the PC's.
+"""
+
+import os
+import socket
+import sys
+import time
+
+_APP = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+_WIN = os.path.join(os.path.dirname(_APP), "win_app")
+for _path in (_WIN, os.path.join(_WIN, "tests")):
+ if _path not in sys.path:
+ sys.path.append(_path)
+
+import protocol
+import receiver
+from return_edge import Rect
+
+import app_config
+import sender as pc_sender_module
+from bridge import KVMController
+from fakes import FakeClipboard, FakeDesktop, FakeInjector
+from test_bridge import FakeClock, FakeQuartz, crossing_config, quiet_logger
+
+TOKEN = "matrix-token"
+MAC_BOUNDS = (0, 0, 1728, 1117)
+PC_MONITORS = [Rect(0, 0, 1920, 1080)]
+
+
+class NoUnlock:
+ def is_locked(self):
+ return None
+
+
+def free_port():
+ with socket.socket() as probe:
+ probe.bind(("127.0.0.1", 0))
+ return probe.getsockname()[1]
+
+
+def wait_for(predicate, timeout=5.0):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if predicate():
+ return True
+ time.sleep(0.01)
+ return False
+
+
+class Duo:
+ """`crossing` is the Mac's crossing settings, `pc` the PC's Config fields. The two links are
+ started separately: `link_mac_to_pc()` is the Mac's own link to the PC, `link_pc_to_mac()` is
+ the PC's link to the Mac, and each can be left down."""
+
+ def __init__(self, crossing=None, pc=None, mac_cfg=None, pc_monitors=None, mac_bounds=MAC_BOUNDS):
+ FakeQuartz.reset_cursor_spies()
+ self.clock = FakeClock()
+ self.feedback = []
+ self.mac_bounds = mac_bounds
+ self.mac_port = free_port()
+ self.pc_port = free_port()
+ while self.pc_port == self.mac_port:
+ self.pc_port = free_port()
+
+ self.mac_desktop = FakeDesktop([Rect(*self._rect(mac_bounds))], cursor=(800, 500))
+ self.pc_desktop = FakeDesktop(pc_monitors or PC_MONITORS, cursor=(900, 500))
+ self.mac_injector = FakeInjector()
+ self.pc_injector = FakeInjector()
+ self.mac_peer = []
+ self.pc_peer = []
+ self.mac_arrangements = []
+ self.pc_arrangements = []
+
+ cfg = mac_cfg or crossing_config(**(crossing or {}))
+ cfg.host, cfg.port, cfg.auth_token = "127.0.0.1", self.pc_port, TOKEN
+ cfg.reconnect_interval_s = 0.05
+ self.mac = KVMController(
+ cfg, logger=quiet_logger(), quartz=FakeQuartz, clock=self.clock, desktop_bounds=lambda: self.mac_bounds
+ )
+ self.mac.on_crossing = lambda kind, step: self.feedback.append((kind, step))
+ self.mac.on_user_alert = lambda title, message: None
+ self.mac_arrivals = []
+
+ pc_fields = dict(
+ host="127.0.0.1",
+ port=self.mac_port,
+ auth_token=TOKEN,
+ mac_host="127.0.0.1",
+ mac_return_edge="left",
+ crossing_resistance_px=40,
+ mac_resistance_px=40,
+ )
+ pc_fields.update(pc or {})
+ self.pc_config = app_config.Config(**pc_fields)
+ self.pc = pc_sender_module.MacSender(
+ desktop=self.pc_desktop, clipboard=FakeClipboard(), is_local=lambda host: False
+ )
+ self.pc_arrivals = []
+ self.pc._arrival_callback = lambda edge, x, y: self.pc_arrivals.append((edge, x, y))
+ self.pc._arrangement_callback = lambda edge, set_at: self.pc_arrangements.append((edge, set_at))
+ self.mac.on_arrangement = lambda edge, set_at: self.mac_arrangements.append((edge, set_at))
+ self.pc_pressure = []
+ self.pc._pressure_callback = lambda edge, pressure, crossed, part: self.pc_pressure.append((edge, crossed))
+
+ # The PC's receiver: what the Mac's link connects to.
+ self.pc_server = receiver.ReceiverServer(
+ status_callback=lambda state, detail: None,
+ clipboard=FakeClipboard(),
+ unlock=NoUnlock(),
+ desktop=self.pc_desktop,
+ injector=self.pc_injector,
+ focus_callback=lambda target: self.pc.set_receiving(target == "windows"),
+ peer_callback=lambda *args: self.pc_peer.append(args),
+ arrangement_callback=lambda edge, set_at: self.pc_arrangements.append((edge, set_at)),
+ )
+ self.pc.send_peer_home = self.pc_server.send_home
+ # The Mac's receiver: what the PC's link connects to.
+ self.mac_server = receiver.ReceiverServer(
+ status_callback=lambda state, detail: None,
+ clipboard=FakeClipboard(),
+ unlock=NoUnlock(),
+ desktop=self.mac_desktop,
+ injector=self.mac_injector,
+ focus_callback=lambda target: self.mac.set_receiving(target == "mac"),
+ peer_callback=lambda *args: self.mac_peer.append(args),
+ arrangement_callback=lambda edge, set_at: self.mac_arrangements.append((edge, set_at)),
+ arrival_callback=lambda edge, x, y: self.mac_arrivals.append((edge, x, y)),
+ self_name="Mac",
+ peer_name="PC",
+ self_target="mac",
+ peer_target="windows",
+ )
+ self.mac.send_peer_home = self.mac_server.send_home
+ self._started = False
+
+ @staticmethod
+ def _rect(bounds):
+ left, top, right, bottom = bounds
+ return left, top, right - left, bottom - top
+
+ # -- links ---------------------------------------------------------------
+
+ def listen(self):
+ """Both receivers, as they run whenever the app is open."""
+ self.pc_server.start(app_config.Config(host="127.0.0.1", port=self.pc_port, auth_token=TOKEN))
+ from config import Config as MacConfig
+
+ self.mac_server.start(MacConfig(host="127.0.0.1", port=self.mac_port, auth_token=TOKEN))
+ return self
+
+ def link_mac_to_pc(self):
+ """The Mac's own link to the PC, up before this returns."""
+ if not self._started:
+ self.mac.start()
+ self._started = True
+ assert wait_for(lambda: self.mac.connected), f"the Mac never connected: {self.mac.connection_status}"
+ return self
+
+ def link_pc_to_mac(self):
+ self.pc.start(self.pc_config)
+ assert wait_for(lambda: self.pc.connected), f"the PC never connected: {self.pc.status}"
+ return self
+
+ def close(self):
+ self.pc.stop()
+ self.mac.stop()
+ self.pc_server.stop()
+ self.mac_server.stop()
+
+ # -- the Mac's pointer ----------------------------------------------------
+
+ def mac_move(self, x, y, dx, dy=0, event_type=FakeQuartz.kCGEventMouseMoved):
+ event = {
+ "location": (x, y),
+ FakeQuartz.kCGMouseEventDeltaX: dx,
+ FakeQuartz.kCGMouseEventDeltaY: dy,
+ }
+ self.clock.value += 0.01
+ return self.mac._event_tap_callback(None, event_type, event, None)
+
+ def mac_push(self, x, y, dx, dy=0, times=12, until=lambda self: self.mac.redirecting):
+ for _ in range(times):
+ self.mac_move(x, y, dx, dy)
+ if until(self):
+ return True
+ return False
+
+ # -- the PC's pointer ----------------------------------------------------
+
+ def pc_push(self, x, y, dx, dy=0, times=12, until=lambda self: self.pc.redirecting):
+ self.pc_desktop.cursor = (x, y)
+ for _ in range(times):
+ self.pc.on_motion(dx, dy)
+ if until(self):
+ return True
+ return False
diff --git a/mac_app/updates.py b/mac_app/updates.py
new file mode 100644
index 0000000..21bfc57
--- /dev/null
+++ b/mac_app/updates.py
@@ -0,0 +1,134 @@
+"""Whether a newer Beamer has been released, shared by mac_app and win_app (two identical copies;
+test_shared_copies checks they match).
+
+One HTTPS request to GitHub's public releases API when the app starts and once a day after, sending
+nothing but the request itself, and only while the `check_updates` setting is on. A newer release
+is shown quietly in the window and the menu; nothing downloads or installs, and nothing pops up.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+import sys
+import threading
+
+LATEST_URL = "https://api.github.com/repos/kalkman-code/beamer/releases/latest"
+RELEASES_PAGE = "https://github.com/kalkman-code/beamer/releases/latest"
+CHECK_EVERY_SECONDS = 24 * 60 * 60
+TIMEOUT_SECONDS = 10.0
+MAX_BYTES = 256 * 1024
+
+LOGGER = logging.getLogger(__name__)
+_VERSION = re.compile(r"^v?(\d+)\.(\d+)(?:\.(\d+))?$")
+
+
+def parse_version(text):
+ """(major, minor, patch) for "1.4", "1.4.0" or "v1.4.0", else None: a local "dev" build or a
+ tag in any other shape never reads as older or newer than anything."""
+ match = _VERSION.match(str(text or "").strip())
+ if not match:
+ return None
+ return tuple(int(part or 0) for part in match.groups())
+
+
+# In a release's notes, where GitHub renders nothing, it offers a patch release as an update too.
+ANNOUNCE = "<!-- announce -->"
+
+
+def newer_release(current, payload):
+ """(version text, page url) when `payload`, the API's JSON, names a release worth offering over
+ `current`, else None. A new minor or major version always is; a patch release (1.4.0 to 1.4.1)
+ only when its notes carry ANNOUNCE, so frequent small releases do not nag. Drafts and
+ prereleases never count."""
+ if not isinstance(payload, dict) or payload.get("draft") or payload.get("prerelease"):
+ return None
+ tag = payload.get("tag_name")
+ theirs, ours = parse_version(tag), parse_version(current)
+ if theirs is None or ours is None or theirs <= ours:
+ return None
+ body = payload.get("body")
+ if theirs[:2] == ours[:2] and not (isinstance(body, str) and ANNOUNCE in body):
+ return None
+ url = payload.get("html_url")
+ if not isinstance(url, str) or not url.startswith("https://github.com/kalkman-code/beamer/"):
+ url = RELEASES_PAGE
+ return (str(tag).lstrip("v"), url)
+
+
+def fetch(url=LATEST_URL):
+ """The response body as bytes. The Mac goes through Foundation, which trusts the system's
+ certificates; a bundled Python has no certificate store of its own there."""
+ if sys.platform == "darwin":
+ import Foundation
+
+ request = Foundation.NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_(
+ Foundation.NSURL.URLWithString_(url), Foundation.NSURLRequestReloadIgnoringLocalCacheData, TIMEOUT_SECONDS)
+ request.setValue_forHTTPHeaderField_("application/vnd.github+json", "Accept")
+ data, response, error = Foundation.NSURLConnection.sendSynchronousRequest_returningResponse_error_(
+ request, None, None)
+ if data is None or error is not None or response is None or response.statusCode() != 200:
+ raise OSError(f"update check failed: {error or (response.statusCode() if response else 'no response')}")
+ return bytes(data)[:MAX_BYTES]
+ import urllib.request
+
+ request = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json"})
+ with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
+ return response.read(MAX_BYTES)
+
+
+class Checker:
+ """Checks now and every CHECK_EVERY_SECONDS on its own thread while `enabled()` says so, and
+ calls `on_result((version, url) or None)` on that thread after each check that got an answer;
+ the owner marshals it. A failed check keeps the last answer and logs once."""
+
+ def __init__(self, current, enabled, on_result, fetcher=fetch, logger=None):
+ self.current = current
+ self.enabled = enabled
+ self.on_result = on_result
+ self.fetcher = fetcher
+ self.logger = logger or LOGGER
+ self.latest = None
+ self._wake = threading.Event()
+ self._stop = threading.Event()
+ self._thread = None
+ self._failed = False
+
+ def start(self):
+ if self._thread is None:
+ self._thread = threading.Thread(target=self._run, name="Beamer-updates", daemon=True)
+ self._thread.start()
+
+ def check_now(self):
+ """After the setting is switched on, rather than waiting a day."""
+ self._wake.set()
+
+ def stop(self):
+ self._stop.set()
+ self._wake.set()
+
+ def check_once(self):
+ if parse_version(self.current) is None or not self.enabled():
+ return
+ try:
+ payload = json.loads(self.fetcher().decode("utf-8"))
+ except Exception as exc:
+ if not self._failed:
+ self.logger.info("could not check for a newer Beamer: %s", exc)
+ self._failed = True
+ return
+ self._failed = False
+ self.latest = newer_release(self.current, payload)
+ if self.latest:
+ self.logger.info("Beamer %s is available", self.latest[0])
+ try:
+ self.on_result(self.latest)
+ except Exception:
+ self.logger.exception("update result callback failed")
+
+ def _run(self):
+ while not self._stop.is_set():
+ self.check_once()
+ self._wake.wait(CHECK_EVERY_SECONDS)
+ self._wake.clear()
diff --git a/mac_app/wake.py b/mac_app/wake.py
index 5d17aaf..770d693 100644
--- a/mac_app/wake.py
+++ b/mac_app/wake.py
@@ -54,11 +54,11 @@ class WakingController(KVMController):
def can_wake(self) -> bool:
return bool(self.cfg.mac_address) and not self.connected
- def set_redirecting(self, value, edge=None, offset=None):
+ def set_redirecting(self, value, edge=None, offset=None, came_home=True):
if value and not self.redirecting and not self.connected and self.cfg.mac_address and not self._refused():
self.wake()
return False
- return super().set_redirecting(value, edge, offset)
+ return super().set_redirecting(value, edge, offset, came_home=came_home)
def _refused(self) -> bool:
"""A PC that answered and refused -- the token, or the protocol version -- is awake, and
@@ -100,15 +100,15 @@ class WakingController(KVMController):
self.logger.warning("Windows did not answer within %.0fs of the wake-on-LAN packet", WAKE_WINDOW_SECONDS)
self._alert("Beamer", NOT_WOKEN_STATUS)
- def _connect_once(self):
- connected = super()._connect_once()
+ def _connect_once(self, host=None):
+ connected = super()._connect_once(host=host)
if connected:
- self._learn_mac()
+ self._learn_mac(host or self.cfg.host)
return connected
- def _learn_mac(self):
+ def _learn_mac(self, host):
try:
- mac = self.mac_lookup(self.cfg.host)
+ mac = self.mac_lookup(host)
except Exception:
self.logger.exception("hardware address lookup failed")
return
diff --git a/mac_app/widgets.py b/mac_app/widgets.py
index 54980d4..38dac0e 100644
--- a/mac_app/widgets.py
+++ b/mac_app/widgets.py
@@ -15,9 +15,10 @@ import Quartz
import objc
import media_keys
+import motion
import theme
from ignored_titles import is_modifier_release, recorded_entry
-from key_codes import KEY_NAME_TO_CODE, SPECIAL_KEY_NAMES, key_title
+from key_codes import KEY_NAME_TO_CODE, SPECIAL_KEY_NAMES, key_cap, key_title
def _autolayout(view):
@@ -86,8 +87,7 @@ def box(fill=None, stroke=None, radius=0.0, cls=None):
def paint(view, fill=None, stroke=None, radius=None):
layer = view.layer()
- layer.setBackgroundColor_(theme.colour(fill).CGColor() if fill else None)
- layer.setBorderColor_(theme.colour(stroke).CGColor() if stroke else None)
+ theme.tint(layer, background=fill, border=stroke)
layer.setBorderWidth_(1 if stroke else 0)
if radius is not None:
layer.setCornerRadius_(radius)
@@ -313,7 +313,14 @@ class Readout:
class LED:
def __init__(self, diameter=8.0):
- self.view = size(box(radius=diameter / 2), diameter, diameter)
+ self.view = size(box(), diameter, diameter)
+ self.view.layer().setMasksToBounds_(False)
+ # The lamp is a sublayer, not the view's own layer: AppKit clears a backing layer's shadow
+ # when the window's appearance changes, which would put the glow out on a palette switch.
+ self.lamp = Quartz.CALayer.layer()
+ self.lamp.setFrame_(((0, 0), (diameter, diameter)))
+ self.lamp.setCornerRadius_(diameter / 2)
+ self.view.layer().addSublayer_(self.lamp)
self.tone = None
self.blink = False
self.set("off")
@@ -322,11 +329,9 @@ class LED:
if (tone, blink) == (self.tone, self.blink):
return
self.tone, self.blink = tone, blink
- layer = self.view.layer()
- layer.setBackgroundColor_(theme.colour(tone).CGColor())
+ layer = self.lamp
+ theme.tint(layer, background=tone, shadow="signal")
glow = tone == "signal"
- layer.setMasksToBounds_(False)
- layer.setShadowColor_(theme.colour("signal").CGColor())
layer.setShadowOffset_((0, 0))
layer.setShadowRadius_(4 if glow else 0)
layer.setShadowOpacity_(0.55 if glow else 0)
@@ -372,6 +377,9 @@ class Pressable(AppKit.NSView):
def isAccessibilityElement(self):
return True
+ def isAccessibilityEnabled(self):
+ return bool(getattr(self, "enabled", True))
+
@objc.python_method
def press(self):
if getattr(self, "enabled", True) and getattr(self, "callback", None) is not None:
@@ -391,6 +399,9 @@ class Pressable(AppKit.NSView):
if ring is not None:
inset = getattr(self, "ring_inset", -3.0)
ring.setFrame_(AppKit.NSInsetRect(self.bounds(), inset, inset))
+ owner = getattr(self, "ring_owner", None)
+ if owner is not None:
+ owner.follow(self)
def resetCursorRects(self):
# A pointing hand is for the one Pressable that opens something outside the app (the
@@ -403,7 +414,7 @@ class Pressable(AppKit.NSView):
if getattr(self, "ring", None) is None:
self.setWantsLayer_(True)
ring = Quartz.CALayer.layer()
- ring.setBorderColor_(theme.colour("signal").CGColor())
+ theme.tint(ring, border="signal")
ring.setBorderWidth_(2)
ring.setCornerRadius_(self.layer().cornerRadius() + 2)
self.layer().addSublayer_(ring)
@@ -494,10 +505,30 @@ class _Target(AppKit.NSObject):
self.callback(sender)
-def field(secure=False, mono=True):
+class _CentredCell(AppKit.NSTextFieldCell):
+ """Text centred in the cell's height, at rest and while typed into, since the field editor lays
+ itself out in drawingRectForBounds too."""
+
+ def drawingRectForBounds_(self, bounds):
+ rect = objc.super(_CentredCell, self).drawingRectForBounds_(bounds)
+ height = self.cellSizeForBounds_(rect).height
+ if height >= rect.size.height:
+ return rect
+ return AppKit.NSMakeRect(rect.origin.x, rect.origin.y + (rect.size.height - height) / 2,
+ rect.size.width, height)
+
+
+class _CentredField(AppKit.NSTextField):
+ @classmethod
+ def cellClass(cls):
+ return _CentredCell
+
+
+def field(secure=False, mono=True, cls=None):
"""A text input on `ground` with an `edge` border and the text inset off it. Returns
(container, control): add the container, read the control."""
- control = _autolayout((AppKit.NSSecureTextField if secure else AppKit.NSTextField).alloc().init())
+ cls = cls or (AppKit.NSSecureTextField if secure else AppKit.NSTextField)
+ control = _autolayout(cls.alloc().init())
control.setBordered_(False)
control.setDrawsBackground_(False)
control.setFocusRingType_(AppKit.NSFocusRingTypeNone)
@@ -513,13 +544,17 @@ def field(secure=False, mono=True):
def field_row(caption, control):
- """Caption on the left in a fixed column, control filling the rest. Returns (row, caption)."""
+ """Caption on the left in a fixed column, control filling the rest. Returns (row, caption).
+ The caption is also the control's name to VoiceOver, which otherwise reads a group of choices
+ or a field with nothing to say what it sets."""
line = stack(vertical=False, spacing=10)
words = Label(caption, theme.TYPE["note"], ink="ink_2", wrap=True)
size(words.view, width=116)
line.addArrangedSubview_(words.view)
line.addArrangedSubview_(control)
hug(control, AppKit.NSLayoutPriorityDefaultLow)
+ if not control.accessibilityLabel():
+ control.setAccessibilityLabel_(caption)
return line, words
@@ -563,6 +598,8 @@ class WayTile:
self.tick = size(_autolayout(_Tick.alloc().init()), 15, 15)
self.name = Label(title, theme.TYPE["body"], 600)
self.detail = Label(detail, theme.TYPE["small"], ink="ink_3", wrap=True)
+ # No detail takes no line, so a tile that is only a name stays one line tall.
+ self.detail.view.setHidden_(not detail)
words = stack(spacing=2)
add(words, self.name.view)
add(words, self.detail.view)
@@ -593,6 +630,7 @@ class WayTile:
def set_detail(self, text):
self.detail.set(text)
+ self.detail.view.setHidden_(not text)
def _toggle(self):
self.value = not self._value
@@ -601,6 +639,8 @@ class WayTile:
class _Track(AppKit.NSView):
+ """The switch's track, drawn; the knob is its own layer so it can slide across."""
+
def isFlipped(self):
return True
@@ -611,9 +651,21 @@ class _Track(AppKit.NSView):
track.fill()
theme.colour("signal" if on else "edge").setStroke()
track.stroke()
- knob = AppKit.NSBezierPath.bezierPathWithOvalInRect_(((18 if on else 3, 3), (12, 12)))
- theme.colour("signal" if on else "ink_3").setFill()
- knob.fill()
+
+ @objc.python_method
+ def place_knob(self, on, animate):
+ knob = getattr(self, "knob", None)
+ if knob is None:
+ self.setWantsLayer_(True)
+ knob = Quartz.CALayer.layer()
+ knob.setCornerRadius_(6)
+ self.layer().addSublayer_(knob)
+ self.knob = knob
+ motion.transaction(animate, motion.DURATION * 0.75)
+ # Layer frames here are in the view's own flipped space, top left at the origin.
+ knob.setFrame_(((18 if on else 3, 3), (12, 12)))
+ theme.tint(knob, background="signal" if on else "ink_3")
+ Quartz.CATransaction.commit()
class Switch:
@@ -622,14 +674,16 @@ class Switch:
def __init__(self, title, on_change=None):
self.on_change = on_change
self._value = False
+ self.enabled = True
self.view = pressable(self._toggle, role=AppKit.NSAccessibilityCheckBoxRole)
self.view.setAccessibilityLabel_(title)
self.track = size(_autolayout(_Track.alloc().init()), 34, 18)
- words = Label(title, theme.TYPE["body"], wrap=True)
+ self.track.place_knob(False, False)
+ self.words = Label(title, theme.TYPE["body"], wrap=True)
line = stack(vertical=False, spacing=12)
- line.addArrangedSubview_(words.view)
+ line.addArrangedSubview_(self.words.view)
line.addArrangedSubview_(self.track)
- hug(words.view, AppKit.NSLayoutPriorityDefaultLow)
+ hug(self.words.view, AppKit.NSLayoutPriorityDefaultLow)
self.view.addSubview_(line)
pin(line, self.view, (3, 0, 3, 0))
@@ -639,12 +693,24 @@ class Switch:
@value.setter
def value(self, value):
- self._value = bool(value)
- self.track.on = self._value
+ value = bool(value)
+ changed = value != self._value
+ self._value = value
+ self.track.on = value
self.track.setNeedsDisplay_(True)
- self.view.setAccessibilityValue_(1 if self._value else 0)
+ self.track.place_knob(value, changed and motion.live(self.view))
+ self.view.setAccessibilityValue_(1 if value else 0)
+
+ def set_enabled(self, enabled):
+ self.enabled = enabled
+ # Off the tab order too, not only faded: a dimmed switch that still takes Space reads as
+ # broken.
+ self.view.enabled = enabled
+ self.view.setAlphaValue_(1.0 if enabled else 0.45)
def _toggle(self):
+ if not self.enabled:
+ return
self.value = not self._value
if self.on_change is not None:
self.on_change(self._value)
@@ -662,6 +728,9 @@ class Segmented:
columns = columns or len(self.choices)
self.view = box("edge", "edge", theme.RADIUS["segment"])
self.view.layer().setMasksToBounds_(True)
+ # One group to VoiceOver, named by its field_row caption, with the choices inside it.
+ self.view.setAccessibilityElement_(True)
+ self.view.setAccessibilityRole_(AppKit.NSAccessibilityRadioGroupRole)
grid = stack(spacing=1)
grid.setDistribution_(AppKit.NSStackViewDistributionFillEqually)
self.cells = []
@@ -676,6 +745,7 @@ class Segmented:
squeeze(words.view)
cell.addSubview_(words.view)
pin(words.view, cell, (6, 4, 6, 4))
+ cell.heightAnchor().constraintGreaterThanOrEqualToConstant_(28).setActive_(True)
row.addArrangedSubview_(cell)
self.cells.append((value, cell, words))
add(grid, row)
@@ -689,14 +759,18 @@ class Segmented:
@value.setter
def value(self, value):
self._value = value
- for candidate, cell, words in self.cells:
- chosen = candidate == value
- # Disabled, the choice stays marked by weight but loses the ink fill, which would
- # otherwise still read as live through the fade.
- lit = chosen and self.enabled
- paint(cell, "ink" if lit else "well")
- words.set(ink="ground" if lit else "ink_2", weight=600 if chosen else 400)
- cell.setAccessibilityValue_(1 if chosen else 0)
+
+ def mark():
+ for candidate, cell, words in self.cells:
+ chosen = candidate == value
+ # Disabled, the choice stays marked by weight but loses the ink fill, which would
+ # otherwise still read as live through the fade.
+ lit = chosen and self.enabled
+ paint(cell, "ink" if lit else "well")
+ words.set(ink="ground" if lit else "ink_2", weight=600 if chosen else 400)
+ cell.setAccessibilityValue_(1 if chosen else 0)
+
+ motion.fade_paint(self.view, mark)
def set_enabled(self, enabled):
self.enabled = enabled
@@ -863,14 +937,20 @@ class _RulerView(_Flipped):
if direction is None or not self.owner.enabled:
objc.super(_RulerView, self).keyDown_(event)
return
- self.owner.nudge(direction)
+ self.owner.nudge(direction, fine=bool(event.modifierFlags() & AppKit.NSEventModifierFlagOption))
def isAccessibilityElement(self):
return True
+ def isAccessibilityEnabled(self):
+ return bool(self.owner.enabled)
+
def accessibilityRole(self):
return AppKit.NSAccessibilitySliderRole
+ def accessibilityLabel(self):
+ return self.owner.title
+
def accessibilityValue(self):
return self.owner.value
@@ -913,9 +993,13 @@ class Ruler:
true value even when it lies outside the ruler, in which case the thumb pins to the end; it
only changes when the ruler is moved. `on_change` fires continuously."""
- def __init__(self, low, high, labels, step=1, scale="linear", minor=25, fill="ink_2", on_change=None):
+ def __init__(self, low, high, labels, step=1, scale="linear", minor=25, fill="ink_2", on_change=None,
+ title="", arrow_step=None):
self.low, self.high, self.labels, self.step, self.scale = low, high, labels, step, scale
self.minor, self.fill, self.on_change = minor, fill, on_change
+ self.title = title
+ # A linear ruler's arrows move this far, and `step` with Option held.
+ self.arrow_step = arrow_step or step
self.enabled = True
self._value = low
self.view = _autolayout(_RulerView.alloc().init())
@@ -942,13 +1026,15 @@ class Ruler:
raw = scale_value(fraction, self.low, self.high, self.scale)
self._set(int(round(raw / self.step) * self.step))
- def nudge(self, direction):
+ def nudge(self, direction, fine=False):
pinned = min(max(self._value, self.low), self.high)
# Equal steps along the ruler rather than in units, so arrows move evenly across a square
# root scale; never less than one step, or a rounded step could go nowhere.
target = scale_value(self.fraction() + direction / self.minor, self.low, self.high, self.scale)
target = int(round(target / self.step) * self.step)
- if self.scale == "linear" or target == pinned:
+ if self.scale == "linear":
+ target = pinned + direction * (self.step if fine else self.arrow_step)
+ elif fine or target == pinned:
target = pinned + direction * self.step
self._set(target)
@@ -982,7 +1068,7 @@ class KeyRecorder:
self.monitor = None
# The keycap's thicker bottom edge is the outer box showing through a 3pt gap.
self.view = pressable(self._clicked, "edge", radius=theme.RADIUS["keycap"])
- self.view.setAccessibilityLabel_("Trigger key")
+ self.view.setAccessibilityLabel_(f"Shortcut key, {key_title(value)}")
face = box("ground", radius=theme.RADIUS["keycap"] - 1)
self.view.addSubview_(face)
pin(face, self.view, (1, 1, 3, 1))
@@ -999,6 +1085,7 @@ class KeyRecorder:
def set_value(self, value):
self.value = value
self.key.set(key_title(value))
+ self.view.setAccessibilityLabel_(f"Shortcut key, {key_title(value)}")
def _clicked(self):
if self.monitor is not None:
@@ -1055,7 +1142,9 @@ class IgnoredRecorder:
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)
+ # Body size, unlike the shortcut's keycap: this is an action at the foot of a list, and at
+ # keycap size it outweighed the entries above it.
+ self.title = Label(self.TITLE, theme.TYPE["body"], 600)
squeeze(self.title.view)
self.hint = Label(self.HINT, theme.TYPE["small"], ink="ink_3", align=AppKit.NSTextAlignmentRight)
line = stack(vertical=False, spacing=10)
@@ -1141,9 +1230,12 @@ class CodeBoxes:
self.view.setDistribution_(AppKit.NSStackViewDistributionFillEqually)
self.fields = []
for index in range(digits):
- container, control = field()
+ container, control = field(cls=_CentredField)
control.setFont_(theme.mono_font(theme.TYPE["keycap"]))
control.setAlignment_(AppKit.NSTextAlignmentCenter)
+ # A fixed box the digit centres in, rather than one that hugs the line and leaves the
+ # digit sitting on the font's descender room.
+ container.heightAnchor().constraintEqualToConstant_(48).setActive_(True)
control.setDelegate_(self.delegate)
control.setAccessibilityLabel_(f"Digit {index + 1}")
self.view.addArrangedSubview_(container)
@@ -1284,6 +1376,7 @@ class Sidebar:
footer = pressable(on_footer)
footer.pointer_cursor = True
footer.setAccessibilityLabel_(footer_label or footer_text)
+ footer.setToolTip_(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)
# A slim right inset, with nothing beside the text: the address is 144pt of a 180pt
@@ -1332,16 +1425,74 @@ class Sidebar:
row.setAccessibilityLabel_(name if tone is None else f"{name}, needs attention")
+class _Overlay(AppKit.NSView):
+ """A view over its host that draws and takes no clicks: the ring's own layer tree. A layer
+ added straight onto a stack view's backing layer is never drawn."""
+
+ def hitTest_(self, _point):
+ return None
+
+ def isAccessibilityElement(self):
+ return False
+
+
+class Ring:
+ """The one ring round a group's chosen tile or chip. It lives over `host`, above what it rings,
+ and slides from the old choice to the new; each ringed view's layout calls `follow`, so a
+ reflow carries the ring with it instead of leaving it behind."""
+
+ def __init__(self, host, radius, inset=0.0):
+ self.overlay = _autolayout(_Overlay.alloc().init())
+ self.overlay.setWantsLayer_(True)
+ host.addSubview_(self.overlay)
+ pin(self.overlay, host)
+ self.host = self.overlay
+ self.inset = inset
+ self.target = None
+ self.enabled = True
+ self.layer = Quartz.CALayer.layer()
+ self.layer.setBorderWidth_(2)
+ self.layer.setCornerRadius_(radius)
+ self.layer.setHidden_(True)
+ self.overlay.layer().addSublayer_(self.layer)
+
+ def show(self, target, enabled=True):
+ moving = self.target is not None and target is not None and target != self.target
+ self.target, self.enabled = target, enabled
+ if target is not None:
+ target.ring_owner = self
+ motion.transaction(moving and motion.live(self.host))
+ self.layer.setHidden_(target is None)
+ if target is not None:
+ self.layer.setFrame_(self._frame(target))
+ theme.tint(self.layer, border="ink" if enabled else "rule")
+ Quartz.CATransaction.commit()
+
+ def follow(self, view):
+ if view is not self.target:
+ return
+ motion.transaction(False)
+ self.layer.setFrame_(self._frame(view))
+ Quartz.CATransaction.commit()
+
+ def _frame(self, target):
+ rect = target.convertRect_toView_(target.bounds(), self.host)
+ return AppKit.NSInsetRect(rect, self.inset, self.inset)
+
+
class ChoiceTiles:
"""One of several, as tiles side by side: each a live preview over its name and a line saying
what it is, the whole tile clickable. The chosen tile takes a 2pt ink border. `.value` reads and
- writes the value rather than the index, like Segmented."""
+ writes the value rather than the index, like Segmented. `columns` pads a short row with empty
+ space so rows of different lengths line up; the Design page's groups need that."""
- def __init__(self, choices, on_change=None):
+ def __init__(self, choices, on_change=None, columns=None):
self.on_change = on_change
self._value = None
self.enabled = True
self.tiles = []
+ self.values = [choice[0] for choice in choices]
+ self.previews = [choice[3] for choice in choices]
self.view = stack(vertical=False, spacing=10)
self.view.setDistribution_(AppKit.NSStackViewDistributionFillEqually)
self.view.setAlignment_(AppKit.NSLayoutAttributeTop)
@@ -1353,13 +1504,31 @@ class ChoiceTiles:
add(column, preview)
column.setCustomSpacing_afterView_(10, preview)
name = Label(title, theme.TYPE["body"], 600)
+ words = Label(detail, theme.TYPE["small"], ink="ink_3", wrap=True)
+ # A narrow tile wraps its detail onto more lines; the row grows to fit rather than
+ # squeezing the title or the last line out.
+ for view in (name.view, words.view):
+ view.setContentCompressionResistancePriority_forOrientation_(
+ AppKit.NSLayoutPriorityRequired, AppKit.NSLayoutConstraintOrientationVertical
+ )
add(column, name.view)
- add(column, Label(detail, theme.TYPE["small"], ink="ink_3", wrap=True).view)
+ add(column, words.view)
tile.addSubview_(column)
- pin(column, tile, (8, 8, 12, 8))
+ # Top-aligned, with the slack below: a tile stretched to its tallest neighbour would
+ # otherwise open a gap between its name and its detail.
+ AppKit.NSLayoutConstraint.activateConstraints_([
+ column.topAnchor().constraintEqualToAnchor_constant_(tile.topAnchor(), 8),
+ column.leadingAnchor().constraintEqualToAnchor_constant_(tile.leadingAnchor(), 8),
+ tile.trailingAnchor().constraintEqualToAnchor_constant_(column.trailingAnchor(), 8),
+ tile.bottomAnchor().constraintGreaterThanOrEqualToAnchor_constant_(column.bottomAnchor(), 12),
+ ])
self.view.addArrangedSubview_(tile)
tile.heightAnchor().constraintEqualToAnchor_(self.view.heightAnchor()).setActive_(True)
self.tiles.append((value, tile, name))
+ _pad(self.view, columns, len(choices))
+ # Linked swaps in one ring for all its rows, so the ring can travel between them.
+ self.ring = Ring(self.view, theme.RADIUS["segment"])
+ self.ring_shared = False
@property
def value(self):
@@ -1368,12 +1537,15 @@ class ChoiceTiles:
@value.setter
def value(self, value):
self._value = value
+ chosen_tile = None
for candidate, tile, name in self.tiles:
chosen = candidate == value
- paint(tile, "ground", "ink" if chosen and self.enabled else "rule")
- tile.layer().setBorderWidth_(2 if chosen else 1)
+ if chosen:
+ chosen_tile = tile
name.set(ink="ink" if self.enabled else "ink_3")
tile.setAccessibilityValue_(1 if chosen else 0)
+ if chosen_tile is not None or not self.ring_shared:
+ self.ring.show(chosen_tile, self.enabled)
def set_enabled(self, enabled):
self.enabled = enabled
@@ -1399,25 +1571,31 @@ class _Chip(AppKit.NSView):
Quartz.CATransaction.setDisableActions_(True)
gradient.setFrame_(self.bounds())
Quartz.CATransaction.commit()
+ owner = getattr(self, "ring_owner", None)
+ if owner is not None:
+ owner.follow(self)
class Swatches:
- """One colour of several from theme.PALETTES: a chip of each palette's gradient over its name,
- the chosen chip ringed in ink. `.value` reads and writes the palette name."""
+ """One colour of several: a chip of each palette's gradient over its name, the chosen chip ringed
+ in ink. `.value` reads and writes the palette name. A choice is (name, title), coloured from
+ theme.PALETTES, or (name, title, hex colours); `columns` pads as ChoiceTiles does."""
- def __init__(self, choices, on_change=None):
+ def __init__(self, choices, on_change=None, columns=None):
self.on_change = on_change
self._value = None
self.enabled = True
self.cells = []
+ self.values = [choice[0] for choice in choices]
self.view = stack(vertical=False, spacing=8)
self.view.setDistribution_(AppKit.NSStackViewDistributionFillEqually)
- for value, title in choices:
+ for choice in choices:
+ value, title = choice[:2]
cell = pressable(lambda value=value: self._choose(value), role=AppKit.NSAccessibilityRadioButtonRole)
cell.setAccessibilityLabel_(title)
chip = size(box(None, "rule", theme.RADIUS["field"], cls=_Chip), height=24)
chip.layer().setMasksToBounds_(True)
- colours = list(theme.PALETTES[value])
+ colours = list(choice[2] if len(choice) > 2 else theme.PALETTES[value])
if len(colours) == 1:
colours *= 2
gradient = Quartz.CAGradientLayer.layer()
@@ -1435,6 +1613,9 @@ class Swatches:
pin(column, cell, (3, 3, 3, 3))
self.view.addArrangedSubview_(cell)
self.cells.append((value, cell, chip, name))
+ _pad(self.view, columns, len(choices))
+ self.ring = Ring(self.view, theme.RADIUS["field"])
+ self.ring_shared = False
@property
def value(self):
@@ -1443,12 +1624,15 @@ class Swatches:
@value.setter
def value(self, value):
self._value = value
+ chosen_chip = None
for candidate, cell, chip, name in self.cells:
chosen = candidate == value
- paint(chip, None, "ink" if chosen and self.enabled else "rule")
- chip.layer().setBorderWidth_(2 if chosen else 1)
+ if chosen:
+ chosen_chip = chip
name.set(ink="ink" if chosen else "ink_2", weight=600 if chosen else 400)
cell.setAccessibilityValue_(1 if chosen else 0)
+ if chosen_chip is not None or not self.ring_shared:
+ self.ring.show(chosen_chip, self.enabled)
def set_enabled(self, enabled):
self.enabled = enabled
@@ -1463,3 +1647,51 @@ class Swatches:
self.value = value
if self.on_change is not None:
self.on_change(value)
+
+
+def _pad(row, columns, count):
+ """Empty cells after the last choice, so a row of `count` sits in a grid `columns` wide."""
+ for _ in range(max(0, (columns or count) - count)):
+ row.addArrangedSubview_(_autolayout(AppKit.NSView.alloc().init()))
+
+
+class Linked:
+ """Several one-of-several rows (ChoiceTiles, Swatches) acting as one choice: choosing in any row
+ clears the others. `.value`, `on_change` and `set_enabled` work as each row's do."""
+
+ def __init__(self, rows, on_change=None, host=None):
+ self.rows = list(rows)
+ self.on_change = on_change
+ self._value = None
+ # With a host holding every row, one ring serves them all and slides between rows.
+ self.ring = None
+ if host is not None and self.rows:
+ first = self.rows[0].ring
+ self.ring = Ring(host, first.layer.cornerRadius(), first.inset)
+ for row in self.rows:
+ row.on_change = self._chosen
+ if self.ring is not None:
+ row.ring.overlay.removeFromSuperview()
+ row.ring = self.ring
+ row.ring_shared = True
+
+ @property
+ def value(self):
+ return self._value
+
+ @value.setter
+ def value(self, value):
+ self._value = value
+ for row in self.rows:
+ row.value = value if value in row.values else None
+ if self.ring is not None and not any(value in row.values for row in self.rows):
+ self.ring.show(None)
+
+ def set_enabled(self, enabled):
+ for row in self.rows:
+ row.set_enabled(enabled)
+
+ def _chosen(self, value):
+ self.value = value
+ if self.on_change is not None:
+ self.on_change(value)
diff --git a/mac_app/windows_input.py b/mac_app/windows_input.py
index 28fe6f6..4e0f65e 100644
--- a/mac_app/windows_input.py
+++ b/mac_app/windows_input.py
@@ -19,6 +19,8 @@ import clipboard_mac
import desktop_mac
import input_injector_mac
import no_unlock
+import receiver
+import return_edge
from receiver import ReceiverServer, ServerState
LOGGER = logging.getLogger("Beamer")
@@ -29,7 +31,7 @@ class WindowsInput:
called from the status tick, so a token or port changed in the window
takes effect without anyone restarting Beamer."""
- def __init__(self, controller, logger=None, arrangement_callback=None):
+ def __init__(self, controller, logger=None, arrangement_callback=None, pressure_callback=None, arrival_callback=None):
self._controller = controller
self._logger = logger or LOGGER
# Windows can change the arrangement too, and it reaches this Mac over
@@ -38,6 +40,7 @@ class WindowsInput:
self._arrangement_callback = arrangement_callback
self._lock = threading.RLock()
self._running_for = None
+ self._ways = None
self.state = ServerState.STOPPED
self.detail = "Not listening"
self.server = ReceiverServer(
@@ -48,18 +51,56 @@ class WindowsInput:
injector=input_injector_mac,
focus_callback=self._on_focus,
arrangement_callback=self._on_arrangement,
+ # The crossing effects: the push home through the return edge, and the PC's pointer landing
+ # here. Both fire on the receiver's session thread; the app marshals them.
+ pressure_callback=pressure_callback,
+ arrival_callback=arrival_callback,
self_name="Mac",
peer_name="PC",
self_target="mac",
peer_target="windows",
)
controller.send_peer_home = self.server.send_home
+ # Pause crossing and the full-screen hold are about this screen: the PC's pointer does not
+ # go home through a held edge either.
+ self.server.edges_held = lambda: controller.crossing_paused or controller.full_screen_app is not None
+ self.server.return_model = self._return_model
+
+ def _return_model(self, edge, resistance):
+ """The way home for the PC's pointer through `edge` of this Mac, from this Mac's own ways
+ in, as for its own pointer: only the chosen thirds, the whole edge, only the notch's own
+ stretch of the top edge, the corner when it sits on that edge, else none. On the receiver's
+ session thread."""
+ crossing_cfg = self._controller.cfg.crossing
+ methods = set(crossing_cfg["methods"])
+ if "part" in methods:
+ return return_edge.PartEdge(edge, crossing_cfg["edge_parts"], resistance)
+ if "edge" in methods:
+ return return_edge.ReturnEdge(edge, resistance)
+ # The same measured range the Mac's own pointer crosses by, read at each push: unmeasured,
+ # the notch is a wall, as it is for the Mac's own pointer.
+ if "notch" in methods and edge == "top":
+ return return_edge.SpanEdge(edge, lambda: self._controller.notch_range, resistance)
+ corner = crossing_cfg["corner"]
+ if "corner" in methods and edge in corner.split("_"):
+ return return_edge.CornerPush(corner, edge, resistance)
+ return None
@property
def receiving(self) -> bool:
return bool(self._controller.receiving)
def sync(self, cfg) -> None:
+ speeds = (cfg.pointer_speed, cfg.scroll_speed, cfg.reverse_scroll)
+ scale = self.server.input_scale
+ if scale is None or (scale.pointer, scale.scroll, scale.reverse) != speeds:
+ self.server.input_scale = receiver.InputScale(*speeds)
+ # A change on the Crossing page reaches the PC's pointer while it is here, not at its next
+ # crossing: the way home is built from these when the PC's input arrives.
+ ways = tuple((key, str(cfg.crossing.get(key))) for key in ("methods", "edge_parts", "corner"))
+ if ways != self._ways:
+ self._ways = ways
+ self.server.rearm_return()
if not cfg.allow_windows_to_drive:
# Stopping hands back whatever the PC was driving, the same as a dropped link.
with self._lock:
@@ -94,8 +135,9 @@ class WindowsInput:
def send_arrangement(self, mac_edge: str, set_at: int) -> bool:
"""Tell the PC over the link it opened to this Mac. Returns False when
- there is nobody connected, which is not a failure worth reporting --
- the hello carries the arrangement on the next connection anyway."""
+ there is nobody connected, which is not a failure worth reporting.
+ The hello names this Mac's way home but carries no stamp, so a change
+ made while nobody was connected reaches the PC only as that."""
return self.server.send_arrangement(mac_edge, int(set_at))
def _on_arrangement(self, mac_edge, set_at) -> None:
diff --git a/theme.py b/theme.py
index c1e476c..ce55215 100644
--- a/theme.py
+++ b/theme.py
@@ -1,8 +1,8 @@
"""Vernier theming for the macOS sender.
Wraps tokens.py, the one home for every colour, size and face both apps draw with, so no hex value
-is written twice. Dark only, by design: the window pins to the palette and does not follow the
-system appearance.
+is written twice. Two palettes, dark and light: `T` holds the one in use and is swapped in place, so
+every reader of `T` and every colour from `colour()` follows a switch without being handed anything.
"""
from __future__ import annotations
@@ -10,11 +10,14 @@ from __future__ import annotations
from pathlib import Path
import AppKit
+import objc
import tokens
T: dict[str, str] = tokens.tokens()
PALETTE = tokens.PALETTE
+PALETTE_LIGHT = tokens.PALETTE_LIGHT
+APPEARANCES = tokens.APPEARANCES
PALETTES = tokens.PALETTES
TYPE = tokens.TYPE
RADIUS = tokens.RADIUS
@@ -117,8 +120,150 @@ def rgb(value: str) -> tuple[float, float, float]:
return tuple(int(value[index:index + 2], 16) / 255 for index in range(0, 6, 2))
+_dark = True
+_static: dict = {}
+_dynamic: dict = {}
+
+
+def is_dark() -> bool:
+ return _dark
+
+
+def set_dark(dark: bool) -> None:
+ global _dark
+ _dark = bool(dark)
+ T.clear()
+ T.update(tokens.PALETTE if _dark else tokens.PALETTE_LIGHT)
+
+
+def wants_dark(choice: str, system_dark: bool) -> bool:
+ """The palette an `appearance` setting asks for: its own, or the system's for "system"."""
+ return {"dark": True, "light": False}.get(choice, bool(system_dark))
+
+
+def system_dark() -> bool:
+ """Whether macOS is in dark mode now. Read off the app, which Beamer never pins; only its settings
+ window is ever given an appearance of its own."""
+ appearance = AppKit.NSApplication.sharedApplication().effectiveAppearance()
+ names = [AppKit.NSAppearanceNameAqua, AppKit.NSAppearanceNameDarkAqua]
+ return appearance.bestMatchFromAppearancesWithNames_(names) == AppKit.NSAppearanceNameDarkAqua
+
+
+def _resolved(name: str):
+ key = (_dark, name)
+ if key not in _static:
+ _static[key] = AppKit.NSColor.colorWithSRGBRed_green_blue_alpha_(*rgb(T[name]), 1.0)
+ return _static[key]
+
+
def colour(name: str):
- return AppKit.NSColor.colorWithSRGBRed_green_blue_alpha_(*rgb(T[name]), 1.0)
+ """A colour that resolves against the palette in use each time it is drawn, so a label, a field or
+ a drawRect keeps up with a switch by being redrawn. It ignores the appearance AppKit offers: the
+ window's appearance is set from the same choice, and a CGColor taken outside drawing would
+ otherwise resolve against the system's."""
+ if name not in _dynamic:
+ _dynamic[name] = AppKit.NSColor.colorWithName_dynamicProvider_(None, lambda _appearance: _resolved(name))
+ return _dynamic[name]
+
+
+def cg(name: str, alpha: float = 1.0):
+ """The palette colour as a CGColor, fixed at the palette in use: layers keep what they are given,
+ so set one with `tint` if it must follow a switch."""
+ return _resolved(name).colorWithAlphaComponent_(alpha).CGColor()
+
+
+# A layer's palette colours are kept on the layer under these keys (CALayer stores any key) as
+# "name" or "name@alpha", and a gradient's as "|"-joined, so `retint` can resolve them again.
+_ROLES = {
+ "background": "setBackgroundColor_",
+ "border": "setBorderColor_",
+ "shadow": "setShadowColor_",
+ "fill": "setFillColor_",
+ "stroke": "setStrokeColor_",
+ "foreground": "setForegroundColor_",
+}
+_KEY = "beamerTint_"
+
+
+def _spec(value) -> str | None:
+ if value is None:
+ return None
+ if isinstance(value, str):
+ return value
+ name, alpha = value
+ return f"{name}@{alpha}"
+
+
+def _cg_spec(spec: str):
+ name, _, alpha = spec.partition("@")
+ return cg(name, float(alpha) if alpha else 1.0)
+
+
+def tint(layer, **roles) -> None:
+ """Sets layer colours by palette name, `background="panel"` or `border=("signal", 0.4)`, and
+ remembers them so `retint` can follow a switch. None clears the colour. `colours=[...]` sets a
+ gradient's stops the same way."""
+ for role, value in roles.items():
+ if role == "colours":
+ specs = [_spec(item) for item in value]
+ layer.setColors_([_cg_spec(spec) for spec in specs])
+ layer.setValue_forKey_("|".join(specs), _KEY + role)
+ continue
+ spec = _spec(value)
+ getattr(layer, _ROLES[role])(_cg_spec(spec) if spec else None)
+ layer.setValue_forKey_(spec, _KEY + role)
+
+
+def retint(layer) -> None:
+ """Resolves every tinted colour on `layer` and its sublayers against the palette in use."""
+ for role, setter in _ROLES.items():
+ spec = layer.valueForKey_(_KEY + role)
+ if spec:
+ getattr(layer, setter)(_cg_spec(str(spec)))
+ specs = layer.valueForKey_(_KEY + "colours")
+ if specs:
+ layer.setColors_([_cg_spec(spec) for spec in str(specs).split("|")])
+ for sublayer in layer.sublayers() or ():
+ retint(sublayer)
+
+
+def repaint(view) -> None:
+ """Brings a view tree up to the palette in use: tinted layers resolve again, views that keep a
+ colour of their own get `refresh_colours()`, and everything redraws. Walked view by view: a
+ layer-backed view's layer does not list its subviews' layers among its sublayers."""
+ if view.layer() is not None:
+ retint(view.layer())
+ refresh = getattr(view, "refresh_colours", None)
+ if callable(refresh):
+ refresh()
+ view.setNeedsDisplay_(True)
+ for subview in view.subviews() or ():
+ repaint(subview)
+
+
+def appearance_named(dark: bool):
+ return AppKit.NSAppearance.appearanceNamed_(AppKit.NSAppearanceNameDarkAqua if dark else AppKit.NSAppearanceNameAqua)
# The longest a line of running text may get before it wraps, whatever the window width.
READING_WIDTH = 560.0
+
+
+class AppearanceWatch(AppKit.NSObject):
+ """Calls `callback()` whenever macOS switches between light and dark, by watching the app's
+ effective appearance, which AppKit has already updated by the time it is told."""
+
+ def initWithCallback_(self, callback):
+ self = objc.super(AppearanceWatch, self).init()
+ if self is None:
+ return None
+ self.callback = callback
+ AppKit.NSApplication.sharedApplication().addObserver_forKeyPath_options_context_(
+ self, "effectiveAppearance", AppKit.NSKeyValueObservingOptionNew, None
+ )
+ return self
+
+ def observeValueForKeyPath_ofObject_change_context_(self, _path, _object, _change, _context):
+ self.callback()
+
+ def stop(self):
+ AppKit.NSApplication.sharedApplication().removeObserver_forKeyPath_(self, "effectiveAppearance")
diff --git a/tokens.py b/tokens.py
index 83c7627..dbb5b81 100644
--- a/tokens.py
+++ b/tokens.py
@@ -1,15 +1,18 @@
-"""Beamer's design tokens: the Vernier direction, chosen 10-09-2026.
+"""Beamer's design tokens: the Vernier direction.
-The mock is docs/designs/claude-2-vernier.html and its reasoning docs/designs/claude-2-vernier-notes.md.
This file is the one home for every colour, size, face and spring both apps draw with. The Mac app
reads it through the root theme.py; win_app/tokens.py is a byte-identical copy because PyInstaller
only bundles what sits under the app, and win_app's tests fail if the two drift. Edit this one, then
copy it across.
-Dark only. `signal` is the one colour that means something is happening: the link is up, input is on
-Windows, pressure is building, a permission is granted. The mock used lime; it was swapped for
-cockpit cyan at build time because lime on near-black is the stock developer-tool look, and B612
-Mono is a cockpit face. Reverting is this one value and `signal_dim`.
+`signal` is the one colour that means something is happening: the link is up, input is on Windows,
+pressure is building, a permission is granted. The mock used lime; it was swapped for cockpit cyan
+at build time because lime on near-black is the stock developer-tool look, and B612 Mono is a
+cockpit face. Reverting is this one value and `signal_dim`, in both palettes.
+
+PALETTE is the dark settings window and PALETTE_LIGHT the light one, the same names in the same
+roles, chosen by the `appearance` setting. The crossing effects and PALETTES take the dark `signal`
+whatever the window shows: they draw on the desktop, not on the window.
"""
PALETTE = {
@@ -32,6 +35,31 @@ PALETTE = {
# panel 5.5, edge on panel 3.5 (control boundaries), signal on panel 10.4, ground on signal 11.1,
# amber on panel 9.8, fault on panel 7.1.
+# Paper rather than the dark palette turned over: modules are lighter than the window, as in the dark
+# one, so a module still lifts off the ground and a well still sets a control apart from its module.
+# signal keeps its hue but drops to a depth that carries text on paper and a ground-coloured glyph on
+# itself. Measured WCAG ratios: ink on panel 16.4, ink_2 on panel 9.1 and on well 7.5, ink_3 on
+# panel 5.6 and on well 4.6, edge on panel 3.9 and on well 3.2, signal on panel 5.9 and on ground 5.4,
+# ground on signal 5.4, ink on signal_dim 12.3, amber on panel 5.4, fault on panel 5.8.
+PALETTE_LIGHT = {
+ "ground": "#f1f0ea",
+ "panel": "#fbfaf6",
+ "well": "#e5e4dc",
+ "rule": "#dcdbd3",
+ "edge": "#7f7e74",
+ "ink": "#1b1c18",
+ "ink_2": "#46463f",
+ "ink_3": "#66655c",
+ "signal": "#006a88",
+ "signal_dim": "#bfe0ea",
+ "amber": "#8f5c00",
+ "fault": "#b53522",
+ "off": "#aeada3",
+}
+
+# The `appearance` setting on both apps: follow the system, or keep one palette.
+APPEARANCES = ("system", "light", "dark")
+
UI_FAMILY = "Hanken Grotesk"
MONO_FAMILY = "B612 Mono"
FONT_FILES = (
diff --git a/win_app/Beamer-Setup.iss b/win_app/Beamer-Setup.iss
index 9c10684..3e5ca8a 100644
--- a/win_app/Beamer-Setup.iss
+++ b/win_app/Beamer-Setup.iss
@@ -25,6 +25,9 @@ UninstallDisplayIcon={app}\Beamer.exe
; can neither close it nor replace its locked exe; setup asks for it to be quit from the tray first.
AppMutex=Beamer.Receiver
SetupIconFile=Beamer.ico
+; Beamer.exe is x64. This refuses 32-bit Windows with the installer's own message; Windows 11 on
+; ARM is allowed, as it runs x64 apps under emulation.
+ArchitecturesAllowed=x64compatible
[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
diff --git a/win_app/Install-Beamer.ps1 b/win_app/Install-Beamer.ps1
index 7f12475..4c95f2a 100644
--- a/win_app/Install-Beamer.ps1
+++ b/win_app/Install-Beamer.ps1
@@ -11,44 +11,10 @@ trap {
break
}
-# The app was called OpenKB until 19-08-2026, then Beamy until 10-09-2026. Only
-# the display name moved each time until now: this rename also moves the data
-# directory, from %LOCALAPPDATA%\OpenKB to %LOCALAPPDATA%\Beamer. app_config.py's
-# migrate_legacy_config copies the OpenKB-era config.json across on first run
-# rather than moving it, so the old directory and its config.json are never
-# touched here.
-$LegacyOpenKBDir = Join-Path $env:LOCALAPPDATA 'OpenKB'
$InstallDir = Join-Path $env:LOCALAPPDATA 'Beamer'
$ExeSource = Join-Path $PSScriptRoot 'dist\Beamer.exe'
$ExeDestination = Join-Path $InstallDir 'Beamer.exe'
-# Everything the OpenKB name left behind, so the rename does not leave a second
-# Start Menu entry, a second logon task, a stale firewall rule for an exe that
-# no longer exists, or an OpenKB.exe that still runs alongside this one.
-$LegacyName = 'OpenKB'
-Get-Process $LegacyName -ErrorAction SilentlyContinue | Stop-Process -Force
-# Stop-Process returns before the exe is released, and deleting it straight away then fails silently.
-Get-Process $LegacyName -ErrorAction SilentlyContinue | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue
-Unregister-ScheduledTask -TaskName $LegacyName -Confirm:$false -ErrorAction SilentlyContinue
-Remove-Item -Path (Join-Path $LegacyOpenKBDir "$LegacyName.exe") -Force -ErrorAction SilentlyContinue
-Remove-Item -Path (Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\$LegacyName.lnk") -Force -ErrorAction SilentlyContinue
-Remove-Item -Path (Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\Startup\$LegacyName.lnk") -Force -ErrorAction SilentlyContinue
-Remove-Item -Path (Join-Path ([Environment]::GetFolderPath('Desktop')) "$LegacyName.lnk") -Force -ErrorAction SilentlyContinue
-# A rule named plain OpenKB also survived on the rig until 15-09-2026: TCP 51820 for any program on
-# every profile, Public included.
-Get-NetFirewallRule -DisplayName "$LegacyName Receiver (TCP-In)", $LegacyName -ErrorAction SilentlyContinue | Remove-NetFirewallRule -ErrorAction SilentlyContinue
-
-# Everything the Beamy name left behind. Its data directory was never its own --
-# it shared OpenKB's, so Beamy.exe there is removed but config.json stays; it is
-# still what migrate_legacy_config reads from.
-Get-Process 'Beamy' -ErrorAction SilentlyContinue | Stop-Process -Force
-Get-Process 'Beamy' -ErrorAction SilentlyContinue | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue
-Remove-Item -Path (Join-Path $LegacyOpenKBDir 'Beamy.exe') -Force -ErrorAction SilentlyContinue
-Remove-Item -Path (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Beamy.lnk') -Force -ErrorAction SilentlyContinue
-Remove-Item -Path (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Startup\Beamy.lnk') -Force -ErrorAction SilentlyContinue
-Remove-Item -Path (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Beamy.lnk') -Force -ErrorAction SilentlyContinue
-Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -Name 'Beamy' -ErrorAction SilentlyContinue
-
# Beamer.exe now carries a requireAdministrator manifest (build.spec uac_admin=True) so
# SendInput can reach elevated windows, e.g. an admin terminal, which UIPI otherwise
# silently discards input for. The firewall rules below need this session elevated too.
@@ -60,8 +26,8 @@ if (-not (Test-Path $ExeSource)) { throw 'The Windows build did not produce Beam
New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
Get-Process 'Beamer' -ErrorAction SilentlyContinue | Stop-Process -Force
Get-Process 'Beamer' -ErrorAction SilentlyContinue | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue
-# The exe can stay locked for a moment after the process has gone (23-09-2026: the copy failed
-# with "being used by another process" straight after Wait-Process returned, and worked on a rerun).
+# The exe can stay locked for a moment after the process has gone: the copy can fail with
+# "being used by another process" straight after Wait-Process returns, and succeed on a rerun.
for ($attempt = 1; ; $attempt++) {
try {
Copy-Item -Path $ExeSource -Destination $ExeDestination -Force -ErrorAction Stop
@@ -95,13 +61,8 @@ Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
if ($IsElevated) {
# Start at logon belongs to the app: the switch on its Overview page writes and removes the
- # Beamer task, and the installer never does, on install or reinstall. A Beamy task is removed,
- # since it starts an exe that no longer exists.
- Unregister-ScheduledTask -TaskName 'Beamy' -Confirm:$false -ErrorAction SilentlyContinue
-
+ # Beamer task, and the installer never does, on install or reinstall.
try {
- Get-NetFirewallRule -DisplayName 'Beamy Receiver (TCP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRule
- Get-NetFirewallRule -DisplayName 'Beamy Pairing (UDP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRule
Get-NetFirewallRule -DisplayName 'Beamer Receiver (TCP-In)' -ErrorAction SilentlyContinue | Remove-NetFirewallRule
# 24820 and 24821, not the old 51820/51821: those sat inside the 49152-65535 range
# Windows hands out for itself, and a WinNAT reservation landing on the receiver's port
diff --git a/win_app/app_config.py b/win_app/app_config.py
index 9fbae5a..fccda56 100644
--- a/win_app/app_config.py
+++ b/win_app/app_config.py
@@ -2,21 +2,25 @@
import json
import os
-import shutil
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
import capture_win
+import effects
import ignored
import protocol
+import return_edge
+import tokens
-GLOW_STYLES = ("glow", "beam")
-GLOW_COLOURS = ("signal", "colourful", "ocean", "sunset", "mono")
+# Today's two styles and five colours, then every crossing effect and colour pack in effects.py.
+# Any colour goes with any style.
+GLOW_STYLES = ("glow", "beam") + effects.EFFECT_IDS
+GLOW_COLOURS = ("signal", "colourful", "ocean", "sunset", "mono") + effects.PACK_IDS
EDGES = ("left", "right", "top", "bottom")
CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")
-METHODS = ("edge", "corner", "shortcut")
+METHODS = ("edge", "part", "corner", "shortcut")
TRIGGER_STYLES = ("double_tap", "hold")
# Any named key that is not a character can be the trigger, recorded by pressing it, as on the
# Mac: a modifier, a function key, a navigation key. Stored as its wire name, which is Mac-shaped --
@@ -35,6 +39,15 @@ UNRECORDABLE_TRIGGER_VKS = {0x08, 0x09, 0x0D, 0x1B, 0x20, 0x2C}
MODIFIER_STYLES = ("semantic", "positional")
+def palette_colours(colour: str) -> tuple:
+ """The colours of a `glow_colour` id: one of today's palettes, else a crossing effect's pack.
+ An unknown id is Signal's, as today's glow always drew it."""
+ if colour in tokens.PALETTES:
+ return tuple(tokens.PALETTES[colour])
+ found = effects.pack(colour) if colour in effects.PACK_IDS else None
+ return tuple(found[1]) if found else tuple(tokens.PALETTES["signal"])
+
+
class ConfigError(Exception):
pass
@@ -50,16 +63,32 @@ class Config:
edge_glow: bool = True
glow_style: str = "glow"
glow_colour: str = "signal"
+ # A switch by the shortcut or a menu, not a crossing, plays an arrival around the pointer.
+ shortcut_arrival: bool = True
+ # What that plays: "match" for whatever the crossing style plays, else see effects.SWITCH_STYLES.
+ shortcut_arrival_style: str = "match"
+ # How long an effect takes to play through once the pointer crosses: see effects.LENGTHS.
+ effect_length: str = "normal"
# The Mac's name from the last pairing, for the window to say who this PC is paired with.
paired_with: str = ""
# Whether each machine may take the other's input. Two plain switches: the
# receiver, and the outward link.
allow_mac_to_drive: bool = True
+ # Ask GitHub once a day whether a newer release is out; see updates.py.
+ check_updates: bool = True
+ # Every address the window shows is hidden.
+ hide_addresses: bool = False
+ # How the Mac's pointer and scroll feel on this PC; see receiver.InputScale.
+ pointer_speed: float = 1.0
+ scroll_speed: float = 1.0
+ reverse_scroll: bool = False
send_to_mac: bool = True
# How input leaves this PC. Any combination of the methods can be on, and
# none of them means the PC can only be driven, never drive.
crossing_methods: list = field(default_factory=lambda: ["edge", "shortcut"])
crossing_corner: str = "top_left"
+ # "Part of the edge": the thirds of the edge to the Mac that cross, as return_edge.PARTS names them.
+ crossing_edge_parts: list = field(default_factory=lambda: ["middle"])
crossing_resistance_px: int = 120
trigger_key: str = "cmd_r"
trigger_style: str = "double_tap"
@@ -88,6 +117,9 @@ class Config:
mac_hardware_address: str = ""
# Keys and buttons that stay on this PC while its input is on the Mac; see ignored.py.
ignored_inputs: list = field(default_factory=list)
+ # The window's own palette: follow Windows, or keep one. tokens.APPEARANCES is the home of
+ # these three values.
+ appearance: str = "system"
def migrated_port(value) -> int:
@@ -114,30 +146,6 @@ def default_config_path() -> Path:
return Path.home() / ".config" / "Beamer" / "config.json"
-def legacy_config_path() -> Path:
- """Where config.json lived under the OpenKB name, before the Beamer rename."""
- base = os.environ.get("LOCALAPPDATA") or os.environ.get("XDG_CONFIG_HOME")
- if base:
- return Path(base) / "OpenKB" / "config.json"
- return Path.home() / ".config" / "OpenKB" / "config.json"
-
-
-def migrate_legacy_config() -> bool:
- """Copy the OpenKB-era config.json into the new Beamer location if Beamer
- has none yet. Never moves or deletes the old file."""
- new_path = default_config_path()
- old_path = legacy_config_path()
- if new_path.exists() or not old_path.exists():
- return False
- new_path.parent.mkdir(parents=True, exist_ok=True)
- # Copied beside, then renamed into place: a copy cut short would otherwise
- # leave a truncated config that shadows the intact old one for ever.
- staged = new_path.with_name(".config.migrating")
- shutil.copyfile(old_path, staged)
- os.replace(staged, new_path)
- return True
-
-
def validate_config(config: Config) -> None:
if not isinstance(config.host, str):
raise ConfigError("host must be text")
@@ -173,6 +181,9 @@ def validate_config(config: Config) -> None:
raise ConfigError(f"crossing_methods must be a list of: {', '.join(METHODS)}")
if config.crossing_corner not in CORNERS:
raise ConfigError(f"crossing_corner must be one of: {', '.join(CORNERS)}")
+ parts = config.crossing_edge_parts
+ if not isinstance(parts, list) or not parts or not all(part in return_edge.PARTS for part in parts):
+ raise ConfigError(f"crossing_edge_parts must be one or more of: {', '.join(return_edge.PARTS)}")
for name in ("crossing_resistance_px", "mac_resistance_px"):
value = getattr(config, name)
try:
@@ -183,6 +194,16 @@ def validate_config(config: Config) -> None:
raise ConfigError(f"{name} must be a whole number of pixels from 0 to 500")
if not isinstance(config.allow_mac_to_drive, bool):
raise ConfigError("allow_mac_to_drive must be true or false")
+ if not isinstance(config.check_updates, bool):
+ raise ConfigError("check_updates must be true or false")
+ if not isinstance(config.hide_addresses, bool):
+ raise ConfigError("hide_addresses must be true or false")
+ for name in ("pointer_speed", "scroll_speed"):
+ value = getattr(config, name)
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not 0.25 <= value <= 4.0:
+ raise ConfigError(f"{name} must be a number from 0.25 to 4")
+ if not isinstance(config.reverse_scroll, bool):
+ raise ConfigError("reverse_scroll must be true or false")
try:
reconnect_interval_s = float(config.reconnect_interval_s)
except (TypeError, ValueError) as exc:
@@ -195,6 +216,13 @@ def validate_config(config: Config) -> None:
raise ConfigError(f"glow_style must be one of: {', '.join(GLOW_STYLES)}")
if config.glow_colour not in GLOW_COLOURS:
raise ConfigError(f"glow_colour must be one of: {', '.join(GLOW_COLOURS)}")
+ if not isinstance(config.shortcut_arrival, bool):
+ raise ConfigError("shortcut_arrival must be true or false")
+ if config.shortcut_arrival_style not in effects.SWITCH_STYLES:
+ raise ConfigError(f"shortcut_arrival_style must be one of: {', '.join(effects.SWITCH_STYLES)}")
+ lengths = tuple(value for value, _name in effects.LENGTHS)
+ if config.effect_length not in lengths:
+ raise ConfigError(f"effect_length must be one of: {', '.join(lengths)}")
if not isinstance(config.paired_with, str):
raise ConfigError("paired_with must be text")
if not isinstance(config.send_to_mac, bool):
@@ -207,6 +235,8 @@ def validate_config(config: Config) -> None:
ignored.validate(config.ignored_inputs)
except ValueError as exc:
raise ConfigError(str(exc)) from exc
+ if config.appearance not in tokens.APPEARANCES:
+ raise ConfigError(f"appearance must be one of: {', '.join(tokens.APPEARANCES)}")
def config_from_dict(raw: dict) -> Config:
@@ -217,19 +247,30 @@ def config_from_dict(raw: dict) -> Config:
raise ConfigError(f"config.json is missing required field(s): {', '.join(missing)}")
trigger_key = raw.get("trigger_key", "cmd_r")
try:
+ glow_style, glow_colour, switch_style = effects.offered(
+ raw.get("glow_style", "glow"), raw.get("glow_colour", "signal"), raw.get("shortcut_arrival_style", "match"))
config = Config(
host=raw["host"],
port=migrated_port(raw["port"]),
auth_token=raw["auth_token"],
reconnect_interval_s=float(raw.get("reconnect_interval_s", 2.0)),
edge_glow=raw.get("edge_glow", True),
- glow_style=raw.get("glow_style", "glow"),
- glow_colour=raw.get("glow_colour", "signal"),
+ glow_style=glow_style,
+ glow_colour=glow_colour,
+ shortcut_arrival=raw.get("shortcut_arrival", True),
+ shortcut_arrival_style=switch_style,
+ effect_length=raw.get("effect_length", "normal"),
paired_with=raw.get("paired_with", "") or "",
allow_mac_to_drive=raw.get("allow_mac_to_drive", True),
+ check_updates=raw.get("check_updates", True),
+ hide_addresses=raw.get("hide_addresses", False),
+ pointer_speed=raw.get("pointer_speed", 1.0),
+ scroll_speed=raw.get("scroll_speed", 1.0),
+ reverse_scroll=raw.get("reverse_scroll", False),
send_to_mac=raw.get("send_to_mac", True),
crossing_methods=list(raw.get("crossing_methods", ["edge", "shortcut"])),
crossing_corner=raw.get("crossing_corner", "top_left"),
+ crossing_edge_parts=raw.get("crossing_edge_parts", ["middle"]),
crossing_resistance_px=int(raw.get("crossing_resistance_px", 120)),
trigger_key=trigger_key,
trigger_style=raw.get("trigger_style", "double_tap"),
@@ -242,6 +283,7 @@ def config_from_dict(raw: dict) -> Config:
arrangement_set_at=int(raw.get("arrangement_set_at", 0)),
mac_resistance_px=int(raw.get("mac_resistance_px", 120)),
ignored_inputs=raw.get("ignored_inputs", []),
+ appearance=raw.get("appearance") if raw.get("appearance") in tokens.APPEARANCES else "system",
)
except (TypeError, ValueError) as exc:
raise ConfigError(f"config.json contains an invalid value: {exc}") from exc
@@ -280,11 +322,20 @@ def config_to_dict(config: Config) -> dict:
"edge_glow": config.edge_glow,
"glow_style": config.glow_style,
"glow_colour": config.glow_colour,
+ "shortcut_arrival": config.shortcut_arrival,
+ "shortcut_arrival_style": config.shortcut_arrival_style,
+ "effect_length": config.effect_length,
"paired_with": config.paired_with,
"allow_mac_to_drive": config.allow_mac_to_drive,
+ "check_updates": config.check_updates,
+ "hide_addresses": config.hide_addresses,
+ "pointer_speed": config.pointer_speed,
+ "scroll_speed": config.scroll_speed,
+ "reverse_scroll": config.reverse_scroll,
"send_to_mac": config.send_to_mac,
"crossing_methods": list(config.crossing_methods),
"crossing_corner": config.crossing_corner,
+ "crossing_edge_parts": list(config.crossing_edge_parts),
"crossing_resistance_px": int(config.crossing_resistance_px),
"trigger_key": config.trigger_key,
"trigger_style": config.trigger_style,
@@ -297,6 +348,7 @@ def config_to_dict(config: Config) -> dict:
"arrangement_set_at": int(config.arrangement_set_at),
"mac_resistance_px": int(config.mac_resistance_px),
"ignored_inputs": list(config.ignored_inputs),
+ "appearance": config.appearance,
}
diff --git a/win_app/build.spec b/win_app/build.spec
index 3ab7aa5..454377e 100644
--- a/win_app/build.spec
+++ b/win_app/build.spec
@@ -8,7 +8,8 @@ analysis = Analysis(
pathex=[str(source_dir)],
binaries=[],
datas=[(str(source_dir / "Beamer.ico"), "."), (str(source_dir / "assets"), "assets"), (str(source_dir.parent / "VERSION"), ".")],
- hiddenimports=["cryptography"],
+ # effects.py imports its fx_* modules by name, which PyInstaller's analysis cannot see.
+ hiddenimports=["cryptography"] + sorted(path.stem for path in source_dir.glob("fx_*.py")),
hookspath=[],
hooksconfig={},
runtime_hooks=[],
diff --git a/win_app/build_win_app.ps1 b/win_app/build_win_app.ps1
index 0f3b519..1fac973 100644
--- a/win_app/build_win_app.ps1
+++ b/win_app/build_win_app.ps1
@@ -21,8 +21,8 @@ Set-Location $ScriptDir
$ProjectDir = Split-Path -Parent $ScriptDir
if ($Release) {
- # docs\ is not part of the build and other sessions write there; anything else uncommitted would
- # ship code that no commit records.
+ # docs\ is not part of the build and changes independently of it; anything else uncommitted
+ # would ship code that no commit records.
$Dirty = git -C $ProjectDir status --porcelain -- . ':(exclude)docs'
if ($Dirty) { throw 'Uncommitted changes outside docs\ - commit them so the release matches a commit' }
$Iscc = Join-Path $env:LOCALAPPDATA 'Programs\Inno Setup 6\ISCC.exe'
diff --git a/win_app/capture_win.py b/win_app/capture_win.py
index 123f644..df8151f 100644
--- a/win_app/capture_win.py
+++ b/win_app/capture_win.py
@@ -13,7 +13,7 @@ Three things here are safety, not features, and none of them may move off the
callback thread:
- A hook that returns 1 while whatever consumes its events is wedged takes
- Toby's keyboard and mouse away with no way back. So the callback itself
+ the user's keyboard and mouse away with no way back. So the callback itself
checks whether redirecting is still live, and the moment the sender says it
is not -- a dropped link, a missed acknowledgement -- it passes the event
through. Nothing it does can block.
@@ -25,7 +25,7 @@ callback thread:
a return crossing -- injected here, then reported by Raw Input as the mouse
moving -- read as this PC's own push against the same edge and sent this
PC's input straight out to the Mac, which left the Mac's own notch and
- shortcut dead until someone pressed Send input to Windows (19-09-2026).
+ shortcut dead until someone pressed Send input to Windows.
- The character a key produces is read with only shift and caps lock applied,
never Ctrl/Alt/Win, exactly as the Mac's translator does it, so a chord
arrives as a modifier plus the plain key rather than as a control character.
@@ -163,7 +163,7 @@ 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. An extended key is
what marks the right Ctrl and the right Alt: Qt 6 reports one with an 0xE0 prefix (0xE01D is
- the right Ctrl, proved on the rig 27-09-2026), and the extended bit at 0x100 is read too."""
+ the right Ctrl), and the extended bit at 0x100 is read too."""
extended = bool(scan & _EXTENDED_SCAN) or scan & 0xFF00 == _EXTENDED_PREFIX
if vk == 0x10:
return VK_SHIFT_RIGHT if scan & 0xFF == _RIGHT_SHIFT_SCAN else VK_SHIFT_LEFT
@@ -176,9 +176,9 @@ def hook_vk(vk: int, scan: int) -> int:
# Windows virtual keys to the wire's key names, which are Mac-shaped: the
# semantic mapping happens here, once, so the Mac injects what it is given
# and nothing translates on arrival. Ctrl becomes Command and the Windows key
-# becomes Control, the exact inverse of the Mac's own key_map, so the
-# shortcuts Toby's fingers know keep working in both directions -- Ctrl+C on
-# this keyboard is Cmd+C on the Mac.
+# becomes Control, the exact inverse of the Mac's own key_map, so familiar
+# shortcuts keep working in both directions -- Ctrl+C on this keyboard is
+# Cmd+C on the Mac.
VK_TO_NAME: Dict[int, str] = {
0x08: "backspace",
0x09: "tab",
diff --git a/win_app/clipboard_win.py b/win_app/clipboard_win.py
index 5f26904..473d1d1 100644
--- a/win_app/clipboard_win.py
+++ b/win_app/clipboard_win.py
@@ -7,9 +7,8 @@ The clipboard is a contended, system-wide resource: any other process that
briefly holds it makes OpenClipboard fail, which is normal and expected, not
exceptional. `_open_clipboard` retries a handful of times with a short sleep
before giving up. This still wants confirmation on real Windows hardware
-under load (see the runtime-verification notes in the task writeup) --
-contention behaviour and timing were chosen to match common guidance, not
-measured on a real desktop.
+under load -- contention behaviour and timing were chosen to match common
+guidance, not measured on a real desktop.
Images cross the wire as PNG but live on this clipboard as CF_DIB, so each
direction converts. The DIB half (`dib_to_bgra`, `bgra_to_dib`) is pure
@@ -56,6 +55,8 @@ if _IS_WINDOWS:
kernel32.GlobalFree.argtypes = [ctypes.c_void_p]
kernel32.GlobalSize.restype = ctypes.c_size_t
kernel32.GlobalSize.argtypes = [ctypes.c_void_p]
+ user32.GetClipboardSequenceNumber.restype = ctypes.c_uint32
+ user32.GetClipboardSequenceNumber.argtypes = []
CF_DIB = 8
CF_UNICODETEXT = 13
@@ -71,6 +72,11 @@ _DIB_HEADER_SIZES = frozenset({40, 52, 56, 108, 124})
_BGR_MASKS = (0x00FF0000, 0x0000FF00, 0x000000FF)
_ALPHA_MASK = 0xFF000000
+# The clipboard's sequence number when it was last sent to the Mac or written from it; None until
+# then and after forget_sync. A switch sends the clipboard only when the number has moved since,
+# so an unchanged screenshot is not pushed across on every switch.
+_synced_sequence = None
+
OPEN_RETRY_ATTEMPTS = 5
OPEN_RETRY_DELAY_SECONDS = 0.05
@@ -317,14 +323,40 @@ def get_contents() -> Tuple[Optional[str], Optional[bytes]]:
return None, None
+def changed_contents() -> Tuple[Optional[str], Optional[bytes]]:
+ """get_contents(), or (None, None) when the clipboard has not changed since it was last sent
+ to or written from the Mac. Either way the current contents count as sent from here on."""
+ global _synced_sequence
+ if not _IS_WINDOWS:
+ return None, None
+ sequence = user32.GetClipboardSequenceNumber()
+ if sequence and sequence == _synced_sequence:
+ return None, None
+ text, png = get_contents()
+ # Only what was read counts as sent: a failed read must not hold this clipboard back.
+ if text is not None or png is not None:
+ _synced_sequence = sequence
+ return text, png
+
+
+def forget_sync() -> None:
+ """A new link: the Mac may have lost what it was sent, so the next switch sends again."""
+ global _synced_sequence
+ _synced_sequence = None
+
+
def set_contents(text: Optional[str], png: Optional[bytes]) -> bool:
"""Replace the Windows clipboard with `text` and/or `png`. Returns True
when at least one was set, False if this isn't Windows or the write
failed. Never raises."""
+ global _synced_sequence
if not _IS_WINDOWS:
return False
try:
- return _set_contents(user32, kernel32, text, png)
+ wrote = _set_contents(user32, kernel32, text, png)
+ if wrote:
+ _synced_sequence = user32.GetClipboardSequenceNumber()
+ return wrote
except Exception:
LOGGER.exception("failed to set the Windows clipboard")
return False
diff --git a/win_app/config.example.json b/win_app/config.example.json
index 92d7fbe..baabeff 100644
--- a/win_app/config.example.json
+++ b/win_app/config.example.json
@@ -1,17 +1,5 @@
{
"host": "192.168.1.20",
"port": 24820,
- "auth_token": "CHANGE_ME",
- "trigger_key": "alt_r",
- "double_tap_ms": 300,
- "key_map": {
- "cmd": "ctrl",
- "cmd_r": "ctrl",
- "ctrl": "cmd",
- "ctrl_r": "cmd",
- "alt": "alt",
- "alt_r": "alt"
- },
- "reconnect_interval_s": 2.0,
- "edge_glow": true
+ "auth_token": "CHANGE_ME"
}
diff --git a/win_app/diagram.py b/win_app/diagram.py
new file mode 100644
index 0000000..45c1907
--- /dev/null
+++ b/win_app/diagram.py
@@ -0,0 +1,302 @@
+"""The Crossing page's two pictures: the arrangement diagram at the top of Ways in, and the push
+strip in Resistance. Geometry is pages_win's, pure and tested; this file only paints it."""
+
+from __future__ import annotations
+
+from PySide6.QtCore import QPointF, QRectF, QSize, Qt
+from PySide6.QtGui import QColor, QPainter, QPainterPath, QPen
+from PySide6.QtWidgets import QSizePolicy, QWidget
+
+import motion
+import pages_win
+import theme
+import tokens
+
+SCREEN = (120.0, 75.0)
+GAP = 14.0
+PAD = 8.0
+CAP_ROW = 34.0
+LIT = 3.0
+CORNER = 16.0
+
+
+def _colour(name: str, alpha: float = 1.0) -> QColor:
+ colour = QColor(theme.colour(name))
+ colour.setAlphaF(max(0.0, min(1.0, alpha)))
+ return colour
+
+
+def _marks(edge, methods, parts, corner, shortcut) -> dict:
+ """Each mark the diagram can draw, keyed (kind, detail), at 1 when the settings light it."""
+ methods = set(methods)
+ marks = {}
+ for side in pages_win.SIDE_ANGLE:
+ marks[("edge", side)] = 1.0 if "edge" in methods and side == edge else 0.0
+ marks[("track", side)] = 1.0 if "part" in methods and side == edge else 0.0
+ for part in pages_win.PART_SPANS:
+ marks[("part", side, part)] = 1.0 if "part" in methods and side == edge and part in parts else 0.0
+ for name in pages_win.CORNER_NAMES:
+ marks[("corner", name)] = 1.0 if "corner" in methods and name == corner else 0.0
+ marks[("cap",)] = 1.0 if shortcut else 0.0
+ return marks
+
+
+class ArrangementDiagram(QWidget):
+ """This PC's screen with your Mac's beside it on the chosen side, and on this PC's screen,
+ lit, whatever crosses; the shortcut as a key cap underneath."""
+
+ def __init__(self, parent: QWidget | None = None) -> None:
+ super().__init__(parent)
+ self.setAccessibleName("Arrangement")
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+ self._state = None
+ self._angle = pages_win.SIDE_ANGLE["right"]
+ self._marks = _marks("right", (), (), "", False)
+ self._cap_text = ""
+ self.setFixedHeight(self._height())
+
+ def sizeHint(self) -> QSize:
+ return QSize(2 * round(SCREEN[0]) + round(GAP) + 2 * round(PAD), self._height())
+
+ def minimumSizeHint(self) -> QSize:
+ return QSize(2 * round(SCREEN[0]) + round(GAP), self._height())
+
+ def _height(self) -> int:
+ _pc, _mac, pair_h = pages_win.arrangement_rects(100.0, 0.0, self._angle, SCREEN, GAP)
+ return round(PAD + pair_h + PAD + CAP_ROW * self._marks[("cap",)])
+
+ def set_state(self, edge, methods, parts, corner, key_name, style) -> None:
+ state = (edge, tuple(methods), tuple(parts), corner, key_name, style)
+ if state == self._state:
+ return
+ first = self._state is None
+ self._state = state
+ shortcut = "shortcut" in methods
+ if shortcut:
+ self._cap_text = pages_win.trigger_phrase(key_name, style)
+ self.setAccessibleDescription(pages_win.ways_summary(methods, edge, parts, corner, key_name, style))
+ targets = _marks(edge, methods, parts, corner, shortcut)
+ start_marks = dict(self._marks)
+ start_angle = self._angle
+ end_angle = pages_win.turn_to(start_angle, edge)
+ if first:
+ end_angle = pages_win.SIDE_ANGLE[edge]
+
+ def apply(t):
+ self._angle = start_angle + (end_angle - start_angle) * t
+ self._marks = {key: start_marks[key] + (targets[key] - start_marks[key]) * t for key in targets}
+ self.setFixedHeight(self._height())
+ self.update()
+
+ def settle():
+ self._angle = end_angle % 360.0
+ self.update()
+
+ if first:
+ apply(1.0)
+ settle()
+ return
+ motion.animate(self, "arrangement", 0.0, 1.0, apply, settle)
+
+ def paintEvent(self, _event) -> None:
+ painter = QPainter(self)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ pc, mac, pair_h = pages_win.arrangement_rects(self.width(), PAD, self._angle, SCREEN, GAP)
+ radius = tokens.RADIUS["field"]
+ self._screen(painter, QRectF(*mac), "Your Mac", "panel", "edge", "ink_3", radius)
+ self._screen(painter, QRectF(*pc), "This PC", "well", "edge", "ink_2", radius)
+ for key, level in self._marks.items():
+ if level <= 0.001:
+ continue
+ kind = key[0]
+ if kind == "edge":
+ self._segment(painter, pc, key[1], 0.0, 1.0, level, "signal", LIT)
+ elif kind == "track":
+ self._track(painter, pc, key[1], level)
+ elif kind == "part":
+ start, end = pages_win.PART_SPANS[key[2]]
+ self._segment(painter, pc, key[1], start, end, level, "signal", LIT, gap=2.0)
+ elif kind == "corner":
+ self._corner(painter, pc, key[1], level)
+ level = self._marks[("cap",)]
+ if level > 0.001 and self._cap_text:
+ self._cap(painter, PAD + pair_h + PAD, level)
+ painter.end()
+
+ def _screen(self, painter, rect: QRectF, name, fill, line, ink, radius) -> None:
+ painter.setPen(QPen(_colour(line), 1.0))
+ painter.setBrush(_colour(fill))
+ painter.drawRoundedRect(rect.adjusted(0.5, 0.5, -0.5, -0.5), radius, radius)
+ painter.setPen(_colour(ink))
+ painter.setFont(theme.font(tokens.TYPE["small"], 600))
+ painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, name)
+
+ @staticmethod
+ def _segment(painter, rect, side, start, end, level, colour, width, gap=0.0) -> None:
+ # Grows from its middle as it comes in.
+ middle = (start + end) / 2.0
+ half = (end - start) / 2.0 * level
+ x1, y1, x2, y2 = pages_win.side_segment(rect, side, middle - half, middle + half, inset=width / 2.0 + 1.0)
+ if gap and level > 0:
+ if x1 == x2:
+ y1, y2 = y1 + gap, y2 - gap
+ else:
+ x1, x2 = x1 + gap, x2 - gap
+ pen = QPen(_colour(colour, level), width)
+ pen.setCapStyle(Qt.PenCapStyle.RoundCap)
+ painter.setPen(pen)
+ painter.drawLine(QPointF(x1, y1), QPointF(x2, y2))
+
+ def _track(self, painter, rect, side, level) -> None:
+ """Part of the edge: the whole side as a dim track, with a divider between the thirds."""
+ self._segment(painter, rect, side, 0.0, 1.0, level, "off", LIT)
+ pen = QPen(_colour("edge", level), 1.0)
+ painter.setPen(pen)
+ for fraction in (1.0 / 3.0, 2.0 / 3.0):
+ x1, y1, _x2, _y2 = pages_win.side_segment(rect, side, fraction, fraction, inset=LIT / 2.0 + 1.0)
+ if side in ("left", "right"):
+ painter.drawLine(QPointF(x1 - 5, y1), QPointF(x1 + 5, y1))
+ else:
+ painter.drawLine(QPointF(x1, y1 - 5), QPointF(x1, y1 + 5))
+
+ @staticmethod
+ def _corner(painter, rect, corner, level) -> None:
+ size = CORNER * (0.4 + 0.6 * level)
+ x, y, w, h = pages_win.corner_box(rect, corner, size)
+ box = QRectF(x, y, w, h).adjusted(2, 2, -2, -2)
+ painter.setPen(QPen(_colour("signal", level), 1.5))
+ painter.setBrush(_colour("signal", 0.35 * level))
+ painter.drawRoundedRect(box, 2, 2)
+
+ def _cap(self, painter, top, level) -> None:
+ key, _sep, how = self._cap_text.partition(", ")
+ face = theme.mono_font(tokens.TYPE["small"], 700)
+ painter.setFont(face)
+ metrics = painter.fontMetrics()
+ key_w = metrics.horizontalAdvance(key) + 18
+ rest = f", {how}"
+ body = theme.font(tokens.TYPE["note"])
+ painter.setFont(body)
+ rest_w = painter.fontMetrics().horizontalAdvance(rest)
+ total = key_w + 2 + rest_w
+ left = (self.width() - total) / 2.0
+ cap = QRectF(left, top + 2 + (1.0 - level) * 6.0, key_w, 24)
+ painter.setOpacity(level)
+ painter.setPen(QPen(_colour("edge"), 1.0))
+ painter.setBrush(_colour("ground"))
+ painter.drawRoundedRect(cap.adjusted(0.5, 0.5, -0.5, -0.5), tokens.RADIUS["keycap"], tokens.RADIUS["keycap"])
+ painter.setPen(QPen(_colour("edge"), 2.0))
+ painter.drawLine(QPointF(cap.left() + 3, cap.bottom() - 1), QPointF(cap.right() - 3, cap.bottom() - 1))
+ painter.setPen(_colour("signal"))
+ painter.setFont(face)
+ painter.drawText(cap.adjusted(0, 0, 0, -2), Qt.AlignmentFlag.AlignCenter, key)
+ painter.setPen(_colour("ink_2"))
+ painter.setFont(body)
+ painter.drawText(QRectF(cap.right() + 2, cap.top(), rest_w + 4, cap.height()),
+ Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, rest)
+ painter.setOpacity(1.0)
+
+
+class PushStrip(QWidget):
+ """A band of this screen's edge: the edge line, your Mac beyond it, and a `signal` fill from the
+ edge as deep as the resistance, with the pointer at its end. A change slides the fill and the
+ pointer to the new depth, lit bright, and the light then settles."""
+
+ HEIGHT = 44
+ MAC = 64.0
+ SETTLE_MS = 700
+
+ def __init__(self, parent: QWidget | None = None) -> None:
+ super().__init__(parent)
+ self.setFixedHeight(self.HEIGHT)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+ self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ self._value = None
+ self._shown = 0.0
+ self._glow = 0.0
+ self._mac_left = False
+
+ def minimumSizeHint(self) -> QSize:
+ return QSize(160, self.HEIGHT)
+
+ def set_edge(self, edge: str) -> None:
+ mac_left = edge == "left"
+ if mac_left != self._mac_left:
+ self._mac_left = mac_left
+ self.update()
+
+ def set_value(self, value: int) -> None:
+ value = float(value)
+ if value == self._value:
+ return
+ first = self._value is None
+ self._value = value
+ self.setAccessibleDescription(f"{int(value)} px")
+ if first:
+ self._shown = value
+ self.update()
+ return
+ start = self._shown
+
+ def apply(depth):
+ self._shown = depth
+ self.update()
+
+ motion.animate(self, "depth", start, value, apply)
+ if motion.should_animate(self):
+ def glow(level):
+ self._glow = level
+ self.update()
+
+ motion.animate(self, "glow", 1.0, 0.0, glow, duration=self.SETTLE_MS)
+
+ def paintEvent(self, _event) -> None:
+ painter = QPainter(self)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ # Drawn with your Mac on the right; flipped when it is on the left.
+ if self._mac_left:
+ painter.translate(self.width(), 0)
+ painter.scale(-1, 1)
+ band = QRectF(0.5, 0.5, self.width() - 1.0, self.height() - 1.0)
+ radius = tokens.RADIUS["field"]
+ edge_x = band.right() - self.MAC
+ painter.setPen(QPen(_colour("rule"), 1.0))
+ painter.setBrush(_colour("well"))
+ painter.drawRoundedRect(band, radius, radius)
+ mac = QRectF(edge_x, band.top(), self.MAC, band.height())
+ path = QPainterPath()
+ path.addRoundedRect(mac, radius, radius)
+ painter.setPen(Qt.PenStyle.NoPen)
+ painter.setBrush(_colour("panel"))
+ painter.drawPath(path)
+ track = edge_x - band.left() - 14.0
+ depth = pages_win.push_depth(self._shown or 0.0, track)
+ if depth > 0.5:
+ fill = QRectF(edge_x - depth, band.top() + 8, depth, band.height() - 16)
+ painter.setBrush(_colour("signal", 0.28 + 0.42 * self._glow))
+ painter.drawRect(fill)
+ painter.setPen(QPen(_colour("signal" if depth > 0.5 or self._glow else "edge"), 2.0))
+ painter.drawLine(QPointF(edge_x, band.top() + 4), QPointF(edge_x, band.bottom() - 4))
+ tip = QPointF(edge_x - depth - (2.0 if depth > 0.5 else 1.0), band.center().y())
+ self._pointer(painter, tip)
+ painter.setPen(_colour("ink_3"))
+ painter.setFont(theme.font(tokens.TYPE["small"], 600))
+ label = QRectF(edge_x, band.top(), self.MAC, band.height())
+ if self._mac_left:
+ # Text drawn in the flipped frame would read backwards.
+ painter.resetTransform()
+ label = QRectF(self.width() - label.right(), label.top(), label.width(), label.height())
+ painter.drawText(label, Qt.AlignmentFlag.AlignCenter, "Your Mac")
+ painter.end()
+
+ def _pointer(self, painter, tip: QPointF) -> None:
+ # An arrow pointing at the edge, its tip where the push has reached.
+ path = QPainterPath()
+ k = 0.9
+ points = ((0, 0), (-14, -8), (-11, 0), (-14, 8))
+ for index, (x, y) in enumerate(points):
+ (path.lineTo if index else path.moveTo)(tip.x() + x * k, tip.y() + y * k)
+ path.closeSubpath()
+ painter.setPen(QPen(_colour("ground"), 1.0))
+ painter.setBrush(_colour("ink"))
+ painter.drawPath(path)
diff --git a/win_app/edge_glow.py b/win_app/edge_glow.py
index 0454c08..880613f 100644
--- a/win_app/edge_glow.py
+++ b/win_app/edge_glow.py
@@ -12,16 +12,26 @@ the edge, and for the beam a profile along it. `signal` with `glow` is the origi
from __future__ import annotations
+import copy
+import ctypes
import time
from PySide6.QtCore import QRect, QRectF, Qt, QTimer
-from PySide6.QtGui import QColor, QImage, QLinearGradient, QPainter, QPainterPath, QPen
+from PySide6.QtGui import QColor, QCursor, QImage, QLinearGradient, QPainter, QPainterPath, QPen
from PySide6.QtWidgets import QApplication, QSizePolicy, QWidget
+import app_config
+import effects
import return_edge as crossing
+import theme
import tokens
BAND_PX = 44
+# How far a corner's light reaches along each of its two walls.
+CORNER_ARM_PX = 200
+# Over how much of its length a third of the edge fades in and out at each end, rather than stopping
+# dead where the third does.
+TAPER_PX = 72
FLASH_SECONDS = tokens.SPRING["flash_seconds"]
STALE_SECONDS = 0.08
@@ -76,6 +86,8 @@ class GlowState:
self.flash = 0.0
self.finish = 0.0
self.centre = -COMET / 2.0
+ # The Design page's Length: how long the flash and the beam's run-off take, as a multiple.
+ self.pace = 1.0
def restart(self) -> None:
self.centre = -COMET / 2.0
@@ -91,11 +103,11 @@ class GlowState:
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)
+ self.flash = max(0.0, self.flash - elapsed / (FLASH_SECONDS * self.pace))
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)
+ self.centre = min(1.0 + COMET, self.centre + elapsed / (FINISH_TRAVERSE_S * self.pace))
+ self.finish = max(0.0, self.finish - elapsed / (FINISH_SECONDS * self.pace))
else:
self.centre += elapsed / traverse_seconds(self.pressure)
if self.centre > 1.0 + COMET / 2.0:
@@ -103,9 +115,61 @@ class GlowState:
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:
+def system_dark() -> bool:
+ """Apps in dark mode. The overlay cannot see the wallpaper, so this is the best it has."""
+ try:
+ import winreg
+
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize") as key:
+ # The apps' mode, not the taskbar's (SystemUsesLightTheme), which Windows lets differ:
+ # windows are what the effects draw over, and the Mac reads its apps' appearance too.
+ return winreg.QueryValueEx(key, "AppsUseLightTheme")[0] == 0
+ except (ImportError, OSError):
+ return True
+
+
+def part_of_monitor(owner, edge: str, part) -> "crossing.Rect":
+ """`owner` cut down along `edge` to its own third `part`, the thirds PartEdge crosses in
+ (return_edge.display_fraction); all of `owner` for no part."""
+ if part not in crossing.PARTS:
+ return owner
+ index = crossing.PARTS.index(part)
+ if edge in ("left", "right"):
+ low, high = owner.y + owner.height * index // 3, owner.y + owner.height * (index + 1) // 3
+ return crossing.Rect(owner.x, low, owner.width, high - low)
+ low, high = owner.x + owner.width * index // 3, owner.x + owner.width * (index + 1) // 3
+ return crossing.Rect(low, owner.y, high - low, owner.height)
+
+
+def corner_of_monitor(owner, corner: str, arm: int = CORNER_ARM_PX) -> "crossing.Rect":
+ """The square at `corner` of `owner` that a corner's light fills, `arm` a side."""
+ vertical, horizontal = corner.split("_")
+ x = owner.x if horizontal == "left" else owner.x + owner.width - arm
+ y = owner.y if vertical == "top" else owner.y + owner.height - arm
+ return crossing.Rect(x, y, arm, arm)
+
+
+HWND_TOPMOST = -1
+SWP_NOSIZE, SWP_NOMOVE, SWP_NOACTIVATE, SWP_NOOWNERZORDER = 0x0001, 0x0002, 0x0010, 0x0200
+
+
+def keep_on_top(widget: QWidget) -> None:
+ """Puts `widget`'s window back at the top of the topmost windows. The taskbar is topmost too and
+ raises itself whenever it is hovered or clicked, and a push into a corner or along its edge is
+ right over it, so the topmost flag Qt sets once at creation leaves the light under it."""
+ try:
+ ctypes.windll.user32.SetWindowPos(int(widget.winId()), HWND_TOPMOST, 0, 0, 0, 0,
+ SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER)
+ except (AttributeError, OSError):
+ pass
+
+
+def paint(painter: QPainter, rect: QRect, edge: str, style: str, colour: str, state: GlowState, band: float = BAND_PX,
+ dark: bool = False, taper: bool = False) -> 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."""
+ falloff inward from it and, for the beam, the comet's profile along it. `dark` lifts the
+ darkest colours as the crossing effects do on a dark appearance; `taper` fades both ends, for a
+ third of the edge."""
beam = style == "beam"
strength = max(state.pressure * 0.85, state.flash, state.finish if beam else 0.0)
if strength <= 0.0:
@@ -116,7 +180,7 @@ def paint(painter: QPainter, rect: QRect, edge: str, style: str, colour: str, st
painter.translate(rect.topLeft())
local = QRect(0, 0, rect.width(), rect.height())
painter.setOpacity(strength)
- painter.fillRect(local, _colours(colour, along, length))
+ painter.fillRect(local, _colours(colour, along, length, dark))
painter.setOpacity(1.0)
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_DestinationIn)
if beam:
@@ -125,16 +189,56 @@ def paint(painter: QPainter, rect: QRect, edge: str, style: str, colour: str, st
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))))
+ if taper and length > 0:
+ ends = _gradient_along(along, length)
+ fade = min(0.25, TAPER_PX / length)
+ for at, alpha in ((0.0, 0.0), (fade, 1.0), (1.0 - fade, 1.0), (1.0, 0.0)):
+ ends.setColorAt(at, QColor(0, 0, 0, round(255 * alpha)))
+ painter.fillRect(local, ends)
painter.restore()
+def paint_corner(painter: QPainter, rect: QRect, corner: str, style: str, colour: str, state: GlowState,
+ band: float = BAND_PX, dark: bool = False) -> None:
+ """Draws the glow into `corner` of `rect`: the band along both of the corner's walls, brightest
+ where they meet and fading out along each, so it reads as the corner rather than two edges.
+ The beam's comet runs in along one wall and out along the other. Each wall is drawn on a layer
+ of its own, as its masks would otherwise cut the other wall's light."""
+ vertical, horizontal = corner.split("_")
+ ratio = painter.device().devicePixelRatioF() if painter.device() is not None else 1.0
+ for wall in (vertical, horizontal):
+ layer = QImage(rect.size() * ratio, QImage.Format.Format_ARGB32_Premultiplied)
+ layer.setDevicePixelRatio(ratio)
+ layer.fill(Qt.GlobalColor.transparent)
+ local = QRect(0, 0, rect.width(), rect.height())
+ side = copy.copy(state)
+ # Along the L the comet travels 0 to 1: the top or bottom wall from its
+ # far end into the corner over the first half, the other wall out of it over the second.
+ if wall == vertical:
+ side.centre = 2.0 * state.centre if horizontal == "right" else 1.0 - 2.0 * state.centre
+ else:
+ side.centre = 2.0 - 2.0 * state.centre if vertical == "bottom" else 2.0 * state.centre - 1.0
+ layer_painter = QPainter(layer)
+ paint(layer_painter, local, wall, style, colour, side, band, dark)
+ layer_painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_DestinationIn)
+ along = wall in ("left", "right")
+ at_corner = (vertical == "bottom") if along else (horizontal == "right")
+ length = local.height() if along else local.width()
+ fade = _gradient_along(along, length)
+ for at, alpha in ((0.0, 1.0), (0.3, 0.75), (1.0, 0.0)):
+ fade.setColorAt(1.0 - at if at_corner else at, QColor(0, 0, 0, round(255 * alpha)))
+ layer_painter.fillRect(local, fade)
+ layer_painter.end()
+ painter.drawImage(rect.topLeft(), layer)
+
+
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:
+def _colours(colour: str, along: bool, length: int, dark: bool = False) -> QLinearGradient:
gradient = _gradient_along(along, length)
- palette = tokens.PALETTES.get(colour, tokens.PALETTES["signal"])
+ palette = effects.legible(app_config.palette_colours(colour), dark)
if len(palette) == 1:
palette = palette * 2
for index, value in enumerate(palette):
@@ -175,31 +279,39 @@ class EdgeGlow(QWidget):
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
self._edge = "left"
+ self._part = None
self._style = "glow"
self._colour = "signal"
self._state = GlowState()
+ self._dark = True
self._updated_at = 0.0
self._ticked_at = 0.0
self._timer = QTimer(self)
self._timer.setInterval(16)
self._timer.timeout.connect(self._tick)
- def configure(self, style: str, colour: str) -> None:
+ def configure(self, style: str, colour: str, length: str = "normal") -> None:
self._style = style
self._colour = colour
+ self._state.pace = effects.pace(length)
- def set_pressure(self, edge: str, pressure: float, crossed: bool) -> None:
+ def set_pressure(self, edge: str, pressure: float, crossed: bool, part=None) -> None:
+ """`part` is the third of the edge being pushed for Part of the edge, which lights only
+ that third, or the corner being pushed into, which lights that corner; None lights the
+ whole edge."""
now = time.monotonic()
- if edge != self._edge or self.isHidden():
- self._edge = edge
+ if edge != self._edge or part != self._part or self.isHidden():
+ self._edge, self._part = edge, part
self._place()
self._state.push(pressure, crossed)
self._updated_at = now
if self.isHidden():
self._ticked_at = now
+ self._dark = system_dark()
self._state.restart()
self.show()
self._timer.start()
+ keep_on_top(self)
self.update()
def _place(self) -> None:
@@ -207,7 +319,16 @@ class EdgeGlow(QWidget):
if not screens:
return
rects = [crossing.Rect(s.geometry().x(), s.geometry().y(), s.geometry().width(), s.geometry().height()) for s in screens]
- owner = crossing.owning_monitor(rects, self._edge)
+ # The display the pointer is pushing on, as the effects' region takes it: on staggered
+ # displays the outermost one may not be it, and a third of the wrong display would light.
+ cursor = QCursor.pos()
+ owner = next((r for r in rects if r.x <= cursor.x() < r.x + r.width and r.y <= cursor.y() < r.y + r.height),
+ None) or crossing.owning_monitor(rects, self._edge)
+ if self._part in crossing.CORNERS:
+ box = corner_of_monitor(owner, self._part, min(CORNER_ARM_PX, owner.width, owner.height))
+ self.setGeometry(QRect(box.x, box.y, box.width, box.height))
+ return
+ owner = part_of_monitor(owner, self._edge, self._part)
if self._edge == "left":
self.setGeometry(QRect(owner.x, owner.y, BAND_PX, owner.height))
elif self._edge == "right":
@@ -227,11 +348,16 @@ class EdgeGlow(QWidget):
self._timer.stop()
self.hide()
return
+ keep_on_top(self)
self.update()
def paintEvent(self, _event) -> None:
painter = QPainter(self)
- paint(painter, self.rect(), self._edge, self._style, self._colour, self._state)
+ if self._part in crossing.CORNERS:
+ paint_corner(painter, self.rect(), self._part, self._style, self._colour, self._state, dark=self._dark)
+ else:
+ paint(painter, self.rect(), self._edge, self._style, self._colour, self._state, dark=self._dark,
+ taper=self._part in crossing.PARTS)
painter.end()
@@ -263,8 +389,8 @@ class GlowPreview(QWidget):
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"]))
+ ground.setColorAt(0.0, QColor(theme.colour("edge")))
+ ground.setColorAt(1.0, QColor(theme.colour("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.
@@ -273,54 +399,93 @@ class GlowPreview(QWidget):
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)
+ paint(layer_painter, self.rect(), self.edge, self.style, self.colour, self.state, dark=theme.is_dark())
layer_painter.end()
painter.save()
painter.setClipPath(outline)
painter.drawImage(0, 0, layer)
painter.restore()
- painter.setPen(QPen(QColor(tokens.PALETTE["rule"]), 1))
+ painter.setPen(QPen(QColor(theme.colour("rule")), 1))
painter.drawPath(outline)
painter.end()
class PreviewLoop:
- """Plays every preview from one clock, and only while someone can see them."""
+ """Plays Glow and Beam's tiles from one clock: only the one the pointer is over, from the moment
+ that looks like intent, and only while someone can see it. Every other tile holds a still, the
+ push part way in, which a tile that starts playing goes on from."""
+
+ HOLD = 0.7
+ INTENT_S = 0.1
def __init__(self, parent: QWidget) -> None:
self.previews: list = []
+ self.running = False
+ self.hovered = None
+ self._hovered_at = 0.0
self._started_at = None
self._ticked_at = 0.0
self._phase = None
self._timer = QTimer(parent)
+ # Precise: a coarse timer may fire up to 5% either side, which lands frames unevenly.
+ self._timer.setTimerType(Qt.TimerType.PreciseTimer)
self._timer.setInterval(16)
self._timer.timeout.connect(self._tick)
def add(self, preview: GlowPreview) -> None:
self.previews.append(preview)
+ self._hold(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
+ if wanted == self.running:
+ return
+ self.running = wanted
+ self._settle()
+ if wanted:
self._timer.start()
- elif not wanted and self._started_at is not None:
- self._started_at = None
+ else:
self._timer.stop()
- for preview in self.previews:
- preview.state = GlowState()
- preview.update()
+
+ def hover(self, preview) -> None:
+ """`preview`, one of this loop's, plays while the pointer is over it; None stops it."""
+ if preview is self.hovered:
+ return
+ self._settle()
+ self.hovered, self._hovered_at = preview, time.monotonic()
+
+ def playing(self, preview) -> bool:
+ return preview is self.hovered and self._started_at is not None
+
+ def _hold(self, preview: GlowPreview) -> None:
+ preview.state = GlowState()
+ preview.state.push(self.HOLD, False)
+ preview.state.centre = 0.5
+ preview.update()
+
+ def _settle(self) -> None:
+ if self.hovered is not None and self._started_at is not None:
+ self._hold(self.hovered)
+ self._started_at = None
def _tick(self) -> None:
+ preview = self.hovered
now = time.monotonic()
+ if preview is None or now - self._hovered_at < self.INTENT_S:
+ return
+ if not preview.isVisible() or preview.visibleRegion().isEmpty():
+ self._settle()
+ return
+ if self._started_at is None:
+ # Where the script's push reaches the held still's pressure.
+ self._started_at = now - PUSH_S * self.HOLD ** (1 / 1.6)
+ self._ticked_at, self._phase = now, "push"
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()
+ 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/effect_overlay.py b/win_app/effect_overlay.py
new file mode 100644
index 0000000..3baec68
--- /dev/null
+++ b/win_app/effect_overlay.py
@@ -0,0 +1,461 @@
+"""The crossing effects on this PC: effects.Player's frames replayed into QPainter on one
+click-through window, sized each frame to what the effect drew.
+
+effects.py records every effect as operations in desktop points; `replay` turns them into Qt paths,
+brushes and pens. The window is today's EdgeGlow pattern: frameless, translucent, input passes
+through it, a tool window (so no taskbar button and no Alt-Tab entry), above everything, the
+taskbar included, never activated. It repaints at 60Hz only while the Player is busy and hides as soon as it is not.
+
+Any exception from an effect or the replay is logged once with the effect's id and turns the new
+effects off for the rest of the run; the app then falls back to today's glow.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import logging
+import math
+import time
+
+from PySide6.QtCore import QPointF, QRect, QRectF, Qt, QTimer
+from PySide6.QtGui import (
+ QBrush,
+ QColor,
+ QConicalGradient,
+ QCursor,
+ QGuiApplication,
+ QLinearGradient,
+ QPainter,
+ QPainterPath,
+ QPen,
+ QRadialGradient,
+)
+from PySide6.QtWidgets import QWidget
+
+import app_config
+import edge_glow
+import effects
+import return_edge as crossing
+
+LOGGER = logging.getLogger(__name__)
+
+FRAME_MS = 16
+# How long without a pressure update before the push is taken to have stopped and drains on its
+# own clock, as EdgeGlow's does.
+STALE_SECONDS = 0.08
+MARGIN = 2
+# canvas's miterLimit is 10 miter lengths, tip to inner corner; Qt measures from the join point in
+# pen widths, which is half that.
+MITER_LIMIT = 5.0
+
+_CAPS = {"butt": Qt.PenCapStyle.FlatCap, "round": Qt.PenCapStyle.RoundCap, "square": Qt.PenCapStyle.SquareCap}
+_JOINS = {"miter": Qt.PenJoinStyle.MiterJoin, "round": Qt.PenJoinStyle.RoundJoin, "bevel": Qt.PenJoinStyle.BevelJoin}
+_COMPOSITE = {
+ "source-over": QPainter.CompositionMode.CompositionMode_SourceOver,
+ "lighter": QPainter.CompositionMode.CompositionMode_Plus,
+}
+
+
+def qcolour(rgba) -> QColor:
+ r, g, b, a = (min(1.0, max(0.0, float(v))) for v in rgba)
+ return QColor.fromRgbF(r, g, b, a)
+
+
+def qpath(path, rule: str = "nonzero") -> QPainterPath:
+ """A recorded path as a QPainterPath. After a close, canvas carries on from the subpath's start;
+ Qt starts the next subpath at the origin, so a close not followed by a move gets one."""
+ out = QPainterPath()
+ out.setFillRule(Qt.FillRule.OddEvenFill if rule == "evenodd" else Qt.FillRule.WindingFill)
+ start = None
+ closed = False
+ for segment in path:
+ kind = segment[0]
+ if closed and kind != "M" and start is not None:
+ out.moveTo(*start)
+ closed = False
+ if kind == "M":
+ start = (segment[1], segment[2])
+ out.moveTo(*start)
+ elif kind == "L":
+ out.lineTo(segment[1], segment[2])
+ elif kind == "Q":
+ out.quadTo(segment[1], segment[2], segment[3], segment[4])
+ elif kind == "C":
+ out.cubicTo(segment[1], segment[2], segment[3], segment[4], segment[5], segment[6])
+ elif kind == "Z":
+ out.closeSubpath()
+ closed = True
+ return out
+
+
+def _stops(stops, reverse: bool = False):
+ """canvas stops as Qt's: sorted by offset keeping the order they were added, and a stop at
+ the same offset as the one before nudged just past it, since Qt keeps only one stop per offset
+ and canvas draws a hard edge there. `reverse` mirrors them, for the conic's opposite winding."""
+ ordered = [(1.0 - offset if reverse else offset, colour) for offset, colour in stops]
+ if reverse:
+ ordered.reverse()
+ ordered.sort(key=lambda stop: stop[0])
+ out = []
+ for offset, colour in ordered:
+ if out and offset <= out[-1][0]:
+ offset = min(1.0, out[-1][0] + 1e-6)
+ if offset <= out[-1][0]:
+ continue
+ out.append((offset, colour))
+ return out
+
+
+def qgradient(gradient):
+ """A recorded Gradient as a Qt gradient. Qt's two-circle radial takes the end circle first;
+ its conic runs anticlockwise in degrees where canvas's runs clockwise in radians, both from
+ three o'clock, so the angle is negated and the stops reversed."""
+ g = gradient.geometry
+ if gradient.kind == "linear":
+ out = QLinearGradient(g[0], g[1], g[2], g[3])
+ stops = _stops(gradient.stops)
+ elif gradient.kind == "radial":
+ out = QRadialGradient(QPointF(g[3], g[4]), g[5], QPointF(g[0], g[1]), g[2])
+ stops = _stops(gradient.stops)
+ else:
+ out = QConicalGradient(g[1], g[2], -math.degrees(g[0]))
+ stops = _stops(gradient.stops, reverse=True)
+ for offset, colour in stops:
+ out.setColorAt(offset, qcolour(colour))
+ return out
+
+
+def replay(painter, pens) -> None:
+ """Draws each Pen's ops in order, inside its display when it names one. Every op sets its own
+ opacity and composition and puts the painter back afterwards, so nothing leaks from one op to
+ the next. Each Gradient becomes one Qt gradient for the frame, however many ops share it."""
+ made = {}
+ for pen in pens:
+ clip = getattr(pen, "clip", None)
+ if clip is not None:
+ painter.save()
+ painter.setClipRect(QRectF(clip[0], clip[1], clip[2] - clip[0], clip[3] - clip[1]))
+ for op in pen.ops:
+ paint = op[2]
+ if isinstance(paint, effects.Gradient):
+ key = id(paint)
+ if key not in made:
+ made[key] = QBrush(qgradient(paint))
+ brush = made[key]
+ else:
+ brush = QBrush(qcolour(paint))
+ painter.save()
+ painter.setOpacity(op[3])
+ painter.setCompositionMode(_COMPOSITE.get(op[4], _COMPOSITE["source-over"]))
+ if op[0] == "fill":
+ painter.fillPath(qpath(op[1], op[5]), brush)
+ else:
+ stroke = QPen(brush, op[5], Qt.PenStyle.SolidLine, _CAPS.get(op[6], Qt.PenCapStyle.FlatCap),
+ _JOINS.get(op[7], Qt.PenJoinStyle.MiterJoin))
+ stroke.setMiterLimit(MITER_LIMIT)
+ painter.strokePath(qpath(op[1]), stroke)
+ painter.restore()
+ if clip is not None:
+ painter.restore()
+
+
+def union_bounds(pens, pad: float = 0.0):
+ """The box round every Pen's bounds grown by `pad`, never past the display a Pen is clipped to,
+ or None."""
+ boxes = []
+ for pen in pens:
+ if pen.bounds is None:
+ continue
+ b = (pen.bounds[0] - pad, pen.bounds[1] - pad, pen.bounds[2] + pad, pen.bounds[3] + pad)
+ clip = getattr(pen, "clip", None)
+ if clip is not None:
+ b = (max(b[0], clip[0]), max(b[1], clip[1]), min(b[2], clip[2]), min(b[3], clip[3]))
+ boxes.append(b)
+ if not boxes:
+ return None
+ return (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes))
+
+
+def system_reduced_motion() -> bool:
+ """Windows' "Show animations in Windows" switched off."""
+ SPI_GETCLIENTAREAANIMATION = 0x1042
+ value = ctypes.c_int(1)
+ try:
+ if ctypes.windll.user32.SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION, 0, ctypes.byref(value), 0):
+ return not value.value
+ except (AttributeError, OSError):
+ pass
+ return False
+
+
+system_dark = edge_glow.system_dark
+
+
+def desktop_box() -> QRect:
+ """The bounding box of every display, in Qt's logical coordinates."""
+ box = QRect()
+ for screen in QGuiApplication.screens():
+ box = box.united(screen.geometry())
+ return box
+
+
+def logical_point(x: float, y: float) -> QPointF:
+ """A point in Windows' physical desktop pixels, as the receiver and sender place the pointer, in
+ Qt's logical coordinates. Qt keeps each screen's top-left where Windows has it and scales
+ everything else in the screen by its device pixel ratio."""
+ for screen in QGuiApplication.screens():
+ g = screen.geometry()
+ ratio = screen.devicePixelRatio() or 1.0
+ if g.x() <= x < g.x() + g.width() * ratio and g.y() <= y < g.y() + g.height() * ratio:
+ return QPointF(g.x() + (x - g.x()) / ratio, g.y() + (y - g.y()) / ratio)
+ return QPointF(x, y)
+
+
+def corner_region(corner: str, edge: str, rects, origin, pointer) -> dict:
+ """The effect's region for a push into `corner` of the display the pinned `pointer` is on: the
+ corner's own box, as the Mac's engine reports one, relative to the desktop's top-left `origin`."""
+ owner = next((r for r in rects if r.x <= pointer[0] < r.x + r.width and r.y <= pointer[1] < r.y + r.height),
+ None) or crossing.owning_monitor(rects, edge)
+ vertical, horizontal = corner.split("_")
+ size = crossing.CORNER_PX
+ x = owner.x if horizontal == "left" else owner.x + owner.width - size
+ y = owner.y if vertical == "top" else owner.y + owner.height - size
+ return {"kind": "corner", "edge": edge, "corner": corner, "x": float(x - origin[0]), "y": float(y - origin[1]),
+ "w": float(size), "h": float(size)}
+
+
+def edge_region(edge: str, rects, origin, pointer=None, part=None) -> dict:
+ """The effect's region for a push through `edge` of this PC: the whole of that edge on the
+ display the pinned `pointer` is on, a point deep, relative to the desktop's top-left `origin`.
+ That is not always the display at the outermost edge: a shorter display's exposed edge crosses
+ too. With no pointer on any display, the one that owns the edge. For Part of the edge, `part`
+ cuts it to the third being pushed."""
+ owner = next((r for r in rects if pointer is not None and r.x <= pointer[0] < r.x + r.width
+ and r.y <= pointer[1] < r.y + r.height), None) or crossing.owning_monitor(rects, edge)
+ owner = edge_glow.part_of_monitor(owner, edge, part)
+ ox, oy = origin
+ if edge in ("left", "right"):
+ x = owner.x if edge == "left" else owner.x + owner.width - 1
+ return {"kind": "edge", "edge": edge, "x": float(x - ox), "y": float(owner.y - oy), "w": 1.0, "h": float(owner.height)}
+ y = owner.y if edge == "top" else owner.y + owner.height - 1
+ return {"kind": "edge", "edge": edge, "x": float(owner.x - ox), "y": float(y - oy), "w": float(owner.width), "h": 1.0}
+
+
+class EffectOverlay(QWidget):
+ """One window for every effect on this PC, departures and arrivals alike."""
+
+ def __init__(self, on_failure=None) -> None:
+ super().__init__(
+ None,
+ Qt.WindowType.Tool
+ | Qt.WindowType.FramelessWindowHint
+ | Qt.WindowType.WindowStaysOnTopHint
+ | Qt.WindowType.WindowTransparentForInput
+ | Qt.WindowType.WindowDoesNotAcceptFocus,
+ )
+ self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
+ self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
+ self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ self.failed = False
+ self._on_failure = on_failure
+ self.player = effects.Player()
+ self._style = None
+ self._fx = None
+ self._palette = ()
+ self._reduced = False
+ self._dark = True
+ self._desk = QRect()
+ self._displays = []
+ self._pens = []
+ self._offset = (0.0, 0.0)
+ self._push = None
+ self._ticked_at = 0.0
+ self._timer = QTimer(self)
+ self._timer.setInterval(FRAME_MS)
+ self._timer.timeout.connect(self._tick)
+
+ def configure(self, style: str, colour: str, length: str = "normal") -> None:
+ if style != self._style:
+ self._style = style
+ self.player = effects.Player()
+ self._push = None
+ try:
+ # Glow and Beam are EdgeGlow's and have no arrival: all this window plays for them
+ # is a switch, by the locator.
+ self._fx = effects.effect(style) if style in effects.EFFECT_IDS else effects.LOCATOR
+ except Exception:
+ self._fx = None
+ self._fail("loading")
+ return
+ # Read each time, like the colours; a Player already playing keeps the pace it started with.
+ if not self.player.busy:
+ self.player.pace = effects.pace(length)
+ try:
+ self._palette = app_config.palette_colours(colour)
+ except Exception:
+ self._fail("loading its colours")
+
+ def push(self, edge: str, pressure: float, crossed: bool, cursor: QPointF | None = None, part=None) -> None:
+ """A pressure update from either link, pushing out through `edge` of this PC, or only its
+ third `part` for Part of the edge, or into the corner `part` names."""
+ if self.failed or self._fx is None:
+ return
+ now = time.monotonic()
+ started = self._start(now)
+ cursor = QCursor.pos() if cursor is None else cursor
+ at = self._relative(cursor.x(), cursor.y())
+ push = self._push
+ if push is None or push["edge"] != edge or push["part"] != part or push["crossed"]:
+ rects = [crossing.Rect(s.geometry().x(), s.geometry().y(), s.geometry().width(), s.geometry().height())
+ for s in QGuiApplication.screens()]
+ origin, pointer = (self._desk.x(), self._desk.y()), (cursor.x(), cursor.y())
+ if part in crossing.CORNERS:
+ region = corner_region(part, edge, rects, origin, pointer)
+ else:
+ region = edge_region(edge, rects, origin, pointer, part)
+ push = self._push = {"edge": edge, "part": part, "region": region, "index": 0, "crossed": False}
+ display, at = self._display(at)
+ push.update(pressure=max(0.0, min(1.0, pressure)), at=at, updated=now, display=display)
+ index = min(3, int(push["pressure"] * 4.0))
+ tick = index if index > push["index"] else None
+ push["index"] = index
+ self.player.push(now, push["region"]["kind"], push["region"], at, 1.0 if crossed else push["pressure"], tick, display)
+ if crossed:
+ push["crossed"] = True
+ self.player.cross(now)
+ if started:
+ self._tick()
+
+ def arrive(self, method: str, edge: str, point: QPointF) -> None:
+ """The pointer landed at `point` (logical desktop coordinates) on `edge` of this PC."""
+ if self.failed or self._fx is None:
+ return
+ now = time.monotonic()
+ started = self._start(now)
+ display, at = self._display(self._relative(point.x(), point.y()))
+ self.player.arrive(now, method, at, edge, display)
+ if started:
+ self._tick()
+
+ def crossed_in(self) -> None:
+ """A crossing landed here that EdgeGlow draws, not this window: a switch waiting to play
+ gives way to it."""
+ if not self.failed:
+ self.player.crossed_in(time.monotonic())
+
+ def switched(self, point: QPointF, choice: str = "match") -> None:
+ """Input came to this PC without a crossing and the pointer is at `point` (logical desktop
+ coordinates); `choice` is the Design page's shortcut_arrival_style."""
+ if self.failed or self._fx is None:
+ return
+ try:
+ fx = effects.switch_effect(choice, self._style)
+ except Exception:
+ self._fail("loading what a switch plays")
+ return
+ now = time.monotonic()
+ self._start(now)
+ display, at = self._display(self._relative(point.x(), point.y()))
+ edge = effects.nearest_edge(at[0] - display[0], at[1] - display[1], display[2], display[3])
+ self.player.switched(now, at, edge, fx, display)
+
+ def stop(self) -> None:
+ self._timer.stop()
+ self.player = effects.Player()
+ self._push = None
+ self._pens = []
+ self.hide()
+
+ def _start(self, now: float) -> bool:
+ """Starts the frame timer if it is not running, and says whether it did: the event that
+ starts it draws the first frame itself rather than a timer interval later."""
+ if self._timer.isActive():
+ return False
+ # Read once per effect rather than every frame.
+ self._reduced = system_reduced_motion()
+ self._dark = system_dark()
+ self._desk = desktop_box()
+ self._displays = [(g.x() - self._desk.x(), g.y() - self._desk.y(), g.width(), g.height())
+ for g in (screen.geometry() for screen in QGuiApplication.screens())]
+ self._ticked_at = now
+ self._timer.start()
+ return True
+
+ def _display(self, at):
+ """The display `at` is on, as (x, y, w, h) relative to the desktop, and `at` kept on it."""
+ return effects.display_for(at, self._displays or [(0.0, 0.0, float(self._desk.width()), float(self._desk.height()))])
+
+ def _relative(self, x: float, y: float):
+ return (min(max(0.0, x - self._desk.x()), self._desk.width() - 1.0),
+ min(max(0.0, y - self._desk.y()), self._desk.height() - 1.0))
+
+ def _drain(self, now: float) -> None:
+ """Pressure only arrives while the pointer pushes, so once it stops the push drains on its
+ own clock, as the model's does, and the Player is fed the falling value every frame."""
+ push = self._push
+ elapsed, self._ticked_at = now - self._ticked_at, now
+ if push is None or push["crossed"]:
+ return
+ if now - push["updated"] > STALE_SECONDS:
+ push["pressure"] = max(0.0, push["pressure"] - elapsed / crossing.DECAY_SECONDS)
+ push["index"] = min(push["index"], int(push["pressure"] * 4.0))
+ self.player.push(now, push["region"]["kind"], push["region"], push["at"], push["pressure"], display=push["display"])
+ if push["pressure"] <= 0.0:
+ self.player.release()
+ self._push = None
+
+ def _tick(self) -> None:
+ now = time.monotonic()
+ try:
+ self._drain(now)
+ pens = self.player.frames(now, self._fx, (float(self._desk.width()), float(self._desk.height()), "windows"),
+ self._palette, self._reduced, self._dark, None)
+ except Exception:
+ self._fail("drawing")
+ return
+ box = union_bounds(pens, MARGIN)
+ if box is None:
+ self._pens = []
+ if not self.player.busy:
+ self._timer.stop()
+ self.hide()
+ return
+ x0 = max(0, math.floor(box[0]))
+ y0 = max(0, math.floor(box[1]))
+ x1 = min(self._desk.width(), math.ceil(box[2]))
+ y1 = min(self._desk.height(), math.ceil(box[3]))
+ if x1 <= x0 or y1 <= y0:
+ self._pens = []
+ self.hide()
+ return
+ self._pens = pens
+ self._offset = (float(x0), float(y0))
+ frame = QRect(self._desk.x() + x0, self._desk.y() + y0, x1 - x0, y1 - y0)
+ if frame != self.geometry():
+ self.setGeometry(frame)
+ if self.isHidden():
+ self.show()
+ edge_glow.keep_on_top(self)
+ self.update()
+
+ def paintEvent(self, _event) -> None:
+ if not self._pens:
+ return
+ painter = QPainter(self)
+ try:
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ painter.translate(-self._offset[0], -self._offset[1])
+ replay(painter, self._pens)
+ except Exception:
+ painter.end()
+ self._fail("replaying")
+ return
+ painter.end()
+
+ def _fail(self, doing: str) -> None:
+ if not self.failed:
+ LOGGER.exception("Crossing effect %s failed while %s; the new effects are off until Beamer restarts", self._style, doing)
+ self.failed = True
+ self.stop()
+ if self._on_failure is not None:
+ self._on_failure()
diff --git a/win_app/effect_previews.py b/win_app/effect_previews.py
new file mode 100644
index 0000000..3fedddd
--- /dev/null
+++ b/win_app/effect_previews.py
@@ -0,0 +1,306 @@
+"""The Design page's pictures of the crossing styles: a still for each tile at the place the page's
+Show at chooses, played on from while the pointer is over it, drawn from effects.preview_scene, the
+same loop the Mac's Design page plays, replayed by the overlay's own `replay`."""
+
+from __future__ import annotations
+
+import logging
+import time
+
+from PySide6.QtCore import QEvent, QObject, QRectF, Qt, QTimer
+from PySide6.QtGui import QColor, QImage, QPainter, QPainterPath, QPen
+from PySide6.QtWidgets import QSizePolicy, QWidget
+
+import edge_glow
+import effects
+import motion
+import theme
+import tokens
+from effect_overlay import replay, system_reduced_motion
+
+LOGGER = logging.getLogger(__name__)
+
+# Part way into the push, where every style shows.
+STILL_AT_S = 1.7
+# One effect layer, reused while the preview's size holds, rather than a new image every frame.
+_LAYERS = {}
+STILL_HEIGHT = 56
+# A tile shows where the style plays rather than the whole scene too small to see: this many scene
+# points across, centred on the crossing at each place, the corner framed with room above the screens.
+STILL_VIEW_W = 480.0
+STILL_CENTRE = {"edge": (effects.PREVIEW_SCREEN[0] + effects.PREVIEW_GAP / 2.0, effects.PREVIEW_SCREEN[1] * 0.45),
+ "corner": (effects.PREVIEW_SCREEN[0] + effects.PREVIEW_GAP / 2.0, 40.0)}
+# A switch plays round a still pointer on one screen: its tile shows that part of the scene part-way
+# through, and the stage the screen less the empty strips above and below, as the Mac's do.
+SWITCH_STILL_AT_S = 0.6
+SWITCH_STILL_VIEW = QRectF(248.0, 138.0, 240.0, 120.0)
+_SCREEN_NAMES = {"mac": "MAC", "windows": "PC"}
+FRAME_MS = 16
+# A pointer passing over tiles on its way elsewhere leaves the tiles it crosses still.
+HOVER_INTENT_S = 0.1
+
+
+def frame_timer(parent: QObject, tick) -> QTimer:
+ """A timer for one frame of animation. Precise: a coarse timer may fire up to 5% either side,
+ which on Windows' clock lands frames unevenly."""
+ timer = QTimer(parent)
+ timer.setTimerType(Qt.TimerType.PreciseTimer)
+ timer.setInterval(FRAME_MS)
+ timer.timeout.connect(tick)
+ return timer
+
+
+def on_screen(widget: QWidget) -> bool:
+ """Whether any of `widget` can be seen: shown in a window that is not minimised, and not
+ scrolled out of its page."""
+ return widget.isVisible() and not widget.window().isMinimized() and not widget.visibleRegion().isEmpty()
+
+
+def _pointer_path(size: float) -> QPainterPath:
+ """An arrow pointer `size` tall with its tip at the origin."""
+ k = size / 16.0
+ path = QPainterPath()
+ for index, (x, y) in enumerate(((0, 0), (0, 14), (3.6, 10.8), (6.2, 16), (8.4, 15), (5.9, 9.9), (10.4, 9.9))):
+ (path.lineTo if index else path.moveTo)(x * k, y * k)
+ path.closeSubpath()
+ return path
+
+
+def paint_scene(painter: QPainter, rect: QRectF, view: QRectF, scene: dict, pointer_size: float, labels: bool) -> None:
+ """Draws the `view` part of a preview_scene (in scene points) into `rect`, scaled to fit and
+ centred: the screens, then the pens, then the pointer, then the notch, the order the scene
+ asks for."""
+ scale = min(rect.width() / view.width(), rect.height() / view.height())
+ width, height = view.width(), view.height()
+ left = rect.x() + (rect.width() - width * scale) / 2.0
+ top = rect.y() + (rect.height() - height * scale) / 2.0
+ painter.save()
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ painter.setClipRect(QRectF(left, top, width * scale, height * scale))
+ painter.translate(left, top)
+ painter.scale(scale, scale)
+ painter.translate(-view.x(), -view.y())
+ radius = tokens.RADIUS["field"] / scale
+ for x, y, w, h, os_name in scene["screens"]:
+ painter.setPen(QPen(QColor(theme.colour("rule")), 1.0 / scale))
+ painter.setBrush(QColor(theme.colour("well")))
+ painter.drawRoundedRect(QRectF(x, y, w, h), radius, radius)
+ if labels:
+ painter.setPen(QColor(theme.colour("ink_3")))
+ painter.setFont(theme.eyebrow_font())
+ # Bottom left of the part of the screen in view, which no crossing in the loop comes near.
+ shown = QRectF(x, y, w, h).intersected(view)
+ painter.save()
+ painter.translate(shown.x(), shown.y())
+ painter.scale(1.0 / scale, 1.0 / scale)
+ corner = QRectF(10, shown.height() * scale - 26, shown.width() * scale - 20, 18)
+ painter.drawText(corner, Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignLeft, _SCREEN_NAMES.get(os_name, ""))
+ painter.restore()
+ # The effects draw on their own layer, as the overlay does over the desktop, so "lighter"
+ # adds to the effect's own light rather than to the screens drawn under it.
+ if not scene["pens"]:
+ _paint_pointer_and_notch(painter, scene, scale, pointer_size)
+ painter.restore()
+ return
+ ratio = painter.device().devicePixelRatioF() if painter.device() is not None else 1.0
+ size = (int(width * scale * ratio) + 1, int(height * scale * ratio) + 1, ratio)
+ layer = _LAYERS.get(size)
+ if layer is None:
+ _LAYERS.clear()
+ layer = _LAYERS[size] = QImage(size[0], size[1], QImage.Format.Format_ARGB32_Premultiplied)
+ layer.setDevicePixelRatio(ratio)
+ layer.fill(Qt.GlobalColor.transparent)
+ layer_painter = QPainter(layer)
+ layer_painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ layer_painter.scale(scale, scale)
+ layer_painter.translate(-view.x(), -view.y())
+ try:
+ replay(layer_painter, scene["pens"])
+ finally:
+ layer_painter.end()
+ painter.save()
+ painter.resetTransform()
+ painter.translate(left, top)
+ painter.drawImage(0, 0, layer)
+ painter.restore()
+ _paint_pointer_and_notch(painter, scene, scale, pointer_size)
+ painter.restore()
+
+
+def _paint_pointer_and_notch(painter: QPainter, scene: dict, scale: float, pointer_size: float) -> None:
+ if scene["pointer"] is not None:
+ px, py, _os = scene["pointer"]
+ painter.save()
+ painter.translate(px, py)
+ painter.scale(1.0 / scale, 1.0 / scale)
+ arrow = _pointer_path(pointer_size)
+ painter.setPen(QPen(QColor("#000000"), 1.0))
+ painter.setBrush(QColor("#ffffff"))
+ painter.drawPath(arrow)
+ painter.restore()
+ if scene["notch"] is not None:
+ nx, ny, nw, nh, nr = scene["notch"]
+ notch = QPainterPath()
+ notch.addRoundedRect(QRectF(nx, ny - nr, nw, nh + nr), nr, nr)
+ painter.setPen(Qt.PenStyle.NoPen)
+ painter.setBrush(QColor("#000000"))
+ painter.drawPath(notch)
+
+
+class EffectStill(QWidget):
+ """A tile's picture: its effect part-way through a push, in the chosen colour. While TileHover
+ has it playing it draws each frame on from that still instead of its cached image."""
+
+ STILL_AT = STILL_AT_S
+
+ def __init__(self, effect_id: str, palette, parent: QWidget | None = None) -> None:
+ super().__init__(parent)
+ self.effect_id = effect_id
+ self.palette = tuple(palette)
+ self.place = "edge"
+ self.pace = 1.0
+ self._image = None
+ self.playing_since = None
+ self.setFixedHeight(STILL_HEIGHT)
+ self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+ self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+
+ def set_palette(self, palette) -> None:
+ if tuple(palette) != self.palette:
+ self.palette = tuple(palette)
+ self._image = None
+ self.update()
+
+ def set_place(self, place: str) -> None:
+ if place != self.place:
+ self.place = place
+ self._image = None
+ self.update()
+
+ def set_pace(self, pace: float) -> None:
+ if pace != self.pace:
+ self.pace = pace
+ self._image = None
+ self.update()
+
+ def refresh_colours(self) -> None:
+ # A cached image, not a live paint: without this an appearance switch leaves it showing
+ # the old palette until something else invalidates the cache.
+ self._image = None
+
+ def paintEvent(self, _event) -> None:
+ if self.playing_since is not None:
+ painter = QPainter(self)
+ try:
+ self._paint_still(painter, self.STILL_AT + max(0.0, time.monotonic() - self.playing_since))
+ except Exception:
+ LOGGER.exception("Could not draw crossing effect %s", self.effect_id)
+ self.playing_since = None
+ painter.end()
+ return
+ ratio = self.devicePixelRatioF()
+ size = self.size() * ratio
+ if self._image is None or self._image.size() != size:
+ self._image = QImage(size, QImage.Format.Format_ARGB32_Premultiplied)
+ self._image.setDevicePixelRatio(ratio)
+ self._image.fill(Qt.GlobalColor.transparent)
+ image_painter = QPainter(self._image)
+ try:
+ self._paint_still(image_painter, self.STILL_AT)
+ except Exception:
+ LOGGER.exception("Could not draw the still of crossing effect %s", self.effect_id)
+ finally:
+ image_painter.end()
+ painter = QPainter(self)
+ painter.drawImage(0, 0, self._image)
+ painter.end()
+
+ def _paint_still(self, painter: QPainter, t: float) -> None:
+ scene = effects.preview_scene(effects.preview_effect(self.effect_id), t, self.place, self.palette,
+ system_reduced_motion(), theme.is_dark(), self.pace)
+ width = STILL_VIEW_W
+ view_h = min(effects.PREVIEW_SCREEN[1], width * self.height() / max(1, self.width()))
+ centre = STILL_CENTRE[self.place]
+ view = QRectF(centre[0] - width / 2.0, centre[1] - view_h / 2.0, width, view_h)
+ paint_scene(painter, QRectF(self.rect()), view, scene, 10.0, labels=False)
+
+
+class SwitchStill(EffectStill):
+ """A Switch tile's picture: what a switch plays for `choice` beside the crossing style, round a
+ still pointer, part-way through."""
+
+ STILL_AT = SWITCH_STILL_AT_S
+
+ def __init__(self, choice: str, crossing_style: str, palette, parent: QWidget | None = None) -> None:
+ super().__init__(choice, palette, parent)
+ self.crossing_style = crossing_style
+
+ def set_crossing_style(self, style: str) -> None:
+ if style != self.crossing_style:
+ self.crossing_style = style
+ self._image = None
+ self.update()
+
+ def _paint_still(self, painter: QPainter, t: float) -> None:
+ fx = effects.switch_effect(self.effect_id, self.crossing_style)
+ scene = effects.preview_switch_scene(fx, t, self.palette, "windows", system_reduced_motion(), theme.is_dark(),
+ self.pace)
+ paint_scene(painter, QRectF(self.rect()), SWITCH_STILL_VIEW, scene, 10.0, labels=False)
+
+
+class TileHover(QObject):
+ """The one tile under the pointer plays its animation and settles back to its still when the
+ pointer leaves; under Reduce Motion it keeps its still. An effect's still plays on from the
+ frame it shows, and Glow and Beam from their held push, so a tile starts without a jump."""
+
+ def __init__(self, loop: edge_glow.PreviewLoop, parent: QObject | None = None) -> None:
+ super().__init__(parent)
+ self.loop = loop
+ self._pictures: dict = {}
+ self.current = None
+ self._timer = frame_timer(self, self._tick)
+
+ def track(self, tile: QWidget, picture: QWidget) -> None:
+ self._pictures[tile] = picture
+ tile.installEventFilter(self)
+
+ def eventFilter(self, watched, event) -> bool:
+ kind = event.type()
+ if kind == QEvent.Type.Enter and watched in self._pictures:
+ self.enter(self._pictures[watched])
+ elif kind == QEvent.Type.Leave and watched in self._pictures and self._pictures[watched] is self.current:
+ self.stop()
+ return False
+
+ def enter(self, picture: QWidget) -> None:
+ if picture is self.current:
+ return
+ self.stop()
+ self.current = picture
+ if system_reduced_motion():
+ return
+ if isinstance(picture, edge_glow.GlowPreview):
+ self.loop.hover(picture)
+ return
+ picture.playing_since = time.monotonic() + HOVER_INTENT_S
+ self._timer.start()
+
+ def stop(self) -> None:
+ picture, self.current = self.current, None
+ self._timer.stop()
+ if picture is None:
+ return
+ played = (self.loop.hovered is picture and self.loop.playing(picture)) or (
+ getattr(picture, "playing_since", None) is not None and time.monotonic() > picture.playing_since
+ )
+ shot = motion.snapshot(picture) if played else None
+ if isinstance(picture, edge_glow.GlowPreview):
+ self.loop.hover(None)
+ else:
+ picture.playing_since = None
+ picture.update()
+ motion.fade_from(picture, shot)
+
+ def _tick(self) -> None:
+ if self.current is not None and on_screen(self.current):
+ self.current.update()
diff --git a/win_app/effects.py b/win_app/effects.py
new file mode 100644
index 0000000..ab4ac74
--- /dev/null
+++ b/win_app/effects.py
@@ -0,0 +1,959 @@
+"""Crossing effects: the departure and arrival animations, drawn once here and replayed natively by
+each app.
+
+An effect draws into a Pen, which offers the part of the HTML canvas API the original designs were
+written against, so each fx_*.py module is a line-for-line port of its design's animation logic. The
+Pen does not draw: it records operations in screen points with every transform already applied, arcs
+already turned into curves, and colours already parsed. The Mac replays them into Core Graphics and
+Windows into QPainter, both checked against the original animation for fidelity.
+
+`Player` owns the timing both apps share: pressure, the quarter ticks, breakthrough, the departure
+finishing and the arrival playing out, so an effect looks the same on both machines.
+
+This file and every fx_*.py are byte-identical in mac_app/ and win_app/; test_shared_copies checks.
+"""
+
+from __future__ import annotations
+
+import colorsys
+import functools
+import math
+import re
+from types import SimpleNamespace
+
+TAU = math.pi * 2.0
+IDENTITY = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)
+
+
+def hash_n(n):
+ """The harness's stable pseudo-random number in [0, 1) for integer `n`; the designs' only
+ randomness, so every frame is a function of its state."""
+ x = math.sin(n * 127.1 + 311.7) * 43758.5453
+ return x - math.floor(x)
+
+
+def clamp(v, a=0.0, b=1.0):
+ return max(a, min(b, v))
+
+
+def lerp(a, b, u):
+ return a + (b - a) * u
+
+
+def ease_out(u):
+ return 1.0 - (1.0 - u) ** 3
+
+
+def ease_in_out(u):
+ return 2.0 * u * u if u < 0.5 else 1.0 - ((-2.0 * u + 2.0) ** 2) / 2.0
+
+
+_NAMED = {"black": (0.0, 0.0, 0.0, 1.0), "white": (1.0, 1.0, 1.0, 1.0), "transparent": (0.0, 0.0, 0.0, 0.0)}
+_RGB = re.compile(r"rgba?\(\s*([-\d.]+)\s*,\s*([-\d.]+)\s*,\s*([-\d.]+)\s*(?:,\s*([-\d.]+)\s*)?\)$")
+
+
+def parse_colour(value):
+ """A CSS colour as the designs write them, "#rgb", "#rrggbb", "#rrggbbaa", "rgb()" or "rgba()",
+ or an (r, g, b[, a]) tuple of 0 to 1 floats, as (r, g, b, a) floats. Anything else is black, as
+ a canvas would leave the previous style; a design that relies on that is a bug to fix there."""
+ if isinstance(value, tuple):
+ return value if len(value) == 4 else (value[0], value[1], value[2], 1.0)
+ return _parse_text(str(value))
+
+
[email protected]_cache(maxsize=4096)
+def _parse_text(value):
+ """parse_colour for text. Cached: the heavier effects parse the same few colours a hundred
+ times a frame."""
+ text = value.strip().lower()
+ if text in _NAMED:
+ return _NAMED[text]
+ if text.startswith("#"):
+ digits = text[1:]
+ if len(digits) in (3, 4):
+ digits = "".join(c * 2 for c in digits)
+ if len(digits) in (6, 8):
+ parts = [int(digits[i:i + 2], 16) / 255.0 for i in range(0, len(digits), 2)]
+ return tuple(parts) if len(parts) == 4 else (parts[0], parts[1], parts[2], 1.0)
+ match = _RGB.match(text)
+ if match:
+ r, g, b = (clamp(float(match.group(i)) / 255.0) for i in (1, 2, 3))
+ a = clamp(float(match.group(4))) if match.group(4) is not None else 1.0
+ return (r, g, b, a)
+ return (0.0, 0.0, 0.0, 1.0)
+
+
+# The least HLS lightness a colour is drawn at on a dark wallpaper, and the most on a light one
+# by the effects in LIGHT_AS_GIVEN.
+DARK_FLOOR = 0.45
+LIGHT_CEILING = 0.6
+
+
+def legible(palette, dark, fx=None):
+ """`palette` as `fx` draws it. On a dark wallpaper every colour darker than DARK_FLOOR is
+ lifted to it, keeping its hue and saturation: the Ink packs lead with near-black inks and Ember
+ ends on a deep red, and effects that drew those, additively on dark most of all, all but
+ vanished. On a light one the effects that draw a pack's colours as given have every colour
+ lighter than LIGHT_CEILING brought down to it, as Mono, Pearl and Contrast all but vanished."""
+ if dark:
+ low, high = DARK_FLOOR, 1.0
+ elif getattr(fx, "id", None) in LIGHT_AS_GIVEN:
+ low, high = 0.0, LIGHT_CEILING
+ else:
+ return list(palette)
+ out = []
+ for colour in palette:
+ r, g, b, _a = parse_colour(colour)
+ h, lightness, sat = colorsys.rgb_to_hls(r, g, b)
+ if not low <= lightness <= high:
+ r, g, b = colorsys.hls_to_rgb(h, clamp(lightness, low, high), sat)
+ out.append("#%02x%02x%02x" % tuple(int(round(v * 255)) for v in (r, g, b)))
+ return out
+
+
+def _apply(m, x, y):
+ a, b, c, d, e, f = m
+ return (a * x + c * y + e, b * x + d * y + f)
+
+
+def _multiply(m, n):
+ """m then n in canvas order: the result maps a point through n first, then m."""
+ a, b, c, d, e, f = m
+ a2, b2, c2, d2, e2, f2 = n
+ return (a * a2 + c * b2, b * a2 + d * b2, a * c2 + c * d2, b * c2 + d * d2, a * e2 + c * f2 + e, b * e2 + d * f2 + f)
+
+
+def _scale_of(m):
+ return math.sqrt(abs(m[0] * m[3] - m[1] * m[2]))
+
+
+class Gradient:
+ """A canvas gradient, its geometry already in screen points. `kind` is "linear" (x0, y0, x1, y1),
+ "radial" (x0, y0, r0, x1, y1, r1) or "conic" (start angle, cx, cy); stops are (offset, rgba)."""
+
+ def __init__(self, kind, geometry):
+ self.kind = kind
+ self.geometry = geometry
+ self.stops = []
+
+ def addColorStop(self, offset, colour):
+ self.stops.append((clamp(float(offset)), parse_colour(colour)))
+
+
+class Pen:
+ """The recording canvas. Style properties keep their canvas names so ports stay line-for-line.
+
+ `ops` is a list of ("fill", path, paint, alpha, composite, rule) and
+ ("stroke", path, paint, alpha, composite, width, cap, join), where path is a list of
+ ("M", x, y), ("L", x, y), ("Q", cx, cy, x, y), ("C", c1x, c1y, c2x, c2y, x, y) and ("Z",),
+ and paint is an rgba tuple or a Gradient. `bounds` is a conservative box round everything drawn."""
+
+ def __init__(self):
+ self.ops = []
+ self.bounds = None
+ self._stack = []
+ self._path = []
+ self._start = None
+ self._current = None
+ self.fillStyle = "#000"
+ self.strokeStyle = "#000"
+ self.lineWidth = 1.0
+ self.lineCap = "butt"
+ self.lineJoin = "miter"
+ self.globalAlpha = 1.0
+ self.globalCompositeOperation = "source-over"
+ self._matrix = IDENTITY
+ # (left, top, right, bottom) of the display this Pen is for, which the replay clips to.
+ self.clip = None
+
+ def save(self):
+ self._stack.append((self.fillStyle, self.strokeStyle, self.lineWidth, self.lineCap, self.lineJoin,
+ self.globalAlpha, self.globalCompositeOperation, self._matrix))
+
+ def restore(self):
+ if self._stack:
+ (self.fillStyle, self.strokeStyle, self.lineWidth, self.lineCap, self.lineJoin,
+ self.globalAlpha, self.globalCompositeOperation, self._matrix) = self._stack.pop()
+
+ def transform(self, a, b, c, d, e, f):
+ self._matrix = _multiply(self._matrix, (a, b, c, d, e, f))
+
+ def setTransform(self, a, b, c, d, e, f):
+ self._matrix = (a, b, c, d, e, f)
+
+ def translate(self, x, y):
+ self.transform(1, 0, 0, 1, x, y)
+
+ def scale(self, x, y):
+ self.transform(x, 0, 0, y, 0, 0)
+
+ def rotate(self, angle):
+ cos, sin = math.cos(angle), math.sin(angle)
+ self.transform(cos, sin, -sin, cos, 0, 0)
+
+ def beginPath(self):
+ self._path = []
+ self._start = None
+ self._current = None
+
+ def moveTo(self, x, y):
+ p = _apply(self._matrix, x, y)
+ self._path.append(("M",) + p)
+ self._start = self._current = p
+
+ def lineTo(self, x, y):
+ if self._current is None:
+ self.moveTo(x, y)
+ return
+ p = _apply(self._matrix, x, y)
+ self._path.append(("L",) + p)
+ self._current = p
+
+ def quadraticCurveTo(self, cx, cy, x, y):
+ if self._current is None:
+ self.moveTo(cx, cy)
+ c = _apply(self._matrix, cx, cy)
+ p = _apply(self._matrix, x, y)
+ self._path.append(("Q",) + c + p)
+ self._current = p
+
+ def bezierCurveTo(self, c1x, c1y, c2x, c2y, x, y):
+ if self._current is None:
+ self.moveTo(c1x, c1y)
+ c1 = _apply(self._matrix, c1x, c1y)
+ c2 = _apply(self._matrix, c2x, c2y)
+ p = _apply(self._matrix, x, y)
+ self._path.append(("C",) + c1 + c2 + p)
+ self._current = p
+
+ def closePath(self):
+ if self._current is not None:
+ self._path.append(("Z",))
+ self._current = self._start
+
+ def rect(self, x, y, w, h):
+ self.moveTo(x, y)
+ self.lineTo(x + w, y)
+ self.lineTo(x + w, y + h)
+ self.lineTo(x, y + h)
+ self.closePath()
+ self.moveTo(x, y)
+
+ def arc(self, x, y, r, a0, a1, anticlockwise=False):
+ """Canvas arc semantics: a line from the current point to the arc's start, then the sweep,
+ drawn as cubic curves in user space so any transform, mirrors included, stays exact."""
+ r = abs(r)
+ if anticlockwise:
+ sweep = -TAU if a0 - a1 >= TAU else -((a0 - a1) % TAU)
+ else:
+ sweep = TAU if a1 - a0 >= TAU else (a1 - a0) % TAU
+ sx, sy = x + r * math.cos(a0), y + r * math.sin(a0)
+ if self._current is None:
+ self.moveTo(sx, sy)
+ else:
+ self.lineTo(sx, sy)
+ if sweep == 0.0 or r == 0.0:
+ return
+ # An eighth of a turn per curve: a quarter's error, 0.03% of the radius at its midpoint,
+ # moved the antialiasing of thin stroked rings visibly against a native arc.
+ pieces = max(1, int(math.ceil(abs(sweep) / (math.pi / 4.0) - 1e-9)))
+ step = sweep / pieces
+ k = 4.0 / 3.0 * math.tan(step / 4.0)
+ angle = a0
+ for _ in range(pieces):
+ end = angle + step
+ c0, s0, c1, s1 = math.cos(angle), math.sin(angle), math.cos(end), math.sin(end)
+ self.bezierCurveTo(x + r * (c0 - k * s0), y + r * (s0 + k * c0),
+ x + r * (c1 + k * s1), y + r * (s1 - k * c1),
+ x + r * c1, y + r * s1)
+ angle = end
+
+ def createLinearGradient(self, x0, y0, x1, y1):
+ return Gradient("linear", _apply(self._matrix, x0, y0) + _apply(self._matrix, x1, y1))
+
+ def createRadialGradient(self, x0, y0, r0, x1, y1, r1):
+ k = _scale_of(self._matrix)
+ return Gradient("radial", _apply(self._matrix, x0, y0) + (r0 * k,) + _apply(self._matrix, x1, y1) + (r1 * k,))
+
+ def createConicGradient(self, angle, x, y):
+ m = self._matrix
+ return Gradient("conic", (angle + math.atan2(m[1], m[0]),) + _apply(m, x, y))
+
+ def fill(self, rule="nonzero"):
+ if self._path:
+ self._record(("fill", list(self._path), self._paint(self.fillStyle), clamp(self.globalAlpha),
+ self.globalCompositeOperation, rule), 0.0)
+
+ def stroke(self):
+ if self._path and self.lineWidth > 0:
+ width = self.lineWidth * _scale_of(self._matrix)
+ self._record(("stroke", list(self._path), self._paint(self.strokeStyle), clamp(self.globalAlpha),
+ self.globalCompositeOperation, width, self.lineCap, self.lineJoin), width)
+
+ def fillRect(self, x, y, w, h):
+ saved = (self._path, self._start, self._current)
+ self.beginPath()
+ self.rect(x, y, w, h)
+ self.fill()
+ self._path, self._start, self._current = saved
+
+ @staticmethod
+ def _paint(style):
+ return style if isinstance(style, Gradient) else parse_colour(style)
+
+ def _record(self, op, width):
+ if op[3] <= 0.0:
+ return
+ paint = op[2]
+ if not isinstance(paint, Gradient) and paint[3] <= 0.0:
+ return
+ xs, ys = [], []
+ for segment in op[1]:
+ xs.extend(segment[1::2])
+ ys.extend(segment[2::2])
+ if not xs:
+ return
+ pad = width / 2.0 + (width * 5.0 if op[0] == "stroke" and op[7] == "miter" else 0.0) + 2.0
+ box = (min(xs) - pad, min(ys) - pad, max(xs) + pad, max(ys) + pad)
+ if self.bounds is None:
+ self.bounds = box
+ else:
+ b = self.bounds
+ self.bounds = (min(b[0], box[0]), min(b[1], box[1]), max(b[2], box[2]), max(b[3], box[3]))
+ self.ops.append(op)
+
+
+def round_rect(pen, x, y, w, h, r):
+ """The harness's BeamerDraw.roundRect: a new path, not a fill."""
+ pen.beginPath()
+ pen.moveTo(x + r, y)
+ _arc_to(pen, x + w, y, x + w, y + h, r)
+ _arc_to(pen, x + w, y + h, x, y + h, r)
+ _arc_to(pen, x, y + h, x, y, r)
+ _arc_to(pen, x, y, x + w, y, r)
+ pen.closePath()
+
+
+def _arc_to(pen, x1, y1, x2, y2, r):
+ """canvas arcTo from the pen's current point, in user space. Only round_rect uses it, whose
+ corners are always right angles, so the tangent points are r along each side."""
+ m = pen._matrix
+ inverse = _invert(m)
+ x0, y0 = _apply(inverse, *pen._current)
+ d1 = math.hypot(x1 - x0, y1 - y0) or 1.0
+ d2 = math.hypot(x2 - x1, y2 - y1) or 1.0
+ ax, ay = x1 - (x1 - x0) / d1 * r, y1 - (y1 - y0) / d1 * r
+ bx, by = x1 + (x2 - x1) / d2 * r, y1 + (y2 - y1) / d2 * r
+ pen.lineTo(ax, ay)
+ k = 0.5522847498
+ pen.bezierCurveTo(ax + (x1 - ax) * k, ay + (y1 - ay) * k, bx + (x1 - bx) * k, by + (y1 - by) * k, bx, by)
+
+
+def _invert(m):
+ a, b, c, d, e, f = m
+ det = a * d - b * c or 1.0
+ return (d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det)
+
+
+def point(x, y):
+ return SimpleNamespace(x=float(x), y=float(y))
+
+
+def state(screen_w, screen_h, os_name, method, palette, *, reduced=False, dark=True, notch=None, **fields):
+ """The `s` an effect reads, with the harness's field names. Departure passes region, point,
+ along (the fraction along the edge), pressure, tick (the last quarter tick, or None) and since
+ (seconds since breakthrough); arrival passes point, edge and since (seconds since landing)."""
+ s = SimpleNamespace(
+ screen=SimpleNamespace(w=float(screen_w), h=float(screen_h), os=os_name),
+ method=method, palette=list(palette), reduced=bool(reduced), scale=1.0, dark=bool(dark),
+ hash=hash_n, memo={},
+ )
+ if notch is not None:
+ s.notch = SimpleNamespace(**notch)
+ for key, value in fields.items():
+ setattr(s, key, value)
+ return s
+
+
+def nearest_edge(x, y, w, h):
+ """The screen edge closest to (x, y). A switch arrival is oriented by it: every effect reads
+ `s.edge`, and the ones that would draw at the edge itself look for method "switch" instead."""
+ return min((("left", x), ("right", w - x), ("top", y), ("bottom", h - y)), key=lambda pair: pair[1])[0]
+
+
+def display_for(at, displays):
+ """The display in `displays`, each (x, y, w, h), that holds the point `at`, else the nearest,
+ and `at` moved onto it: a point on no display is where the OS puts the pointer, on the nearest."""
+ x, y = at
+
+ def gap(rect):
+ rx, ry, rw, rh = rect
+ return math.hypot(max(rx - x, 0.0, x - (rx + rw - 1.0)), max(ry - y, 0.0, y - (ry + rh - 1.0)))
+
+ rx, ry, rw, rh = (float(v) for v in min(displays, key=gap))
+ return (rx, ry, rw, rh), (min(max(float(x), rx), rx + rw - 1.0), min(max(float(y), ry), ry + rh - 1.0))
+
+
+class Effect:
+ def __init__(self, id, name, intensity, blurb, depart, arrive, depart_seconds, arrive_seconds):
+ self.id = id
+ self.name = name
+ self.intensity = intensity
+ self.blurb = blurb
+ self.depart = depart
+ self.arrive = arrive
+ self.depart_seconds = min(0.8, float(depart_seconds))
+ self.arrive_seconds = min(0.8, float(arrive_seconds))
+
+
+# Every direction built, in the order the Design pages list them: each direction's quiet, medium
+# and showpiece effect, and its three colour packs. Ids are the settings values, so never rename one.
+ALL_DIRECTIONS = (
+ ("fx_membrane", "Membrane", ("skin", "film", "rupture"), ("oil_slick", "soap_bubble", "pearl")),
+ ("fx_sparks", "Sparks", ("flint", "filings", "discharge"), ("ember", "forge", "sparkler_gold")),
+ ("fx_instrument", "Instrument", ("rule", "gauge", "rangefinder"), ("phosphor", "sodium", "contrast")),
+ ("fx_ink", "Ink", ("capillary", "viscous_drop", "sumi_bloom"), ("indigo_ink", "matcha", "terracotta")),
+ ("fx_warp", "Warp", ("light_slit", "hyperdrive", "wormhole"), ("neon", "vaporwave", "cyber")),
+)
+# Directions kept in the code but offered nowhere: not on the Design pages, not as a setting. A
+# setting that chose one of their effects or packs becomes its stand-in when it is read, and a
+# switch that played one plays whatever the crossing plays.
+HIDDEN = ("fx_ink", "fx_warp")
+STAND_INS = {"capillary": "glow", "viscous_drop": "glow", "sumi_bloom": "glow",
+ "indigo_ink": "colourful", "matcha": "colourful", "terracotta": "colourful",
+ "light_slit": "beam", "hyperdrive": "glow", "wormhole": "glow",
+ "neon": "colourful", "vaporwave": "colourful", "cyber": "colourful"}
+DIRECTIONS = tuple(direction for direction in ALL_DIRECTIONS if direction[0] not in HIDDEN)
+EFFECT_IDS = tuple(effect for _module, _name, effects, _packs in DIRECTIONS for effect in effects)
+# The effects whose designs draw a pack's colours as given on a light wallpaper; the others shade
+# them for light themselves.
+LIGHT_AS_GIVEN = tuple(effect for module, _name, effects, _packs in ALL_DIRECTIONS if module in ("fx_ink", "fx_warp")
+ for effect in effects)
+PACK_IDS = tuple(pack for _module, _name, _effects, packs in DIRECTIONS for pack in packs)
+
+_loaded = None
+
+
+def _load():
+ """Imports the fx_* modules on first use, hidden ones included; each has EFFECTS (Effect list)
+ and PACKS (dict of id to (name, colours)), in ALL_DIRECTIONS order."""
+ global _loaded
+ if _loaded is None:
+ import importlib
+ effects, packs = {}, {}
+ for module_name, _name, effect_ids, pack_ids in ALL_DIRECTIONS:
+ module = importlib.import_module(module_name)
+ by_id = {effect.id: effect for effect in module.EFFECTS}
+ for effect_id in effect_ids:
+ effects[effect_id] = by_id[effect_id]
+ for pack_id in pack_ids:
+ packs[pack_id] = module.PACKS[pack_id]
+ _loaded = (effects, packs)
+ return _loaded
+
+
+def effect(effect_id):
+ return _load()[0].get(effect_id)
+
+
+def _locator_arrive(pen, s):
+ """Glow and Beam have no arrival, so a switch into this machine shows where the pointer is with
+ one ring in the chosen colours closing onto its tip: 220pt across to 32pt in 0.45s, decelerating,
+ thickening as it closes, then a soft glow at the tip and gone by 0.72s. A dark halo under the
+ colour keeps it legible on a light wallpaper. Reduce motion keeps the size fixed: two still
+ rings fading in and out."""
+ t = s.since
+ x, y = s.point.x, s.point.y
+ colours = s.palette or ["#5fd4f4"]
+ if s.reduced:
+ a = clamp(t / 0.1) * (1.0 - clamp((t - 0.35) / 0.35))
+ rings = ((16.0, 3.0, a), (30.0, 2.0, 0.55 * a))
+ else:
+ # A cubic ease-out: a quintic closed the ring within 0.15s, too fast for the eye to follow in.
+ k = ease_out(clamp(t / 0.45))
+ a = clamp(t / 0.08) * (1.0 - clamp((t - 0.52) / 0.2))
+ rings = ((lerp(110.0, 16.0, k), lerp(2.0, 3.0, k), a),)
+ if t > 0.38:
+ bloom = clamp((t - 0.38) / 0.12) * (1.0 - clamp((t - 0.5) / 0.22))
+ glow = pen.createRadialGradient(x, y, 0.0, x, y, 26.0)
+ r, g, b, _a = parse_colour(colours[0])
+ glow.addColorStop(0.0, (r, g, b, 0.45 * bloom))
+ glow.addColorStop(1.0, (r, g, b, 0.0))
+ pen.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ pen.fillStyle = glow
+ pen.beginPath()
+ pen.arc(x, y, 26.0, 0.0, TAU)
+ pen.fill()
+ pen.globalCompositeOperation = "source-over"
+ pen.lineJoin = "round"
+ for radius, width, alpha in rings:
+ if alpha <= 0.0:
+ continue
+ pen.globalAlpha = alpha
+ pen.beginPath()
+ pen.arc(x, y, radius, 0.0, TAU)
+ pen.strokeStyle = "rgba(0,0,0,0.3)" if s.dark else "rgba(0,0,0,0.5)"
+ pen.lineWidth = width + 3.0
+ pen.stroke()
+ if len(colours) == 1:
+ pen.strokeStyle = colours[0]
+ else:
+ ring = pen.createConicGradient(-math.pi / 2.0, x, y)
+ for index, colour in enumerate(list(colours) + [colours[0]]):
+ ring.addColorStop(index / len(colours), colour)
+ pen.strokeStyle = ring
+ pen.lineWidth = width
+ pen.stroke()
+ pen.globalAlpha = 1.0
+
+
+# What a switch plays when the chosen style is Glow or Beam, which have no arrival of their own.
+LOCATOR = Effect("locator", "Ring", "quiet", "A ring in the chosen colours closes onto the pointer.",
+ lambda pen, s: None, _locator_arrive, 0.0, 0.72)
+
+
+# Glow and Beam as the Design pages' large previews draw them, in the same scene as the effects. On
+# screen each app draws them with its own glow window, which these follow: a band along the edge,
+# deepening with the push and flashing through at breakthrough, or a thin line with a comet running
+# along it that runs off the end; in a corner, the band along both walls, brightest where they meet.
+CLASSIC_BAND = 44.0
+CLASSIC_ARM = 200.0
+CLASSIC_FLASH_S = 0.35
+CLASSIC_FINISH_S = 0.6
+_CLASSIC_COMET = 0.3
+_CLASSIC_STOPS = 24
+_CLASSIC_LAYERS = 10
+
+
+def _palette_at(palette, u):
+ colours = [parse_colour(c) for c in (palette or ["#5fd4f4"])]
+ if len(colours) == 1:
+ return colours[0]
+ at = clamp(u) * (len(colours) - 1)
+ i = min(len(colours) - 2, int(at))
+ a, b = colours[i], colours[i + 1]
+ k = at - i
+ return tuple(lerp(a[n], b[n], k) for n in range(4))
+
+
+def _classic_wall(pen, s, beam, x, y, length, inward, horizontal, strength, depth, alpha_at):
+ """One wall's light: `length` along from (x, y), horizontally or not, falling off over `depth`
+ in the direction `inward` (+1 or -1). One gradient along the wall carries the palette and how lit
+ each point is; canvas has no mask to cut it with a falloff inward, so it is stacked in layers of
+ shrinking depth, which add up to the falloff."""
+ along = pen.createLinearGradient(x, y, x + length, y) if horizontal else pen.createLinearGradient(x, y, x, y + length)
+ for i in range(_CLASSIC_STOPS + 1):
+ u = i / _CLASSIC_STOPS
+ r, g, b, _a = _palette_at(s.palette, u)
+ along.addColorStop(u, (r, g, b, clamp(strength * alpha_at(u))))
+ pen.fillStyle = along
+ # The beam is a thin line with a short glow behind it; the glow a band that falls off evenly.
+ profile = ((0.05, 0.75), (0.16, 0.3), (0.45, 0.12)) if beam else tuple(((k + 1) / _CLASSIC_LAYERS, 1.0 / _CLASSIC_LAYERS)
+ for k in range(_CLASSIC_LAYERS))
+ for reach, alpha in profile:
+ d = depth * reach
+ pen.globalAlpha = alpha
+ if horizontal:
+ pen.fillRect(x, y if inward > 0 else y - d, length, d)
+ else:
+ pen.fillRect(x if inward > 0 else x - d, y, d, length)
+ pen.globalAlpha = 1.0
+
+
+def _comet(position, centre, flash):
+ base = max(0.2, min(1.0, flash))
+ reach = max(0.0, 1.0 - abs(position - centre) / (_CLASSIC_COMET / 2.0))
+ return base + (1.0 - base) * reach * reach
+
+
+def _classic_depart(beam):
+ def depart(pen, s):
+ since = getattr(s, "since", None)
+ pressure = 0.0 if since is not None else s.pressure
+ flash = 0.0 if since is None else max(0.0, 1.0 - since / CLASSIC_FLASH_S)
+ finish = 0.0 if since is None else max(0.0, 1.0 - since / CLASSIC_FINISH_S)
+ strength = max(pressure * 0.85, flash, finish if beam else 0.0)
+ if strength <= 0.0:
+ return
+ depth = CLASSIC_BAND if beam else CLASSIC_BAND * (0.35 + 0.65 * max(pressure, flash))
+ # The comet sweeps as the push builds, then runs off the far end after breakthrough.
+ centre = -0.15 + 1.1 * pressure if since is None else 0.95 + (1.0 + _CLASSIC_COMET) * (1.0 - finish)
+ lit = (lambda u: _comet(u, centre, flash)) if beam else (lambda u: 1.0)
+ r = s.region
+ w, h = s.screen.w, s.screen.h
+ pen.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ if r.kind == "corner":
+ vertical, horizontal = getattr(r, "corner", "top_right").split("_")
+ arm = min(CLASSIC_ARM, w, h)
+ right, bottom = horizontal == "right", vertical == "bottom"
+ fade = lambda d: max(0.0, 1.0 - d) ** 1.4
+ # The comet runs in along the top or bottom wall and out along the side.
+ wall_y = h if bottom else 0.0
+ x0 = w - arm if right else 0.0
+ along_h = (lambda u: fade(1.0 - u) * (_comet(0.5 * u, centre, flash) if beam else 1.0)) if right else \
+ (lambda u: fade(u) * (_comet(0.5 * (1.0 - u), centre, flash) if beam else 1.0))
+ _classic_wall(pen, s, beam, x0, wall_y, arm, -1 if bottom else 1, True, strength, depth, along_h)
+ wall_x = w if right else 0.0
+ y0 = h - arm if bottom else 0.0
+ along_v = (lambda u: fade(1.0 - u) * (_comet(1.0 - 0.5 * u, centre, flash) if beam else 1.0)) if bottom else \
+ (lambda u: fade(u) * (_comet(0.5 + 0.5 * u, centre, flash) if beam else 1.0))
+ _classic_wall(pen, s, beam, wall_x, y0, arm, -1 if right else 1, False, strength, depth, along_v)
+ elif r.kind == "notch":
+ # At the notch Glow and Beam do not draw: the Mac's notch style plays there instead.
+ pass
+ elif r.edge in ("left", "right"):
+ x = r.x if r.edge == "left" else r.x + r.w
+ _classic_wall(pen, s, beam, x, r.y, r.h, 1 if r.edge == "left" else -1, False, strength, depth, lit)
+ else:
+ y = r.y if r.edge == "top" else r.y + r.h
+ _classic_wall(pen, s, beam, r.x, y, r.w, 1 if r.edge == "top" else -1, True, strength, depth, lit)
+ pen.globalCompositeOperation = "source-over"
+ return depart
+
+
+CLASSIC = {
+ "glow": Effect("glow", "Glow", "classic", "A band of light that deepens the harder you push.",
+ _classic_depart(False), lambda pen, s: None, CLASSIC_FLASH_S, 0.0),
+ "beam": Effect("beam", "Beam", "classic", "A thin line with a comet of light running along it.",
+ _classic_depart(True), lambda pen, s: None, CLASSIC_FINISH_S, 0.0),
+}
+
+
+def preview_effect(style):
+ """The Effect the Design pages' previews play for `style`: one of the effects, or Glow and Beam
+ as CLASSIC draws them. None for anything else."""
+ return CLASSIC.get(style) or (effect(style) if style in EFFECT_IDS else None)
+
+
+# What a switch into a machine may play, the Design pages' own choice for it: whatever the crossing
+# style plays ("match", which is the ring for Glow and Beam), the ring, or any one effect.
+SWITCH_STYLES = ("match", "locator") + EFFECT_IDS
+
+
+def offered(style, colour, switch):
+ """A saved crossing style, colour and switch style, each hidden one swapped for its stand-in."""
+ hidden = {effect for module, _name, effects, _packs in ALL_DIRECTIONS if module in HIDDEN for effect in effects}
+ return STAND_INS.get(style, style), STAND_INS.get(colour, colour), "match" if switch in hidden else switch
+
+
+def switch_style_groups():
+ """The Design pages' choices for SWITCH_STYLES, as (group title or None, ((value, name), ...)),
+ the effects grouped by direction as the style tiles are. Only the first group when the effects
+ cannot load; the overlay has already said why."""
+ groups = [(None, (("match", "Same as crossing"), ("locator", "Ring")))]
+ try:
+ found = [(title, tuple((effect_id, effect(effect_id).name) for effect_id in effect_ids))
+ for _module, title, effect_ids, _packs in DIRECTIONS]
+ except Exception:
+ return groups
+ return groups + found
+
+
+def switch_effect(choice, crossing_style):
+ """The Effect a switch plays for the `choice` setting beside the crossing's `crossing_style`."""
+ style = crossing_style if choice == "match" else choice
+ return effect(style) if style in EFFECT_IDS else LOCATOR
+
+
+def pack(pack_id):
+ """(name, colours) for a pack id, or None."""
+ return _load()[1].get(pack_id)
+
+
+def draw(effect_obj, kind, s, origin=(0.0, 0.0)):
+ """One frame of `kind` ("depart" or "arrive") into a new Pen, or None when it draws nothing.
+ `origin` shifts everything drawn, for a scene holding more than one screen. A failing effect
+ raises; the caller logs it once and turns the effects off for the run."""
+ limit = effect_obj.depart_seconds if kind == "depart" else effect_obj.arrive_seconds
+ since = getattr(s, "since", None)
+ if since is not None and since > limit + 0.05:
+ return None
+ if kind == "depart" and since is None and s.pressure <= 0.0:
+ return None
+ pen = Pen()
+ if origin != (0.0, 0.0):
+ pen.translate(*origin)
+ (effect_obj.depart if kind == "depart" else effect_obj.arrive)(pen, s)
+ if kind == "depart" and since is None and s.pressure < PUSH_FADE:
+ # Several designs' reduced-motion pushes draw at a floor opacity however light the push, so
+ # the first touch and the drain to nothing each popped by that floor.
+ k = s.pressure / PUSH_FADE
+ pen.ops = [op[:3] + (op[3] * k,) + op[4:] for op in pen.ops]
+ return pen if pen.ops else None
+
+
+# The pressure below which a push fades in and out as a whole.
+PUSH_FADE = 0.1
+
+
+PREVIEW_SCREEN = (800.0, 450.0)
+PREVIEW_GAP = 40.0
+PREVIEW_NOTCH = {"x": 307.5, "y": 0.0, "w": 185.0, "h": 32.0, "r": 10.0}
+PREVIEW_LOOP_S = 4.4
+_P_GLIDE, _P_PUSH, _P_CROSS, _P_REST = 0.4, 0.6, 2.2, 3.4
+
+
+def preview_size(method):
+ """The preview scene's size in its own points: two screens side by side for an edge or a
+ corner, stacked with the PC above for the notch. The Design pages scale it to fit."""
+ w, h = PREVIEW_SCREEN
+ if method == "switch":
+ return (w, h)
+ return (w, h * 2 + PREVIEW_GAP) if method == "notch" else (w * 2 + PREVIEW_GAP, h)
+
+
+def preview_scene(fx, t, method, palette, reduced=False, dark=True, pace=1.0):
+ """The Design pages' loop, identical on both apps: the pointer glides to the Mac's boundary,
+ pushes through with three ticks, lands on the PC, and rests. Returns dict(screens=[(x, y, w,
+ h, os)], notch=(x, y, w, h, r) or None, pointer=(x, y, os) or None, pens=[Pen]) for time `t`
+ seconds; the caller draws the screens, then the pens, then the pointer, then the notch."""
+ t = t % PREVIEW_LOOP_S
+ w, h = PREVIEW_SCREEN
+ if method == "notch":
+ pc_origin, mac_origin = (0.0, 0.0), (0.0, h + PREVIEW_GAP)
+ region = {"kind": "notch", "edge": "top", "x": PREVIEW_NOTCH["x"], "y": 0.0, "w": PREVIEW_NOTCH["w"], "h": 1.0}
+ at, start = (w / 2.0, 0.0), (w / 2.0 - 90.0, 220.0)
+ land, land_edge, inside = (w / 2.0 + 10.0, h - 2.0), "bottom", (w / 2.0 + 40.0, h - 140.0)
+ notch = PREVIEW_NOTCH
+ else:
+ mac_origin, pc_origin = (0.0, 0.0), (w + PREVIEW_GAP, 0.0)
+ if method == "corner":
+ region = {"kind": "corner", "edge": "right", "corner": "top_right", "x": w - 8.0, "y": 0.0, "w": 8.0, "h": 8.0}
+ at, start, land, inside = (w - 1.0, 0.0), (w - 220.0, 160.0), (2.0, 4.0), (200.0, 140.0)
+ else:
+ region = {"kind": "edge", "edge": "right", "x": w - 1.0, "y": 0.0, "w": 1.0, "h": h}
+ at, start, land, inside = (w - 1.0, h * 0.45), (w - 260.0, h * 0.55), (2.0, h * 0.45), (240.0, h * 0.5)
+ land_edge, notch = "left", None
+ scene = {
+ "screens": [mac_origin + (w, h, "mac"), pc_origin + (w, h, "windows")],
+ "notch": None if notch is None else (mac_origin[0] + notch["x"], mac_origin[1], notch["w"], notch["h"], notch["r"]),
+ "pointer": None,
+ "pens": [],
+ }
+ common = dict(reduced=reduced, dark=dark)
+ palette = legible(palette, dark, fx)
+ mac_notch = notch if method == "notch" else None
+ if t < _P_CROSS:
+ if t < _P_GLIDE:
+ u = ease_in_out(t / _P_GLIDE)
+ p = (lerp(start[0], at[0], u), lerp(start[1], at[1], u))
+ else:
+ p = at
+ scene["pointer"] = (mac_origin[0] + p[0], mac_origin[1] + p[1], "mac")
+ if t >= _P_PUSH:
+ u = (t - _P_PUSH) / (_P_CROSS - _P_PUSH)
+ pressure = clamp(0.5 - 0.5 * math.cos(math.pi * u))
+ index = min(3, int(pressure * 4.0))
+ tick = None
+ if index:
+ crossed_at = _P_PUSH + (_P_CROSS - _P_PUSH) * math.acos(1.0 - 2.0 * index / 4.0) / math.pi
+ tick = SimpleNamespace(index=index, age=t - crossed_at)
+ s = state(w, h, "mac", method, palette, notch=mac_notch, region=SimpleNamespace(**region),
+ point=point(*at), along=at[1] / h if region["edge"] == "right" else at[0] / w,
+ pressure=pressure, tick=tick, since=None, **common)
+ pen = draw(fx, "depart", s, mac_origin)
+ if pen is not None:
+ scene["pens"].append(pen)
+ return scene
+ since = (t - _P_CROSS) / pace
+ s = state(w, h, "mac", method, palette, notch=mac_notch, region=SimpleNamespace(**region), point=point(*at),
+ along=0.5, pressure=0.0, tick=None, since=since, **common)
+ pen = draw(fx, "depart", s, mac_origin)
+ if pen is not None:
+ scene["pens"].append(pen)
+ s = state(w, h, "windows", method, palette, point=point(*land), edge=land_edge, since=since, **common)
+ pen = draw(fx, "arrive", s, pc_origin)
+ if pen is not None:
+ scene["pens"].append(pen)
+ u = ease_in_out(clamp((t - _P_CROSS - 0.1) / (_P_REST - _P_CROSS - 0.1)))
+ p = (lerp(land[0], inside[0], u), lerp(land[1], inside[1], u))
+ scene["pointer"] = (pc_origin[0] + p[0], pc_origin[1] + p[1], "windows")
+ return scene
+
+
+# How long a switch arrival waits for a crossing arrival that would replace it. Both come in over
+# the LAN within a few milliseconds of each other.
+SWITCH_SETTLE_S = 0.12
+
+
+SWITCH_LOOP_S = 2.0
+_S_START = 0.35
+
+
+def preview_switch_scene(fx, t, palette, os_name="mac", reduced=False, dark=True, pace=1.0):
+ """The Design pages' loop for what a switch plays, in preview_scene's shape: one screen, the
+ pointer still near its middle, and `fx`'s switch arrival round it every SWITCH_LOOP_S."""
+ t = t % SWITCH_LOOP_S
+ w, h = PREVIEW_SCREEN
+ at = (w * 0.46, h * 0.44)
+ scene = {"screens": [(0.0, 0.0, w, h, os_name)], "notch": None, "pointer": (at[0], at[1], os_name), "pens": []}
+ since = (t - _S_START) / pace
+ if since >= 0.0:
+ s = state(w, h, os_name, "switch", legible(palette, dark, fx), reduced=reduced, dark=dark, point=point(*at),
+ edge=nearest_edge(at[0], at[1], w, h), since=since)
+ pen = draw(fx, "arrive", s)
+ if pen is not None:
+ scene["pens"].append(pen)
+ return scene
+
+
+# The Design pages' Length: how long an effect takes to play through once the pointer crosses, and
+# to land, as a multiple of its own timing. The push itself follows the hand, so it has no pace.
+LENGTHS = (("short", "Short"), ("normal", "Normal"), ("long", "Long"))
+PACES = {"short": 0.75, "normal": 1.0, "long": 1.5}
+
+
+def pace(length):
+ return PACES.get(length, 1.0)
+
+
+class Player:
+ """The timeline of one machine's effects, fed the same events the glow is fed today.
+
+ `push` while pressure builds against a boundary, `cross` when it gives, `arrive` when the
+ pointer lands on this machine by a crossing, `switched` when input arrives any other way, then
+ `frames(now)` returns the Pens to draw, or an empty list once everything has played out. Both a
+ departure (finishing after a cross) and an arrival can be in flight at once. Coordinates are
+ points relative to the desktop's top-left corner.
+
+ Every event may name its `display`, (x, y, w, h) in the same coordinates: the effect then plays
+ on that display alone, as the designs were drawn for one screen, and its Pen is clipped to it.
+ Without one it plays on the whole `screen` given to `frames`."""
+
+ def __init__(self, pace=1.0):
+ self.depart = None
+ self.arrival = None
+ self.crossed_at = None
+ # How long everything after the push takes, as a multiple of each effect's own timing.
+ self.pace = pace
+
+ def push(self, now, method, region, at, pressure, tick_index=None, display=None):
+ """`region` is dict(kind, edge, corner?, x, y, w, h); `at` is (x, y) of the pinned pointer.
+ `tick_index` is the quarter just passed (1 to 3), if one was."""
+ d = self.depart
+ if d is None or d["crossed_at"] is not None:
+ d = self.depart = {"method": method, "tick": None, "crossed_at": None, "display": None}
+ # A push that goes on without naming its display, as a drain between events does, stays
+ # on the one it started on.
+ d.update(region=dict(region), at=at, pressure=clamp(pressure), method=method,
+ display=d["display"] if display is None else display)
+ if tick_index:
+ d["tick"] = (int(tick_index), now)
+
+ def cross(self, now):
+ if self.depart is not None:
+ self.depart.update(crossed_at=now, pressure=0.0)
+
+ def release(self):
+ """The push stopped short: pressure is already draining through `push` calls, so this
+ only forgets a departure that has drained to nothing."""
+ if self.depart is not None and self.depart["crossed_at"] is None and self.depart["pressure"] <= 0.0:
+ self.depart = None
+
+ def arrive(self, now, method, at, edge, display=None):
+ """A crossing landed the pointer here. It replaces a switch arrival still waiting to start."""
+ self.arrival = {"method": method, "at": at, "edge": edge, "started": now, "switch": False, "display": display}
+ self.crossed_at = now
+
+ def crossed_in(self, now):
+ """A crossing landed the pointer here and something else draws it, as Glow and Beam do: a
+ switch arrival gives way to it all the same."""
+ if self.arrival is not None and self.arrival["switch"]:
+ self.arrival = None
+ self.crossed_at = now
+
+ def switched(self, now, at, edge, fx=None, display=None):
+ """Input came here by the shortcut, a menu or a switch rather than a crossing. It starts
+ SWITCH_SETTLE_S later and gives way to a crossing in that time: one machine's crossing can
+ send this machine's own input home over one link while its pointer lands here over the
+ other, and only the crossing should show. `fx` is what it plays when that is not the
+ effect `frames` is given, which the Design pages let differ from the crossing's."""
+ if self.crossed_at is not None and now - self.crossed_at < SWITCH_SETTLE_S:
+ return
+ self.arrival = {"method": "switch", "at": at, "edge": edge, "started": now + SWITCH_SETTLE_S, "switch": True,
+ "fx": fx, "display": display}
+
+ def frames(self, now, fx, screen, palette, reduced, dark, notch=None):
+ """Pens for this frame. `screen` is (w, h, os name); `notch` the Mac's dict(x, y, w, h, r)."""
+ pens = []
+ w, h, os_name = screen
+ d = self.depart
+ if d is not None:
+ since = None if d["crossed_at"] is None else (now - d["crossed_at"]) / self.pace
+ if since is not None and since > fx.depart_seconds + 0.05:
+ self.depart = None
+ elif since is not None or d["pressure"] > 0.0:
+ frame, local_notch = _frame(d.get("display"), w, h, notch)
+ ox, oy, fw, fh = frame
+ region = _region_on(d["region"], frame)
+ x, y = d["at"][0] - ox, d["at"][1] - oy
+ along = clamp(y / fh if region["edge"] in ("left", "right") else x / fw)
+ # A tick is the push's: the designs' own departures play with none, and one carried
+ # past the crossing flashed a quarter mark into Rule's shutter.
+ tick = None
+ if d["tick"] is not None and since is None:
+ tick = SimpleNamespace(index=d["tick"][0], age=now - d["tick"][1])
+ s = state(fw, fh, os_name, d["method"], legible(palette, dark, fx), reduced=reduced, dark=dark,
+ notch=local_notch, region=SimpleNamespace(**region), point=point(x, y), along=along,
+ pressure=d["pressure"], tick=tick, since=since)
+ pen = _clipped(draw(fx, "depart", s, (ox, oy)), frame)
+ if pen is not None:
+ pens.append(pen)
+ a = self.arrival
+ if a is not None:
+ since = (now - a["started"]) / self.pace
+ arrival_fx = a.get("fx") or fx
+ if since > arrival_fx.arrive_seconds + 0.05:
+ self.arrival = None
+ elif since >= 0.0:
+ frame, local_notch = _frame(a.get("display"), w, h, notch)
+ ox, oy, fw, fh = frame
+ # A switch lands wherever the pointer was, often below the notch but nowhere near it,
+ # and effects that see a notch above the pointer draw round the notch.
+ s = state(fw, fh, os_name, a["method"], legible(palette, dark, arrival_fx), reduced=reduced,
+ dark=dark, notch=None if a["switch"] else local_notch,
+ point=point(a["at"][0] - ox, a["at"][1] - oy), edge=a["edge"], since=since)
+ pen = _clipped(draw(arrival_fx, "arrive", s, (ox, oy)), frame)
+ if pen is not None:
+ pens.append(pen)
+ return pens
+
+ @property
+ def busy(self):
+ return self.depart is not None or self.arrival is not None
+
+
+def _frame(display, w, h, notch):
+ """The (x, y, w, h) an effect plays in, and the notch in that frame's own coordinates, or None
+ when the notch is not on it."""
+ if display is None:
+ return (0.0, 0.0, float(w), float(h)), notch
+ x, y, dw, dh = (float(v) for v in display)
+ if notch is not None and x <= notch["x"] and notch["x"] + notch["w"] <= x + dw and y <= notch["y"] < y + dh:
+ notch = dict(notch, x=notch["x"] - x, y=notch["y"] - y)
+ else:
+ notch = None
+ return (x, y, dw, dh), notch
+
+
+def _region_on(region, frame):
+ """`region` in `frame`'s coordinates and cut to it: an edge strip measured along the whole
+ desktop runs past a shorter display, and an effect drawing along its strip would draw there."""
+ x, y, w, h = frame
+ left, top = max(region["x"] - x, 0.0), max(region["y"] - y, 0.0)
+ right, bottom = min(region["x"] - x + region["w"], w), min(region["y"] - y + region["h"], h)
+ return dict(region, x=left, y=top, w=max(right - left, 1.0), h=max(bottom - top, 1.0))
+
+
+def _clipped(pen, frame):
+ """`pen` clipped to `frame`, its bounds cut to match, or None when nothing is left inside."""
+ if pen is None or pen.bounds is None:
+ return pen
+ x, y, w, h = frame
+ b = pen.bounds
+ box = (max(b[0], x), max(b[1], y), min(b[2], x + w), min(b[3], y + h))
+ if box[2] <= box[0] or box[3] <= box[1]:
+ return None
+ pen.bounds = box
+ pen.clip = (x, y, x + w, y + h)
+ return pen
diff --git a/win_app/firewall_win.py b/win_app/firewall_win.py
index baaa4af..67d4c0a 100644
--- a/win_app/firewall_win.py
+++ b/win_app/firewall_win.py
@@ -110,7 +110,7 @@ def _rule_applies(rule: dict, exe: str, port: int, protocol: str = "tcp") -> boo
def _lan_networks(networks: Sequence[dict]) -> list:
"""The interface(s) the Mac would arrive on. Internet-connected first; a Hyper-V switch on
Public with no route out is not the LAN and must not trigger the trust offer while Wi-Fi is
- Private, which is the owner's machine today."""
+ Private, the common case."""
ranked = {"internet": 3, "localnetwork": 2, "subnet": 1}
best = 0
for network in networks:
diff --git a/win_app/fx_ink.py b/win_app/fx_ink.py
new file mode 100644
index 0000000..d0e587f
--- /dev/null
+++ b/win_app/fx_ink.py
@@ -0,0 +1,958 @@
+"""Ink: liquid moving between vessels. A viscous drop swells, necks and drips through the boundary,
+blooming into fluid wash on arrival.
+"""
+
+import math
+
+import effects
+
+
+def _colour_at(pal, i):
+ """pal[i]; past the pack's length JS reads undefined there, and a colour assignment from
+ undefined is invalid CSS, so canvas leaves fillStyle/strokeStyle at whatever it already was."""
+ return pal[i] if i < len(pal) else None
+
+
+def get_depart_geometry(s):
+ r = s.region
+ bx, by = s.point.x, s.point.y
+ nx = ny = tx = ty = 0.0
+ is_corner = r.kind == "corner"
+ is_notch = r.kind == "notch"
+
+ if is_notch:
+ n = getattr(s, "notch", None)
+ if n is None:
+ from types import SimpleNamespace
+ n = SimpleNamespace(x=771, y=0, w=185, h=32, r=10)
+ bx = effects.clamp(s.point.x, n.x + 24, n.x + n.w - 24)
+ by = n.h # Bottom lip of the hardware notch
+ nx, ny = 0, 1 # Inward into Mac screen space below notch
+ tx, ty = 1, 0 # Along bottom lip
+ elif is_corner:
+ corner = getattr(r, "corner", "top_right")
+ right, top = "right" in corner, "top" in corner
+ bx, by = (s.screen.w if right else 0), (0 if top else s.screen.h)
+ nx, ny = (-0.7071 if right else 0.7071), (0.7071 if top else -0.7071)
+ tx, ty = ny, -nx
+ else:
+ edge = r.edge
+ if edge == "right":
+ bx, by = s.screen.w, s.point.y
+ nx, ny, tx, ty = -1, 0, 0, 1
+ elif edge == "left":
+ bx, by = 0, s.point.y
+ nx, ny, tx, ty = 1, 0, 0, 1
+ elif edge == "top":
+ bx, by = s.point.x, 0
+ nx, ny, tx, ty = 0, 1, 1, 0
+ else: # bottom
+ bx, by = s.point.x, s.screen.h
+ nx, ny, tx, ty = 0, -1, 1, 0
+
+ return bx, by, nx, ny, tx, ty, is_corner, is_notch
+
+
+def get_arrive_geometry(s):
+ if s.edge == "right":
+ nx, ny = -1, 0
+ elif s.edge == "left":
+ nx, ny = 1, 0
+ elif s.edge == "top":
+ nx, ny = 0, 1
+ else:
+ nx, ny = 0, -1
+
+ near_top, near_bottom = s.point.y < 50, s.point.y > s.screen.h - 50
+ is_corner = s.method == "corner" and s.edge in ("left", "right") and (near_top or near_bottom)
+ if is_corner:
+ nx, ny = 0.7071 * nx, 0.7071 if near_top else -0.7071
+ is_notch = s.method == "notch"
+ return nx, ny, is_corner, is_notch
+
+
+def inward_quarter(nx, ny):
+ """The start and end angles of the quarter turn a corner's wedge fills, centred on the corner's
+ inward normal: the design drew the top right corner's, pi/2 to pi, for every corner."""
+ middle = math.atan2(ny, nx)
+ return middle - math.pi / 4, middle + math.pi / 4
+
+
+def tick_ripple(tick):
+ if tick is None:
+ return 0.0
+ return math.sin(tick.age * 28) * math.exp(-tick.age * 7)
+
+
+def draw_halo(ctx, s, alpha):
+ if s.dark:
+ ctx.strokeStyle = "#ffffff"
+ ctx.globalAlpha = 0.28 * alpha
+ else:
+ ctx.strokeStyle = "#000000"
+ ctx.globalAlpha = 0.16 * alpha
+
+
+# ----------------------------------------------------
+# Effect 1: Capillary (Quiet)
+# ----------------------------------------------------
+
+def _capillary_depart(ctx, s):
+ pal = s.palette
+ bx, by, nx, ny, tx, ty, is_corner, _is_notch = get_depart_geometry(s)
+
+ since = getattr(s, "since", None)
+ if since is not None:
+ if since >= 0.45:
+ return
+ t = since / 0.45
+ alpha = max(0.0, 1 - t * 1.5)
+ if alpha <= 0.001:
+ return
+
+ if s.reduced:
+ ctx.globalAlpha = alpha * 0.4
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx + nx * 4, by + ny * 4, 16, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ # Snapped bead moving forward into the boundary
+ bead_dist = t * 16
+ bead_r = max(0.0, 4.5 * (1 - t))
+ if bead_r > 0.5:
+ ctx.globalAlpha = alpha * 0.85
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx - nx * bead_dist, by - ny * bead_dist, bead_r, 0, math.pi * 2)
+ ctx.fill()
+
+ # Meniscus recoil against wall
+ recoil = max(0.0, 1 - t * 2.2)
+ if recoil > 0.01:
+ span = 36 * recoil
+ depth = 8 * recoil
+ ctx.globalAlpha = alpha * 0.5
+ ctx.fillStyle = pal[min(1, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.quadraticCurveTo(bx + nx * depth, by + ny * depth, bx + tx * span, by + ty * span)
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ p = s.pressure
+ if p <= 0.001:
+ return
+
+ if s.reduced:
+ alpha = 0.15 + 0.65 * p
+ if is_corner:
+ ctx.globalAlpha = alpha * 0.4
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.arc(bx, by, 36, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.85
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx, by, 22, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+ else:
+ span = 42
+ depth = 14
+ ctx.globalAlpha = alpha * 0.4
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 4), by - ty * (span + 4))
+ ctx.quadraticCurveTo(bx + nx * (depth + 4), by + ny * (depth + 4), bx + tx * (span + 4), by + ty * (span + 4))
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.85
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.quadraticCurveTo(bx + nx * depth, by + ny * depth, bx + tx * span, by + ty * span)
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ ripple = tick_ripple(getattr(s, "tick", None))
+ vis_p = effects.clamp(p ** 1.2 + ripple * 0.08, 0.0, 1.2)
+ span = 24 + 48 * vis_p
+ depth = 6 + 22 * vis_p
+
+ if is_corner:
+ cr = 8 + 36 * vis_p
+ # Soft outer wash
+ ctx.globalAlpha = 0.3 * p
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr + 6, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ # Main pigment body
+ ctx.globalAlpha = 0.7 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ # Dense inner core
+ ctx.globalAlpha = 0.9 * p
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr * 0.55, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ # Straight edge and notch meniscus
+ draw_halo(ctx, s, p * 0.4)
+ ctx.lineWidth = 1.5 / s.scale
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 4), by - ty * (span + 4))
+ ctx.quadraticCurveTo(bx + nx * (depth + 4), by + ny * (depth + 4), bx + tx * (span + 4), by + ty * (span + 4))
+ ctx.stroke()
+
+ # Layer 1: Outer wash
+ ctx.globalAlpha = 0.3 * p
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 6), by - ty * (span + 6))
+ ctx.quadraticCurveTo(bx + nx * (depth + 5), by + ny * (depth + 5), bx + tx * (span + 6), by + ty * (span + 6))
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 2: Main fluid body with wetting fillets
+ ctx.globalAlpha = 0.7 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.bezierCurveTo(
+ bx - tx * span * 0.5 + nx * depth * 0.4, by - ty * span * 0.5 + ny * depth * 0.4,
+ bx - tx * span * 0.2 + nx * depth, by - ty * span * 0.2 + ny * depth,
+ bx + nx * depth, by + ny * depth,
+ )
+ ctx.bezierCurveTo(
+ bx + tx * span * 0.2 + nx * depth, by + ty * span * 0.2 + ny * depth,
+ bx + tx * span * 0.5 + nx * depth * 0.4, by + ty * span * 0.5 + ny * depth * 0.4,
+ bx + tx * span, by + ty * span,
+ )
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 3: Concentrated core near wall
+ ctx.globalAlpha = 0.9 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span * 0.6), by - ty * (span * 0.6))
+ ctx.quadraticCurveTo(bx + nx * (depth * 0.5), by + ny * (depth * 0.5), bx + tx * (span * 0.6), by + ty * (span * 0.6))
+ ctx.closePath()
+ ctx.fill()
+
+
+def _capillary_arrive(ctx, s):
+ since = getattr(s, "since", None)
+ if since is None or since >= 0.50 or since < 0:
+ return
+ pal = s.palette
+ t = since / 0.50
+ alpha = max(0.0, 1 - t)
+ if alpha <= 0.001:
+ return
+
+ nx, ny, _is_corner, _is_notch = get_arrive_geometry(s)
+
+ if s.reduced:
+ a = math.sin(t * math.pi)
+ ctx.globalAlpha = a * 0.4
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.arc(s.point.x, s.point.y, 32, 0, math.pi * 2)
+ ctx.fill()
+
+ ctx.globalAlpha = a * 0.8
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(s.point.x, s.point.y, 18, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ u = effects.ease_out(t)
+ radius = 10 + 44 * u
+ cx = s.point.x + nx * (8 * u)
+ cy = s.point.y + ny * (8 * u)
+
+ # Halo for dark background contrast
+ draw_halo(ctx, s, alpha * 0.6)
+ ctx.lineWidth = 1.5 / s.scale
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius + 2, 0, math.pi * 2)
+ ctx.stroke()
+
+ # Outer soft wash
+ ctx.globalAlpha = alpha * 0.3
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius, 0, math.pi * 2)
+ ctx.fill()
+
+ # Mid pigment bleed
+ ctx.globalAlpha = alpha * 0.6
+ ctx.fillStyle = pal[min(1, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius * 0.62, 0, math.pi * 2)
+ ctx.fill()
+
+ # Dense landing core
+ ctx.globalAlpha = alpha * 0.9
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius * 0.28, 0, math.pi * 2)
+ ctx.fill()
+
+ # Subtle capillary perimeter rim
+ ctx.globalAlpha = alpha * 0.45
+ ctx.strokeStyle = pal[0]
+ ctx.lineWidth = 1 / s.scale
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius, 0, math.pi * 2)
+ ctx.stroke()
+
+
+# ----------------------------------------------------
+# Effect 2: Viscous Drop (Medium)
+# ----------------------------------------------------
+
+def _viscous_drop_depart(ctx, s):
+ pal = s.palette
+ bx, by, nx, ny, tx, ty, is_corner, _is_notch = get_depart_geometry(s)
+
+ since = getattr(s, "since", None)
+ if since is not None:
+ if since >= 0.55:
+ return
+ t = since / 0.55
+ alpha = max(0.0, 1 - t * 1.3)
+ if alpha <= 0.001:
+ return
+
+ if s.reduced:
+ ctx.globalAlpha = alpha * 0.5
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx + nx * 6, by + ny * 6, 22, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ # Detached droplet travelling across boundary
+ drop_dist = t * 24
+ drop_r = max(0.0, 6 * (1 - t * 0.8))
+ if drop_r > 0.5:
+ ctx.globalAlpha = alpha * 0.9
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx - nx * drop_dist, by - ny * drop_dist, drop_r, 0, math.pi * 2)
+ ctx.fill()
+
+ # Secondary satellite droplet (capillary pinch-off)
+ sat_dist = t * 12
+ sat_r = max(0.0, 2.2 * (1 - t))
+ if sat_r > 0.5:
+ ctx.globalAlpha = alpha * 0.7
+ ctx.beginPath()
+ ctx.arc(bx - nx * sat_dist, by - ny * sat_dist, sat_r, 0, math.pi * 2)
+ ctx.fill()
+
+ # Snapped meniscus recoiling and rippling
+ recoil = max(0.0, 1 - t * 1.8) * math.cos(t * 12)
+ if abs(recoil) > 0.01:
+ span = 42 * (1 - t)
+ depth = 12 * recoil
+ ctx.globalAlpha = alpha * 0.55
+ ctx.fillStyle = pal[min(1, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.quadraticCurveTo(bx + nx * depth, by + ny * depth, bx + tx * span, by + ty * span)
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ p = s.pressure
+ if p <= 0.001:
+ return
+
+ if s.reduced:
+ alpha = 0.15 + 0.75 * p
+ if is_corner:
+ ctx.globalAlpha = alpha * 0.4
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.arc(bx, by, 44, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.9
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx, by, 26, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+ else:
+ span = 52
+ depth = 18
+ ctx.globalAlpha = alpha * 0.4
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 4), by - ty * (span + 4))
+ ctx.quadraticCurveTo(bx + nx * (depth + 4), by + ny * (depth + 4), bx + tx * (span + 4), by + ty * (span + 4))
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.9
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.quadraticCurveTo(bx + nx * depth, by + ny * depth, bx + tx * span, by + ty * span)
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ ripple = tick_ripple(getattr(s, "tick", None))
+ vis_p = effects.clamp(p ** 1.25 + ripple * 0.12, 0.0, 1.3)
+ span = 28 + 44 * vis_p
+ depth = 8 + 32 * vis_p
+ neck_w = span * (1 - vis_p * 0.38)
+
+ if is_corner:
+ cr = 10 + 44 * vis_p
+ ctx.globalAlpha = 0.3 * p
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr + 8, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = 0.75 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ # Bulging droplet apex in corner
+ hx, hy = bx + nx * (cr * 0.75), by + ny * (cr * 0.75)
+ ctx.globalAlpha = 0.95 * p
+ ctx.beginPath()
+ ctx.arc(hx, hy, 10 + 12 * vis_p, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ # Straight edge and notch necked droplet
+ draw_halo(ctx, s, p * 0.45)
+ ctx.lineWidth = 2 / s.scale
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 6), by - ty * (span + 6))
+ ctx.quadraticCurveTo(bx + nx * (depth + 6), by + ny * (depth + 6), bx + tx * (span + 6), by + ty * (span + 6))
+ ctx.stroke()
+
+ # Outer soft wash
+ ctx.globalAlpha = 0.32 * p
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 5), by - ty * (span + 5))
+ ctx.bezierCurveTo(
+ bx - tx * neck_w + nx * (depth * 0.4), by - ty * neck_w + ny * (depth * 0.4),
+ bx - tx * (span * 0.3) + nx * (depth + 4), by - ty * (span * 0.3) + ny * (depth + 4),
+ bx + nx * (depth + 4), by + ny * (depth + 4),
+ )
+ ctx.bezierCurveTo(
+ bx + tx * (span * 0.3) + nx * (depth + 4), by + ty * (span * 0.3) + ny * (depth + 4),
+ bx + tx * neck_w + nx * (depth * 0.4), by + ty * neck_w + ny * (depth * 0.4),
+ bx + tx * (span + 5), by + ty * (span + 5),
+ )
+ ctx.closePath()
+ ctx.fill()
+
+ # Main viscous droplet with necking
+ ctx.globalAlpha = 0.8 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.bezierCurveTo(
+ bx - tx * neck_w * 0.8 + nx * (depth * 0.3), by - ty * neck_w * 0.8 + ny * (depth * 0.3),
+ bx - tx * (neck_w * 0.4) + nx * (depth * 0.8), by - ty * (neck_w * 0.4) + ny * (depth * 0.8),
+ bx + nx * depth, by + ny * depth,
+ )
+ ctx.bezierCurveTo(
+ bx + tx * (neck_w * 0.4) + nx * (depth * 0.8), by + ty * (neck_w * 0.4) + ny * (depth * 0.8),
+ bx + tx * neck_w * 0.8 + nx * (depth * 0.3), by + ty * neck_w * 0.8 + ny * (depth * 0.3),
+ bx + tx * span, by + ty * span,
+ )
+ ctx.closePath()
+ ctx.fill()
+
+ # Dense concentrated core droplet at apex
+ ctx.globalAlpha = 0.95 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx + nx * (depth * 0.72), by + ny * (depth * 0.72), 6 + 10 * vis_p, 0, math.pi * 2)
+ ctx.fill()
+
+
+def _viscous_drop_arrive(ctx, s):
+ since = getattr(s, "since", None)
+ if since is None or since >= 0.60 or since < 0:
+ return
+ pal = s.palette
+ t = since / 0.60
+ alpha = max(0.0, 1 - t)
+ if alpha <= 0.001:
+ return
+
+ nx, ny, _is_corner, _is_notch = get_arrive_geometry(s)
+
+ if s.reduced:
+ a = math.sin(t * math.pi)
+ cx, cy = s.point.x, s.point.y
+ ctx.globalAlpha = a * 0.42
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ for i in range(0, 37):
+ ang = (i / 36) * math.pi * 2
+ r = 38 * (1 + 0.2 * math.sin(6 * ang))
+ px, py = cx + math.cos(ang) * r, cy + math.sin(ang) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = a * 0.85
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(cx, cy, 20, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ u = effects.ease_out(t)
+ base_r = 12 + 62 * u
+ cx = s.point.x + nx * (12 * u)
+ cy = s.point.y + ny * (12 * u)
+
+ # Organic 6-lobed bloom boundary
+ draw_halo(ctx, s, alpha * 0.65)
+ ctx.lineWidth = 1.5 / s.scale
+ ctx.beginPath()
+ for i in range(0, 41):
+ a = (i / 40) * math.pi * 2
+ r = (base_r + 2) * (1 + 0.25 * math.sin(6 * a + 0.4) + 0.08 * math.cos(3 * a))
+ px, py = cx + math.cos(a) * r, cy + math.sin(a) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.stroke()
+
+ # Layer 1: Outer wash bloom
+ ctx.globalAlpha = alpha * 0.32
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ for i in range(0, 41):
+ a = (i / 40) * math.pi * 2
+ r = base_r * (1 + 0.26 * math.sin(6 * a + 0.4) + 0.08 * math.cos(3 * a))
+ px, py = cx + math.cos(a) * r, cy + math.sin(a) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 2: Mid-tone pigment diffusion
+ ctx.globalAlpha = alpha * 0.62
+ ctx.fillStyle = pal[min(1, len(pal) - 1)]
+ ctx.beginPath()
+ for i in range(0, 33):
+ a = (i / 32) * math.pi * 2
+ r = (base_r * 0.62) * (1 + 0.22 * math.sin(5 * a + 1.2))
+ px, py = cx + math.cos(a) * r, cy + math.sin(a) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 3: Central dense impact droplet
+ ctx.globalAlpha = alpha * 0.92
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(cx, cy, base_r * 0.28, 0, math.pi * 2)
+ ctx.fill()
+
+ # 8 micro-satellite droplets radiating outward
+ num_sats = 8
+ for j in range(num_sats):
+ ang = (j / num_sats) * math.pi * 2 + s.hash(j) * 0.4
+ dist = base_r * 0.7 + 36 * u * s.hash(j + 10)
+ sat_r = max(0.0, (2.8 - 2.2 * u) * s.hash(j + 20))
+ if sat_r > 0.4:
+ ctx.globalAlpha = alpha * 0.75 * (1 - u * 0.6)
+ colour = _colour_at(pal, 0 if j % 2 == 0 else 1)
+ if colour is not None:
+ ctx.fillStyle = colour
+ ctx.beginPath()
+ ctx.arc(cx + math.cos(ang) * dist, cy + math.sin(ang) * dist, sat_r, 0, math.pi * 2)
+ ctx.fill()
+
+
+# ----------------------------------------------------
+# Effect 3: Sumi Bloom (Showpiece)
+# ----------------------------------------------------
+
+def _sumi_bloom_depart(ctx, s):
+ pal = s.palette
+ bx, by, nx, ny, tx, ty, is_corner, _is_notch = get_depart_geometry(s)
+
+ since = getattr(s, "since", None)
+ if since is not None:
+ if since >= 0.70:
+ return
+ t = since / 0.70
+ alpha = max(0.0, 1 - t * 1.25)
+ if alpha <= 0.001:
+ return
+
+ if s.reduced:
+ ctx.globalAlpha = alpha * 0.6
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx + nx * 8, by + ny * 8, 28, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ # Rayleigh-Plateau droplet train breaking into seam
+ num_drops = 4
+ for k in range(num_drops):
+ lead = t * (28 + k * 10)
+ r_drop = max(0.0, (5.5 - k * 1.1) * (1 - t * 0.9))
+ if r_drop > 0.4:
+ ctx.globalAlpha = alpha * (0.92 - k * 0.15)
+ colour = _colour_at(pal, 0 if k % 2 == 0 else 1)
+ if colour is not None:
+ ctx.fillStyle = colour
+ ctx.beginPath()
+ ctx.arc(bx - nx * lead + tx * ((s.hash(k + 30) - 0.5) * 8), by - ny * lead + ty * ((s.hash(k + 30) - 0.5) * 8), r_drop, 0, math.pi * 2)
+ ctx.fill()
+
+ # Parent meniscus recoil & damped oscillation
+ recoil = max(0.0, 1 - t * 1.6) * math.cos(t * 14)
+ if abs(recoil) > 0.01:
+ span = 56 * (1 - t)
+ depth = 16 * recoil
+ ctx.globalAlpha = alpha * 0.65
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.bezierCurveTo(
+ bx - tx * (span * 0.4) + nx * depth, by - ty * (span * 0.4) + ny * depth,
+ bx + tx * (span * 0.4) + nx * depth, by + ty * (span * 0.4) + ny * depth,
+ bx + tx * span, by + ty * span,
+ )
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ p = s.pressure
+ if p <= 0.001:
+ return
+
+ if s.reduced:
+ alpha = 0.2 + 0.8 * p
+ if is_corner:
+ ctx.globalAlpha = alpha * 0.45
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.arc(bx, by, 54, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.95
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx, by, 32, *inward_quarter(nx, ny))
+ ctx.lineTo(bx, by)
+ ctx.closePath()
+ ctx.fill()
+ else:
+ span = 64
+ depth = 24
+ ctx.globalAlpha = alpha * 0.45
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 6), by - ty * (span + 6))
+ ctx.quadraticCurveTo(bx + nx * (depth + 6), by + ny * (depth + 6), bx + tx * (span + 6), by + ty * (span + 6))
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = alpha * 0.95
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.quadraticCurveTo(bx + nx * depth, by + ny * depth, bx + tx * span, by + ty * span)
+ ctx.closePath()
+ ctx.fill()
+ return
+
+ ripple = tick_ripple(getattr(s, "tick", None))
+ vis_p = effects.clamp(p ** 1.3 + ripple * 0.16, 0.0, 1.35)
+ span = 36 + 54 * vis_p
+ depth = 12 + 42 * vis_p
+ neck_w = span * (1 - vis_p * 0.46)
+
+ if is_corner:
+ cr = 14 + 56 * vis_p
+ ctx.globalAlpha = 0.35 * p
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr + 10, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ ctx.globalAlpha = 0.8 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx, by)
+ ctx.arc(bx, by, cr, *inward_quarter(nx, ny))
+ ctx.closePath()
+ ctx.fill()
+
+ # Fluid bridge head pulling diagonally inward
+ hx, hy = bx + nx * (cr * 0.8), by + ny * (cr * 0.8)
+ ctx.globalAlpha = 0.95 * p
+ ctx.beginPath()
+ ctx.arc(hx, hy, 12 + 16 * vis_p, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ # Straight edge and notch: full fluid bridge with Rayleigh instability ripples
+ draw_halo(ctx, s, p * 0.55)
+ ctx.lineWidth = 2 / s.scale
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 8), by - ty * (span + 8))
+ ctx.quadraticCurveTo(bx + nx * (depth + 8), by + ny * (depth + 8), bx + tx * (span + 8), by + ty * (span + 8))
+ ctx.stroke()
+
+ # Layer 1: Wide pigment seepage
+ ctx.globalAlpha = 0.35 * p
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * (span + 8), by - ty * (span + 8))
+ ctx.bezierCurveTo(
+ bx - tx * neck_w + nx * (depth * 0.4), by - ty * neck_w + ny * (depth * 0.4),
+ bx - tx * (span * 0.25) + nx * (depth + 6), by - ty * (span * 0.25) + ny * (depth + 6),
+ bx + nx * (depth + 6), by + ny * (depth + 6),
+ )
+ ctx.bezierCurveTo(
+ bx + tx * (span * 0.25) + nx * (depth + 6), by + ty * (span * 0.25) + ny * (depth + 6),
+ bx + tx * neck_w + nx * (depth * 0.4), by + ty * neck_w + ny * (depth * 0.4),
+ bx + tx * (span + 8), by + ty * (span + 8),
+ )
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 2: Main calligraphic fluid bridge with necking
+ ctx.globalAlpha = 0.82 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.moveTo(bx - tx * span, by - ty * span)
+ ctx.bezierCurveTo(
+ bx - tx * neck_w * 0.85 + nx * (depth * 0.35), by - ty * neck_w * 0.85 + ny * (depth * 0.35),
+ bx - tx * (neck_w * 0.35) + nx * (depth * 0.85), by - ty * (neck_w * 0.35) + ny * (depth * 0.85),
+ bx + nx * depth, by + ny * depth,
+ )
+ ctx.bezierCurveTo(
+ bx + tx * (neck_w * 0.35) + nx * (depth * 0.85), by + ty * (neck_w * 0.35) + ny * (depth * 0.85),
+ bx + tx * neck_w * 0.85 + nx * (depth * 0.35), by + ty * neck_w * 0.85 + ny * (depth * 0.35),
+ bx + tx * span, by + ty * span,
+ )
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 3: Pendent droplet bulb with intense Sumi density
+ ctx.globalAlpha = 0.95 * p
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(bx + nx * (depth * 0.76), by + ny * (depth * 0.76), 8 + 14 * vis_p, 0, math.pi * 2)
+ ctx.fill()
+
+
+def _sumi_bloom_arrive(ctx, s):
+ since = getattr(s, "since", None)
+ if since is None or since >= 0.75 or since < 0:
+ return
+ pal = s.palette
+ t = since / 0.75
+ alpha = max(0.0, 1 - t)
+ if alpha <= 0.001:
+ return
+
+ nx, ny, _is_corner, _is_notch = get_arrive_geometry(s)
+
+ if s.reduced:
+ a = math.sin(t * math.pi)
+ cx, cy = s.point.x, s.point.y
+ ctx.globalAlpha = a * 0.45
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ ctx.arc(cx, cy, 42, 0, math.pi * 2)
+ ctx.fill()
+
+ ctx.globalAlpha = a * 0.75
+ colour = _colour_at(pal, 1)
+ if colour is not None:
+ ctx.fillStyle = colour
+ ctx.beginPath()
+ ctx.arc(cx, cy, 26, 0, math.pi * 2)
+ ctx.fill()
+
+ ctx.globalAlpha = a * 0.95
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(cx, cy, 14, 0, math.pi * 2)
+ ctx.fill()
+ return
+
+ u = effects.ease_out(t)
+ base_r = 14 + 76 * u
+ cx = s.point.x + nx * (14 * u)
+ cy = s.point.y + ny * (14 * u)
+
+ # Halo for contrast
+ draw_halo(ctx, s, alpha * 0.75)
+ ctx.lineWidth = 1.5 / s.scale
+ ctx.beginPath()
+ ctx.arc(cx, cy, base_r + 2, 0, math.pi * 2)
+ ctx.stroke()
+
+ # Layer 1: Outermost dilute pigment wash
+ ctx.globalAlpha = alpha * 0.28
+ ctx.fillStyle = pal[len(pal) - 1]
+ ctx.beginPath()
+ for i in range(0, 45):
+ a = (i / 44) * math.pi * 2
+ r = base_r * (1 + 0.22 * math.sin(7 * a + 0.5) + 0.1 * math.cos(3 * a))
+ px, py = cx + math.cos(a) * r, cy + math.sin(a) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 2: Mid-tone pigment diffusion
+ ctx.globalAlpha = alpha * 0.55
+ ctx.fillStyle = pal[min(2, len(pal) - 1)]
+ ctx.beginPath()
+ for i in range(0, 37):
+ a = (i / 36) * math.pi * 2
+ r = (base_r * 0.68) * (1 + 0.24 * math.sin(5 * a + 1.1))
+ px, py = cx + math.cos(a) * r, cy + math.sin(a) * r
+ if i == 0:
+ ctx.moveTo(px, py)
+ else:
+ ctx.lineTo(px, py)
+ ctx.closePath()
+ ctx.fill()
+
+ # Layer 3: Inner dense wash
+ ctx.globalAlpha = alpha * 0.8
+ ctx.fillStyle = pal[min(1, len(pal) - 1)]
+ ctx.beginPath()
+ ctx.arc(cx, cy, base_r * 0.38, 0, math.pi * 2)
+ ctx.fill()
+
+ # Layer 4: Deep Sumi stone core
+ ctx.globalAlpha = alpha * 0.95
+ ctx.fillStyle = pal[0]
+ ctx.beginPath()
+ ctx.arc(cx, cy, base_r * 0.18, 0, math.pi * 2)
+ ctx.fill()
+
+ # 16 curling ink-in-water filament tendrils
+ num_filaments = 16
+ ctx.lineWidth = (1.5 - 0.8 * u) / s.scale
+ for m in range(num_filaments):
+ start_ang = (m / num_filaments) * math.pi * 2 + s.hash(m + 50) * 0.3
+ curl_dir = 1 if m % 2 == 0 else -1
+ r1 = base_r * 0.35
+ r2 = base_r * (0.8 + 0.35 * s.hash(m + 70))
+ x1 = cx + math.cos(start_ang) * r1
+ y1 = cy + math.sin(start_ang) * r1
+ mid_ang = start_ang + curl_dir * (0.4 + 0.3 * u)
+ x_mid = cx + math.cos(mid_ang) * (r1 + (r2 - r1) * 0.55)
+ y_mid = cy + math.sin(mid_ang) * (r1 + (r2 - r1) * 0.55)
+ end_ang = mid_ang + curl_dir * 0.25
+ x2 = cx + math.cos(end_ang) * r2
+ y2 = cy + math.sin(end_ang) * r2
+
+ ctx.globalAlpha = alpha * 0.7 * (1 - u * 0.4)
+ colour = _colour_at(pal, m % 3)
+ if colour is not None:
+ ctx.strokeStyle = colour
+ ctx.beginPath()
+ ctx.moveTo(x1, y1)
+ ctx.quadraticCurveTo(x_mid, y_mid, x2, y2)
+ ctx.stroke()
+
+
+EFFECTS = [
+ effects.Effect(
+ "capillary", "Capillary", "quiet",
+ "A soft pigment meniscus swells against the boundary with viscous surface tension. On "
+ "breakthrough, it releases cleanly and diffuses as a calm, translucent wash on the "
+ "arrival screen.",
+ _capillary_depart, _capillary_arrive, 0.45, 0.50,
+ ),
+ effects.Effect(
+ "viscous_drop", "Viscous drop", "medium",
+ "An organic ink droplet gathers at the pointer, flattening against the glass edge before "
+ "necking through the seam. On arrival, it splashes into a multi-lobed pigment bloom that "
+ "bleeds outward.",
+ _viscous_drop_depart, _viscous_drop_arrive, 0.55, 0.60,
+ ),
+ effects.Effect(
+ "sumi_bloom", "Sumi bloom", "showpiece",
+ "Dense calligraphic ink pulls from the boundary into a viscous bridge that necks and "
+ "snaps through the seam. It arrives as an ink-in-water vortex bloom, unfurling delicate "
+ "pigment filaments that dissolve into the screen.",
+ _sumi_bloom_depart, _sumi_bloom_arrive, 0.70, 0.75,
+ ),
+]
+
+PACKS = {
+ "indigo_ink": ("Indigo ink", ["#16243b", "#253d66", "#3f639e", "#6891ce", "#a8c5ed"]),
+ "matcha": ("Matcha", ["#233818", "#3e5c2c", "#638a44", "#92b86e", "#cde6b0"]),
+ "terracotta": ("Terracotta", ["#4d1f16", "#7c3423", "#b35338", "#d97b5d", "#f3b59f"]),
+}
diff --git a/win_app/fx_instrument.py b/win_app/fx_instrument.py
new file mode 100644
index 0000000..84bbc5a
--- /dev/null
+++ b/win_app/fx_instrument.py
@@ -0,0 +1,733 @@
+"""Instrument: crossing is a measurement taken, read off a scale one click at a time, closed by a
+shutter where you left and locked on by the same instrument where you land.
+
+Effects: Rule (quiet), Gauge (medium), Rangefinder (showpiece). Packs: Phosphor, Sodium, Contrast.
+"""
+
+from __future__ import annotations
+
+import math
+from types import SimpleNamespace
+
+from effects import Effect, clamp, lerp
+
+PI = math.pi
+TAU = PI * 2.0
+SQ = math.sqrt(0.5)
+
+
+def roles(s):
+ p = s.palette
+ n = len(p)
+ return SimpleNamespace(lit=p[0], dim=p[1 % n], hot=p[n - 1])
+
+
+# Pen.arc's own one-cubic-Bezier-per-pi/2 tessellation reads as visibly faceted next to the design's
+# native canvas arc at the dial and reticle radii drawn here. Doubling the density (pi/4 a piece)
+# is the best trade-off found by measurement: finer still fixes some states and reopens others
+# elsewhere in the same sweep, so this is the port's fix, not a tuned-away symptom.
+def detent(u, n, slide=0.4):
+ """n equal detents, each move taking the first `slide` of its slot and then holding."""
+ if u <= 0:
+ return 0.0
+ if u >= 1:
+ return 1.0
+ k = math.floor(u * n)
+ f = u * n - k
+ return min(1.0, (k + clamp(f / slide)) / n)
+
+
+def ink(ctx, s, colour, w, alpha, build):
+ if alpha <= 0.003:
+ return
+ ctx.beginPath()
+ build()
+ ctx.lineCap = "butt"
+ ctx.lineJoin = "miter"
+ if s.dark:
+ ctx.globalAlpha = alpha * 0.14
+ ctx.strokeStyle = colour
+ ctx.lineWidth = w + 5
+ ctx.stroke()
+ ctx.globalAlpha = alpha * (0.5 if s.dark else 0.62)
+ ctx.strokeStyle = "#000"
+ ctx.lineWidth = w + 2
+ ctx.stroke()
+ ctx.globalAlpha = alpha
+ ctx.strokeStyle = colour
+ ctx.lineWidth = w
+ ctx.stroke()
+
+
+def fill_with(ctx, colour, alpha, build):
+ if alpha <= 0.003:
+ return
+ ctx.beginPath()
+ build()
+ ctx.globalAlpha = alpha
+ ctx.fillStyle = colour
+ ctx.fill()
+
+
+def tick_to(ctx, ray, d, o1, o2):
+ p = ray.at(d)
+ ctx.moveTo(p.x + p.nx * o1, p.y + p.ny * o1)
+ ctx.lineTo(p.x + p.nx * o2, p.y + p.ny * o2)
+
+
+def rail_to(ctx, ray, d0, d1, o, move=True):
+ n = max(1, math.ceil(abs(d1 - d0) / 3))
+ for i in range(n + 1):
+ p = ray.at(d0 + (d1 - d0) * i / n)
+ x, y = p.x + p.nx * o, p.y + p.ny * o
+ if i == 0 and move:
+ ctx.moveTo(x, y)
+ else:
+ ctx.lineTo(x, y)
+
+
+def band_to(ctx, ray, d0, d1, o1, o2):
+ rail_to(ctx, ray, d0, d1, o1, True)
+ rail_to(ctx, ray, d1, d0, o2, False)
+ ctx.closePath()
+
+
+# The hardware notch as a rail: down its left side, round the bottom, up its right side, and out
+# along the top edge either way, so a scale can hug it and never draw inside the black.
+def notch_track(n):
+ r, v, q, b = n.r, n.h - n.r, PI / 2 * n.r, n.w - 2 * n.r
+ L = 2 * v + 2 * q + b
+
+ def at(t):
+ if t < -1e-6:
+ return SimpleNamespace(x=n.x + t, y=0, nx=0, ny=1)
+ if t < v:
+ return SimpleNamespace(x=n.x, y=max(0, t), nx=-1, ny=0)
+ if t < v + q:
+ a = PI - (t - v) / q * PI / 2
+ c, si = math.cos(a), math.sin(a)
+ return SimpleNamespace(x=n.x + r + r * c, y=v + r * si, nx=c, ny=si)
+ if t < v + q + b:
+ return SimpleNamespace(x=n.x + r + (t - v - q), y=n.h, nx=0, ny=1)
+ if t < v + 2 * q + b:
+ a = PI / 2 - (t - v - q - b) / q * PI / 2
+ c, si = math.cos(a), math.sin(a)
+ return SimpleNamespace(x=n.x + n.w - r + r * c, y=v + r * si, nx=c, ny=si)
+ if t <= L + 1e-6:
+ return SimpleNamespace(x=n.x + n.w, y=max(0, L - t), nx=1, ny=0)
+ return SimpleNamespace(x=n.x + n.w + (t - L), y=0, nx=0, ny=1)
+
+ def t_of(px):
+ lx, rx = n.x + r, n.x + n.w - r
+ if lx <= px <= rx:
+ return v + q + (px - lx)
+ if px < lx:
+ return v + (PI - math.acos(clamp((px - lx) / r, -1, 0))) / (PI / 2) * q
+ return v + q + b + (PI / 2 - math.acos(clamp((px - rx) / r, 0, 1))) / (PI / 2) * q
+
+ return SimpleNamespace(L=L, at=at, tOf=t_of)
+
+
+# Sets up the drawing frame for where the crossing happens and returns rays running outward from
+# the pointer along the boundary. Edge and corner transform the context so local x runs along
+# the edge and local y points into the screen; the notch stays in screen points.
+def frame(ctx, s, depart):
+ W, H, P = s.screen.w, s.screen.h, s.point
+ right = bottom = False
+ if depart:
+ r = s.region
+ kind, edge = r.kind, r.edge
+ if kind == "corner":
+ right = "right" in r.corner
+ bottom = "bottom" in r.corner
+ else:
+ edge, kind = s.edge, "edge"
+ n = getattr(s, "notch", None)
+ if n and edge == "top" and n.x - 2 <= P.x <= n.x + n.w + 2:
+ kind = "notch"
+ else:
+ cx = 0 if P.x < 24 else (1 if P.x > W - 24 else -1)
+ cy = 0 if P.y < 24 else (1 if P.y > H - 24 else -1)
+ if cx >= 0 and cy >= 0:
+ kind = "corner"
+ right, bottom = cx == 1, cy == 1
+ if kind == "notch":
+ tr = notch_track(s.notch)
+ tp = tr.tOf(P.x)
+ c = tr.at(tp)
+ return SimpleNamespace(
+ kind=kind, track=tr, tp=tp, centre=c, tangent=SimpleNamespace(x=-c.ny, y=c.nx),
+ rays=[SimpleNamespace(at=lambda d: tr.at(tp + d), max=tr.L - tp),
+ SimpleNamespace(at=lambda d: tr.at(tp - d), max=tp)],
+ )
+ if kind == "corner":
+ ctx.transform(-1 if right else 1, 0, 0, -1 if bottom else 1, W if right else 0, H if bottom else 0)
+ return SimpleNamespace(
+ kind=kind, centre=SimpleNamespace(x=0, y=0, nx=SQ, ny=SQ), tangent=SimpleNamespace(x=SQ, y=-SQ),
+ rays=[SimpleNamespace(at=lambda d: SimpleNamespace(x=d, y=0, nx=0, ny=1), max=400),
+ SimpleNamespace(at=lambda d: SimpleNamespace(x=0, y=d, nx=1, ny=0), max=400)],
+ )
+ if edge == "right":
+ ctx.transform(0, 1, -1, 0, W, P.y)
+ lo, hi = P.y, H - P.y
+ elif edge == "left":
+ ctx.transform(0, 1, 1, 0, 0, P.y)
+ lo, hi = P.y, H - P.y
+ elif edge == "top":
+ ctx.transform(1, 0, 0, 1, P.x, 0)
+ lo, hi = P.x, W - P.x
+ else:
+ ctx.transform(1, 0, 0, -1, P.x, H)
+ lo, hi = P.x, W - P.x
+ return SimpleNamespace(
+ kind="edge", centre=SimpleNamespace(x=0, y=0, nx=0, ny=1), tangent=SimpleNamespace(x=1, y=0),
+ rays=[SimpleNamespace(at=lambda d: SimpleNamespace(x=d, y=0, nx=0, ny=1), max=hi),
+ SimpleNamespace(at=lambda d: SimpleNamespace(x=-d, y=0, nx=0, ny=1), max=lo)],
+ )
+
+
+def tick_flash(s, span=0.22):
+ return 1 - s.tick.age / span if s.tick is not None and s.tick.age < span else 0
+
+
+def comb(ctx, items):
+ def build():
+ for ray, d, a, b in items:
+ tick_to(ctx, ray, d, a, b)
+ return build
+
+
+def normal_line(ctx, c, o1, o2):
+ def build():
+ ctx.moveTo(c.x + c.nx * o1, c.y + c.ny * o1)
+ ctx.lineTo(c.x + c.nx * o2, c.y + c.ny * o2)
+ return build
+
+
+def rule_depart(ctx, s):
+ C, SP, N = roles(s), 6, 12
+ p, reach, done = s.pressure, SP * N, False
+ if s.since is None:
+ alpha = clamp(p * 3)
+ else:
+ u = s.since / 0.45
+ if u >= 1:
+ return
+ p, done = 1, True
+ if s.reduced:
+ alpha = 1 - detent(u, 4, 0.25)
+ else:
+ reach = SP * N * (1 - detent(u, 4))
+ alpha = 1 - clamp((u - 0.75) / 0.25)
+ if alpha <= 0:
+ return
+ flash, k = tick_flash(s), frame(ctx, s, True)
+ off, on, hot = [], [], []
+ for ray in k.rays:
+ for i in range(1, N + 1):
+ d = i * SP
+ if d > ray.max or d > reach + 0.01:
+ break
+ major = i % 3 == 0
+ length = 10 if major else 5
+ (on if (done or i / N <= p + 1e-6) else off).append((ray, d, 2, 2 + length))
+ if flash and major and i == s.tick.index * 3:
+ hot.append((ray, d, 2, 2 + length + (0 if s.reduced else 7 * flash)))
+ if reach > 0.5:
+ def rails():
+ for ray in k.rays:
+ rail_to(ctx, ray, 0, min(reach, ray.max), 2)
+ ink(ctx, s, C.dim, 1, alpha * 0.45, rails)
+ ink(ctx, s, C.dim, 1.25, alpha * 0.5, comb(ctx, off))
+ ink(ctx, s, C.hot if done else C.lit, 1.25, alpha, comb(ctx, on))
+ ink(ctx, s, C.hot, 1.5, alpha * flash, comb(ctx, hot))
+ ink(ctx, s, C.hot if done else C.lit, 1.5, alpha, normal_line(ctx, k.centre, 2, 17))
+
+
+def rule_arrive(ctx, s):
+ t = s.since
+ if t >= 0.6:
+ return
+ C = roles(s)
+ c = 1 if s.reduced else detent(t / 0.28, 3)
+ locked = t >= 0.26
+ flash = clamp(1 - (t - 0.26) / 0.12) if locked else 0
+ alpha = 1 if t < 0.38 else 1 - (t - 0.38) / 0.22
+ if s.method == "switch":
+ # A switch came in by no edge, so there is no register to mark: only the cross.
+ rule_cross(ctx, s, C, c, locked, flash, alpha)
+ return
+ ctx.save()
+ k = frame(ctx, s, False)
+
+ def ticks():
+ for ray in k.rays:
+ for i in range(1, 5):
+ if i * 6 <= ray.max:
+ tick_to(ctx, ray, i * 6, 2, 10 if i == 4 else 6)
+ ink(ctx, s, C.lit, 1.25, alpha * 0.9, ticks)
+ ink(ctx, s, C.lit, 1.5, alpha, normal_line(ctx, k.centre, 2, 12))
+ if k.kind == "notch":
+ o = lerp(28, 12, c)
+
+ def hug():
+ for ray in k.rays:
+ rail_to(ctx, ray, 0, min(38, ray.max), o)
+ ink(ctx, s, C.lit if locked else C.dim, 1.25, alpha, hug)
+ ink(ctx, s, C.hot, 2, alpha * flash, hug)
+ ink(ctx, s, C.hot, 1.5, alpha, lambda: tick_to(ctx, k.rays[0], 0, o, o + 10))
+ ctx.restore()
+ return
+ ctx.restore()
+ rule_cross(ctx, s, C, c, locked, flash, alpha)
+
+
+def rule_cross(ctx, s, C, c, locked, flash, alpha):
+ r, P = lerp(40, 22, c), s.point
+
+ def arms():
+ for a in range(4):
+ dx, dy = math.cos(a * PI / 2), math.sin(a * PI / 2)
+ ctx.moveTo(P.x + dx * r, P.y + dy * r)
+ ctx.lineTo(P.x + dx * (r + 9), P.y + dy * (r + 9))
+ ink(ctx, s, C.lit if locked else C.dim, 1.5, alpha, arms)
+ ink(ctx, s, C.hot, 2, alpha * flash, arms)
+
+
+def gauge_notch(ctx, s, k, C):
+ tr, J = k.track, 32
+ L = tr.L
+ ray = SimpleNamespace(at=tr.at)
+ if s.since is None:
+ p = s.pressure
+ alpha = clamp(p * 3)
+ q = detent(p, 16, 0.5)
+ lit_to = (math.floor(p * 16 + 1e-6) / 16) if s.reduced else q
+ flash = tick_flash(s)
+ off, on, hot = [], [], []
+ for j in range(J + 1):
+ major = j % 8 == 0
+ length = 10 if major else 5
+ (on if j / J <= lit_to + 1e-6 else off).append((ray, j * L / J, 4, 4 + length))
+ if flash and j == s.tick.index * 8:
+ hot.append((ray, j * L / J, 4, 4 + length + (0 if s.reduced else 7 * flash)))
+ ink(ctx, s, C.dim, 1, alpha * 0.45, lambda: rail_to(ctx, ray, 0, L, 2))
+ if lit_to > 0:
+ ink(ctx, s, C.lit, 2, alpha, lambda: rail_to(ctx, ray, 0, L * lit_to, 2))
+ ink(ctx, s, C.dim, 1.25, alpha * 0.5, comb(ctx, off))
+ ink(ctx, s, C.lit, 1.25, alpha, comb(ctx, on))
+ ink(ctx, s, C.hot, 1.5, alpha * flash, comb(ctx, hot))
+ if not s.reduced:
+ ink(ctx, s, C.lit, 2, alpha, lambda: tick_to(ctx, ray, L * q, 2, 22))
+ return
+ u = s.since
+ if u >= 0.6:
+ return
+ fade = 1 if u < 0.4 else 1 - (u - 0.4) / 0.2
+ shut = 1 if s.reduced else detent(u / 0.36, 4)
+ a, b = k.tp * shut, L - (L - k.tp) * shut
+
+ def blades():
+ band_to(ctx, ray, 0, max(a, 0.5), 2, 20)
+ band_to(ctx, ray, min(b, L - 0.5), L, 2, 20)
+ fill_with(ctx, "#000", 0.5 * fade, blades)
+
+ def edges():
+ tick_to(ctx, ray, a, 2, 20)
+ tick_to(ctx, ray, b, 2, 20)
+ ink(ctx, s, C.lit, 1.5, fade, edges)
+
+ def teeth():
+ for j in range(J + 1):
+ d = j * L / J
+ if a < d < b:
+ tick_to(ctx, ray, d, 4, 14 if j % 8 == 0 else 9)
+ ink(ctx, s, C.hot, 1.25, fade * 0.9, teeth)
+ ink(ctx, s, C.hot, 2, fade, lambda: rail_to(ctx, ray, 0, L, 2))
+
+
+def gauge_depart(ctx, s):
+ C, G = roles(s), 16
+ k = frame(ctx, s, True)
+ if k.kind == "notch":
+ return gauge_notch(ctx, s, k, C)
+ R0 = 58 if k.kind == "corner" else 46
+ sweep = PI / 2 if k.kind == "corner" else PI
+
+ def grads(o, lit_to, flash_k, flash_len):
+ off, on, hot = [], [], []
+ for j in range(G + 1):
+ ang = sweep * j / G
+ cs, sn = math.cos(ang), math.sin(ang)
+ length = 10 if j % 4 == 0 else 5
+ (on if j / G <= lit_to + 1e-6 else off).append((cs, sn, R0 - length, R0))
+ if j == flash_k:
+ hot.append((cs, sn, R0 - length, R0 + flash_len))
+
+ def draw(items):
+ def build():
+ for cs, sn, a, b in items:
+ ctx.moveTo(cs * a, sn * a)
+ ctx.lineTo(cs * b, sn * b)
+ return build
+ return SimpleNamespace(off=draw(off), on=draw(on), hot=draw(hot))
+
+ if s.since is None:
+ p = s.pressure
+ alpha = clamp(p * 3)
+ q = detent(p, G, 0.5)
+ lit_to = (math.floor(p * G + 1e-6) / G) if s.reduced else q
+ flash = tick_flash(s)
+ g = grads(0, lit_to, s.tick.index * 4 if flash else -1, 0 if s.reduced else 8 * flash)
+ ink(ctx, s, C.dim, 1, alpha * 0.45, lambda: ctx.arc(0, 0, R0 + 3, 0, sweep))
+ if lit_to > 0:
+ ink(ctx, s, C.lit, 2.2, alpha, lambda: ctx.arc(0, 0, R0 + 3, 0, sweep * lit_to))
+ ink(ctx, s, C.dim, 1.25, alpha * 0.5, g.off)
+ ink(ctx, s, C.lit, 1.25, alpha, g.on)
+ ink(ctx, s, C.hot, 1.5, alpha * flash, g.hot)
+ if not s.reduced:
+ ang = sweep * q
+
+ def needle():
+ ctx.moveTo(math.cos(ang) * 9, math.sin(ang) * 9)
+ ctx.lineTo(math.cos(ang) * (R0 - 13), math.sin(ang) * (R0 - 13))
+ ink(ctx, s, C.lit, 2, alpha, needle)
+ ink(ctx, s, C.lit, 1.25, alpha, lambda: ctx.arc(0, 0, 5, 0, sweep))
+ return
+ u = s.since
+ if u >= 0.6:
+ return
+ fade = (1 - detent(u / 0.6, 4, 0.25)) if s.reduced else (1 if u < 0.4 else 1 - (u - 0.4) / 0.2)
+ shut = 1 if s.reduced else detent(u / 0.36, 4)
+ a = R0 * (1 - shut)
+ rot = shut * PI / 6
+
+ def blade():
+ ctx.moveTo(R0, 0)
+ ctx.arc(0, 0, R0, 0, sweep)
+ if a > 0.5:
+ ctx.lineTo(a * math.cos(sweep), a * math.sin(sweep))
+ ctx.arc(0, 0, a, sweep, 0, True)
+ else:
+ ctx.lineTo(0, 0)
+ ctx.closePath()
+ fill_with(ctx, "#000", 0.5 * fade, blade)
+ length = math.sqrt(max(0, R0 * R0 - a * a))
+ if length > 0.5:
+ def spokes():
+ for i in range(6):
+ f = i * PI / 3 + rot
+ px, py = a * math.cos(f), a * math.sin(f)
+ ctx.moveTo(px, py)
+ ctx.lineTo(px - math.sin(f) * length, py + math.cos(f) * length)
+ ink(ctx, s, C.lit, 1.25, fade, spokes)
+ g = grads(0, 1, -1, 0)
+ ink(ctx, s, C.hot, 1.25, fade * 0.9, g.on)
+ ink(ctx, s, C.hot, 2, fade, lambda: ctx.arc(0, 0, R0 + 3, 0, sweep))
+
+
+def gauge_arrive(ctx, s):
+ t = s.since
+ if t >= 0.7:
+ return
+ C = roles(s)
+ c = 1 if s.reduced else detent(t / 0.34, 4)
+ lock_at = 0.3
+ locked = t >= lock_at
+ flash = clamp(1 - (t - lock_at) / 0.14) if locked else 0
+ alpha = 1 if t < 0.46 else 1 - (t - 0.46) / 0.24
+ ctx.save()
+ k = frame(ctx, s, False)
+ if k.kind == "notch":
+ tr, L = k.track, k.track.L
+ o = lerp(34, 10, c)
+ ray = SimpleNamespace(at=tr.at)
+
+ def ticks():
+ for j in range(25):
+ tick_to(ctx, ray, j * L / 24, o, o + (8 if j % 6 == 0 else 4))
+ ink(ctx, s, C.lit, 1.5, alpha, lambda: rail_to(ctx, ray, 0, L, o))
+ ink(ctx, s, C.lit if locked else C.dim, 1.25, alpha, ticks)
+ ink(ctx, s, C.hot, 1.75, alpha * flash, ticks)
+ ink(ctx, s, C.hot, 2, alpha, lambda: tick_to(ctx, ray, k.tp, o, o + 14))
+ ctx.restore()
+ return
+ if k.kind == "corner" and s.method != "switch":
+ # A switch came in by no edge, so a pointer that happens to sit near a corner has no
+ # corner register to mark, as Rule and Rangefinder skip theirs.
+ J = lerp(96, 30, c)
+
+ def bracket():
+ ctx.moveTo(J, 1)
+ ctx.lineTo(1, 1)
+ ctx.lineTo(1, J)
+ ink(ctx, s, C.lit, 1.75, alpha, bracket)
+ ctx.restore()
+ P, r, rot = s.point, lerp(96, 30, c), c * PI / 3
+
+ def ticks():
+ for j in range(24):
+ a = rot + j * TAU / 24
+ length = 8 if j % 6 == 0 else 4
+ ctx.moveTo(P.x + math.cos(a) * r, P.y + math.sin(a) * r)
+ ctx.lineTo(P.x + math.cos(a) * (r - length), P.y + math.sin(a) * (r - length))
+ ink(ctx, s, C.lit, 1.5, alpha, lambda: ctx.arc(P.x, P.y, r, 0, TAU))
+ ink(ctx, s, C.lit if locked else C.dim, 1.25, alpha, ticks)
+ ink(ctx, s, C.hot, 1.75, alpha * flash, ticks)
+
+ def cross():
+ for q in range(4):
+ dx, dy = math.cos(q * PI / 2), math.sin(q * PI / 2)
+ ctx.moveTo(P.x + dx * (r + 3), P.y + dy * (r + 3))
+ ctx.lineTo(P.x + dx * (r + 15), P.y + dy * (r + 15))
+ ink(ctx, s, C.lit, 1.5, alpha, cross)
+
+
+def lamps(ctx, s, k, C, count, flash, alpha):
+ c, t = k.centre, k.tangent
+ spots = []
+ for i in range(3):
+ if k.kind == "corner":
+ o = 32 + 11 * i
+ spots.append((c.x + c.nx * o, c.y + c.ny * o))
+ else:
+ spots.append((c.x + c.nx * 38 + t.x * 10 * (i - 1), c.y + c.ny * 38 + t.y * 10 * (i - 1)))
+
+ def box(items):
+ def build():
+ for x, y in items:
+ ctx.rect(x - 2.5, y - 2.5, 5, 5)
+ return build
+ lit, dark = spots[:count], spots[count:]
+ ink(ctx, s, C.dim, 1, alpha * 0.6, box(dark))
+ if lit:
+ def halo():
+ for x, y in lit:
+ ctx.rect(x - 3.5, y - 3.5, 7, 7)
+ fill_with(ctx, "#000", alpha * 0.6, halo)
+ fill_with(ctx, C.lit, alpha, box(lit))
+ if flash:
+ fill_with(ctx, C.hot, alpha * flash, box(lit[-1:]))
+
+
+def rangefinder_depart(ctx, s):
+ C = roles(s)
+ k = frame(ctx, s, True)
+ SP = 6
+ SPAN = 108 if k.kind == "notch" else 150
+ if s.since is None:
+ p = s.pressure
+ alpha = clamp(p * 3)
+ flash = tick_flash(s)
+ close = 0 if s.reduced else detent(p, 16, 0.45)
+ off, on, jaws = [], [], []
+ for ray in k.rays:
+ lim = min(SPAN, ray.max)
+ J = lerp(lim, 8, close)
+ lit_from = lim * (1 - p) if s.reduced else J
+ jaws.append((ray, J))
+ i = 1
+ while i * SP <= lim:
+ (on if i * SP >= lit_from - 0.01 else off).append((ray, i * SP, 1, 1 + (12 if i % 5 == 0 else 5)))
+ i += 1
+
+ def rails():
+ for ray in k.rays:
+ rail_to(ctx, ray, 0, min(SPAN, ray.max), 1)
+ ink(ctx, s, C.dim, 1, alpha * 0.45, rails)
+ ink(ctx, s, C.dim, 1.25, alpha * 0.5, comb(ctx, off))
+ ink(ctx, s, C.lit, 1.25, alpha, comb(ctx, on))
+ ink(ctx, s, C.dim, 1, alpha * 0.7, normal_line(ctx, k.centre, 1, 28))
+
+ def jaw_marks():
+ for ray, J in jaws:
+ tick_to(ctx, ray, J, 0, 24)
+ rail_to(ctx, ray, J, J + 7, 24)
+ ink(ctx, s, C.lit, 2, alpha, jaw_marks)
+
+ def jaw_fill():
+ for ray, J in jaws:
+ a, b, c = ray.at(J), ray.at(J - 3), ray.at(J + 3)
+ ctx.moveTo(a.x + a.nx * 1, a.y + a.ny * 1)
+ ctx.lineTo(b.x + b.nx * 8, b.y + b.ny * 8)
+ ctx.lineTo(c.x + c.nx * 8, c.y + c.ny * 8)
+ ctx.closePath()
+ fill_with(ctx, C.lit, alpha, jaw_fill)
+
+ def jaw_flash():
+ for ray, J in jaws:
+ tick_to(ctx, ray, J, 0, 24 if s.reduced else 24 + 16 * flash)
+ ink(ctx, s, C.hot, 1.25, alpha * flash, jaw_flash)
+ lamps(ctx, s, k, C, s.tick.index if s.tick else 0, flash, alpha)
+ return
+ u = s.since
+ if u >= 0.8:
+ return
+ fade = 1 if u < 0.55 else 1 - (u - 0.55) / 0.25
+ A = 0 if s.reduced else SPAN * (1 - detent(u / 0.42, 4))
+ slit = 70 if s.reduced else 70 * (1 - detent(u / 0.55, 5))
+ blades, on = [], []
+ for ray in k.rays:
+ lim = min(SPAN, ray.max)
+ if A < lim:
+ blades.append((ray, A, lim))
+ i = 1
+ while i * SP <= min(A, lim):
+ on.append((ray, i * SP, 1, 1 + (12 if i % 5 == 0 else 5)))
+ i += 1
+
+ def band():
+ for ray, a, b in blades:
+ band_to(ctx, ray, a, b, 0, 26)
+ fill_with(ctx, "#000", 0.5 * fade, band)
+
+ def rails2():
+ for ray, a, b in blades:
+ rail_to(ctx, ray, a, b, 26)
+ ink(ctx, s, C.dim, 1, fade * 0.7, rails2)
+
+ def edges():
+ for ray, a, _b in blades:
+ tick_to(ctx, ray, a, 0, 26)
+ ink(ctx, s, C.lit, 2, fade, edges)
+ ink(ctx, s, C.hot, 1.25, fade, comb(ctx, on))
+ if slit > 0.5:
+ ink(ctx, s, C.hot, 2.5, fade, normal_line(ctx, k.centre, 0, slit))
+ lamps(ctx, s, k, C, 3, 0, fade)
+
+
+def rangefinder_arrive(ctx, s):
+ t = s.since
+ if t >= 0.8:
+ return
+ C = roles(s)
+ c = 1 if s.reduced else detent(t / 0.4, 4)
+ LOCK = 0.34
+ locked = t >= LOCK
+ flash = clamp(1 - (t - LOCK) / 0.18) if locked else 0
+ alpha = 1 if t < 0.55 else 1 - (t - 0.55) / 0.25
+ if s.method == "switch":
+ # A switch came in by no edge, so there are no jaws to close along it: only the dial.
+ rangefinder_dial(ctx, s, C, c, locked, flash, alpha)
+ return
+ ctx.save()
+ k = frame(ctx, s, False)
+ JM = 60 if k.kind == "notch" else 104
+ on, jaws = [], []
+ for ray in k.rays:
+ J = min(JM, ray.max) * c
+ if J > 1:
+ jaws.append((ray, J))
+ i = 1
+ while i * 6 <= J:
+ on.append((ray, i * 6, 1, 1 + (12 if i % 5 == 0 else 5)))
+ i += 1
+ ink(ctx, s, C.lit, 1.25, alpha, comb(ctx, on))
+
+ def jaw_marks():
+ for ray, J in jaws:
+ tick_to(ctx, ray, J, 0, 22)
+ rail_to(ctx, ray, J, J + 7, 22)
+ ink(ctx, s, C.lit, 2, alpha, jaw_marks)
+ if k.kind == "notch":
+ tr, L = k.track, k.track.L
+ o = lerp(28, 9, c)
+ ray = SimpleNamespace(at=tr.at)
+
+ def outline():
+ rail_to(ctx, ray, 0, L, o)
+ ink(ctx, s, C.lit if locked else C.dim, 1.5, alpha, outline)
+ ink(ctx, s, C.hot, 2.25, alpha * flash, outline)
+
+ def teeth():
+ for j in range(37):
+ tick_to(ctx, ray, j * L / 36, o, o + (7 if j % 9 == 0 else 3))
+ ink(ctx, s, C.dim, 1, alpha * 0.8, teeth)
+ ink(ctx, s, C.hot, 2, alpha, lambda: tick_to(ctx, ray, k.tp, o, o + 16))
+ ctx.restore()
+ return
+ ctx.restore()
+ rangefinder_dial(ctx, s, C, c, locked, flash, alpha)
+
+
+def rangefinder_dial(ctx, s, C, c, locked, flash, alpha):
+ P = s.point
+ r = lerp(96, 34, c)
+ rot = c * 4 * (TAU / 36) * 2
+ ink(ctx, s, C.lit, 1.5, alpha, lambda: ctx.arc(P.x, P.y, r, 0, TAU))
+
+ def grads():
+ for j in range(36):
+ a = rot + j * TAU / 36
+ length = 9 if j % 9 == 0 else 4
+ ctx.moveTo(P.x + math.cos(a) * r, P.y + math.sin(a) * r)
+ ctx.lineTo(P.x + math.cos(a) * (r + length), P.y + math.sin(a) * (r + length))
+ ink(ctx, s, C.dim, 1.1, alpha * 0.85, grads)
+ ink(ctx, s, C.hot, 1.5, alpha * flash, grads)
+
+ def outer_ticks():
+ for q in range(4):
+ dx, dy = math.cos(q * PI / 2), math.sin(q * PI / 2)
+ ctx.moveTo(P.x + dx * (r + 12), P.y + dy * (r + 12))
+ ctx.lineTo(P.x + dx * (r + 22), P.y + dy * (r + 22))
+ ink(ctx, s, C.lit, 1.25, alpha, outer_ticks)
+
+ def spokes():
+ for q in range(4):
+ dx, dy = math.cos(q * PI / 2), math.sin(q * PI / 2)
+ a = max(20, 0.6 * r)
+ ctx.moveTo(P.x + dx * a, P.y + dy * a)
+ ctx.lineTo(P.x + dx * (r - 6), P.y + dy * (r - 6))
+ ink(ctx, s, C.dim, 1, alpha * 0.8, spokes)
+
+ b = r * 0.66
+
+ def brackets():
+ for sx, sy in ((1, 1), (-1, 1), (-1, -1), (1, -1)):
+ ctx.moveTo(P.x + sx * (b - 9), P.y + sy * b)
+ ctx.lineTo(P.x + sx * b, P.y + sy * b)
+ ctx.lineTo(P.x + sx * b, P.y + sy * (b - 9))
+ ink(ctx, s, C.lit if locked else C.dim, 1.75, alpha, brackets)
+ ink(ctx, s, C.hot, 2.25, alpha * flash, brackets)
+ if locked:
+ def corners():
+ for q in range(4):
+ dx, dy = math.cos(q * PI / 2), math.sin(q * PI / 2)
+ ctx.rect(P.x + dx * (r + 6) - 2, P.y + dy * (r + 6) - 2, 4, 4)
+ fill_with(ctx, C.hot, alpha, corners)
+
+
+EFFECTS = [
+ Effect(
+ "rule", "Rule", "quiet",
+ "A fine ruler rises along the edge round the pointer and lights outward one division at a "
+ "time as the push builds, the three quarter detents marked long. At breakthrough it closes "
+ "on the pointer in four clicks; on the other screen a short register mark sits where you "
+ "came in and a four-arm cross steps in three clicks onto the landing point.",
+ rule_depart, rule_arrive, 0.45, 0.6,
+ ),
+ Effect(
+ "gauge", "Gauge", "medium",
+ "A half dial seated on the edge at the pointer, a quarter dial in the corner and a "
+ "graduated collar round the notch, whose needle clicks round sixteen detents as the push "
+ "builds. At breakthrough an iris shuts over the dial in four steps; on the other screen a "
+ "graduated ring contracts onto the landing point, turning one graduation per click, and "
+ "flashes as it locks.",
+ gauge_depart, gauge_arrive, 0.6, 0.7,
+ ),
+ Effect(
+ "rangefinder", "Rangefinder", "showpiece",
+ "A long scale runs along the edge and a pair of caliper jaws closes on the pointer in "
+ "detents, lighting the divisions it passes, while three tally lamps light at each quarter. "
+ "At breakthrough shutter blades slide in from both ends and a bright slit at the pointer "
+ "shuts; on the far screen the jaws open outward from the entry point as a graduated "
+ "reticle with corner brackets steps in, turns and locks onto the landing point.",
+ rangefinder_depart, rangefinder_arrive, 0.8, 0.8,
+ ),
+]
+
+PACKS = {
+ "phosphor": ("Phosphor", ["#3dff7f", "#1f9e52", "#caffdc"]),
+ "sodium": ("Sodium", ["#ffa51f", "#c46a12", "#ffe0a3"]),
+ "contrast": ("Contrast", ["#f0e442", "#56b4e9", "#ffffff"]),
+}
diff --git a/win_app/fx_membrane.py b/win_app/fx_membrane.py
new file mode 100644
index 0000000..8f2c89b
--- /dev/null
+++ b/win_app/fx_membrane.py
@@ -0,0 +1,546 @@
+"""Membrane: crossing is pushing through a skin, the boundary stretching thin under the pointer
+until it tears, and the same skin on the other screen rippling out from where you came through and
+healing behind you.
+"""
+
+import math
+from types import SimpleNamespace
+
+import effects
+
+TAU = effects.TAU
+clamp = effects.clamp
+lerp = effects.lerp
+ease_out = effects.ease_out
+
+
+# The radius of a switch's ring round the pointer, before the effect's own gap from the edge.
+POINT_RING = 14
+
+
+def smooth(a, b, x):
+ u = clamp((x - a) / (b - a))
+ return u * u * (3 - 2 * u)
+
+
+def bump(x):
+ return math.exp(-x * x)
+
+
+def rgb(h):
+ return [int(h[1:3], 16), int(h[3:5], 16), int(h[5:7], 16)]
+
+
+def hue(pal, u):
+ n = len(pal)
+ f = math.fmod(math.fmod(u, n) + n, n)
+ i = int(math.floor(f)) % n
+ k = f - math.floor(f)
+ a, b = pal[i], pal[(i + 1) % n]
+ return [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k]
+
+
+def rgba(c, a):
+ return f"rgba({math.trunc(c[0])},{math.trunc(c[1])},{math.trunc(c[2])},{clamp(a):.3f})"
+
+
+def ink(a):
+ return f"rgba(0,0,0,{clamp(a):.3f})"
+
+
+def line(a, b):
+ length = math.hypot(b[0] - a[0], b[1] - a[1])
+
+ def at(u):
+ return (a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u)
+
+ return SimpleNamespace(len=length, at=at)
+
+
+def arc(cx, cy, r, a0, a1, mapper):
+ length = abs(a1 - a0) * r
+
+ def at(u):
+ a = a0 + (a1 - a0) * u
+ return mapper(cx + r * math.cos(a), cy + r * math.sin(a))
+
+ return SimpleNamespace(len=length, at=at)
+
+
+def same(x, y):
+ return (x, y)
+
+
+def sample(segs, anchor, ref):
+ pts = []
+ for j, sg in enumerate(segs):
+ n = max(1, math.ceil(sg.len / 4))
+ for i in range(1 if j else 0, n + 1):
+ x, y = sg.at(i / n)
+ pts.append(SimpleNamespace(x=x, y=y))
+ t = 0.0
+ i0 = 0
+ best = math.inf
+ for i, p in enumerate(pts):
+ if i:
+ t += math.hypot(p.x - pts[i - 1].x, p.y - pts[i - 1].y)
+ p.t = t
+ a = pts[max(0, i - 1)]
+ b = pts[min(len(pts) - 1, i + 1)]
+ tx, ty = b.x - a.x, b.y - a.y
+ m = math.hypot(tx, ty) or 1.0
+ p.nx, p.ny = -ty / m, tx / m
+ dd = (p.x - anchor[0]) ** 2 + (p.y - anchor[1]) ** 2
+ if dd < best:
+ best, i0 = dd, i
+ o = pts[i0]
+ flip = -1.0 if o.nx * (o.x - ref[0]) + o.ny * (o.y - ref[1]) < 0 else 1.0
+ for p in pts:
+ p.nx *= flip
+ p.ny *= flip
+ p.d = p.t - o.t
+ p.end = min(p.t, t - p.t)
+ return SimpleNamespace(pts=pts, total=t)
+
+
+def edge_geo(s, edge):
+ W, H = s.screen.w, s.screen.h
+ side = edge in ("left", "right")
+
+ def mapper(u, v):
+ if edge == "left":
+ return (v, u)
+ if edge == "right":
+ return (W - v, u)
+ if edge == "top":
+ return (u, v)
+ return (u, H - v)
+
+ u0 = s.point.y if side else s.point.x
+ return SimpleNamespace(kind="edge", map=mapper, u0=u0, centre=mapper(u0, 0))
+
+
+def geo_of(s, leaving):
+ W, H = s.screen.w, s.screen.h
+ p = s.point
+ n = getattr(s, "notch", None)
+ if leaving:
+ r = s.region
+ if r.kind == "notch":
+ return SimpleNamespace(kind="notch", anchor=(p.x, p.y), centre=(p.x, 0))
+ if r.kind == "corner":
+ cx = W if "right" in r.corner else 0
+ cy = H if "bottom" in r.corner else 0
+ return SimpleNamespace(kind="corner", cx=cx, cy=cy, centre=(cx, cy))
+ return edge_geo(s, r.edge)
+ if s.method == "switch":
+ # A switch, away from any edge: the skin closes as a small ring round the pointer.
+ return SimpleNamespace(kind="point", centre=(p.x, p.y))
+ if n is not None and s.edge == "top" and n.x - 24 < p.x < n.x + n.w + 24:
+ return SimpleNamespace(kind="notch", anchor=(p.x, p.y), centre=(p.x, p.y))
+ cx = 0 if p.x < 20 else (W if p.x > W - 20 else -1)
+ cy = 0 if p.y < 20 else (H if p.y > H - 20 else -1)
+ if cx >= 0 and cy >= 0:
+ return SimpleNamespace(kind="corner", cx=cx, cy=cy, centre=(cx, cy))
+ return edge_geo(s, s.edge)
+
+
+def contour(s, geo, g, L, o):
+ if geo.kind == "edge":
+ mapper, u0 = geo.map, geo.u0
+ return sample([line(mapper(u0 - L, g), mapper(u0 + L, g))], mapper(u0, g), geo.centre)
+ if geo.kind == "point":
+ cx, cy = geo.centre
+ R = POINT_RING + g
+ # Starting opposite the top, so the ring's gap and bulge sit above the pointer's tip.
+ return sample([arc(cx, cy, R, math.pi / 2, math.pi / 2 + TAU, same)], (cx, cy - R), geo.centre)
+ if geo.kind == "corner":
+ sx = -1 if geo.cx else 1
+ sy = -1 if geo.cy else 1
+
+ def M(a, b):
+ return (geo.cx + sx * a, geo.cy + sy * b)
+
+ rho = max(3, o["rho"])
+ c = g + rho
+ arm = max(c + 12, L)
+ k = c - rho / math.sqrt(2)
+ return sample([line(M(arm, g), M(c, g)), arc(c, c, rho, -math.pi / 2, -math.pi, M),
+ line(M(g, c), M(g, arm))], M(k, k), geo.centre)
+ n = s.notch
+ lo = n.h - n.r
+ x0, x1 = n.x - g, n.x + n.w + g
+ R = n.r + g
+ arm = o.get("arm") or 0
+ f = max(2, min(8, lo - g - 2))
+ segs = []
+ if arm:
+ segs.append(line((x0 - f - arm, g), (x0 - f, g)))
+ segs.append(arc(x0 - f, g + f, f, -math.pi / 2, 0, same))
+ segs.append(line((x0, g + f), (x0, lo)))
+ else:
+ segs.append(line((x0, 0), (x0, lo)))
+ segs.append(arc(n.x + n.r, lo, R, math.pi, math.pi / 2, same))
+ segs.append(line((n.x + n.r, n.h + g), (n.x + n.w - n.r, n.h + g)))
+ segs.append(arc(n.x + n.w - n.r, lo, R, math.pi / 2, 0, same))
+ if arm:
+ segs.append(line((x1, lo), (x1, g + f)))
+ segs.append(arc(x1 + f, g + f, f, math.pi, math.pi * 1.5, same))
+ segs.append(line((x1 + f, g), (x1 + f + arm, g)))
+ else:
+ segs.append(line((x1, lo), (x1, 0)))
+ return sample(segs, geo.anchor, (n.x + n.w / 2, 0))
+
+
+def trace(ctx, C, off, keep):
+ ctx.beginPath()
+ pen = False
+ for p in C.pts:
+ if keep and not keep(p):
+ pen = False
+ continue
+ o = off(p)
+ x, y = p.x + p.nx * o, p.y + p.ny * o
+ if pen:
+ ctx.lineTo(x, y)
+ else:
+ ctx.moveTo(x, y)
+ pen = True
+
+
+def along(ctx, C, stop):
+ P = C.pts
+ A, Z = P[0], P[-1]
+ dx, dy = Z.x - A.x, Z.y - A.y
+ l2 = (dx * dx + dy * dy) or 1.0
+ g = ctx.createLinearGradient(A.x, A.y, Z.x, Z.y)
+ every = max(1, math.ceil(len(P) / 30))
+ idx = list(range(0, len(P), every))
+ if idx[-1] != len(P) - 1:
+ idx.append(len(P) - 1)
+ last = 0.0
+ for i in idx:
+ p = P[i]
+ q = clamp(((p.x - A.x) * dx + (p.y - A.y) * dy) / l2)
+ if q < last:
+ q = last
+ last = q
+ g.addColorStop(q, stop(p))
+ return g
+
+
+def film_layer(C, off, keep, lw, alpha, colour, halo=1):
+ def path(ctx):
+ trace(ctx, C, off, keep)
+
+ def paint(ctx, U):
+ if U:
+ return along(ctx, C, lambda p: ink(alpha(p) * U))
+ return along(ctx, C, lambda p: rgba(colour(p), alpha(p)))
+
+ return SimpleNamespace(lw=lw, halo=halo, path=path, paint=paint)
+
+
+def ring_layer(c, r, lw, a, pal, phase):
+ def path(ctx):
+ ctx.beginPath()
+ ctx.arc(c[0], c[1], r, 0, TAU)
+
+ def paint(ctx, U):
+ if U:
+ return ink(a * U)
+ g = ctx.createConicGradient(phase, c[0], c[1])
+ for j in range(13):
+ g.addColorStop(j / 12, rgba(hue(pal, phase + (j / 12) * len(pal) * 2), a))
+ return g
+
+ return SimpleNamespace(lw=lw, halo=1, path=path, paint=paint)
+
+
+def render(ctx, s, layers):
+ ctx.lineJoin = "round"
+ ctx.lineCap = "round"
+ U = 0.32 if s.dark else 0.58
+ pad = 1.6 if s.dark else 2.4
+ ctx.globalCompositeOperation = "source-over"
+ for l in layers:
+ h = l.halo
+ l.path(ctx)
+ ctx.lineWidth = l.lw + pad * h
+ ctx.strokeStyle = l.paint(ctx, U * h)
+ ctx.stroke()
+ ctx.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ for l in layers:
+ l.path(ctx)
+ ctx.lineWidth = l.lw
+ ctx.strokeStyle = l.paint(ctx, 0)
+ ctx.stroke()
+
+
+def sheen(ctx, s, C, off, keep, base, alpha, colour):
+ runs = []
+ cur = None
+ for p in C.pts:
+ if keep and not keep(p):
+ cur = None
+ continue
+ if cur is None:
+ cur = []
+ runs.append(cur)
+ cur.append(p)
+ ctx.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ ctx.fillStyle = along(ctx, C, lambda p: rgba(colour(p), alpha(p)))
+ ctx.beginPath()
+ for run in runs:
+ if len(run) < 2:
+ continue
+ for i, p in enumerate(run):
+ o = off(p)
+ x, y = p.x + p.nx * o, p.y + p.ny * o
+ if i:
+ ctx.lineTo(x, y)
+ else:
+ ctx.moveTo(x, y)
+ for i in range(len(run) - 1, -1, -1):
+ p = run[i]
+ ctx.lineTo(p.x - p.nx * base, p.y - p.ny * base)
+ ctx.closePath()
+ ctx.fill()
+
+
+def _sign(x):
+ return (x > 0) - (x < 0)
+
+
+def _depart(ctx, s, P):
+ broke = s.since is not None
+ t = s.since if broke else 0.0
+ secs = P["departSeconds"]
+ if broke and t >= secs:
+ return
+ p = 1.0 if broke else s.pressure
+ if not (p > 0):
+ return
+ red = s.reduced
+ pal = [rgb(h) for h in s.palette]
+ geo = geo_of(s, True)
+ notch = geo.kind == "notch"
+ corner = geo.kind == "corner"
+ g = 5 if notch else P["g"]
+ L = 250 if notch else (P["L"] * 0.8 if corner else P["L"])
+ u = t / secs
+ if broke:
+ level = ((1 - u) ** 1.25) * (1 + 0.6 * math.exp(-t * 18))
+ else:
+ level = smooth(0, 0.14, p) * (0.42 + 0.58 * p)
+ tick = getattr(s, "tick", None)
+ age = tick.age if (tick and not broke) else -1
+ wob = math.exp(-age * 10) * math.sin(age * 44) if (age >= 0 and not red) else 0.0
+ pulse = 0.5 * math.exp(-age * 9) if (age >= 0 and red) else 0.0
+ w = 44.0 if red else lerp(86, 34, p)
+ D = min(g, 0.6 * g if red else g * (0.18 + 0.82 * p) * (1 + 0.4 * wob))
+ if broke and not red:
+ D *= math.exp(-7 * t) * math.cos(21 * t)
+ gap = (18.0 if red else 3 + P["retract"] * t) if broke else -1.0
+ curl = P["curl"] * min(1.0, t * 14) if (broke and not red) else 0.0
+ keep = (lambda q: abs(q.d) >= gap) if broke else None
+ phase = 0.0 if red else 1.3 * p + (2.4 * t if broke else 0.0)
+ pS = 0.5 if red else p
+ rho = 20.0 if red else lerp(44, 9, p)
+
+ def wave(d):
+ if not P["waves"] or age < 0 or red:
+ return 0.0
+ front = abs(d) - 240 * age
+ return 3.2 * math.exp(-3.2 * age) * math.sin(front / 5) * bump(front / 24)
+
+ layers = []
+ main = None
+ for k in range(P["fringes"]):
+ vis = clamp((p - k / 4) / 0.04) if k else 1.0
+ if vis <= 0:
+ continue
+ C = contour(s, geo, g + k * P["sp"], L, {"rho": rho, "arm": 60})
+ crowd = k * P["sp"] * 0.62 * pS
+
+ def off(q, crowd=crowd, k=k):
+ base = -(D + crowd) * bump(q.d / w) + wave(q.d)
+ if curl:
+ base += curl * smooth(gap + 16, gap, abs(q.d))
+ return base
+
+ lw = (1.1 if s.dark else 1.4) if k else P["lw"] * (0.85 if red else 1 - 0.3 * p)
+
+ def alpha(q, vis=vis, k=k):
+ a = level * vis * (1 + pulse) * (1 - smooth(0.45 * L, L, abs(q.d))) * smooth(0, 24, q.end)
+ if notch:
+ a *= 0.55 + 0.45 * bump(q.d / 150)
+ if not broke:
+ a *= 1 - 0.5 * (p ** 4) * bump(q.d / (0.45 * w))
+ return a * (0.8 if k else 1.0)
+
+ def colour(q, k=k):
+ return hue(pal, phase + q.d / 88 + k * 0.9 + 1.4 * pS * bump(q.d / w))
+
+ layers.append(film_layer(C, off, keep, lw, alpha, colour, (0.7 if s.dark else 0.4) if k else 1))
+ if not k:
+ main = SimpleNamespace(C=C, off=off, alpha=alpha, colour=colour)
+
+ if P["sheen"]:
+ sheen(ctx, s, main.C, main.off, keep, g, lambda q: main.alpha(q) * (0.2 if s.dark else 0.3), main.colour)
+ render(ctx, s, layers)
+ if P["beads"] and broke and not red:
+ U = 0.32 if s.dark else 0.58
+ for sgn in (-1, 1):
+ q = None
+ best = math.inf
+ for c in main.C.pts:
+ if _sign(c.d) == sgn and abs(c.d) >= gap and abs(c.d) - gap < best:
+ best = abs(c.d) - gap
+ q = c
+ if q is None:
+ continue
+ a = main.alpha(q)
+ if a <= 0.01:
+ continue
+ o = main.off(q)
+ x, y = q.x + q.nx * o, q.y + q.ny * o
+ r = 1.4 + 2.2 * min(1.0, t * 6)
+ ctx.globalCompositeOperation = "source-over"
+ ctx.fillStyle = ink(a * U)
+ ctx.beginPath()
+ ctx.arc(x, y, r + 1.2, 0, TAU)
+ ctx.fill()
+ ctx.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ ctx.fillStyle = rgba(main.colour(q), a)
+ ctx.beginPath()
+ ctx.arc(x, y, r, 0, TAU)
+ ctx.fill()
+
+
+def _arrive(ctx, s, P):
+ t = s.since
+ secs = P["arriveSeconds"]
+ if not (t < secs):
+ return
+ red = s.reduced
+ pal = [rgb(h) for h in s.palette]
+ geo = geo_of(s, False)
+ u = t / secs
+ notch = geo.kind == "notch"
+ corner = geo.kind == "corner"
+ g = 6 if notch else P["g"]
+ L = P["aL"] * 0.85 if corner else P["aL"]
+ if red:
+ level = smooth(0, 0.05, t) * (1 - smooth(0.4, 1, u))
+ else:
+ level = 1 - smooth(0.45, 1, u)
+ gap = -1.0 if red else P["gap0"] * (max(0.0, 1 - t / 0.2) ** 1.5)
+ bul = 0.45 * P["bulge"] if red else max(-0.7 * g, P["bulge"] * math.exp(-6.5 * t) * math.cos(17 * t))
+
+ def wave(d):
+ if not P["aWave"] or red:
+ return 0.0
+ front = abs(d) - 300 * t
+ return 2.6 * math.exp(-3 * t) * math.sin(front / 5) * bump(front / 26)
+
+ C = contour(s, geo, g, L, {"rho": 22, "arm": 64})
+ keep = (lambda q: abs(q.d) >= gap) if gap > 0 else None
+
+ def off(q):
+ return bul * bump(q.d / 30) + wave(q.d)
+
+ phase = 0.0 if red else 2.6 - 1.8 * u
+
+ def alpha(q):
+ return level * (1 - smooth(0.5 * L, L, abs(q.d))) * smooth(0, 20, q.end)
+
+ def colour(q):
+ return hue(pal, phase + q.d / 88 + 1.2 * bump(q.d / 30))
+
+ layers = [film_layer(C, off, keep, P["lw"], alpha, colour)]
+ for i, R in enumerate(P["rings"]):
+ tau = t - i * P["stagger"]
+ if tau < 0 or tau >= P["ringDur"]:
+ continue
+ v = tau / P["ringDur"]
+ r = P["still"][i] if red else 8 + (R - 8) * ease_out(v)
+ a = (math.sin(math.pi * v) if red else (1 - v) ** 1.3) * (0.85 if i else 1.0)
+ lw = 1.5 if red else lerp(2.6, 0.9, v)
+ if notch:
+ Cr = contour(s, geo, g + 0.6 * r, 0, {"arm": 0})
+ layers.append(film_layer(
+ Cr, lambda q: 0, None, lw,
+ (lambda q, a=a: a * (1 - smooth(50, 140, abs(q.d)))),
+ (lambda q, i=i: hue(pal, phase + i * 1.1 + q.d / 70)),
+ ))
+ else:
+ layers.append(ring_layer(geo.centre, r, lw, a, pal, phase + i * 1.1))
+
+ if P["disc"]:
+ c = geo.anchor if notch else geo.centre
+ Rd = 64.0 if red else 10 + 104 * ease_out(min(1.0, t / 0.55))
+ aD = (0.5 * math.sin(math.pi * u) if red else 0.6 * ((1 - u) ** 1.2)) * (1.0 if s.dark else 0.7)
+ rg = ctx.createRadialGradient(c[0], c[1], 0, c[0], c[1], Rd)
+ for j in range(17):
+ q = j / 16
+ rg.addColorStop(q, rgba(
+ hue(pal, phase + q * 3),
+ aD * (0.5 + 0.5 * math.cos(q * TAU * 3.5)) * ((1 - q) ** 0.8) * smooth(0, 0.15, q),
+ ))
+ ctx.globalCompositeOperation = "lighter" if s.dark else "source-over"
+ ctx.fillStyle = rg
+ ctx.beginPath()
+ ctx.arc(c[0], c[1], Rd, 0, TAU)
+ ctx.fill()
+ render(ctx, s, layers)
+
+
+def _make(id_, name, intensity, blurb, depart_seconds, arrive_seconds, P):
+ def depart(ctx, s):
+ _depart(ctx, s, P)
+
+ def arrive(ctx, s):
+ _arrive(ctx, s, P)
+
+ return effects.Effect(id_, name, intensity, blurb, depart, arrive, depart_seconds, arrive_seconds)
+
+
+EFFECTS = [
+ _make("skin", "Skin", "quiet",
+ "A single iridescent hairline sits just inside the edge and dimples under the pointer as "
+ "you push, thinning and shifting colour. It parts at the pointer and the two ends pull "
+ "back; on the other screen the same hairline closes behind the pointer and one ripple "
+ "spreads out.",
+ 0.45, 0.6,
+ {"departSeconds": 0.45, "arriveSeconds": 0.6, "g": 6, "L": 110, "lw": 2.0, "fringes": 1,
+ "sp": 0, "retract": 300, "curl": 3, "sheen": False, "beads": False, "waves": False,
+ "aL": 84, "gap0": 16, "bulge": 9, "rings": [58], "still": [40], "stagger": 0,
+ "ringDur": 0.5, "disc": False, "aWave": False}),
+ _make("film", "Film", "medium",
+ "A band of interference fringes, one added at each quarter tick, crowds and thins into the "
+ "dent under the pointer, so the band itself is the pressure meter. At breakthrough the film "
+ "tears and each fringe peels back with a curled rim; on the other side the skin bulges in "
+ "around the arriving pointer, springs back, heals, and throws two ripples.",
+ 0.55, 0.7,
+ {"departSeconds": 0.55, "arriveSeconds": 0.7, "g": 7, "L": 150, "lw": 2.2, "fringes": 4,
+ "sp": 3.6, "retract": 330, "curl": 5, "sheen": False, "beads": False, "waves": False,
+ "aL": 110, "gap0": 26, "bulge": 14, "rings": [74, 104], "still": [44, 80],
+ "stagger": 0.09, "ringDur": 0.55, "disc": False, "aWave": False}),
+ _make("rupture", "Rupture", "showpiece",
+ "The whole edge becomes a visible soap film with a sheen behind its fringes; every tick "
+ "sends a shudder along it, and at breakthrough it bursts, the torn rims racing away along "
+ "the edge carrying beads of film. The arrival opens a set of Newton's rings around the "
+ "entry point while the skin bulges in, heals and sends a surface wave along the edge.",
+ 0.7, 0.8,
+ {"departSeconds": 0.7, "arriveSeconds": 0.8, "g": 8, "L": 220, "lw": 2.6, "fringes": 4,
+ "sp": 4, "retract": 420, "curl": 6, "sheen": True, "beads": True, "waves": True,
+ "aL": 118, "gap0": 34, "bulge": 18, "rings": [70, 96, 118], "still": [36, 64, 92],
+ "stagger": 0.08, "ringDur": 0.6, "disc": True, "aWave": True}),
+]
+
+PACKS = {
+ "oil_slick": ("Oil slick", ["#8a4dff", "#2f7dff", "#16c6b0", "#9fdc4a", "#f0c23c", "#e8477f"]),
+ "soap_bubble": ("Soap bubble", ["#ffd98e", "#ff9cc2", "#c3a6ff", "#8fcfff", "#9ef2cf"]),
+ "pearl": ("Pearl", ["#fbf4e8", "#f2c9d6", "#c6dcf2", "#d9f0dc", "#ffffff"]),
+}
diff --git a/win_app/fx_sparks.py b/win_app/fx_sparks.py
new file mode 100644
index 0000000..b60128f
--- /dev/null
+++ b/win_app/fx_sparks.py
@@ -0,0 +1,484 @@
+"""Sparks: crossing is a charge that discharges, sparks gathering at the pointer, sucked through
+the point at breakthrough, and thrown back out where it lands."""
+
+from __future__ import annotations
+
+import math
+from types import SimpleNamespace
+
+import effects
+from effects import TAU, clamp, lerp
+
+INWARD = {"right": (-1, 0), "left": (1, 0), "top": (0, 1), "bottom": (0, -1)}
+
+
+def ease_out(u):
+ return 1 - (1 - clamp(u)) ** 3
+
+
+def ease_in(u):
+ return clamp(u) * clamp(u)
+
+
+def rot(n, a):
+ c, k = math.cos(a), math.sin(a)
+ return (n[0] * c - n[1] * k, n[0] * k + n[1] * c)
+
+
+def turn(a, b):
+ return math.atan2(math.sin(a - b), math.cos(a - b))
+
+
+def rgba(hex_colour, a):
+ v = int(hex_colour[1:], 16)
+ return f"rgba({(v >> 16) & 255},{(v >> 8) & 255},{v & 255},{clamp(a):.3f})"
+
+
+def heat(s, pal, h):
+ k = clamp(h) if s.dark else 0.46 * clamp(h)
+ return pal[min(len(pal) - 1, math.floor((1 - k) * len(pal)))]
+
+
+def shade(s, a):
+ return f"rgba(0,0,0,{clamp(a * (0.3 if s.dark else 0.62)):.3f})"
+
+
+def glow_mode(ctx, s):
+ ctx.globalCompositeOperation = "lighter" if s.dark else "source-over"
+
+
+def depart_frame(s):
+ r, p, W, H = s.region, s.point, s.screen.w, s.screen.h
+ if r.kind == "notch" and getattr(s, "notch", None):
+ n = s.notch
+ x = clamp(p.x, n.x + n.r + 6, n.x + n.w - n.r - 6)
+ return SimpleNamespace(kind="notch", o=SimpleNamespace(x=x, y=n.y + n.h + 1), n=(0, 1),
+ spread=1.25, sink=SimpleNamespace(x=x, y=n.y + n.h - 12))
+ if r.kind == "corner":
+ c = SimpleNamespace(x=W if "right" in r.corner else 0, y=0 if "top" in r.corner else H)
+ e = (-1 if c.x else 1, -1 if c.y else 1)
+ return SimpleNamespace(kind="corner", c=c, e=e,
+ o=SimpleNamespace(x=c.x + e[0] * 2, y=c.y + e[1] * 2),
+ n=(e[0] * math.sqrt(0.5), e[1] * math.sqrt(0.5)), spread=0.66,
+ sink=SimpleNamespace(x=c.x - e[0] * 8, y=c.y - e[1] * 8))
+ n = INWARD[r.edge]
+ return SimpleNamespace(kind="edge", o=SimpleNamespace(x=p.x + n[0], y=p.y + n[1]), n=n,
+ spread=1.34, sink=SimpleNamespace(x=p.x - n[0] * 8, y=p.y - n[1] * 8))
+
+
+def arrive_frame(s):
+ p, W, H = s.point, s.screen.w, s.screen.h
+ if s.method == "switch":
+ # A switch, away from any edge: the sparks go off all round the pointer, thrown up and falling.
+ return SimpleNamespace(kind="point", o=SimpleNamespace(x=p.x, y=p.y), n=(0, -1), spread=math.pi)
+ nt = getattr(s, "notch", None)
+ if nt and s.edge == "top" and nt.x - 4 <= p.x <= nt.x + nt.w + 4:
+ x = clamp(p.x, nt.x + nt.r + 4, nt.x + nt.w - nt.r - 4)
+ return SimpleNamespace(kind="notch", o=SimpleNamespace(x=x, y=nt.y + nt.h + 1),
+ src=SimpleNamespace(x=x, y=nt.y + nt.h - 10), n=(0, 1), spread=1.3)
+ n0, near = INWARD[s.edge], 30
+ ex, ey, corner = n0[0], n0[1], False
+ if ex != 0:
+ if p.y < near:
+ ey, corner = 1, True
+ elif p.y > H - near:
+ ey, corner = -1, True
+ else:
+ if p.x < near:
+ ex, corner = 1, True
+ elif p.x > W - near:
+ ex, corner = -1, True
+ if corner:
+ c = SimpleNamespace(x=0 if ex > 0 else W, y=0 if ey > 0 else H)
+ return SimpleNamespace(kind="corner", c=c, e=(ex, ey),
+ o=SimpleNamespace(x=c.x + ex * 3, y=c.y + ey * 3),
+ n=(ex * math.sqrt(0.5), ey * math.sqrt(0.5)), spread=0.66)
+ return SimpleNamespace(kind="edge", o=SimpleNamespace(x=p.x, y=p.y), n=(ex, ey), spread=1.34)
+
+
+def boundary(ctx, s, f, length, a, colour, width):
+ if a <= 0.01 or length <= 0.5 or f.kind == "point":
+ return
+ W, H = s.screen.w, s.screen.h
+ ctx.beginPath()
+ if f.kind == "notch":
+ n, d = s.notch, 1.6
+ ctx.moveTo(n.x - d, n.y)
+ ctx.lineTo(n.x - d, n.y + n.h - n.r)
+ ctx.quadraticCurveTo(n.x - d, n.y + n.h + d, n.x + n.r, n.y + n.h + d)
+ ctx.lineTo(n.x + n.w - n.r, n.y + n.h + d)
+ ctx.quadraticCurveTo(n.x + n.w + d, n.y + n.h + d, n.x + n.w + d, n.y + n.h - n.r)
+ ctx.lineTo(n.x + n.w + d, n.y)
+
+ def grad(colour_fn):
+ g = ctx.createLinearGradient(f.o.x - length, 0, f.o.x + length, 0)
+ g.addColorStop(0, colour_fn(0))
+ g.addColorStop(0.5, colour_fn(1))
+ g.addColorStop(1, colour_fn(0))
+ return g
+ elif f.kind == "corner":
+ c, e = f.c, f.e
+ ix, iy = c.x + e[0] * 1, c.y + e[1] * 1
+ ctx.moveTo(c.x + e[0] * length, iy)
+ ctx.lineTo(ix, iy)
+ ctx.lineTo(ix, c.y + e[1] * length)
+
+ def grad(colour_fn):
+ g = ctx.createRadialGradient(c.x, c.y, 0, c.x, c.y, length)
+ g.addColorStop(0, colour_fn(1))
+ g.addColorStop(1, colour_fn(0))
+ return g
+ else:
+ n = f.n
+ t = (-n[1], n[0])
+ if n[0] != 0:
+ b = SimpleNamespace(x=1 if n[0] > 0 else W - 1, y=f.o.y)
+ else:
+ b = SimpleNamespace(x=f.o.x, y=1 if n[1] > 0 else H - 1)
+ x0, y0 = b.x - t[0] * length, b.y - t[1] * length
+ x1, y1 = b.x + t[0] * length, b.y + t[1] * length
+ ctx.moveTo(x0, y0)
+ ctx.lineTo(x1, y1)
+
+ def grad(colour_fn):
+ g = ctx.createLinearGradient(x0, y0, x1, y1)
+ g.addColorStop(0, colour_fn(0))
+ g.addColorStop(0.5, colour_fn(1))
+ g.addColorStop(1, colour_fn(0))
+ return g
+ ctx.lineCap = "round"
+ ctx.lineJoin = "round"
+ ctx.globalCompositeOperation = "source-over"
+ ctx.lineWidth = width + 2
+ ctx.strokeStyle = grad(lambda x: shade(s, x * a))
+ ctx.stroke()
+ glow_mode(ctx, s)
+ ctx.lineWidth = width
+ ctx.strokeStyle = grad(lambda x: rgba(colour, x * a))
+ ctx.stroke()
+
+
+def streak(ctx, s, x0, y0, x1, y1, w, colour, a):
+ if a <= 0.01:
+ return
+ ctx.beginPath()
+ ctx.moveTo(x0, y0)
+ ctx.lineTo(x1, y1)
+ ctx.lineCap = "round"
+ ctx.globalCompositeOperation = "source-over"
+ ctx.strokeStyle = shade(s, a)
+ ctx.lineWidth = w + (1.8 if s.dark else 1.4)
+ ctx.stroke()
+ glow_mode(ctx, s)
+ ctx.strokeStyle = rgba(colour, a)
+ ctx.lineWidth = w
+ ctx.stroke()
+
+
+def glow(ctx, s, x, y, r, colour, a):
+ if a <= 0.01 or r <= 0.3:
+ return
+ if not s.dark:
+ d = ctx.createRadialGradient(x, y, 0, x, y, r * 0.75)
+ d.addColorStop(0, f"rgba(0,0,0,{clamp(0.4 * a):.3f})")
+ d.addColorStop(1, "rgba(0,0,0,0)")
+ ctx.globalCompositeOperation = "source-over"
+ ctx.fillStyle = d
+ ctx.beginPath()
+ ctx.arc(x, y, r * 0.75, 0, TAU)
+ ctx.fill()
+ g = ctx.createRadialGradient(x, y, 0, x, y, r)
+ g.addColorStop(0, rgba(colour, a))
+ g.addColorStop(0.28, rgba(colour, a * 0.5))
+ g.addColorStop(1, rgba(colour, 0))
+ glow_mode(ctx, s)
+ ctx.fillStyle = g
+ ctx.beginPath()
+ ctx.arc(x, y, r, 0, TAU)
+ ctx.fill()
+
+
+def dot(ctx, s, x, y, r, colour, a):
+ if a <= 0.01 or r <= 0.2:
+ return
+ ctx.globalCompositeOperation = "source-over"
+ ctx.fillStyle = shade(s, a)
+ ctx.beginPath()
+ ctx.arc(x, y, r + 1, 0, TAU)
+ ctx.fill()
+ glow_mode(ctx, s)
+ ctx.fillStyle = rgba(colour, a)
+ ctx.beginPath()
+ ctx.arc(x, y, r, 0, TAU)
+ ctx.fill()
+
+
+def crackle(ctx, s, ax, ay, bx, by, seed, colour, a):
+ if a <= 0.01:
+ return
+ dx, dy = bx - ax, by - ay
+ L = math.hypot(dx, dy) or 1
+ nx, ny = -dy / L, dx / L
+ ctx.beginPath()
+ ctx.moveTo(ax, ay)
+ for k in range(1, 7):
+ u = k / 7
+ j = (s.hash(seed * 13 + k) * 2 - 1) * min(14, L * 0.2) * math.sin(math.pi * u)
+ ctx.lineTo(ax + dx * u + nx * j, ay + dy * u + ny * j)
+ ctx.lineTo(bx, by)
+ ctx.lineJoin = "miter"
+ ctx.lineCap = "round"
+ ctx.globalCompositeOperation = "source-over"
+ ctx.strokeStyle = shade(s, a)
+ ctx.lineWidth = 2.8
+ ctx.stroke()
+ glow_mode(ctx, s)
+ ctx.strokeStyle = rgba(colour, a)
+ ctx.lineWidth = 1.1
+ ctx.stroke()
+
+
+def filing(s, f, i, R, p, align):
+ h1, h2, h3, h4 = s.hash(i * 7 + 1), s.hash(i * 7 + 2), s.hash(i * 7 + 3), s.hash(i * 7 + 4)
+ direction = rot(f.n, (h1 * 2 - 1) * f.spread)
+ r0 = R * (0.3 + 0.7 * math.sqrt(h2))
+ r = r0 * (1 - 0.6 * ease_in(p))
+ radial, loose = math.atan2(-direction[1], -direction[0]), h4 * TAU
+ k = clamp(p * 1.8) if align else 1
+ orient = loose + turn(radial, loose) * k + math.sin(p * 29 + i * 1.7) * 0.35 * (1 - k)
+ return SimpleNamespace(x=f.o.x + direction[0] * r, y=f.o.y + direction[1] * r, orient=orient,
+ appear=0.02 + h3 * 0.7, near=1 - r / R)
+
+
+def crawler_at(s, f, side, dist):
+ if f.kind == "notch":
+ n = s.notch
+ x = f.o.x + side * dist
+ cx = clamp(x, n.x - 2.5, n.x + n.w + 2.5)
+ over = abs(x - cx)
+ return SimpleNamespace(x=cx, y=max(1, n.y + n.h + 2.5 - over))
+ if f.kind == "corner":
+ if side > 0:
+ return SimpleNamespace(x=f.c.x + f.e[0] * (dist + 3), y=f.c.y + f.e[1] * 2.5)
+ return SimpleNamespace(x=f.c.x + f.e[0] * 2.5, y=f.c.y + f.e[1] * (dist + 3))
+ t = (-f.n[1], f.n[0])
+ return SimpleNamespace(x=f.o.x + t[0] * side * dist + f.n[0] * 2.5,
+ y=f.o.y + t[1] * side * dist + f.n[1] * 2.5)
+
+
+def make_depart(cfg):
+ def depart(ctx, s):
+ t, pal = s.since, s.palette
+ if t is not None and t >= cfg.departSeconds:
+ return
+ if t is None and s.pressure <= 0:
+ return
+ f = depart_frame(s)
+ if s.reduced:
+ depart_still(ctx, s, f, cfg)
+ return
+ p = s.pressure if t is None else 1
+ tick = 1 - s.tick.age / 0.16 if (t is None and s.tick and s.tick.age < 0.16) else 0
+
+ def length(q):
+ return cfg.len0 + cfg.len1 * q
+
+ if t is None:
+ if cfg.flash:
+ boundary(ctx, s, f, cfg.R * (0.45 + 0.75 * p), (0.2 + 0.55 * p + 0.3 * tick) * clamp(p * 4),
+ heat(s, pal, 0.55 + 0.45 * p), 1.4 + 0.6 * p)
+ for i in range(cfg.N):
+ q = filing(s, f, i, cfg.R, p, cfg.align)
+ vis = clamp((p - q.appear) / 0.1)
+ if vis <= 0:
+ continue
+ pull = tick * 0.16
+ x, y = lerp(q.x, f.o.x, pull), lerp(q.y, f.o.y, pull)
+ l = length(p) * (1 + tick * 0.6)
+ cx, cy = math.cos(q.orient) * l / 2, math.sin(q.orient) * l / 2
+ streak(ctx, s, x - cx, y - cy, x + cx, y + cy, 1 + 0.6 * p,
+ heat(s, pal, 0.2 + 0.45 * p + 0.35 * q.near), vis * (0.35 + 0.65 * p))
+ for j in range(cfg.crawl):
+ side = 1 if j % 2 else -1
+ u = (s.hash(j * 5 + 200) + p * 1.7) % 1
+ a = clamp((p - 0.18) / 0.2) * (0.4 + 0.6 * p) * clamp(u * 5) * clamp((1 - u) * 6)
+ L = cfg.R * 1.3
+ d = L * (1 - u)
+ head, tail = crawler_at(s, f, side, d), crawler_at(s, f, side, d + 7)
+ streak(ctx, s, tail.x, tail.y, head.x, head.y, 1.3, heat(s, pal, 0.8), a)
+ if tick and cfg.arcs:
+ for k in range(2):
+ q = filing(s, f, (s.tick.index * 11 + k * 17) % cfg.N, cfg.R, p, True)
+ crackle(ctx, s, q.x, q.y, f.o.x, f.o.y, s.tick.index * 3 + k, heat(s, pal, 1), tick)
+ glow(ctx, s, f.o.x, f.o.y, cfg.core * (0.35 + 0.65 * p) * (1 + 0.4 * tick),
+ heat(s, pal, 0.6 + 0.4 * p), 0.25 + 0.6 * p)
+ dot(ctx, s, f.o.x, f.o.y, 1.2 + 1.6 * p + tick, heat(s, pal, 1), 0.5 + 0.5 * p)
+ return
+
+ u = clamp(t / cfg.implode)
+ if u < 1:
+ for i in range(cfg.N):
+ q = filing(s, f, i, cfg.R, 1, cfg.align)
+ e1, e0 = ease_in(u), ease_in(u - 0.32)
+ dx, dy = f.sink.x - q.x, f.sink.y - q.y
+ dl = math.hypot(dx, dy) or 1
+ half = length(1) * 0.5 * (1 - u)
+ ax, ay = dx / dl * half, dy / dl * half
+ streak(ctx, s, lerp(q.x, f.sink.x, e0) - ax, lerp(q.y, f.sink.y, e0) - ay,
+ lerp(q.x, f.sink.x, e1) + ax, lerp(q.y, f.sink.y, e1) + ay,
+ 1.3 + 0.9 * u, heat(s, pal, 0.7 + 0.3 * u), 1)
+ for j in range(cfg.crawl):
+ side = 1 if j % 2 else -1
+ d0 = cfg.R * 1.3 * (1 - (s.hash(j * 5 + 200) + 1.7) % 1)
+ head = crawler_at(s, f, side, d0 * (1 - ease_in(u)))
+ tail = crawler_at(s, f, side, d0 * (1 - ease_in(u - 0.35)) + 4)
+ streak(ctx, s, tail.x, tail.y, head.x, head.y, 1.5, heat(s, pal, 0.9), 1 - u * 0.5)
+ if cfg.arcs and t < 0.14:
+ if f.kind == "notch":
+ ends = [crawler_at(s, f, -1, 200), crawler_at(s, f, 1, 200)]
+ else:
+ ends = [crawler_at(s, f, -1, cfg.flash * 0.8), crawler_at(s, f, 1, cfg.flash * 0.8)]
+ for k, e in enumerate(ends):
+ crackle(ctx, s, e.x, e.y, f.o.x, f.o.y, 40 + k, heat(s, pal, 1), 1 - t / 0.14)
+ fade = 1 - t / cfg.departSeconds
+ if cfg.flash:
+ boundary(ctx, s, f, cfg.flash * (1 - ease_out(t / (cfg.departSeconds * 0.85))), fade,
+ heat(s, pal, 1), 2)
+ glow(ctx, s, f.o.x, f.o.y, cfg.core * 1.3 * (1 - ease_in(t / (cfg.implode + 0.1))), heat(s, pal, 1), 1)
+ dot(ctx, s, f.o.x, f.o.y, 3 * fade, heat(s, pal, 1), fade)
+ return depart
+
+
+def spark_pos(src, direction, v, drag, g, tt):
+ d = v / drag * (1 - math.exp(-drag * tt))
+ return SimpleNamespace(x=src.x + direction[0] * d, y=src.y + direction[1] * d + 0.5 * g * tt * tt)
+
+
+def make_arrive(cfg):
+ def arrive(ctx, s):
+ t, pal = s.since, s.palette
+ if t >= cfg.arriveSeconds:
+ return
+ f = arrive_frame(s)
+ if s.reduced:
+ arrive_still(ctx, s, f, cfg)
+ return
+ src = getattr(f, "src", None) or f.o
+ if cfg.flash:
+ boundary(ctx, s, f, 4 + cfg.flash * ease_out(t / 0.2),
+ 0.95 * (1 - clamp(t / (cfg.arriveSeconds * 0.7))), heat(s, pal, 1), 1.8)
+ pv = clamp(t / 0.16)
+ glow(ctx, s, f.o.x, f.o.y, cfg.pop * (0.35 + 0.65 * ease_out(pv)), heat(s, pal, 1), 1 - pv)
+ for i in range(cfg.M):
+ h1, h2, h3, h4 = s.hash(i * 5 + 101), s.hash(i * 5 + 102), s.hash(i * 5 + 103), s.hash(i * 5 + 104)
+ direction = rot(f.n, (h1 * 2 - 1) * f.spread * (0.86 if f.kind == "edge" else 1))
+ v = cfg.V * (0.5 + 0.5 * h2)
+ life = cfg.life * (0.5 + 0.5 * h3)
+ tt = t - h4 * 0.04
+ if tt <= 0:
+ continue
+ if tt < life:
+ k = tt / life
+ head = spark_pos(src, direction, v, cfg.drag, cfg.G, tt)
+ tail = spark_pos(src, direction, v, cfg.drag, cfg.G, max(0, tt - 0.045))
+ flick = 1 if i % 3 else 0.7 + 0.3 * math.cos(tt * 70 + i)
+ streak(ctx, s, tail.x, tail.y, head.x, head.y, 0.9 + 1.1 * (1 - k),
+ heat(s, pal, 1 - k * 0.6), (1 - k) ** 0.45 * flick)
+ if i < cfg.branch:
+ ts = life * 0.42
+ bt = tt - ts
+ bl = life * 0.55
+ if 0 < bt < bl:
+ o = spark_pos(src, direction, v, cfg.drag, cfg.G, ts)
+ d = v / cfg.drag * math.exp(-cfg.drag * ts) * cfg.drag
+ for sgn in (-1, 1):
+ bd = rot(direction, sgn * (0.5 + 0.4 * h4))
+ k = bt / bl
+ head = spark_pos(o, bd, d * 0.45, cfg.drag, cfg.G, bt)
+ tail = spark_pos(o, bd, d * 0.45, cfg.drag, cfg.G, max(0, bt - 0.03))
+ streak(ctx, s, tail.x, tail.y, head.x, head.y, 0.8 + 0.6 * (1 - k),
+ heat(s, pal, 0.9 - k * 0.8), 1 - k)
+ dot(ctx, s, f.o.x, f.o.y, 2.6 * (1 - clamp(t / 0.3)), heat(s, pal, 1), 1 - clamp(t / 0.3))
+ return arrive
+
+
+def still_fan(ctx, s, f, count, r0, r1, pal, alpha_of):
+ for i in range(count):
+ a = alpha_of(i)
+ if a <= 0.01:
+ continue
+ direction = rot(f.n, lerp(-f.spread * 0.92, f.spread * 0.92, 0.5 if count == 1 else i / (count - 1)))
+ k = 0.72 if i % 2 else 1
+ streak(ctx, s, f.o.x + direction[0] * r0, f.o.y + direction[1] * r0,
+ f.o.x + direction[0] * (r0 + (r1 - r0) * k), f.o.y + direction[1] * (r0 + (r1 - r0) * k),
+ 1.6, heat(s, pal, 0.55 if i % 2 else 0.95), a)
+
+
+def depart_still(ctx, s, f, cfg):
+ t, pal = s.since, s.palette
+ p = s.pressure if t is None else 1
+ A = 1 if t is None else 1 - clamp(t / cfg.departSeconds)
+ tick = 1 - s.tick.age / 0.2 if (t is None and s.tick and s.tick.age < 0.2) else 0
+
+ def lit(i):
+ return A * clamp((p - (i % 4) * 0.25) / 0.06) * (0.45 + 0.55 * p)
+
+ if cfg.flash:
+ boundary(ctx, s, f, cfg.R * 0.9, A * (0.2 + 0.6 * p), heat(s, pal, 1), 1.6)
+ still_fan(ctx, s, f, cfg.still, cfg.stillR[0], cfg.stillR[1], pal, lit)
+ glow(ctx, s, f.o.x, f.o.y, cfg.core * 0.7, heat(s, pal, 0.6 + 0.4 * p), A * clamp(0.25 + 0.55 * p + 0.3 * tick))
+ dot(ctx, s, f.o.x, f.o.y, 2.2, heat(s, pal, 1), A * (0.5 + 0.5 * p))
+
+
+def arrive_still(ctx, s, f, cfg):
+ t, pal = s.since, s.palette
+ A = 0.35 + 0.65 * t / 0.08 if t < 0.08 else 1 - clamp((t - 0.08) / (cfg.arriveSeconds - 0.08))
+ if cfg.flash:
+ boundary(ctx, s, f, cfg.flash * 0.6, A * 0.8, heat(s, pal, 1), 1.8)
+ still_fan(ctx, s, f, cfg.still, cfg.stillR[0] + 4, cfg.stillR[1] + 8, pal, lambda i: A)
+ glow(ctx, s, f.o.x, f.o.y, cfg.pop * 0.8, heat(s, pal, 1), A * 0.9)
+ dot(ctx, s, f.o.x, f.o.y, 2.4, heat(s, pal, 1), A)
+
+
+def effect(id_, name, intensity, blurb, depart_cfg, arrive_cfg):
+ cfg = SimpleNamespace(**depart_cfg, **arrive_cfg)
+ return effects.Effect(id_, name, intensity, blurb, make_depart(cfg), make_arrive(cfg),
+ depart_cfg["departSeconds"], arrive_cfg["arriveSeconds"])
+
+
+EFFECTS = [
+ effect(
+ "flint", "Flint", "quiet",
+ "A single hot point at the pointer draws in a few close sparks as you push, snaps them "
+ "through the edge, and a pinch of sparks pops out where you land. Small enough to leave on "
+ "all day.",
+ dict(N=8, R=40, align=False, len0=2, len1=5, crawl=0, arcs=False, flash=0, core=13,
+ implode=0.14, departSeconds=0.4, still=5, stillR=(8, 16)),
+ dict(M=12, V=420, drag=7, G=260, life=0.45, branch=0, pop=11, arriveSeconds=0.45),
+ ),
+ effect(
+ "filings", "Filings", "medium",
+ "Scattered sparks swing round to point at the pointer and creep in like iron filings to a "
+ "magnet, the edge warming beside it; at breakthrough they are sucked through the point, and "
+ "on the other screen the same sparks are thrown back out and fall.",
+ dict(N=24, R=72, align=True, len0=2.5, len1=8, crawl=0, arcs=False, flash=70, core=18,
+ implode=0.2, departSeconds=0.55, still=9, stillR=(12, 26)),
+ dict(M=26, V=500, drag=6.5, G=320, life=0.62, branch=0, pop=20, arriveSeconds=0.65),
+ ),
+ effect(
+ "discharge", "Discharge", "showpiece",
+ "The boundary charges up: sparks crawl along it and forty filings wheel in, with a crackle "
+ "arcing to the pointer at every tick. At breakthrough the whole charge implodes through the "
+ "point with a last arc; where it lands it goes off like a sparkler, stars splitting as they "
+ "fall.",
+ dict(N=40, R=104, align=True, len0=3, len1=11, crawl=8, arcs=True, flash=120, core=26,
+ implode=0.24, departSeconds=0.75, still=13, stillR=(14, 34)),
+ dict(M=30, V=600, drag=6, G=260, life=0.72, branch=9, pop=30, arriveSeconds=0.78),
+ ),
+]
+
+PACKS = {
+ "ember": ("Ember", ["#ffe4ad", "#ffb04a", "#ff6a24", "#d8321a", "#8e1a10"]),
+ "forge": ("Forge", ["#fff4dc", "#ffc15e", "#ff7f2a", "#b8c4d2", "#5d7896"]),
+ "sparkler_gold": ("Sparkler gold", ["#ffffff", "#fff1bf", "#ffd35c", "#f0a531"]),
+}
diff --git a/win_app/fx_warp.py b/win_app/fx_warp.py
new file mode 100644
index 0000000..2adb36c
--- /dev/null
+++ b/win_app/fx_warp.py
@@ -0,0 +1,291 @@
+"""Warp: crossing is travel through a portal, the edge opening as a slot that stretches light and
+the pointer's trail into speed lines, arriving as a streak that decelerates into the pointer.
+"""
+
+import math
+
+import effects
+
+PACKS = {
+ "neon": ("Neon", ["#ff0055", "#00ffcc", "#ffcc00"]),
+ "vaporwave": ("Vaporwave", ["#ff71ce", "#01cdfe", "#05ffa1", "#b967ff", "#fffb96"]),
+ "cyber": ("Cyber", ["#fcee0a", "#00f0ff", "#ff003c"]),
+}
+
+
+def _normal_for_depart(s):
+ nx, ny = 0, 0
+ if s.region.edge == "right":
+ nx = 1
+ elif s.region.edge == "left":
+ nx = -1
+ elif s.region.edge == "top":
+ ny = -1
+ elif s.region.edge == "bottom":
+ ny = 1
+
+ if s.region.kind == "corner":
+ # From the corner's name: the region's edge is the side the other machine is on, which
+ # for a corner push is often the vertical side.
+ corner = getattr(s.region, "corner", "")
+ nx = 1 if "right" in corner else -1
+ ny = -1 if "top" in corner else 1
+ length = math.hypot(nx, ny)
+ nx /= length
+ ny /= length
+ return nx, ny
+
+
+def _normal_for_arrive(s):
+ nx, ny = 0, 0
+ if s.edge == "right":
+ nx = -1
+ elif s.edge == "left":
+ nx = 1
+ elif s.edge == "top":
+ ny = 1
+ elif s.edge == "bottom":
+ ny = -1
+
+ if s.edge in ("left", "right") and (s.point.y < 20 or s.point.y > s.screen.h - 20):
+ ny = 1 if s.point.y < 20 else -1
+ length = math.hypot(nx, ny)
+ nx /= length
+ ny /= length
+ return nx, ny
+
+
+def _draw_slot(ctx, s, p, thickness):
+ r = s.region
+ col = s.palette[0]
+
+ if r.kind == "notch":
+ n = s.notch
+ out = thickness * p
+ ctx.globalAlpha = p * 0.8
+ ctx.fillStyle = col
+ effects.round_rect(ctx, n.x - out, -20, n.w + out * 2, n.h + 20 + out, 14)
+ ctx.fill()
+ ctx.globalAlpha = p * 0.4
+ ctx.fillStyle = "#fff"
+ effects.round_rect(ctx, n.x - out / 2, -20, n.w + out, n.h + 20 + out / 2, 14)
+ ctx.fill()
+ return
+
+ w = thickness * p
+ length = 40 + 120 * p
+ x = y = 0
+
+ if r.kind == "corner":
+ size = 8 + w
+ corner = getattr(r, "corner", "top_right")
+ right, bottom = "right" in corner, "bottom" in corner
+ x0 = s.screen.w - size if right else 0
+ y0 = s.screen.h - size if bottom else 0
+ ctx.globalAlpha = p * 0.8
+ ctx.fillStyle = col
+ ctx.fillRect(x0, y0, size, size)
+ ctx.fillStyle = "#fff"
+ ctx.globalAlpha = p * 0.4
+ ctx.fillRect(s.screen.w - size / 2 if right else 0, s.screen.h - size / 2 if bottom else 0, size / 2, size / 2)
+ return
+
+ ctx.globalAlpha = p * 0.8
+ ctx.fillStyle = col
+ if r.edge == "right":
+ x, y = s.screen.w - w, s.point.y - length / 2
+ ctx.fillRect(x, y, w, length)
+ elif r.edge == "left":
+ x, y = 0, s.point.y - length / 2
+ ctx.fillRect(x, y, w, length)
+ elif r.edge == "top":
+ x, y = s.point.x - length / 2, 0
+ ctx.fillRect(x, y, length, w)
+ elif r.edge == "bottom":
+ x, y = s.point.x - length / 2, s.screen.h - w
+ ctx.fillRect(x, y, length, w)
+
+ ctx.fillStyle = "#fff"
+ ctx.globalAlpha = p * 0.4
+ w = w / 2
+ if r.edge == "right":
+ x, y = s.screen.w - w, s.point.y - length / 2
+ ctx.fillRect(x, y, w, length)
+ elif r.edge == "left":
+ x, y = 0, s.point.y - length / 2
+ ctx.fillRect(x, y, w, length)
+ elif r.edge == "top":
+ x, y = s.point.x - length / 2, 0
+ ctx.fillRect(x, y, length, w)
+ elif r.edge == "bottom":
+ x, y = s.point.x - length / 2, s.screen.h - w
+ ctx.fillRect(x, y, length, w)
+
+
+def _draw_converge(ctx, s, p, max_len, thickness, num_lines, colour):
+ """A switch, away from any edge: the streaks come in from all round and decelerate onto the
+ pointer. Reduce motion holds them still round it and only fades them."""
+ count = max(6, num_lines)
+ ctx.lineCap = "round"
+ for i in range(count):
+ rand = s.hash(i)
+ angle = math.pi * 2 * (i + 0.35 * (rand - 0.5)) / count
+ dx, dy = math.cos(angle), math.sin(angle)
+ if s.reduced:
+ inner, length = 14, max_len * 0.25 * (0.6 + 0.4 * rand)
+ else:
+ inner, length = 12 + max_len * 0.45 * p * p, max_len * 0.45 * p * (0.5 + 0.5 * rand)
+ ctx.globalAlpha = p * (0.5 + 0.5 * rand)
+ ctx.strokeStyle = colour
+ ctx.lineWidth = thickness * (0.5 + 0.5 * rand)
+ ctx.beginPath()
+ ctx.moveTo(s.point.x + dx * (inner + length), s.point.y + dy * (inner + length))
+ ctx.lineTo(s.point.x + dx * inner, s.point.y + dy * inner)
+ ctx.stroke()
+
+
+def _draw_arrival(ctx, s, p, max_len, thickness, num_lines, colour):
+ if s.method == "switch":
+ _draw_converge(ctx, s, p, max_len, thickness, num_lines, colour)
+ return
+ if s.reduced:
+ # A fixed slot along the edge where the pointer came in, so Reduce motion still marks the
+ # landing; the design's lone dot, a few points across, did not.
+ nx, ny = _normal_for_arrive(s)
+ tx, ty = -ny, nx
+ half = 28 + thickness * 2
+ ctx.globalAlpha = p
+ ctx.lineCap = "round"
+ ctx.strokeStyle = "rgba(0,0,0,0.45)" if not s.dark else "rgba(0,0,0,0.25)"
+ ctx.lineWidth = thickness + 3
+ ctx.beginPath()
+ ctx.moveTo(s.point.x - tx * half, s.point.y - ty * half)
+ ctx.lineTo(s.point.x + tx * half, s.point.y + ty * half)
+ ctx.stroke()
+ ctx.strokeStyle = colour
+ ctx.lineWidth = thickness
+ ctx.stroke()
+ ctx.fillStyle = colour
+ ctx.beginPath()
+ ctx.arc(s.point.x + nx * 10, s.point.y + ny * 10, thickness, 0, math.pi * 2)
+ ctx.fill()
+ return
+ nx, ny = _normal_for_arrive(s)
+ dx, dy = nx, ny
+
+ for i in range(num_lines):
+ rand = s.hash(i)
+ offset = (rand - 0.5) * 40
+ ox = dy * offset
+ oy = -dx * offset
+ length = max_len * p * (0.5 + 0.5 * rand)
+
+ ctx.globalAlpha = p * (0.5 + 0.5 * rand)
+ ctx.strokeStyle = colour
+ ctx.lineWidth = thickness * (0.5 + 0.5 * rand)
+ ctx.lineCap = "round"
+ ctx.beginPath()
+ ctx.moveTo(s.point.x + ox, s.point.y + oy)
+ ctx.lineTo(s.point.x + ox + dx * length, s.point.y + oy + dy * length)
+ ctx.stroke()
+
+ ctx.globalAlpha = p
+ ctx.strokeStyle = "#fff"
+ ctx.lineWidth = thickness * 0.5
+ ctx.beginPath()
+ ctx.moveTo(s.point.x, s.point.y)
+ ctx.lineTo(s.point.x + dx * max_len * p, s.point.y + dy * max_len * p)
+ ctx.stroke()
+
+
+def _draw_depart_trails(ctx, s, p, max_len, thickness, num_lines, colour):
+ if s.reduced:
+ return
+ nx, ny = _normal_for_depart(s)
+ dx, dy = -nx, -ny
+ for i in range(num_lines):
+ rand = s.hash(i + 100)
+ offset = (rand - 0.5) * (140 if s.region.kind == "notch" else 60)
+ ox = dy * offset
+ oy = -dx * offset
+ length = max_len * p * (0.5 + 0.5 * rand)
+
+ ctx.globalAlpha = p * (0.5 + 0.5 * rand)
+ ctx.strokeStyle = colour
+ ctx.lineWidth = thickness * rand
+ ctx.lineCap = "round"
+ ctx.beginPath()
+ ctx.moveTo(s.point.x + ox, s.point.y + oy)
+ ctx.lineTo(s.point.x + ox + dx * length, s.point.y + oy + dy * length)
+ ctx.stroke()
+
+
+def _light_slit_depart(ctx, s):
+ p = s.pressure
+ t = s.since
+ if t is not None:
+ p = max(0.0, 1 - (t / 0.4))
+ if p <= 0:
+ return
+ _draw_slot(ctx, s, p, 10)
+ if t is not None:
+ _draw_depart_trails(ctx, s, max(0.0, 1 - t / 0.4), 60, 4, 3, s.palette[0])
+
+
+def _light_slit_arrive(ctx, s):
+ p = max(0.0, 1 - (s.since / 0.4))
+ if p <= 0:
+ return
+ _draw_arrival(ctx, s, p, 60, 4, 3, s.palette[len(s.palette) - 1])
+
+
+def _hyperdrive_depart(ctx, s):
+ p = s.pressure
+ t = s.since
+ if t is not None:
+ p = max(0.0, 1 - (t / 0.6))
+ if p <= 0:
+ return
+ _draw_slot(ctx, s, p, 20)
+ if t is not None:
+ _draw_depart_trails(ctx, s, max(0.0, 1 - t / 0.6), 100, 6, 8, s.palette[1 % len(s.palette)])
+ elif p > 0.1:
+ _draw_depart_trails(ctx, s, p, 40, 2, 4, s.palette[0])
+
+
+def _hyperdrive_arrive(ctx, s):
+ p = max(0.0, 1 - (s.since / 0.6))
+ if p <= 0:
+ return
+ _draw_arrival(ctx, s, p, 100, 6, 8, s.palette[len(s.palette) - 1])
+
+
+def _wormhole_depart(ctx, s):
+ p = s.pressure
+ t = s.since
+ if t is not None:
+ p = max(0.0, 1 - (t / 0.8))
+ if p <= 0:
+ return
+ _draw_slot(ctx, s, p, 32)
+ if t is not None:
+ _draw_depart_trails(ctx, s, max(0.0, 1 - t / 0.8), 160, 8, 15, s.palette[2 % len(s.palette)])
+ elif p > 0.1:
+ _draw_depart_trails(ctx, s, p, 80, 4, 8, s.palette[1 % len(s.palette)])
+
+
+def _wormhole_arrive(ctx, s):
+ p = max(0.0, 1 - (s.since / 0.8))
+ if p <= 0:
+ return
+ _draw_arrival(ctx, s, p, 160, 8, 15, s.palette[len(s.palette) - 1])
+
+
+EFFECTS = [
+ effects.Effect("light_slit", "Light slit", "quiet", "A subtle slit opens, pulling in faint trails.",
+ _light_slit_depart, _light_slit_arrive, 0.4, 0.4),
+ effects.Effect("hyperdrive", "Hyperdrive", "medium", "Speed lines accelerate towards the portal.",
+ _hyperdrive_depart, _hyperdrive_arrive, 0.6, 0.6),
+ effects.Effect("wormhole", "Wormhole", "showpiece", "A dynamic stretching grid of light.",
+ _wormhole_depart, _wormhole_arrive, 0.8, 0.8),
+]
diff --git a/win_app/input_injector.py b/win_app/input_injector.py
index f4cd8db..655f0f3 100644
--- a/win_app/input_injector.py
+++ b/win_app/input_injector.py
@@ -31,7 +31,7 @@ INPUT_KEYBOARD = 1
# value the Mac stamps into kCGEventSourceUserData. Raw Input has no injected
# flag: a SendInput move reaches a WM_INPUT sink exactly as the hand's does,
# hDevice NULL, and this value coming back in RAWMOUSE.ulExtraInformation is
-# the only thing that tells the two apart (proved on the rig, 19-09-2026).
+# the only thing that tells the two apart.
INJECTED_MARK = 0xBEA3
KEYEVENTF_EXTENDEDKEY = 0x0001
@@ -334,8 +334,8 @@ def inject_mouse_move(dx: int, dy: int) -> None:
# 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
+# the foreground app closes (closing a Hyper-V VM Connection window did it).
+# 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
@@ -526,8 +526,9 @@ def plan_scroll_units(dy, dx, mode: str, accum: List[float]) -> Tuple[int, int]:
accum[0] += dy * WHEEL_UNITS_PER_PIXEL
accum[1] += dx * WHEEL_UNITS_PER_PIXEL
else:
- accum[0] += int(dy) * 120
- accum[1] += int(dx) * 120
+ # float, not int: a receiver's scroll speed can make a click a fraction of one.
+ accum[0] += float(dy) * 120
+ accum[1] += float(dx) * 120
whole_y = int(accum[0])
whole_x = int(accum[1])
accum[0] -= whole_y
diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.py
index 9774d2e..450fcc9 100644
--- a/win_app/kvm_bridge_win.py
+++ b/win_app/kvm_bridge_win.py
@@ -32,6 +32,7 @@ from PySide6.QtWidgets import (
QWidget,
)
+import app_config
from app_config import (
Config,
ConfigError,
@@ -41,24 +42,31 @@ from app_config import (
default_config,
default_config_path,
load_config,
- migrate_legacy_config,
save_config,
)
import autostart_win
import capture_win
import desktop_win
-from edge_glow import EdgeGlow, GlowPreview as EdgeGlowPreview, PreviewLoop
+import effects
+from diagram import ArrangementDiagram, PushStrip
+from edge_glow import EdgeGlow, PreviewLoop
+from effect_overlay import EffectOverlay, logical_point
+from effect_previews import EffectStill, SwitchStill, TileHover
import firewall_win
import ignored
+import motion
+import pairing
from pairing import PAIRING_PORT, Announcer, local_address_towards
import pages_win
import protocol
+import receiver
from receiver import ReceiverServer, ServerState
import return_edge
import sender
from sender import MacSender
import theme
import tokens
+import updates
import widgets
LOGGER = logging.getLogger(__name__)
@@ -70,10 +78,10 @@ except OSError:
VERSION = "dev"
HOME_PAGE = "https://kalkmancode.co.uk/beamer"
-HOME_PAGE_TEXT = "kalkmancode.co.uk/beamer"
+HOME_PAGE_TEXT = "Beamer's website"
IDLE_CODE = "––– –––"
-PAIR_HINT = "Press Pair a Mac, then type this code into Beamer on the Mac."
+PAIR_HINT = "Type this code into Beamer on the Mac."
STATUS_TITLES = {
ServerState.STOPPED: "Receiver stopped",
@@ -86,7 +94,7 @@ STATUS_TITLES = {
SIDEBAR_LINK_WORDS = {
ServerState.STOPPED: "Stopped",
ServerState.WAITING: "Waiting",
- ServerState.CONNECTED: "Linked",
+ ServerState.CONNECTED: "Connected",
ServerState.ERROR: "Error",
}
@@ -97,7 +105,7 @@ HEADING_ROLE = {
"fault": "heading-fault",
}
-EDGE_CHOICES = (("left", "Left"), ("right", "Right"), ("top", "Top"), ("bottom", "Bottom"))
+EDGE_CHOICES = pages_win.SIDE_CHOICES
CORNER_CHOICES = (
("top_left", "Top-left"),
("top_right", "Top-right"),
@@ -105,7 +113,7 @@ CORNER_CHOICES = (
("bottom_right", "Bottom-right"),
)
TRIGGER_STYLE_CHOICES = (("double_tap", "Double-tap"), ("hold", "Hold"))
-MODIFIER_STYLE_CHOICES = (("semantic", "Semantic"), ("positional", "Positional"))
+MODIFIER_STYLE_CHOICES = (("semantic", "Same shortcuts"), ("positional", "Same positions"))
MODIFIER_NOTES = {
"semantic": "Ctrl arrives on the Mac as Command and the Windows key as Control, so Ctrl+C "
"copies there too.",
@@ -113,14 +121,6 @@ MODIFIER_NOTES = {
"key as Command.",
}
FULL_SCREEN_CHECK_MS = 1000
-GLOW_STYLE_CHOICES = (("glow", "Glow"), ("beam", "Beam"))
-GLOW_COLOUR_CHOICES = (
- ("signal", "Signal"),
- ("colourful", "Colourful"),
- ("ocean", "Ocean"),
- ("sunset", "Sunset"),
- ("mono", "Mono"),
-)
# How long a dragged slider waits, still, before the value it settled on is written to disk.
SETTLE_MS = 300
@@ -137,7 +137,12 @@ def asset_path(name: str) -> Path:
ICON_PATH = asset_path("Beamer.ico")
+# Where configure_logging put the log, for the tray's Open log folder.
+LOG_PATH: Optional[Path] = None
+
+
def configure_logging() -> Optional[Path]:
+ global LOG_PATH
candidates = [default_config_path().parent, Path(tempfile.gettempdir()) / "Beamer"]
for directory in candidates:
try:
@@ -150,6 +155,7 @@ def configure_logging() -> Optional[Path]:
# way to tell a key the Mac never sent from one Windows swallowed.
root_logger.setLevel(logging.DEBUG if os.environ.get("BEAMER_DEBUG") else logging.INFO)
root_logger.addHandler(handler)
+ LOG_PATH = log_path
return log_path
except OSError:
continue
@@ -158,10 +164,10 @@ def configure_logging() -> Optional[Path]:
def status_icon(state: ServerState, size: int = 64) -> QPixmap:
- """The shipped colour mark with the state dot over its lower right corner, as Vernier's tray
- table draws it: signal connected, amber waiting, fault needs attention, off stopped."""
+ """The shipped colour mark with the state dot over its lower right corner: signal connected,
+ amber waiting, fault needs attention, off stopped."""
# Ratio pinned to 1: the plain pixmap(size, size) comes back at the screen's scale (96px at
- # 150%), which once failed a width check and left the tray showing only the dot.
+ # 150%), which fails the width check below and leaves the tray showing only the dot.
pixmap = QIcon(str(ICON_PATH)).pixmap(QSize(size, size), 1.0)
if pixmap.isNull() or pixmap.width() != size:
pixmap = QPixmap(size, size)
@@ -183,7 +189,10 @@ class StatusBridge(QObject):
"""Marshals receiver-thread status callbacks onto the GUI thread."""
changed = Signal(object, str)
- pressure = Signal(str, float, bool)
+ # The fourth names which third of the edge a Part of the edge push is in, else None.
+ pressure = Signal(str, float, bool, object)
+ # (method, edge, x, y): the pointer landed on this PC at desktop pixel (x, y).
+ arrived = Signal(str, str, float, float)
firewall = Signal(object)
paired = Signal(str, str, str)
# The other direction: this PC's own input going to the Mac.
@@ -195,6 +204,10 @@ class StatusBridge(QObject):
arrangement = Signal(str, int)
alert = Signal(str, str)
mac_learned = Signal(str)
+ # (version, url) when a newer Beamer is out, else None.
+ update = Signal(object)
+ # The firewall rules are in place (or could not be), so the sockets may open.
+ rules_ready = Signal()
class WindowsApplication(QWidget):
@@ -211,6 +224,7 @@ class WindowsApplication(QWidget):
self.bridge = StatusBridge()
self.bridge.changed.connect(self._on_status)
self.bridge.pressure.connect(self._on_pressure)
+ self.bridge.arrived.connect(self._on_arrival)
self.bridge.firewall.connect(self._on_firewall)
self.bridge.paired.connect(self._on_paired)
self.bridge.sending.connect(self._on_sending)
@@ -218,10 +232,15 @@ class WindowsApplication(QWidget):
self.bridge.focus.connect(self._on_focus)
self.bridge.learned.connect(self._on_learned)
self.bridge.arrangement.connect(self._on_arrangement)
+ self.bridge.update.connect(self._on_update)
+ self.bridge.rules_ready.connect(self._listen)
+ self._update = None
+ self._effects_failed = False
# Announces this PC from launch, configured or not: pairing is how a fresh install
# gets its token, so it cannot wait for the receiver to be listening.
self.announcer = Announcer(self._announced_port, self.bridge.paired.emit, logger=LOGGER)
self._code_shown = False
+ self._code_addresses: list = []
self._firewall_advice: Optional[firewall_win.Advice] = None
self._firewall_status: Optional[firewall_win.FirewallStatus] = None
self._firewall_tone: Optional[str] = None
@@ -231,9 +250,15 @@ class WindowsApplication(QWidget):
self._host = default_config().host
self._last_seen_state: Optional[ServerState] = None
self.glow: Optional[EdgeGlow] = None
+ self.effects: Optional[EffectOverlay] = None
self.server = ReceiverServer(
self._set_status,
- pressure_callback=self.bridge.pressure.emit,
+ pressure_callback=lambda edge, pressure, crossed, part=None: self.bridge.pressure.emit(edge, pressure, crossed, part),
+ # The Mac's notch crossing lands on this PC's bottom edge, and that is the only
+ # arrival an effect draws differently. No edge is the Mac's shortcut or menu.
+ arrival_callback=lambda edge, x, y: self.bridge.arrived.emit(
+ "switch" if edge is None else "notch" if edge == "bottom" else "edge", edge or "", float(x), float(y)
+ ),
focus_callback=self.bridge.focus.emit,
peer_callback=self.bridge.learned.emit,
arrangement_callback=self.bridge.arrangement.emit,
@@ -244,8 +269,15 @@ class WindowsApplication(QWidget):
redirect_callback=self.bridge.redirecting.emit,
pressure_callback=self.bridge.pressure.emit,
arrangement_callback=self.bridge.arrangement.emit,
+ arrival_callback=lambda edge, x, y: self.bridge.arrived.emit(
+ "switch" if edge is None else "edge", edge or "", float(x), float(y)
+ ),
)
self.sender.send_peer_home = self.server.send_home
+ # Pause crossing and the full-screen hold are about this screen: the Mac's pointer does
+ # not go home through a held edge either.
+ self.server.edges_held = lambda: self.sender.edges_held
+ self.server.return_model = self._return_model
self.sender.on_alert = self.bridge.alert.emit
self.sender.on_mac_learned = self.bridge.mac_learned.emit
self.bridge.alert.connect(self._on_alert)
@@ -253,24 +285,34 @@ class WindowsApplication(QWidget):
self.hooks = capture_win.Hooks(self._on_hook_key, self.sender.on_mouse, self.sender.on_motion)
self._trigger = capture_win.Trigger()
self._sending_detail = "Not connected to the Mac"
+ self.update_checker = updates.Checker(
+ VERSION, lambda: self._config is None or self._config.check_updates, self.bridge.update.emit, logger=LOGGER
+ )
try:
self._config = load_config(config_path)
+ self._apply_input_scale(self._config)
self._host = self._config.host
self._status = ServerState.WAITING
self._status_detail = f"Ready on TCP port {self._config.port}"
except ConfigError as exc:
LOGGER.info("Configuration is not ready: %s", exc)
self._status = ServerState.ERROR
- self._status_detail = "Enter a shared token to finish setup"
+ self._status_detail = "Not paired yet: press Pair a Mac on Overview"
+
+ # Before any widget is built: every control takes its colours from the palette in use.
+ appearance = self._config.appearance if self._config is not None else "system"
+ theme.set_dark(theme.wants_dark(appearance, theme.system_dark()))
self.setWindowTitle("Beamer")
self.resize(820, 720)
self.setMinimumSize(*tokens.MIN_WINDOW["windows"])
self.setWindowIcon(QIcon(str(ICON_PATH)))
self.preview_loop = PreviewLoop(self)
+ self.tile_hover = TileHover(self.preview_loop, self)
self._build_window()
self._apply_theme()
self._build_tray()
+ theme.watch_system(self._apply_appearance)
self.refresh_timer = QTimer(self)
self.refresh_timer.setInterval(250)
@@ -283,10 +325,6 @@ class WindowsApplication(QWidget):
# Otherwise the heading, the "Input:"/"Now:" readouts and the sidebar dots sit blank
# for the first 250ms every launch, waiting for the timer's first tick.
self._refresh_window()
- # start() triggers the first read through the WAITING transition; without a config the
- # receiver never starts, so the row would otherwise say "Checking" forever.
- if self._config is None:
- self._check_firewall()
# -- window and pages -----------------------------------------------------------------
@@ -296,13 +334,16 @@ class WindowsApplication(QWidget):
outer.setSpacing(0)
row = QWidget()
+ # The cross-fade's own widget when the appearance changes: sidebar and pages, everything
+ # below the native title bar and above the footer, which is thin enough to just flip.
+ self._body = row
row_layout = QHBoxLayout(row)
row_layout.setContentsMargins(0, 0, 0, 0)
row_layout.setSpacing(0)
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
+ pages_win.PAGES, self._select_page, foot=f"Beamer {VERSION}\n{HOME_PAGE_TEXT}", on_foot=self.open_home_page,
+ foot_tip=HOME_PAGE,
)
self.sidebar.setFixedWidth(theme.SIDEBAR_WIDTH)
row_layout.addWidget(self.sidebar)
@@ -316,9 +357,8 @@ class WindowsApplication(QWidget):
footer.setProperty("vernier", "commit")
footer_layout = QHBoxLayout(footer)
footer_layout.setContentsMargins(16, 10, 16, 10)
- footer_layout.addWidget(
- widgets.label("Closing this window keeps Beamer running in the tray.", "note", wrap=True)
- )
+ self.footer_note = widgets.label(pages_win.footer("overview"), "note", wrap=True)
+ footer_layout.addWidget(self.footer_note)
outer.addWidget(footer)
current = self._config or default_config()
@@ -327,13 +367,11 @@ class WindowsApplication(QWidget):
"crossing": self._crossing_page,
"design": self._design_page,
"keyboard": self._keyboard_page,
- "pairing": self._pairing_page,
"connection": self._connection_page,
- "firewall": self._firewall_page,
}
self._page_indexes: dict = {}
for key, name, purpose in pages_win.PAGES:
- scroll, layout = self._page_shell(name, purpose)
+ scroll, layout = self._page_shell(name, purpose, pages_win.SCOPE.get(key))
builders[key](layout, current)
layout.addStretch(1)
self._page_indexes[key] = self.stack.addWidget(scroll)
@@ -344,7 +382,7 @@ class WindowsApplication(QWidget):
self._select_page("overview")
- def _page_shell(self, title: str, purpose: str):
+ def _page_shell(self, title: str, purpose: str, scope: Optional[str] = None):
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setFrameShape(QFrame.Shape.NoFrame)
@@ -359,6 +397,10 @@ class WindowsApplication(QWidget):
heading.setFont(theme.font(theme.HEADING, 700))
layout.addWidget(heading)
layout.addWidget(widgets.label(purpose, "note", wrap=True))
+ if scope is not None:
+ # Whose settings these are, not something happening now, so not signal: on light,
+ # signal reads as a link.
+ layout.addWidget(widgets.label(scope, "note-quiet", wrap=True))
scroll.setWidget(page)
return scroll, layout
@@ -369,31 +411,87 @@ class WindowsApplication(QWidget):
self._page = key
self.stack.setCurrentIndex(index)
self.sidebar.select(key)
+ self.footer_note.setText(pages_win.footer(key))
if key != "keyboard":
self.ignored_recorder.cancel()
+ if key != "crossing":
self.trigger_recorder.cancel()
self._run_previews()
# -- Overview ---------------------------------------------------------------------------
def _overview_page(self, layout, current) -> None:
- layout.addWidget(self._link_module())
+ # Pairing leads until there is a Mac, since nothing else here works without one; once
+ # paired it moves down beside the other once-only settings (_place_pairing).
+ self.overview_layout = layout
+ self.link_module = self._link_module()
+ layout.addWidget(self.link_module)
layout.addWidget(self._input_module())
- layout.addWidget(self._daily_module(current))
+ layout.addWidget(self._directions_module(current))
+ self.sign_in_module = self._sign_in_module()
+ layout.addWidget(self.sign_in_module)
+ layout.addWidget(self._updates_module(current))
+ self._pairing_block(layout, current)
+
+ def _updates_module(self, current: Config) -> QWidget:
+ module = widgets.Module("Updates")
+ self.updates_switch = widgets.Switch("Check for updates")
+ self.updates_switch.setFont(theme.font(theme.TYPE["body"]))
+ self.updates_switch.setChecked(current.check_updates)
+ self.updates_switch.toggled.connect(self._set_check_updates)
+ module.body.addWidget(self.updates_switch)
+ module.body.addWidget(widgets.label(
+ "Asks GitHub once a day whether there is a newer Beamer. Nothing is sent but the request itself.",
+ "note",
+ wrap=True,
+ ))
+ self.update_button = QPushButton("Download")
+ self.update_button.setProperty("vernier", "primary")
+ self.update_button.clicked.connect(self.open_update)
+ self.update_button.setVisible(False)
+ module.body.addWidget(self.update_button)
+ return module
+
+ def _set_check_updates(self, enabled: bool) -> None:
+ if self._config is None:
+ return
+ self._config.check_updates = bool(enabled)
+ self._persist()
+ if enabled:
+ self.update_checker.check_now()
+ else:
+ self._on_update(None)
+
+ def _on_update(self, found) -> None:
+ """(version, url) for a newer release, or None; on the GUI thread."""
+ self._update = found
+ self.update_button.setText(f"Download Beamer {found[0]}" if found else "Download")
+ motion.set_shown(self.update_button, found is not None)
+ self.header_action.setText(f"Beamer {found[0]} is available…" if found else f"Beamer {VERSION}")
+ self.header_action.setEnabled(found is not None)
+
+ def open_update(self) -> None:
+ if self._update:
+ QDesktopServices.openUrl(QUrl(self._update[1]))
+
+ def open_log_folder(self) -> None:
+ folder = LOG_PATH.parent if LOG_PATH is not None else default_config_path().parent
+ QDesktopServices.openUrl(QUrl.fromLocalFile(str(folder)))
def _link_module(self) -> QWidget:
module = widgets.Module("Link")
- led_row = QHBoxLayout()
- led_row.setSpacing(8)
+ heading_row = QHBoxLayout()
+ heading_row.setSpacing(10)
self.led = widgets.Led()
- led_row.addWidget(self.led, 0, Qt.AlignmentFlag.AlignVCenter)
- led_row.addStretch(1)
- module.body.addLayout(led_row)
+ heading_row.addWidget(self.led, 0, Qt.AlignmentFlag.AlignVCenter)
self.status_heading = widgets.label("", "heading", wrap=True)
self.status_heading.setFont(theme.font(theme.HEADING, 700))
- module.body.addWidget(self.status_heading)
+ heading_row.addWidget(self.status_heading, 1)
+ module.body.addLayout(heading_row)
self.status_detail = widgets.label("", "note", wrap=True)
module.body.addWidget(self.status_detail)
+ self.outward_line = widgets.label("", "note", wrap=True)
+ module.body.addWidget(self.outward_line)
where_row = QHBoxLayout()
where_row.setSpacing(6)
where_row.addWidget(widgets.label("Input:", "note"))
@@ -402,10 +500,11 @@ class WindowsApplication(QWidget):
module.body.addLayout(where_row)
# Shown only while there is a figure: the trip is measured while input is on the Mac.
self.round_trip_row = QWidget()
+ self.round_trip_row.setProperty("vernier", "plain")
trip_row = QHBoxLayout(self.round_trip_row)
trip_row.setContentsMargins(0, 0, 0, 0)
trip_row.setSpacing(6)
- trip_row.addWidget(widgets.label("Round trip:", "note"))
+ trip_row.addWidget(widgets.label("Delay:", "note"))
self.round_trip_readout = widgets.label("", "readout", wrap=True)
trip_row.addWidget(self.round_trip_readout, 1)
self.round_trip_row.setVisible(False)
@@ -421,12 +520,18 @@ class WindowsApplication(QWidget):
self.redirect_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.redirect_button.clicked.connect(self.toggle_redirect)
module.body.addWidget(self.redirect_button)
+ # Why the button above is dimmed, while it is.
+ self.redirect_note = widgets.label("Switch on This PC drives your Mac, below, to send input from here.",
+ "note", wrap=True)
+ self.redirect_note.setVisible(False)
+ module.body.addWidget(self.redirect_note)
self.pause_button = QPushButton("Pause crossing")
self.pause_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.pause_button.clicked.connect(self.toggle_pause)
- module.body.addWidget(self.pause_button)
self.crossing_state = widgets.label("", "note", wrap=True)
- module.body.addWidget(self.crossing_state)
+ # Hidden while only the shortcut is chosen: there is no edge to pause.
+ self.pause_row = self._row(self.pause_button, self.crossing_state)
+ module.body.addWidget(self.pause_row)
return module
def toggle_redirect(self) -> None:
@@ -436,18 +541,17 @@ class WindowsApplication(QWidget):
self.sender.crossing_paused = not self.sender.crossing_paused
self._refresh_window()
+ def _crossing_state_args(self) -> tuple:
+ config = self._config
+ methods = set(config.crossing_methods) if config is not None else set()
+ return (
+ config is not None, bool(config and config.mac_host), bool(config and config.send_to_mac),
+ self.sender.connected, bool(methods & {"edge", "part", "corner"}),
+ self.sender.crossing_paused, self.sender.full_screen_app,
+ )
+
def _crossing_state_sentence(self) -> str:
- methods = set(self._config.crossing_methods) if self._config is not None else set()
- if not methods & {"edge", "corner"}:
- return "Only the shortcut is switched on; there is nothing to pause."
- if self.sender.crossing_paused:
- return "Paused. The edge and corner do nothing until you resume; the shortcut still works."
- if self.sender.full_screen_app is not None:
- return (
- f"Off while {self.sender.full_screen_app} is full screen, so the pointer stays put at "
- "the edges; the shortcut still works."
- )
- return "On. Pause it to lean on an edge without switching."
+ return pages_win.crossing_state_sentence(*self._crossing_state_args())
def _check_full_screen(self) -> None:
"""The Mac's rule: a full-screen app in front holds the edges, the shortcut still works.
@@ -472,14 +576,15 @@ class WindowsApplication(QWidget):
self._config.mac_hardware_address = address
self._persist()
- def _daily_module(self, current: Config) -> QWidget:
- module = widgets.Module("Every day")
- self.allow_switch = widgets.Switch("Let your Mac drive this PC")
+ def _directions_module(self, current: Config) -> QWidget:
+ module = widgets.Module("Directions")
+ # The tray's words, so the two never disagree.
+ self.allow_switch = widgets.Switch("Your Mac drives this PC")
self.allow_switch.setFont(theme.font(theme.TYPE["body"]))
self.allow_switch.setChecked(current.allow_mac_to_drive)
self.allow_switch.toggled.connect(self._set_allow_drive)
module.body.addWidget(self.allow_switch)
- self.send_switch = widgets.Switch("Send this PC's keyboard and mouse to your Mac")
+ self.send_switch = widgets.Switch("This PC drives your Mac")
self.send_switch.setFont(theme.font(theme.TYPE["body"]))
self.send_switch.setChecked(current.send_to_mac)
self.send_switch.toggled.connect(self._toggle_sending)
@@ -487,6 +592,13 @@ class WindowsApplication(QWidget):
self.send_hint = widgets.label("", "note", wrap=True)
self.send_hint.setVisible(False)
module.body.addWidget(self.send_hint)
+ if self._config is None:
+ self.allow_switch.setEnabled(False)
+ self.send_switch.setEnabled(False)
+ return module
+
+ def _sign_in_module(self) -> QWidget:
+ module = widgets.Module("At sign-in")
self.logon_switch = widgets.Switch("Start Beamer when you sign in")
self.logon_switch.setFont(theme.font(theme.TYPE["body"]))
exe = autostart_win.installed_exe()
@@ -503,13 +615,11 @@ class WindowsApplication(QWidget):
wrap=True,
)
module.body.addWidget(self.logon_hint)
- if self._config is None:
- self.allow_switch.setEnabled(False)
- self.send_switch.setEnabled(False)
return module
def _set_allow_drive(self, enabled: bool) -> None:
- """Replaces the old Start/Stop receiver button: this switch is what persists."""
+ """Starts or stops the receiver. There is no separate Start/Stop button: this switch is
+ what persists."""
if self._config is None:
return
self._config.allow_mac_to_drive = bool(enabled)
@@ -548,69 +658,171 @@ class WindowsApplication(QWidget):
if enabled:
self._start_sending(self._config)
else:
+ # Input comes home by this switch and shows where the pointer is, as any switch does;
+ # stopping would bring it home too, silently, as it does for a reload or quitting.
+ self.sender.set_redirecting(False)
self._stop_sending()
# -- Crossing -----------------------------------------------------------------------------
def _crossing_page(self, layout, current: Config) -> None:
layout.addWidget(self._ways_module(current))
- layout.addWidget(self._resistance_module(current))
+ self.resistance_module = self._resistance_module(current)
+ layout.addWidget(self.resistance_module)
+ self.shortcut_module = self._shortcut_module(current)
+ layout.addWidget(self.shortcut_module)
+ self._reflect_ways()
+
+ @staticmethod
+ def _row(*items) -> QWidget:
+ """Widgets and layouts that show and hide as one row of a module."""
+ row = QWidget()
+ row.setProperty("vernier", "plain")
+ column = QVBoxLayout(row)
+ column.setContentsMargins(0, 0, 0, 0)
+ column.setSpacing(8)
+ for item in items:
+ (column.addLayout if isinstance(item, QHBoxLayout) else column.addWidget)(item)
+ return row
def _ways_module(self, current: Config) -> QWidget:
module = widgets.Module("Ways in")
+ self.ways_summary = widgets.label("", "note", wrap=True)
+ module.body.addWidget(self.ways_summary)
+ self.arrangement_diagram = ArrangementDiagram()
+ module.body.addWidget(self.arrangement_diagram)
self.way_boxes: dict = {}
- for value, text in (("edge", "Edge"), ("corner", "Corner"), ("shortcut", "Shortcut")):
+ for value, text, detail in pages_win.WAY_ROWS:
box = QCheckBox(text)
box.setChecked(value in current.crossing_methods)
- box.toggled.connect(self._ways_changed)
- module.body.addWidget(box)
+ box.toggled.connect(lambda on, v=value: self._ways_changed(v, on))
self.way_boxes[value] = box
+ if not detail:
+ module.body.addWidget(box)
+ continue
+ box.setAccessibleDescription(detail)
+ line = QHBoxLayout()
+ line.setSpacing(8)
+ line.addWidget(box)
+ line.addWidget(widgets.label(detail, "small"))
+ line.addStretch(1)
+ module.body.addLayout(line)
- module.body.addWidget(
- widgets.label(
- "Which edge of this PC leads to your Mac. It is the same border both ways, so "
- "setting it here moves it on the Mac too.",
- "note",
- wrap=True,
- )
- )
- module.body.addWidget(widgets.label("Edge", "key"))
self.edge_choice = widgets.Choice(
- EDGE_CHOICES, columns=4, current=current.mac_return_edge or "right", on_change=self._set_arrangement
+ EDGE_CHOICES, columns=4, current=current.mac_return_edge, on_change=self._set_arrangement
)
- module.body.addWidget(self.edge_choice.view)
+ self.edge_choice.set_names("Where your Mac is")
+ self.edge_unlearned = widgets.label(pages_win.NOT_LEARNED_EDGE, "note", wrap=True)
+ self.edge_unlearned.setVisible(not current.mac_return_edge)
+ self.crossing_rows = {
+ "edge": self._row(
+ widgets.label("Where your Mac is", "key"),
+ widgets.label(
+ "One border, walked both ways, so changing it here moves it on your Mac too.",
+ "note",
+ wrap=True,
+ ),
+ self.edge_choice.view,
+ self.edge_unlearned,
+ ),
+ }
+
+ chips = QHBoxLayout()
+ chips.setSpacing(4)
+ self.part_buttons: dict = {}
+ for part in return_edge.PARTS:
+ button = QPushButton()
+ button.setProperty("vernier", "choice")
+ button.setCheckable(True)
+ button.setMinimumHeight(widgets.MIN_TARGET)
+ button.setCursor(Qt.CursorShape.PointingHandCursor)
+ button.setChecked(part in current.crossing_edge_parts)
+ button.clicked.connect(lambda on, p=part: self._set_part(p, on))
+ chips.addWidget(button, 1)
+ self.part_buttons[part] = button
+ self.parts_note = widgets.label("", "note", wrap=True)
+ self.crossing_rows["parts"] = self._row(widgets.label("Parts", "key"), chips, self.parts_note)
- module.body.addWidget(widgets.label("Corner", "key"))
self.corner_choice = widgets.Choice(
CORNER_CHOICES, columns=2, current=current.crossing_corner, on_change=self._set_corner
)
- module.body.addWidget(self.corner_choice.view)
- self.corner_choice.set_enabled("corner" in current.crossing_methods)
+ self.corner_choice.set_names("Corner")
+ self.crossing_rows["corner"] = self._row(widgets.label("Corner", "key"), self.corner_choice.view)
- self.dragging_switch = widgets.Switch("Never while dragging")
+ self.dragging_switch = widgets.Switch("Don't cross while dragging")
self.dragging_switch.setFont(theme.font(theme.TYPE["body"]))
self.dragging_switch.setChecked(current.block_while_dragging)
self.dragging_switch.toggled.connect(self._set_block_while_dragging)
- module.body.addWidget(self.dragging_switch)
+ self.crossing_rows["dragging"] = self._row(self.dragging_switch)
+ for key in ("edge", "parts", "corner", "dragging"):
+ module.body.addWidget(self.crossing_rows[key])
now_row = QHBoxLayout()
now_row.setSpacing(6)
- # Named, not just "Now": this line is the Mac's half of the border --
- # the edge and push it asks for when it is the one sending -- and under
- # a column of this PC's own controls it reads as one of them otherwise.
- now_row.addWidget(widgets.label("Your Mac asks for:", "note"))
+ # The Mac's half of the border -- the edge and push it asks for when it is the one
+ # sending. Hidden until the Mac has said, rather than reading "not set yet".
+ now_row.addWidget(widgets.label("Coming back from your Mac:", "note"))
self.return_readout = widgets.label("", "readout", wrap=True)
now_row.addWidget(self.return_readout, 1)
- module.body.addLayout(now_row)
+ self.return_row = self._row(now_row)
+ self.return_row.setVisible(False)
+ module.body.addWidget(self.return_row)
return module
- def _ways_changed(self, *_ignored) -> None:
+ def _ways_changed(self, way: str, on: bool) -> None:
+ if self._config is None:
+ return
+ self._config.crossing_methods = pages_win.toggle_way(self._config.crossing_methods, way, on)
+ self._persist()
+ self.sender.update_config(self._config)
+ self._reflect_ways()
+ # The Design page's preview opens where the pointer crosses and says when a place is not a way in.
+ self._reflect_look()
+
+ def _set_part(self, part: str, on: bool) -> None:
if self._config is None:
return
- self._config.crossing_methods = [value for value, box in self.way_boxes.items() if box.isChecked()]
+ self._config.crossing_edge_parts = pages_win.toggle_part(self._config.crossing_edge_parts, part, on)
self._persist()
- self.corner_choice.set_enabled(self.way_boxes["corner"].isChecked())
self.sender.update_config(self._config)
+ self._reflect_ways()
+ # The Design page's preview opens where the pointer crosses and says when a place is not a way in.
+ self._reflect_look()
+
+ def _reflect_ways(self) -> None:
+ """The ways' boxes, the parts' chips and which rows show, from the config: a row a chosen
+ way does not use is hidden, not dimmed, and comes back the moment one does."""
+ config = self._config or default_config()
+ for value, box in self.way_boxes.items():
+ if box.isChecked() != (value in config.crossing_methods):
+ box.blockSignals(True)
+ box.setChecked(value in config.crossing_methods)
+ box.blockSignals(False)
+ edge = config.mac_return_edge or "right"
+ names = pages_win.part_names(edge)
+ for part, button in self.part_buttons.items():
+ button.setText(names[part])
+ button.setChecked(part in config.crossing_edge_parts)
+ self.parts_note.setText(
+ f"Crosses only along {pages_win.parts_phrase(edge, config.crossing_edge_parts)}; the rest of "
+ "it is a wall. Choose any, but at least one."
+ )
+ shown = pages_win.crossing_rows(config.crossing_methods)
+ for key, row in self.crossing_rows.items():
+ motion.set_shown(row, key in shown)
+ motion.set_shown(self.resistance_module, "resistance" in shown)
+ motion.set_shown(self.shortcut_module, "shortcut" in shown)
+ key_name = TRIGGER_KEYS.get(config.trigger_key, config.trigger_key)
+ summary = pages_win.ways_summary(config.crossing_methods, config.mac_return_edge, config.crossing_edge_parts,
+ config.crossing_corner, key_name, config.trigger_style)
+ if summary != self.ways_summary.text():
+ shot = motion.snapshot(self.ways_summary)
+ self.ways_summary.setText(summary)
+ motion.fade_from(self.ways_summary, shot)
+ motion.set_shown(self.edge_unlearned, not config.mac_return_edge)
+ self.arrangement_diagram.set_state(edge, config.crossing_methods, config.crossing_edge_parts,
+ config.crossing_corner, key_name, config.trigger_style)
+ self.resistance_strip.set_edge(edge)
def _set_arrangement(self, pc_edge: str) -> None:
"""The edge of THIS PC that leads to the Mac -- one border, walked either way. Not an
@@ -626,6 +838,7 @@ class WindowsApplication(QWidget):
self.server.send_arrangement(mac_edge, self._config.arrangement_set_at)
self.sender.update_config(self._config)
self._reflect_look()
+ self._reflect_ways()
def _set_block_while_dragging(self, enabled: bool) -> None:
if self._config is None:
@@ -640,17 +853,19 @@ class WindowsApplication(QWidget):
self._config.crossing_corner = corner
self._persist()
self.sender.update_config(self._config)
+ self._reflect_ways()
def _on_arrangement(self, mac_edge: str, set_at: int) -> None:
"""The Mac changed the arrangement, over either link. `mac_edge` is always the edge of
the MAC that leads here; an arrival older than what this end already holds is ignored."""
if self._config is None:
return
- if self._config.arrangement_set_at and not protocol.arrangement_wins(set_at, self._config.arrangement_set_at):
- LOGGER.info("Ignoring an older arrangement from the Mac (%s vs %s)", set_at, self._config.arrangement_set_at)
- return
pc_edge = return_edge.OPPOSITE.get(mac_edge)
- if pc_edge is None:
+ if pc_edge is None or pc_edge == self._config.mac_return_edge:
+ # One change on the Mac reaches this PC over both links, so the second copy finds it applied.
+ return
+ if self._config.arrangement_set_at and not protocol.arrangement_wins(set_at, self._config.arrangement_set_at):
+ LOGGER.info("Ignoring an arrangement from the Mac that is no newer than this PC's (%s vs %s)", set_at, self._config.arrangement_set_at)
return
self._config.mac_return_edge = pc_edge
self._config.arrangement_set_at = int(set_at)
@@ -658,13 +873,17 @@ class WindowsApplication(QWidget):
self.sender.update_config(self._config)
self.edge_choice.set_value(pc_edge)
self._reflect_look()
+ self._reflect_ways()
def _resistance_module(self, current: Config) -> QWidget:
module = widgets.Module("Resistance")
+ self.resistance_strip = PushStrip()
+ self.resistance_strip.set_edge(current.mac_return_edge or "right")
+ self.resistance_strip.set_value(current.crossing_resistance_px)
+ module.body.addWidget(self.resistance_strip)
row = QHBoxLayout()
row.setSpacing(10)
- self.resistance_slider = QSlider(Qt.Orientation.Horizontal)
- self.resistance_slider.setRange(0, 500)
+ self.resistance_slider = widgets.Ruler("Resistance", pages_win.RESISTANCE_MAX)
self.resistance_slider.setValue(current.crossing_resistance_px)
self.resistance_slider.valueChanged.connect(self._resistance_changed)
row.addWidget(self.resistance_slider, 1)
@@ -678,6 +897,7 @@ class WindowsApplication(QWidget):
def _resistance_changed(self, value: int) -> None:
self.resistance_readout.setText(f"{value} px")
+ self.resistance_strip.set_value(value)
self._update_resistance_hint(value)
if self._config is None:
return
@@ -697,15 +917,64 @@ class WindowsApplication(QWidget):
# -- Keyboard -----------------------------------------------------------------------------
def _keyboard_page(self, layout, current: Config) -> None:
- layout.addWidget(self._shortcut_module(current))
- layout.addWidget(self._ignored_module(current))
+ # The modifier keys are set once; the stays-here list is the one people come back to.
layout.addWidget(self._modifier_module(current))
+ layout.addWidget(self._ignored_module(current))
+ layout.addWidget(self._speed_module(current))
+
+ def _speed_module(self, current: Config) -> QWidget:
+ """How the Mac's pointer feels on this PC: the Mac sends what its own acceleration made of
+ the hand's movement, and this PC's settings decide the rest."""
+ module = widgets.Module("The Mac's pointer here")
+ self.speed_sliders = {}
+ self.speed_readouts = {}
+ for key, name, value in (("pointer_speed", "Pointer speed", current.pointer_speed),
+ ("scroll_speed", "Scroll speed", current.scroll_speed)):
+ module.body.addWidget(widgets.label(name, "body"))
+ row = QHBoxLayout()
+ row.setSpacing(10)
+ slider = widgets.Ruler(name, 400, minimum=25)
+ slider.setValue(round(value * 100))
+ slider.valueChanged.connect(lambda percent, key=key: self._speed_changed(key, percent))
+ row.addWidget(slider, 1)
+ readout = widgets.label(f"{round(value * 100)}%", "readout")
+ row.addWidget(readout)
+ module.body.addLayout(row)
+ self.speed_sliders[key], self.speed_readouts[key] = slider, readout
+ module.body.addWidget(widgets.label(
+ "For the Mac's trackpad or mouse while it drives this PC.", "note", wrap=True
+ ))
+ self.reverse_scroll_switch = widgets.Switch("Reverse the Mac's scrolling")
+ self.reverse_scroll_switch.setFont(theme.font(theme.TYPE["body"]))
+ self.reverse_scroll_switch.setChecked(current.reverse_scroll)
+ self.reverse_scroll_switch.toggled.connect(self._reverse_scroll_changed)
+ module.body.addWidget(self.reverse_scroll_switch)
+ return module
+
+ def _speed_changed(self, key: str, percent: int) -> None:
+ self.speed_readouts[key].setText(f"{percent}%")
+ if self._config is None:
+ return
+ setattr(self._config, key, percent / 100)
+ self._apply_input_scale(self._config)
+ self._debounce_save()
+
+ def _reverse_scroll_changed(self, enabled: bool) -> None:
+ if self._config is None:
+ return
+ self._config.reverse_scroll = bool(enabled)
+ self._apply_input_scale(self._config)
+ self._debounce_save()
+
+ def _apply_input_scale(self, config: Config) -> None:
+ self.server.input_scale = receiver.InputScale(config.pointer_speed, config.scroll_speed, config.reverse_scroll)
def _modifier_module(self, current: Config) -> QWidget:
module = widgets.Module("Modifier keys")
self.modifier_choice = widgets.Choice(
MODIFIER_STYLE_CHOICES, columns=2, current=current.modifier_style, on_change=self._set_modifier_style
)
+ self.modifier_choice.set_names("Modifier keys")
module.body.addWidget(self.modifier_choice.view)
self.modifier_note = widgets.label(MODIFIER_NOTES[current.modifier_style], "note", wrap=True)
module.body.addWidget(self.modifier_note)
@@ -726,7 +995,8 @@ class WindowsApplication(QWidget):
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)
+ self.ignored_recorder = widgets.InputRecorder("Add a key or button", self._record_ignored, capture_win.hook_vk,
+ mono=False)
module.body.addWidget(self.ignored_recorder)
self._show_ignored(list(current.ignored_inputs))
return module
@@ -740,11 +1010,12 @@ class WindowsApplication(QWidget):
row = QFrame()
row.setProperty("vernier", "entry")
row_layout = QHBoxLayout(row)
- row_layout.setContentsMargins(12, 6, 6, 6)
+ row_layout.setContentsMargins(12, 2, 4, 2)
name = widgets.label(capture_win.input_title(entry), "readout")
row_layout.addWidget(name, 1)
remove = QPushButton("Remove")
remove.setProperty("vernier", "remove")
+ remove.setMinimumHeight(widgets.MIN_TARGET)
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))
@@ -801,6 +1072,7 @@ class WindowsApplication(QWidget):
self._record_trigger,
capture_win.hook_vk,
keys_only=True,
+ name="Shortcut key",
)
self.trigger_recorder.HINT = "Click, then press the key"
self.trigger_recorder.hint.setText(self.trigger_recorder.HINT)
@@ -811,21 +1083,23 @@ class WindowsApplication(QWidget):
self.trigger_style_choice = widgets.Choice(
TRIGGER_STYLE_CHOICES, columns=2, current=current.trigger_style, on_change=self._set_trigger_style
)
- module.body.addWidget(self.trigger_style_choice.view)
+ self.trigger_style_choice.set_names("How you press it")
+ module.body.addWidget(self._row(widgets.label("How you press it", "key"), self.trigger_style_choice.view))
self.style_hint = widgets.label("", "note", wrap=True)
module.body.addWidget(self.style_hint)
- row = QHBoxLayout()
- row.setSpacing(10)
- self.double_tap_slider = QSlider(Qt.Orientation.Horizontal)
+ head = QHBoxLayout()
+ head.setSpacing(10)
+ head.addWidget(widgets.label("Time between taps", "key"))
+ head.addStretch(1)
+ self.double_tap_readout = widgets.label(f"{current.double_tap_ms} ms", "readout")
+ head.addWidget(self.double_tap_readout)
# The Mac's range: the store takes 50 to 2000 ms, but only about 150 to 600 is useful.
- self.double_tap_slider.setRange(50, 1000)
+ self.double_tap_slider = widgets.Ruler("Time between taps", 1000, minimum=50)
self.double_tap_slider.setValue(current.double_tap_ms)
self.double_tap_slider.valueChanged.connect(self._double_tap_changed)
- row.addWidget(self.double_tap_slider, 1)
- self.double_tap_readout = widgets.label(f"{current.double_tap_ms} ms", "readout")
- row.addWidget(self.double_tap_readout)
- module.body.addLayout(row)
- self.double_tap_slider.setEnabled(current.trigger_style != "hold")
+ self.double_tap_row = self._row(head, self.double_tap_slider)
+ module.body.addWidget(self.double_tap_row)
+ self.double_tap_row.setVisible(current.trigger_style != "hold")
self._update_style_hint(current.trigger_style)
return module
@@ -849,6 +1123,7 @@ class WindowsApplication(QWidget):
self._config.trigger_key = name
self._persist()
self._configure_trigger(self._config)
+ self._reflect_ways()
if ignored.key(value) in self._config.ignored_inputs:
# The shortcut always stays with Beamer, so it cannot also be on the stays-here list.
self._set_ignored([entry for entry in self._config.ignored_inputs if entry != ignored.key(value)])
@@ -859,8 +1134,9 @@ class WindowsApplication(QWidget):
self._config.trigger_style = value
self._persist()
self._configure_trigger(self._config)
- self.double_tap_slider.setEnabled(value != "hold")
+ motion.set_shown(self.double_tap_row, value != "hold")
self._update_style_hint(value)
+ self._reflect_ways()
def _update_style_hint(self, style: str) -> None:
text = (
@@ -883,76 +1159,249 @@ class WindowsApplication(QWidget):
def _design_page(self, layout, current: Config) -> None:
layout.addWidget(self._on_screen_module(current))
- layout.addWidget(self._edge_look_module(current))
+ self.look_module = self._edge_look_module(current)
+ layout.addWidget(self.look_module)
+ layout.addWidget(self._appearance_module(current))
+ self._reflect_look()
+
+ def _appearance_module(self, current: Config) -> QWidget:
+ """The settings window's own palette. Last on the page, and never hidden with the
+ crossing animations above it: it is chosen once, not part of what they show."""
+ module = widgets.Module("Appearance")
+ self.appearance_choice = widgets.Choice(
+ (("system", "System"), ("light", "Light"), ("dark", "Dark")), 3, current.appearance,
+ on_change=self._appearance_chosen,
+ )
+ module.body.addWidget(self._row(widgets.label("This window", "key"), self.appearance_choice.view))
+ module.body.addWidget(widgets.label("System follows Windows' light or dark setting.", "note", wrap=True))
+ return module
+
+ def _appearance_chosen(self, choice: str) -> None:
+ # Applies the moment it is chosen, not after _debounce_save's pause: the choice is the change.
+ self._apply_appearance(choice)
+ if self._config is None:
+ return
+ self._config.appearance = choice
+ self._persist()
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 = widgets.Switch("Animate crossings on this PC")
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(
- "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.",
+ "Lights this PC as you push toward your Mac. Switched off, crossing still works. "
+ "Your Mac sets how its own edge and notch look.",
"note",
wrap=True,
)
)
+ self.landing_toggle = widgets.Switch("Show where the pointer lands")
+ self.landing_toggle.setFont(theme.font(theme.TYPE["body"]))
+ self.landing_toggle.setChecked(current.shortcut_arrival)
+ self.landing_toggle.toggled.connect(self._apply_look)
+ # The landing plays through the same animations, so it goes with them when they are off.
+ self.landing_row = self._row(
+ self.landing_toggle,
+ widgets.label(
+ "When the shortcut or a menu brings input to this PC, an animation plays around the "
+ "pointer. Choose it under Style for: Shortcut and menu.",
+ "note",
+ wrap=True,
+ ),
+ )
+ self.landing_row.layout().setSpacing(12)
+ module.body.addWidget(self.landing_row)
return module
def _edge_look_module(self, current: Config) -> QWidget:
- module = widgets.Module("Edge and corner")
+ module = widgets.Module("Style and colour")
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,
+ colours = app_config.palette_colours(current.glow_colour)
+ # Which animation the tiles below choose. Not saved: it only says which one is being worked on.
+ self.design_mode_choice = widgets.Choice(
+ (("crossing", "Crossing"), ("switch", "Shortcut and menu")), 2, "crossing", on_change=self._preview_method
+ )
+ self.design_mode_choice.set_names("Style for")
+ self.style_for_row = self._row(widgets.label("Style for", "key"), self.design_mode_choice.view)
+ module.body.addWidget(self.style_for_row)
+ # Where every tile below plays its style: never switched off by the style, and what differs
+ # there is said beneath it. The edge or a corner; a PC has no notch to show.
+ self.effect_method_choice = widgets.Choice(
+ (("edge", "Edge"), ("corner", "Corner")), 2, "edge", on_change=self._place_picked
)
+ self.effect_method_choice.set_names("Show at")
+ self._place_chosen = False
+ self.place_note = widgets.label("", "small", wrap=True)
+ self.preview_at_row = self._row(widgets.label("Show at", "key"), self.effect_method_choice.view, self.place_note)
+ module.body.addWidget(self.preview_at_row)
+ module.body.addSpacing(6)
+ self.effect_stills = {}
+ groups = []
+ for title, items in pages_win.style_groups():
+ # Glow and Beam as stills of the same scene as the effects, so every tile reads alike.
+ tiles = [(style, name, detail, self.effect_stills.setdefault(style, EffectStill(style, colours)))
+ for style, name, detail in items]
+ groups.append((title, tiles))
+ self.glow_style_choice = widgets.TileGroups(groups, 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.Swatches(GLOW_COLOUR_CHOICES, current.glow_colour, on_change=self._apply_look)
+ self.switch_stills = {}
+ switch_groups = []
+ for title, items in pages_win.switch_groups():
+ tiles = []
+ for choice, name, detail in items:
+ picture = self.switch_stills[choice] = SwitchStill(choice, current.glow_style, colours)
+ tiles.append((choice, name, detail, picture))
+ switch_groups.append((title, tiles))
+ self.switch_style_choice = widgets.TileGroups(switch_groups, current.shortcut_arrival_style, on_change=self._apply_look)
+ module.body.addWidget(self.switch_style_choice.view)
+ # Each tile plays its preview while the pointer is over it.
+ for choices, pictures in ((self.glow_style_choice, self.effect_stills),
+ (self.switch_style_choice, self.switch_stills)):
+ for value, picture in pictures.items():
+ self.tile_hover.track(choices.tile(value), picture)
+ # The chosen style's name and what it does, under the tiles that chose it.
+ self.effect_name = widgets.label("", "key")
+ self.effect_note = widgets.label("", "note", wrap=True)
+ caption = self._row(self.effect_name, self.effect_note)
+ caption.layout().setSpacing(2)
+ module.body.addWidget(caption)
+ module.body.addSpacing(6)
+ # Every style and every switch plays at this length, so it follows the tiles either way.
+ self.length_choice = widgets.Choice(effects.LENGTHS, 3, current.effect_length, on_change=self._apply_look)
+ self.length_choice.set_names("Length")
+ module.body.addWidget(self._row(
+ widgets.label("Length", "key"), self.length_choice.view,
+ widgets.label("How long each animation takes to play through once the pointer crosses, and to land.",
+ "small", wrap=True),
+ ))
+ module.body.addSpacing(10)
+ colour_head = QHBoxLayout()
+ colour_head.setSpacing(8)
+ colour_head.addWidget(widgets.label("Colour", "key"))
+ self.colour_note = widgets.label("For the crossing and the shortcut alike", "small")
+ colour_head.addWidget(self.colour_note)
+ colour_head.addStretch(1)
+ module.body.addLayout(colour_head)
+ self.glow_colour_choice = widgets.SwatchGroups(
+ [(title, [(value, name, app_config.palette_colours(value)) for value, name in items])
+ for title, items in pages_win.colour_groups()],
+ current.glow_colour,
+ on_change=self._apply_look,
+ )
module.body.addWidget(self.glow_colour_choice.view)
- self._reflect_look()
+ self._look = None
return module
+ def _preview_method(self, _method) -> None:
+ self._reflect_look()
+
+ def _place_picked(self, _place) -> None:
+ self._place_chosen = True
+ self._reflect_look()
+
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."""
+ """The switch, style and colour save and apply the moment they change. They only decide
+ how crossing is drawn on this PC, 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()
+ self._config.shortcut_arrival = self.landing_toggle.isChecked()
+ self._config.shortcut_arrival_style = self.switch_style_choice.value or "match"
self._config.glow_style = self.glow_style_choice.value
self._config.glow_colour = self.glow_colour_choice.value
+ self._config.effect_length = self.length_choice.value or "normal"
self._persist()
- if not self._config.edge_glow and self.glow is not None:
- self.glow.hide()
+ self._hide_crossing()
def _reflect_look(self) -> None:
on = self.glow_toggle.isChecked()
- self.glow_style_choice.set_enabled(on)
- self.glow_colour_choice.set_enabled(on)
+ landing = self.landing_toggle.isChecked()
+ # With the animations off, what they look like cannot apply, so it is hidden, not faded.
+ motion.set_shown(self.landing_row, on)
+ motion.set_shown(self.look_module, on)
+ # Style for exists only while a switch plays anything; otherwise the module is Crossing.
+ motion.set_shown(self.style_for_row, landing)
+ self.colour_note.setVisible(landing)
+ if not landing:
+ self.design_mode_choice.set_value("crossing")
+ switching = landing and self.design_mode_choice.value == "switch"
+ style = self.glow_style_choice.value
edge = (self._config.mac_return_edge if self._config is not None else "") or "right"
- for preview in self.glow_previews.values():
- preview.set_look(self.glow_colour_choice.value or "signal", edge)
+ colour = self.glow_colour_choice.value or "signal"
+ methods = self._config.crossing_methods if self._config is not None else ()
+ if not self._place_chosen:
+ # Until a place is picked here, the preview opens where the pointer actually crosses.
+ self.effect_method_choice.set_value(pages_win.preview_place(methods))
+ method = self.effect_method_choice.value or "edge"
+ switch_style = (self.switch_style_choice.value or "match") if switching else None
+ length = self.length_choice.value or "normal"
+ look = (style, colour, switching, switch_style, method, edge, length)
+ previous, self._look = self._look, look
+ # Each still redrawn by this change cross-fades: every one with the colour or the length, the
+ # crossing's with the place, the Shortcut and menu stills with the crossing style beside them.
+ stills = []
+ if previous is not None and (previous[1], previous[6]) != (colour, length):
+ stills = [*self.effect_stills.values(), *self.switch_stills.values()]
+ elif previous is not None and previous[4] != method:
+ stills = list(self.effect_stills.values())
+ elif previous is not None and previous[0] != style:
+ stills = list(self.switch_stills.values())
+ still_shots = {still: shot for still in stills if (shot := motion.snapshot(still)) is not None}
+ if previous is not None and previous[2] != switching:
+ leaving = self.glow_style_choice.view if switching else self.switch_style_choice.view
+ arriving = self.switch_style_choice.view if switching else self.glow_style_choice.view
+ tiles_shot = motion.snapshot(leaving)
+ leaving.setVisible(False)
+ arriving.setVisible(True)
+ motion.fade_from(arriving, tiles_shot, fade_in=True)
+ else:
+ self.glow_style_choice.view.setVisible(not switching)
+ self.switch_style_choice.view.setVisible(switching)
+ motion.set_shown(self.preview_at_row, not switching)
+ note = pages_win.place_note(style, method, methods)
+ self.place_note.setText(note)
+ self.place_note.setVisible(bool(note))
+ if switching and pages_win.effects_load_error() is None:
+ fx = effects.switch_effect(switch_style, style)
+ self.effect_name.setText(("Same as crossing: " if switch_style == "match" else "") + fx.name)
+ else:
+ fx = (effects.preview_effect(style) if pages_win.effects_load_error() is None
+ else effects.CLASSIC.get(style)) or effects.CLASSIC["glow"]
+ self.effect_name.setText(f"{fx.name}, {fx.intensity}")
+ self.effect_note.setText(
+ "The effects stopped working and are off until Beamer restarts, so crossings show Glow in "
+ "the same colours. The log says why."
+ if self._effects_failed
+ else f"{fx.blurb} It plays around the pointer when the shortcut or a menu brings input to this PC."
+ if switching
+ else fx.blurb
+ )
+ colours = app_config.palette_colours(colour)
+ for still in (*self.effect_stills.values(), *self.switch_stills.values()):
+ still.set_palette(colours)
+ for still in self.switch_stills.values():
+ still.set_crossing_style(style)
+ pace = effects.pace(length)
+ for still in (*self.effect_stills.values(), *self.switch_stills.values()):
+ still.set_pace(pace)
+ for still in self.effect_stills.values():
+ still.set_place(method)
+ for still, shot in still_shots.items():
+ motion.fade_from(still, shot)
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()
- )
+ window, with the glow switched on, and then a tile only while the pointer is over it."""
+ wanted = self.isVisible() and not self.isMinimized() and self._page == "design" and self.glow_toggle.isChecked()
+ if not wanted:
+ self.tile_hover.stop()
+ self.preview_loop.run(wanted)
def _debounce_save(self) -> None:
"""A ruler being dragged writes once at the end rather than on every step."""
@@ -969,6 +1418,9 @@ class WindowsApplication(QWidget):
return False
try:
save_config(self.config_path, self._config)
+ # A change on the Crossing page reaches the Mac's pointer while it is here, not at its
+ # next crossing: the way home is built from these settings when it arrives.
+ self.server.rearm_return()
return True
except (ConfigError, OSError):
LOGGER.exception("Setting could not be saved")
@@ -976,42 +1428,77 @@ class WindowsApplication(QWidget):
# -- Pairing --------------------------------------------------------------------------
- def _pairing_page(self, layout, current: Config) -> None:
- module = widgets.Module("Pairing code")
- head = QHBoxLayout()
- head.setSpacing(16)
- head.addWidget(module.eyebrow, 0, Qt.AlignmentFlag.AlignTop)
+ def _pairing_block(self, layout, current: Config) -> None:
+ module = widgets.Module("Your Mac")
+ self.mac_module = module
+ self.paired_heading = widgets.label("", "tile-name", wrap=True)
+ module.body.addWidget(self.paired_heading)
+ self.pair_intro = widgets.label(
+ "Press Pair a Mac, then on your Mac choose this PC and type the six-digit code shown here. "
+ "You only do this once.",
+ "note",
+ wrap=True,
+ )
+ module.body.addWidget(self.pair_intro)
+ # The last pairing's outcome; takes no room while there is none.
self.pair_note = widgets.label("", "note", wrap=True)
- self.pair_note.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop)
- head.addWidget(self.pair_note, 1)
- module.body.addLayout(head)
+ self.pair_note.setVisible(False)
+ module.body.addWidget(self.pair_note)
+ self.pair_button = QPushButton()
+ self.pair_button.setProperty("vernier", "primary")
+ self.pair_button.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.pair_button.clicked.connect(self._toggle_pairing)
+ module.body.addWidget(self.pair_button, 0, Qt.AlignmentFlag.AlignLeft)
+ layout.addWidget(module)
+
+ self.code_module = widgets.Module("Pairing code")
code_row = QHBoxLayout()
code_row.setSpacing(18)
self.code_label = widgets.label(IDLE_CODE, "code-idle")
self.code_label.setFont(theme.mono_font(theme.PAIRING_CODE))
+ # Reachable by Tab and read out digit by digit, so a screen reader user can type it.
+ self.code_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByKeyboard
+ | Qt.TextInteractionFlag.TextSelectableByMouse)
+ self.code_label.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.code_label.setAccessibleName("Pairing code")
# The digits have no descenders, so the line box can be trimmed to the ink.
self.code_label.setFixedHeight(round(theme.PAIRING_CODE))
code_row.addWidget(self.code_label, 1, Qt.AlignmentFlag.AlignVCenter)
- count = QVBoxLayout()
- count.setSpacing(8)
- count.addStretch(1)
self.count_label = widgets.label("1:00", "count-idle")
self.count_label.setFont(theme.mono_font(theme.COUNT))
- self.count_label.setAlignment(Qt.AlignmentFlag.AlignRight)
- count.addWidget(self.count_label, 0, Qt.AlignmentFlag.AlignRight)
- self.pair_button = QPushButton("Pair a Mac")
- self.pair_button.setProperty("vernier", "primary")
- self.pair_button.setCursor(Qt.CursorShape.PointingHandCursor)
- self.pair_button.clicked.connect(self._toggle_pairing)
- count.addWidget(self.pair_button, 0, Qt.AlignmentFlag.AlignRight)
- count.addStretch(1)
- code_row.addLayout(count)
- module.body.addLayout(code_row)
+ self.count_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
+ self.count_label.setAccessibleName("Time left")
+ code_row.addWidget(self.count_label, 0, Qt.AlignmentFlag.AlignVCenter)
+ self.code_module.body.addLayout(code_row)
self.drain = widgets.Drain()
- module.body.addWidget(self.drain)
- layout.addWidget(module)
- self._say_pairing(f"Paired with {current.paired_with}." if current.paired_with else PAIR_HINT, "note")
+ self.code_module.body.addWidget(self.drain)
+ self.code_module.body.addWidget(widgets.label(PAIR_HINT, "note", wrap=True))
+ # Pairing by address, for a network whose broadcasts never reach the Mac.
+ self.address_note = widgets.label("", "note", wrap=True)
+ self.address_note.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
+ self.code_module.body.addWidget(self.address_note)
+ self.code_module.setVisible(False)
+ layout.addWidget(self.code_module)
+ self._show_paired(current.paired_with)
+
+ def _show_paired(self, name: str) -> None:
+ self.paired_heading.setText(f"Paired with {name}" if name else "Not paired yet")
+ self.pair_intro.setVisible(not name)
+ if self.announcer.code is None:
+ self.pair_button.setText("Pair a different Mac" if name else "Pair a Mac")
+ self._place_pairing(bool(name))
+
+ def _place_pairing(self, paired: bool) -> None:
+ """First of Overview's modules until a Mac is paired, then just above At sign-in. The page's
+ title and purpose sit in the same layout, above the modules."""
+ layout = getattr(self, "overview_layout", None)
+ if layout is None or not hasattr(self, "code_module"):
+ return
+ for widget in (self.mac_module, self.code_module):
+ layout.removeWidget(widget)
+ at = layout.indexOf(self.sign_in_module if paired else self.link_module)
+ layout.insertWidget(at, self.mac_module)
+ layout.insertWidget(at + 1, self.code_module)
def _toggle_pairing(self) -> None:
if self.announcer.code is not None:
@@ -1020,42 +1507,71 @@ class WindowsApplication(QWidget):
if self.announcer.error:
self._say_pairing(f"Pairing is not available: {self.announcer.error}", "note-fault")
return
+ self._say_pairing("", "note")
self.announcer.begin_pairing()
self._refresh_pairing()
+ def _pairing_addresses(self) -> list:
+ """The one address worth typing on the Mac: this PC's on the network that reaches the Mac
+ it last knew, else on the default route. Every adapter's address, virtual switches and
+ the hotspot included, only when neither can be found."""
+ mac = self._config.mac_host if self._config is not None else ""
+ # Connecting a UDP socket only picks the interface; nothing is sent to either address.
+ for target in (mac, "192.0.2.1"):
+ if not target:
+ continue
+ try:
+ address = local_address_towards(target)
+ except OSError:
+ continue
+ if address and not address.startswith(("127.", "0.")):
+ return [address]
+ return pairing._local_ipv4_addresses()
+
def _refresh_pairing(self) -> None:
code = self.announcer.code
if code is not None:
seconds = self.announcer.seconds_left
- self.code_label.setText(f"{code[:3]} {code[3:]}")
+ shown = f"{code[:3]} {code[3:]}"
+ if self.code_label.text() != shown:
+ self.code_label.setText(shown)
+ self.code_label.setAccessibleName(f"Pairing code {' '.join(code)}")
widgets.set_role(self.code_label, "code")
self.count_label.setText(f"{seconds // 60}:{seconds % 60:02d}")
widgets.set_role(self.count_label, "count")
self.drain.set_remaining(seconds)
self.pair_button.setText("Cancel")
- self._say_pairing(PAIR_HINT, "note")
+ if not self._code_shown:
+ self._code_addresses = self._pairing_addresses()
+ self.address_note.setVisible(bool(self._code_addresses))
+ motion.set_shown(self.code_module, True)
+ # Every tick, so switching Hide addresses while a code is up applies at once.
+ note = self._shown(
+ f"Not listed on the Mac? Type this PC's address there: {', '.join(self._code_addresses)}"
+ ) if self._code_addresses else ""
+ if self.address_note.text() != note:
+ self.address_note.setText(note)
self._code_shown = True
return
if not self._code_shown:
return
self._code_shown = False
- self.code_label.setText(IDLE_CODE)
- widgets.set_role(self.code_label, "code-idle")
- self.count_label.setText("1:00")
- widgets.set_role(self.count_label, "count-idle")
+ motion.set_shown(self.code_module, False)
+ self.code_label.setAccessibleName("Pairing code")
self.drain.set_remaining(0)
- self.pair_button.setText("Pair a Mac")
+ self._show_paired(self._config.paired_with if self._config is not None else "")
outcome = self.announcer.outcome
if outcome == "refused":
- self._say_pairing("A wrong code was entered, so that code is cancelled. Press Pair a Mac for a fresh one.", "note-fault")
+ self._say_pairing("A wrong code was entered, so that code is cancelled. Pair again for a fresh one.", "note-fault")
elif outcome == "expired":
- self._say_pairing("The code expired. Press Pair a Mac for a fresh one.", "note-amber")
+ self._say_pairing("The code expired. Pair again for a fresh one.", "note-amber")
elif outcome is None:
self._say_pairing("Pairing cancelled.", "note")
def _say_pairing(self, text: str, tone: str) -> None:
if text != self.pair_note.text():
self.pair_note.setText(text)
+ self.pair_note.setVisible(bool(text))
widgets.set_role(self.pair_note, tone)
def _on_paired(self, token: str, mac_name: str, mac_address: str) -> None:
@@ -1087,55 +1603,103 @@ class WindowsApplication(QWidget):
self.token_entry.setText(token)
self._refresh_pairing()
who = mac_name or "your Mac"
- self._say_pairing(f"Paired with {who}. The receiver restarted with the new token.", "note-live")
+ self._show_paired(candidate.paired_with)
+ self._say_pairing("Paired. The receiver restarted with the new token.", "note-live")
LOGGER.info("Paired with %s", who)
# -- Connection -------------------------------------------------------------------------
def _connection_page(self, layout, current: Config) -> None:
- module = widgets.Module("Listening")
+ self._firewall_module(layout)
+ privacy = widgets.Module("Addresses")
+ self.hide_switch = widgets.Switch("Hide addresses")
+ self.hide_switch.setFont(theme.font(theme.TYPE["body"]))
+ self.hide_switch.setChecked(current.hide_addresses)
+ self.hide_switch.toggled.connect(self._set_hide_addresses)
+ privacy.body.addWidget(self.hide_switch)
+ privacy.body.addWidget(widgets.label(
+ "Hides every IP and hardware address in this window and the tray.",
+ "note",
+ wrap=True,
+ ))
+ layout.addWidget(privacy)
+ module = widgets.Module("This PC")
fields = QGridLayout()
fields.setHorizontalSpacing(10)
fields.setVerticalSpacing(10)
fields.setColumnStretch(1, 1)
+
+ def field(row, caption, entry, span=2):
+ # The caption is the field's buddy and its accessible name, so a screen reader and
+ # Alt+letter both reach the field by what it is called.
+ key = widgets.label(caption, "key")
+ key.setBuddy(entry)
+ entry.setAccessibleName(caption)
+ fields.addWidget(key, row, 0)
+ fields.addWidget(entry, row, 1, 1, span)
+
# The address the Mac connects to. Pairing fills it in; a hand set-up copies it from here.
self.host_entry = QLineEdit(self._host)
- fields.addWidget(widgets.label("This PC's address", "key"), 0, 0)
- fields.addWidget(self.host_entry, 0, 1, 1, 2)
+ field(0, "This PC's address", self.host_entry)
self.port_entry = QLineEdit(str(current.port))
- fields.addWidget(widgets.label("Listen port", "key"), 1, 0)
- fields.addWidget(self.port_entry, 1, 1, 1, 2)
+ field(1, "Port", self.port_entry)
self.token_entry = QLineEdit(current.auth_token)
self.token_entry.setEchoMode(QLineEdit.EchoMode.Password)
self.token_entry.setMinimumWidth(80)
- fields.addWidget(widgets.label("Shared token", "key"), 2, 0)
- fields.addWidget(self.token_entry, 2, 1)
+ field(2, "Shared token", self.token_entry, span=1)
self.show_token = QPushButton("Show")
self.show_token.setProperty("vernier", "small")
self.show_token.setCheckable(True)
+ self.show_token.setMinimumHeight(widgets.MIN_TARGET)
self.show_token.setCursor(Qt.CursorShape.PointingHandCursor)
self.show_token.setToolTip("Show the shared token in this window")
+ self.show_token.setAccessibleName("Show the shared token")
self.show_token.toggled.connect(self._update_token_visibility)
fields.addWidget(self.show_token, 2, 2)
module.body.addLayout(fields)
mac_row = QHBoxLayout()
mac_row.setSpacing(6)
- mac_row.addWidget(widgets.label("Mac address:", "note"))
- self.mac_host_readout = widgets.label(current.mac_host or "Not learned yet", "readout", wrap=True)
+ mac_row.addWidget(widgets.label("Your Mac's IP address:", "note"))
+ self.mac_host_readout = widgets.label(self._shown(current.mac_host) or "Not learned yet", "readout", wrap=True)
+ self.mac_host_readout.setAccessibleName("Your Mac's IP address")
mac_row.addWidget(self.mac_host_readout, 1)
module.body.addLayout(mac_row)
+ self._show_host_entry()
self.save_message = widgets.label("", "note", wrap=True)
+ self.save_message.setVisible(False)
module.body.addWidget(self.save_message)
- self.save_button = QPushButton("Save and restart receiver")
+ self.save_button = QPushButton("Save and reconnect")
self.save_button.setProperty("vernier", "primary")
self.save_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.save_button.clicked.connect(self.save)
module.body.addWidget(self.save_button, 0, Qt.AlignmentFlag.AlignLeft)
layout.addWidget(module)
+ def _shown(self, text: str) -> str:
+ """`text` as the window may show it: with Hide addresses on, no address in it."""
+ return pages_win.redact(text, bool(self._config is not None and self._config.hide_addresses))
+
+ def _set_hide_addresses(self, enabled: bool) -> None:
+ if self._config is None:
+ return
+ self._config.hide_addresses = bool(enabled)
+ self._persist()
+ self._show_host_entry()
+ self.mac_host_readout.setText(self._shown(self._config.mac_host) or "Not learned yet")
+ self._refresh_pairing()
+ self._refresh_window()
+ self.tray.setToolTip(self._title())
+ self.status_action.setText(self._title())
+
+ def _show_host_entry(self) -> None:
+ """The address field as dots while addresses are hidden, still editable."""
+ hide = bool(self._config is not None and self._config.hide_addresses)
+ self.host_entry.setEchoMode(QLineEdit.EchoMode.Password if hide else QLineEdit.EchoMode.Normal)
+
def _update_token_visibility(self, checked: bool) -> None:
self.token_entry.setEchoMode(QLineEdit.EchoMode.Normal if checked else QLineEdit.EchoMode.Password)
self.show_token.setText("Hide" if checked else "Show")
+ self.show_token.setAccessibleName("Hide the shared token" if checked else "Show the shared token")
def save(self) -> None:
current = self._config or default_config()
@@ -1150,6 +1714,7 @@ class WindowsApplication(QWidget):
self._apply_config(candidate)
except (ConfigError, TypeError, ValueError) as exc:
self.save_message.setText(str(exc))
+ self.save_message.setVisible(True)
widgets.set_role(self.save_message, "note-fault")
return
except OSError as exc:
@@ -1157,14 +1722,16 @@ class WindowsApplication(QWidget):
QMessageBox.critical(self, "Save failed", str(exc))
return
self.save_message.setText("Saved.")
+ self.save_message.setVisible(True)
widgets.set_role(self.save_message, "note-live")
def _apply_config(self, config: Config) -> None:
if self.server.listening:
self.server.stop()
self._config = config
- if not config.edge_glow and self.glow is not None:
- self.glow.hide()
+ self._apply_input_scale(config)
+ if not config.edge_glow:
+ self._hide_crossing()
self.allow_switch.setEnabled(True)
self.allow_switch.setChecked(config.allow_mac_to_drive)
if config.allow_mac_to_drive:
@@ -1176,15 +1743,15 @@ class WindowsApplication(QWidget):
self._start_sending(config)
else:
self._stop_sending()
- self.mac_host_readout.setText(config.mac_host or "Not learned yet")
+ self.mac_host_readout.setText(self._shown(config.mac_host) or "Not learned yet")
- # -- Firewall ---------------------------------------------------------------------------
+ # -- Firewall, on Connection --------------------------------------------------------------
- def _firewall_page(self, layout, current: Config) -> None:
+ def _firewall_module(self, layout) -> None:
module = widgets.Module("Windows Firewall")
self.firewall_note = widgets.label("Checking Windows Firewall…", "note", wrap=True)
module.body.addWidget(self.firewall_note)
- self.firewall_button = QPushButton("Check again")
+ self.firewall_button = QPushButton("Checking…")
self.firewall_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.firewall_button.setEnabled(False)
self.firewall_button.clicked.connect(self._firewall_action)
@@ -1305,12 +1872,31 @@ class WindowsApplication(QWidget):
return
theme.apply_titlebar(hwnd)
+ def _apply_appearance(self, choice: Optional[str] = None) -> None:
+ """Brings the window to the palette the appearance setting and Windows ask for, cross-faded
+ while it is visible. Called for the control's own choice, on load, and by
+ theme.watch_system whenever Windows' own light or dark setting changes while open."""
+ if choice is None:
+ choice = self.appearance_choice.value if hasattr(self, "appearance_choice") else None
+ if choice is None:
+ choice = self._config.appearance if self._config is not None else "system"
+ dark = theme.wants_dark(choice, theme.system_dark())
+ if dark == theme.is_dark():
+ return
+ shot = motion.snapshot(self._body)
+ theme.set_dark(dark)
+ self._apply_theme()
+ widgets.refresh_colours(self)
+ motion.fade_from(self._body, shot)
+
def _build_tray(self) -> None:
self.tray = QSystemTrayIcon(QIcon(status_icon(self._status)), self)
self.tray.setToolTip(self._title())
menu = QMenu()
- header = menu.addAction(f"Beamer {VERSION}")
- header.setEnabled(False)
+ # The version line; it becomes the way to a newer release when there is one.
+ self.header_action = menu.addAction(f"Beamer {VERSION}")
+ self.header_action.setEnabled(False)
+ self.header_action.triggered.connect(self.open_update)
menu.addSeparator()
self.open_action = menu.addAction("Open Beamer")
self.open_action.triggered.connect(self.show_window)
@@ -1323,11 +1909,11 @@ class WindowsApplication(QWidget):
menu.addSeparator()
# One tick per direction, each the same switch the Overview page shows, so either
# direction can be turned off while the other keeps working and the two never disagree.
- self.drive_action = menu.addAction("Mac drives this PC")
+ self.drive_action = menu.addAction("Your Mac drives this PC")
self.drive_action.setCheckable(True)
self.drive_action.toggled.connect(self.allow_switch.setChecked)
self.allow_switch.toggled.connect(self.drive_action.setChecked)
- self.send_action = menu.addAction("This PC drives the Mac")
+ self.send_action = menu.addAction("This PC drives your Mac")
self.send_action.setCheckable(True)
self.send_action.toggled.connect(self.send_switch.setChecked)
self.send_switch.toggled.connect(self.send_action.setChecked)
@@ -1335,6 +1921,7 @@ class WindowsApplication(QWidget):
self.send_action.setChecked(self.send_switch.isChecked())
menu.addSeparator()
menu.addAction("Reload configuration").triggered.connect(self.reload_config)
+ menu.addAction("Open log folder").triggered.connect(self.open_log_folder)
menu.addSeparator()
menu.addAction("About Beamer").triggered.connect(self.show_about)
menu.addAction("Quit Beamer").triggered.connect(self.quit)
@@ -1360,27 +1947,27 @@ class WindowsApplication(QWidget):
def _reflect_config(self, config: Config) -> None:
"""Every control on every page set from `config`, without any of them saving back."""
- for box in (*self.way_boxes.values(), self.dragging_switch, self.glow_toggle,
+ for box in (*self.way_boxes.values(), self.dragging_switch, self.glow_toggle, self.landing_toggle,
self.resistance_slider, self.double_tap_slider):
box.blockSignals(True)
try:
- for value, box in self.way_boxes.items():
- box.setChecked(value in config.crossing_methods)
self.dragging_switch.setChecked(config.block_while_dragging)
self.glow_toggle.setChecked(config.edge_glow)
+ self.landing_toggle.setChecked(config.shortcut_arrival)
+ self.switch_style_choice.set_value(config.shortcut_arrival_style)
self.resistance_slider.setValue(config.crossing_resistance_px)
self.double_tap_slider.setValue(config.double_tap_ms)
finally:
- for box in (*self.way_boxes.values(), self.dragging_switch, self.glow_toggle,
+ for box in (*self.way_boxes.values(), self.dragging_switch, self.glow_toggle, self.landing_toggle,
self.resistance_slider, self.double_tap_slider):
box.blockSignals(False)
self.resistance_readout.setText(f"{config.crossing_resistance_px} px")
self._update_resistance_hint(config.crossing_resistance_px)
self.double_tap_readout.setText(f"{config.double_tap_ms} ms")
- self.double_tap_slider.setEnabled(config.trigger_style != "hold")
+ self.resistance_strip.set_value(config.crossing_resistance_px)
+ motion.set_shown(self.double_tap_row, config.trigger_style != "hold")
self.corner_choice.set_value(config.crossing_corner)
- self.corner_choice.set_enabled("corner" in config.crossing_methods)
- self.edge_choice.set_value(config.mac_return_edge or "right")
+ self.edge_choice.set_value(config.mac_return_edge)
self.trigger_recorder.set_title(TRIGGER_KEYS.get(config.trigger_key, config.trigger_key))
self.trigger_style_choice.set_value(config.trigger_style)
self._update_style_hint(config.trigger_style)
@@ -1388,21 +1975,65 @@ class WindowsApplication(QWidget):
self.modifier_note.setText(MODIFIER_NOTES[config.modifier_style])
self.glow_style_choice.set_value(config.glow_style)
self.glow_colour_choice.set_value(config.glow_colour)
+ self.length_choice.set_value(config.effect_length)
self._reflect_look()
+ self.appearance_choice.set_value(config.appearance)
+ self._apply_appearance(config.appearance)
+ self._reflect_ways()
self._show_ignored(list(config.ignored_inputs))
+ for key, slider in self.speed_sliders.items():
+ slider.blockSignals(True)
+ slider.setValue(round(getattr(config, key) * 100))
+ slider.blockSignals(False)
+ self.speed_readouts[key].setText(f"{slider.value()}%")
+ for switch, value in ((self.reverse_scroll_switch, config.reverse_scroll),
+ (self.updates_switch, config.check_updates),
+ (self.hide_switch, config.hide_addresses)):
+ switch.blockSignals(True)
+ switch.setChecked(value)
+ switch.blockSignals(False)
self.host_entry.setText(config.host)
+ # The switch above was set with its signal blocked, so its handler never ran.
+ self._show_host_entry()
self.port_entry.setText(str(config.port))
self.token_entry.setText(config.auth_token)
+ self._show_paired(config.paired_with)
def _on_tray_activated(self, reason) -> None:
if reason in (QSystemTrayIcon.ActivationReason.Trigger, QSystemTrayIcon.ActivationReason.DoubleClick):
self.show_window()
def start(self) -> None:
+ self.update_checker.start()
+ if firewall_win.is_elevated():
+ # Beamer's own rules before any socket opens: a listener Windows has no rule for makes
+ # it ask, and a click on Allow there writes rules for every network, public ones too,
+ # where Beamer's are for private networks only.
+ threading.Thread(target=self._rules_then_listen, name="Beamer-firewall-first", daemon=True).start()
+ else:
+ self._listen()
+
+ def _rules_then_listen(self) -> None:
+ try:
+ exe, port = self._firewall_target()
+ status = firewall_win.status(exe, port)
+ if not status.error and not status.allowed and not status.blocked:
+ LOGGER.info("Adding this PC's firewall rules before listening")
+ firewall_win.repair(exe, port, ("Private",))
+ except Exception:
+ LOGGER.exception("The firewall rules could not be added before listening")
+ self.bridge.rules_ready.emit()
+
+ def _listen(self) -> None:
+ if self._closing:
+ return
self.announcer.start()
if self._config is not None:
self.server.start(self._config)
self._start_sending(self._config)
+ # After the rules, so the firewall module reads what start() just wrote, and with no config
+ # the receiver never starts, so nothing else would ever read it.
+ self._check_firewall()
def _configure_trigger(self, config: Config) -> None:
self._trigger.configure(config.trigger_key, config.trigger_style, config.double_tap_ms)
@@ -1477,9 +2108,11 @@ class WindowsApplication(QWidget):
return
self.sender.update_config(self._config)
self._start_sending(self._config)
- self.mac_host_readout.setText(self._config.mac_host or "Not learned yet")
+ shown = pages_win.redact(self._config.mac_host, self._config.hide_addresses)
+ self.mac_host_readout.setText(shown or "Not learned yet")
self.edge_choice.set_value(self._config.mac_return_edge)
self._reflect_look()
+ self._reflect_ways()
def _on_sending(self, connected: bool, detail: str) -> None:
self._sending_detail = detail
@@ -1536,11 +2169,11 @@ class WindowsApplication(QWidget):
return
self._closing = True
self.refresh_timer.stop()
+ self.update_checker.stop()
self.announcer.stop()
self.server.stop()
self._stop_sending()
- if self.glow is not None:
- self.glow.hide()
+ self._hide_crossing()
self.tray.hide()
QApplication.quit()
@@ -1566,13 +2199,93 @@ class WindowsApplication(QWidget):
self.hooks.stop()
self._sending_detail = "Off"
- def _on_pressure(self, edge: str, pressure: float, crossed: bool) -> None:
+ def _effect_overlay(self) -> Optional[EffectOverlay]:
+ """The crossing effects' window when the chosen style is one of them and they have not
+ failed this run; None means the plain glow draws instead."""
+ config = self._config
+ if self._closing or config is None or not config.edge_glow or not pages_win.is_effect(config.glow_style):
+ return None
+ if self.effects is None:
+ self.effects = EffectOverlay(on_failure=self._on_effects_failed)
+ if self.effects.failed:
+ return None
+ self.effects.configure(config.glow_style, config.glow_colour, config.effect_length)
+ if self.effects.failed or self.effects._fx is None:
+ return None
+ return self.effects
+
+ def _on_pressure(self, edge: str, pressure: float, crossed: bool, part=None) -> None:
if self._closing or self._config is None or not self._config.edge_glow:
return
+ overlay = self._effect_overlay()
+ if overlay is not None:
+ overlay.push(edge, pressure, crossed, part=part)
+ return
+ style = self._config.glow_style
if self.glow is None:
self.glow = EdgeGlow()
- self.glow.configure(self._config.glow_style, self._config.glow_colour)
- self.glow.set_pressure(edge, pressure, crossed)
+ # An effect that failed earlier in the run falls back to the plain glow, in its colour.
+ self.glow.configure(style if style in ("glow", "beam") else "glow", self._config.glow_colour,
+ self._config.effect_length)
+ self.glow.set_pressure(edge, pressure, crossed, part)
+
+ def _on_arrival(self, method: str, edge: str, x: float, y: float) -> None:
+ """A crossing landed the pointer on `edge`, or with method "switch" input came here by a
+ switch and the pointer is wherever it was left."""
+ if method == "switch":
+ overlay = self._switch_overlay()
+ if overlay is not None:
+ overlay.switched(logical_point(x, y), self._config.shortcut_arrival_style)
+ return
+ overlay = self._effect_overlay()
+ if overlay is not None:
+ overlay.arrive(method, edge, logical_point(x, y))
+ elif self.effects is not None:
+ self.effects.crossed_in()
+
+ def _switch_overlay(self) -> Optional[EffectOverlay]:
+ """The effects' window for a switch into this PC, when the Design page asks to show where
+ the pointer lands: the chosen effect's arrival, or the locator with Glow and Beam."""
+ config = self._config
+ if self._closing or config is None or not config.edge_glow or not config.shortcut_arrival:
+ return None
+ if self.effects is None:
+ self.effects = EffectOverlay(on_failure=self._on_effects_failed)
+ if self.effects.failed:
+ return None
+ self.effects.configure(config.glow_style, config.glow_colour, config.effect_length)
+ if self.effects.failed or self.effects._fx is None:
+ return None
+ return self.effects
+
+ def _return_model(self, edge: str, resistance: int):
+ """The way home for the Mac's pointer through `edge` of this screen, from this PC's own
+ ways in, as for this PC's own mouse: only the chosen thirds, the whole edge, the corner
+ when it sits on that edge, else none (the Mac's shortcut still switches). On the
+ receiver's session thread."""
+ config = self._config
+ if config is None:
+ return return_edge.ReturnEdge(edge, resistance)
+ methods = set(config.crossing_methods)
+ if "part" in methods:
+ return return_edge.PartEdge(edge, config.crossing_edge_parts, resistance)
+ if "edge" in methods:
+ return return_edge.ReturnEdge(edge, resistance)
+ corner = config.crossing_corner
+ if "corner" in methods and edge in corner.split("_"):
+ return return_edge.CornerPush(corner, edge, resistance)
+ return None
+
+ def _on_effects_failed(self) -> None:
+ """The overlay turned the effects off for the run; the Design page says so."""
+ self._effects_failed = True
+ self._reflect_look()
+
+ def _hide_crossing(self) -> None:
+ if self.glow is not None:
+ self.glow.hide()
+ if self.effects is not None:
+ self.effects.stop()
def _set_status(self, state: ServerState, detail: str) -> None:
"""Called from the receiver's thread — hand off to the GUI thread."""
@@ -1609,9 +2322,14 @@ class WindowsApplication(QWidget):
if state is ServerState.CONNECTED and detail.startswith("Connected to "):
who = (self._config.paired_with if self._config is not None else "") or "Your Mac"
detail = f"{who} at {detail[len('Connected to '):]}"
+ detail = self._shown(detail)
heading = STATUS_TITLES[state]
if heading != self.status_heading.text():
+ first = not self.status_heading.text()
+ shot = None if first else motion.snapshot(self.status_heading)
self.status_heading.setText(heading)
+ widgets.set_role(self.status_heading, HEADING_ROLE[tone])
+ motion.fade_from(self.status_heading, shot, fade_in=True)
widgets.set_role(self.status_heading, HEADING_ROLE[tone])
if detail != self.status_detail.text():
self.status_detail.setText(detail)
@@ -1631,14 +2349,26 @@ class WindowsApplication(QWidget):
sending = self._config is not None and self._config.send_to_mac
self.redirect_button.setEnabled(sending)
self.redirect_action.setEnabled(sending)
+ self.redirect_note.setVisible(not sending and self._config is not None)
pause_text = "Resume crossing" if self.sender.crossing_paused else "Pause crossing"
if pause_text != self.pause_button.text():
self.pause_button.setText(pause_text)
self.pause_action.setText(pause_text)
widgets.set_role(self.pause_button, "primary" if self.sender.crossing_paused else "")
- sentence = self._crossing_state_sentence()
+ args = self._crossing_state_args()
+ sentence = pages_win.crossing_state_sentence(*args)
if sentence != self.crossing_state.text():
+ shot = motion.snapshot(self.crossing_state)
self.crossing_state.setText(sentence)
+ motion.fade_from(self.crossing_state, shot)
+ armed = args[4]
+ self.pause_button.setVisible(armed)
+ motion.set_shown(self.pause_row, armed or pages_win.crossing_state_blocked(*args[:4]))
+ outward = pages_win.outward_link_line(self.sender.connected)
+ if outward != self.outward_line.text():
+ shot = motion.snapshot(self.outward_line)
+ self.outward_line.setText(outward)
+ motion.fade_from(self.outward_line, shot)
# "On your Mac" above already says this while redirecting; the hint is for the rest --
# not connected, or the hooks failing to install -- and stays quiet in the boring case.
send_hint = "" if self.sender.redirecting or self._sending_detail in (
@@ -1653,16 +2383,15 @@ class WindowsApplication(QWidget):
self._refresh_pairing()
edge = self.server.return_edge
resistance = self.server.return_resistance
- if edge and resistance is not None:
- text = f"{edge} edge · {resistance} px"
- else:
- text = "not set yet"
+ known = bool(edge) and resistance is not None
+ text = f"{edge} edge · {resistance} px" if known else ""
if text != self.return_readout.text():
self.return_readout.setText(text)
+ motion.set_shown(self.return_row, known)
def _title(self) -> str:
with self._status_lock:
- return f"Beamer — {self._status.value}: {self._status_detail}"
+ return self._shown(f"Beamer — {self._status.value}: {self._status_detail}")
def parse_args() -> argparse.Namespace:
@@ -1690,18 +2419,16 @@ def main() -> None:
kernel32.CloseHandle(mutex)
return
arguments = parse_args()
- if arguments.config == default_config_path():
- migrate_legacy_config()
log_path = configure_logging()
LOGGER.info("Starting Beamer Windows receiver")
if log_path is not None:
LOGGER.info("Logging to %s", log_path)
- # Above normal, so a busy rig cannot starve the hooks: Windows removes a
+ # Above normal, so a busy machine cannot starve the hooks: Windows removes a
# low-level hook whose callback misses its timeout, silently and for good,
# and every Beamer thread must win the CPU for the hook thread to get the
# GIL. Beamer idles near 0%, so the class costs the rest of the machine
- # nothing (a video pipeline held half the rig on 23-09-2026 when the
- # PC's mouse was stranded on the Mac).
+ # nothing (for example, a video pipeline holding half the CPU once left
+ # the PC's mouse stranded on the Mac).
kernel32.GetCurrentProcess.restype = ctypes.c_void_p
kernel32.SetPriorityClass.argtypes = [ctypes.c_void_p, ctypes.c_ulong]
if not kernel32.SetPriorityClass(kernel32.GetCurrentProcess(), 0x8000): # ABOVE_NORMAL_PRIORITY_CLASS
diff --git a/win_app/motion.py b/win_app/motion.py
new file mode 100644
index 0000000..d038a5e
--- /dev/null
+++ b/win_app/motion.py
@@ -0,0 +1,303 @@
+"""The settings window's motion: every visual change runs 200 ms with an ease-out, the next change
+interrupts it from wherever it had got to, and nothing moves while the window cannot be seen or
+while Windows' "Show animations in Windows" is off. Qt's own animations only, no library."""
+
+from __future__ import annotations
+
+from PySide6.QtCore import QEasingCurve, QEvent, QRect, QRectF, Qt, QVariantAnimation
+from PySide6.QtGui import QColor, QPainter, QPen
+from PySide6.QtWidgets import QGraphicsOpacityEffect, QLabel, QWidget
+
+DURATION = 200
+QWIDGETSIZE_MAX = 16777215
+
+
+def reduced() -> bool:
+ """Read at each change, as the setting can flip while the window is open."""
+ try:
+ from effect_overlay import system_reduced_motion
+ except Exception:
+ return False
+ return system_reduced_motion()
+
+
+def should_animate(widget: QWidget) -> bool:
+ window = widget.window()
+ return window.isVisible() and not window.isMinimized() and not reduced()
+
+
+def _runs(owner) -> dict:
+ runs = getattr(owner, "_motion_runs", None)
+ if runs is None:
+ runs = {}
+ owner._motion_runs = runs
+ return runs
+
+
+def running(owner, key: str) -> bool:
+ return key in _runs(owner)
+
+
+def stop(owner, key: str) -> None:
+ animation = _runs(owner).pop(key, None)
+ if animation is not None:
+ animation.stop()
+ animation.deleteLater()
+
+
+def animate(owner: QWidget, key: str, start, end, apply, done=None, duration: int = DURATION,
+ curve=QEasingCurve.Type.OutCubic, force: bool = False):
+ """Runs `apply(value)` from `start` to `end`, then `done()`. A second call with the same key
+ replaces the first without calling its `done`, so the caller restarts from the current value.
+ Instant, `apply(end)` then `done()`, when the window cannot be seen or motion is reduced."""
+ stop(owner, key)
+ if not force and not should_animate(owner):
+ apply(end)
+ if done is not None:
+ done()
+ return None
+ animation = QVariantAnimation(owner)
+ animation.setDuration(duration)
+ animation.setEasingCurve(QEasingCurve(curve))
+ animation.setStartValue(start)
+ animation.setEndValue(end)
+ animation.valueChanged.connect(apply)
+ runs = _runs(owner)
+
+ def finished():
+ if runs.get(key) is animation:
+ del runs[key]
+ animation.deleteLater()
+ if done is not None:
+ done()
+
+ animation.finished.connect(finished)
+ runs[key] = animation
+ apply(start)
+ animation.start()
+ return animation
+
+
+class _Fade(QGraphicsOpacityEffect):
+ """Marks an opacity effect as motion's own, so it is never mistaken for a widget's dimming."""
+
+
+def _fade_of(widget: QWidget):
+ effect = widget.graphicsEffect()
+ if isinstance(effect, _Fade):
+ return effect
+ if effect is not None:
+ return None
+ effect = _Fade(widget)
+ effect.setOpacity(1.0)
+ widget.setGraphicsEffect(effect)
+ return effect
+
+
+def _drop_fade(widget: QWidget) -> None:
+ if isinstance(widget.graphicsEffect(), _Fade):
+ widget.setGraphicsEffect(None)
+
+
+def _width_for(widget: QWidget) -> int:
+ width = widget.width()
+ parent = widget.parentWidget()
+ if parent is not None and (width <= 0 or widget.isHidden()):
+ margins = parent.contentsMargins()
+ width = parent.width() - margins.left() - margins.right()
+ if parent.layout() is not None:
+ inner = parent.layout().contentsMargins()
+ width -= inner.left() + inner.right()
+ return width
+
+
+def _natural_height(widget: QWidget) -> int:
+ width = _width_for(widget)
+ if widget.hasHeightForWidth() and width > 0:
+ height = widget.heightForWidth(width)
+ if height > 0:
+ return height
+ return widget.sizeHint().height()
+
+
+def target_shown(widget: QWidget) -> bool:
+ """Where `set_shown` is taking the widget, which may not be where it is yet."""
+ target = getattr(widget, "_motion_shown", None)
+ return (not widget.isHidden()) if target is None else target
+
+
+def set_shown(widget: QWidget, shown: bool) -> None:
+ """Shows or hides a row or module by sliding its height open or shut and fading it; the cap on
+ its height comes off at the end, so later layout is never held to the animated size."""
+ shown = bool(shown)
+ if target_shown(widget) == shown:
+ return
+ moving = running(widget, "shown")
+ widget._motion_shown = shown
+
+ layout = widget.layout()
+
+ def finish():
+ widget.setMaximumHeight(QWIDGETSIZE_MAX)
+ _drop_fade(widget)
+ if layout is not None and not layout.isEnabled():
+ layout.setEnabled(True)
+ layout.invalidate()
+ widget.setVisible(shown)
+ widget._motion_shown = None
+
+ if not should_animate(widget):
+ stop(widget, "shown")
+ finish()
+ return
+ fade = _fade_of(widget)
+ start_height = widget.height() if (moving or not widget.isHidden()) else 0
+ start_opacity = fade.opacity() if (fade is not None and moving) else (0.0 if shown else 1.0)
+ end_height = _natural_height(widget) if shown else 0
+ if layout is not None and layout.isEnabled():
+ # The contents keep their full-size places while the height changes, so the row is
+ # uncovered or covered like a blind rather than squeezed; the layout comes back at the end.
+ full = end_height if shown else widget.height()
+ layout.setGeometry(QRect(0, 0, _width_for(widget), full))
+ layout.setEnabled(False)
+ widget.setMaximumHeight(start_height)
+ widget.setVisible(True)
+
+ def apply(t):
+ widget.setMaximumHeight(round(start_height + (end_height - start_height) * t))
+ if fade is not None:
+ fade.setOpacity(start_opacity + ((1.0 if shown else 0.0) - start_opacity) * t)
+
+ animate(widget, "shown", 0.0, 1.0, apply, finish)
+
+
+def snapshot(widget: QWidget):
+ """What `widget` looks like now, for `fade_from` after the change; None when no fade would
+ play, so the caller changes it straight away."""
+ # Scrolled out of its page, the fade would play where no one sees it, and the grab costs a paint.
+ if not widget.isVisible() or widget.width() <= 0 or widget.visibleRegion().isEmpty() or not should_animate(widget):
+ return None
+ return widget.grab(), widget.geometry()
+
+
+def fade_from(widget: QWidget, shot, fade_in: bool = False) -> None:
+ """Lays `shot`, taken by `snapshot` before a change, over `widget` and fades it out, so the old
+ picture dissolves into the new. `fade_in` also brings the widget itself up from nothing, for a
+ widget with no background of its own, where the old would otherwise sit on top of the new."""
+ old = getattr(widget, "_motion_ghost", None)
+ if old is not None:
+ stop(old, "ghost")
+ old.deleteLater()
+ widget._motion_ghost = None
+ # Stopped, the old fade never ran its finish: a widget it was bringing up would stay
+ # part faded until some later change.
+ _drop_fade(widget)
+ if shot is None or widget.parentWidget() is None:
+ return
+ pixmap, geometry = shot
+ ghost = QLabel(widget.parentWidget())
+ ghost.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ ghost.setStyleSheet("background: transparent;")
+ ghost.setPixmap(pixmap)
+ ghost.setGeometry(geometry)
+ ghost.show()
+ ghost.raise_()
+ widget._motion_ghost = ghost
+ ghost_fade = _Fade(ghost)
+ ghost.setGraphicsEffect(ghost_fade)
+ new_fade = _fade_of(widget) if fade_in else None
+
+ def apply(t):
+ ghost_fade.setOpacity(1.0 - t)
+ if new_fade is not None:
+ new_fade.setOpacity(t)
+
+ def finish():
+ if getattr(widget, "_motion_ghost", None) is ghost:
+ widget._motion_ghost = None
+ ghost.deleteLater()
+ if new_fade is not None:
+ _drop_fade(widget)
+
+ animate(ghost, "ghost", 0.0, 1.0, apply, finish, force=True)
+
+
+def lerp_rect(a: QRectF, b: QRectF, t: float) -> QRectF:
+ return QRectF(a.x() + (b.x() - a.x()) * t, a.y() + (b.y() - a.y()) * t,
+ a.width() + (b.width() - a.width()) * t, a.height() + (b.height() - a.height()) * t)
+
+
+class Ring(QWidget):
+ """The chosen choice's ring, drawn over a group of choices and slid from one to the next, across
+ the group's rows. `locate(widget)` gives the rect to ring in that widget's own coordinates. The
+ ring is worked out at paint time, so it follows the layout as the window resizes."""
+
+ def __init__(self, host: QWidget, locate, colour, radius: float, width: float = 2.0) -> None:
+ super().__init__(host)
+ self._host = host
+ self._locate = locate
+ self._colour = colour
+ self._radius = radius
+ self._width = width
+ self._target = None
+ self._from = None
+ self._t = 1.0
+ self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground)
+ self.setStyleSheet("background: transparent;")
+ self.setGeometry(host.rect())
+ host.installEventFilter(self)
+ self.show()
+
+ def eventFilter(self, watched, event) -> bool:
+ # A ring being collected can still be asked, its host outliving it, with its fields gone.
+ if watched is getattr(self, "_host", None) and event.type() in (QEvent.Type.Resize, QEvent.Type.LayoutRequest):
+ self.setGeometry(self._host.rect())
+ self.raise_()
+ self.update()
+ return False
+
+ def _rect_of(self, widget):
+ if widget is None or not widget.isVisibleTo(self._host):
+ return None
+ rect = self._locate(widget)
+ return QRectF(rect).translated(widget.mapTo(self._host, widget.rect().topLeft()).toPointF())
+
+ def current(self):
+ """The rect the ring is drawn at now, in the host's coordinates."""
+ end = self._rect_of(self._target)
+ if end is None:
+ return None
+ if self._from is None or self._t >= 1.0:
+ return end
+ return lerp_rect(self._from, end, self._t)
+
+ def follow(self, target: QWidget | None) -> None:
+ if target is self._target:
+ return
+ start = self.current()
+ self._target = target
+ self.raise_()
+ if start is None or target is None:
+ stop(self, "ring")
+ self._from, self._t = None, 1.0
+ self.update()
+ return
+ self._from = start
+
+ def apply(t):
+ self._t = t
+ self.update()
+
+ animate(self, "ring", 0.0, 1.0, apply)
+
+ def paintEvent(self, _event) -> None:
+ rect = self.current()
+ if rect is None:
+ return
+ painter = QPainter(self)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ colour = self._colour() if callable(self._colour) else self._colour
+ painter.setPen(QPen(QColor(colour), self._width))
+ painter.setBrush(Qt.BrushStyle.NoBrush)
+ painter.drawRoundedRect(rect, self._radius, self._radius)
diff --git a/win_app/pages_win.py b/win_app/pages_win.py
index a76b29e..6e9398c 100644
--- a/win_app/pages_win.py
+++ b/win_app/pages_win.py
@@ -5,40 +5,359 @@ Pure, so the rules are tested without Qt.
from __future__ import annotations
-# (key, name, what the page is for), in sidebar order; Ctrl+1 is the first.
+import re
+
+import effects
+
+# (key, name, what the page is for), in sidebar order, which is setup order; Ctrl+1 is the first.
PAGES = (
("overview", "Overview",
- "Where input is right now, and the controls you reach for every day."),
+ "Where input is right now, and the controls you reach for every day. Pair with your Mac here "
+ "first."),
("crossing", "Crossing",
- "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."),
+ "Choose how the pointer or a key moves input to your Mac, and how hard the edge pushes back "
+ "first."),
("keyboard", "Keyboard",
- "The key that sends input to your Mac, the keys and buttons that stay on this PC, and how its "
- "Ctrl and Windows keys arrive on the Mac."),
- ("pairing", "Pairing",
- "Connect a Mac to this PC by typing the code it shows here. Once per Mac."),
+ "How this PC's Ctrl and Windows keys arrive on your Mac, the keys and buttons that stay here, "
+ "and how fast your Mac's pointer moves here."),
+ ("design", "Design",
+ "How crossing looks on this PC: the light as you push toward your Mac, and where the pointer "
+ "lands."),
("connection", "Connection",
- "This PC's address, listen port and shared token, and the Mac address pairing learned."),
- ("firewall", "Firewall",
- "Windows Firewall must let Beamer through before a Mac can connect."),
+ "Whether Windows Firewall lets your Mac in, this PC's address, port and shared token, and your "
+ "Mac's IP address, which pairing learns."),
)
KEYS = tuple(page[0] for page in PAGES)
+# Under the purpose on the pages whose settings are this PC's alone, so nobody looks for the Mac's
+# on the PC: each app sets only its own machine.
+SCOPE = {
+ "crossing": "For this PC only; your Mac keeps its own. Only which side your Mac is on is shared. This PC's "
+ "resistance is also what its pointer meets at your Mac's edge on the way back.",
+ "design": "For this PC's screen only; your Mac keeps its own.",
+ "keyboard": "For this PC's keyboard only; your Mac keeps its own.",
+}
+# The window's footer; the first sentence goes on Connection, whose changes wait for its button.
+FOOTER_APPLY = "Changes apply as you make them."
+FOOTER_TRAY = "Closing this window keeps Beamer running in the tray."
+
+
+def footer(page: str) -> str:
+ return FOOTER_TRAY if page == "connection" else f"{FOOTER_APPLY} {FOOTER_TRAY}"
def dots(config_error: bool, firewall_tone: str | None) -> dict:
"""Page key to the tone of its sidebar dot, for the pages that need one.
- `firewall_tone` is the note tone the Firewall page is already showing -- "note" is its
- healthy end-state (the button just offers a manual re-check), so only "note-amber" and
- "note-fault" earn a dot; a plain boolean would also mark the healthy state."""
- marks = {}
- if config_error:
- marks["connection"] = "fault"
+ `firewall_tone` is the note tone Connection's firewall module is already showing -- "note" is
+ its healthy end-state (the button just offers a manual re-check), so only "note-amber" and
+ "note-fault" earn a dot; a plain boolean would also mark the healthy state. Both problems sit
+ on Connection, and a fault outranks amber."""
+ if config_error or firewall_tone == "note-fault":
+ return {"connection": "fault"}
if firewall_tone == "note-amber":
- marks["firewall"] = "amber"
- elif firewall_tone == "note-fault":
- marks["firewall"] = "fault"
- return marks
+ return {"connection": "amber"}
+ return {}
+
+
+# The Design page's styles and colours: Classic first, then each crossing effects direction in
+# effects.DIRECTIONS order. Classic's Glow and Beam light this PC's edge or corner as the pointer
+# leaves; the effects draw the departure and the arrival, at an edge, a corner or the Mac's notch.
+CLASSIC = "Classic"
+TODAY_STYLES = (
+ ("glow", "Glow", "A band of light that deepens the harder you push."),
+ ("beam", "Beam", "A thin line with a comet of light running along it."),
+)
+TODAY_COLOURS = (("signal", "Signal"), ("colourful", "Colourful"), ("ocean", "Ocean"), ("sunset", "Sunset"), ("mono", "Mono"))
+
+
+def effects_load_error():
+ """None when every crossing effect loads, else the exception: the Design page then offers only
+ Classic's styles and colours rather than failing to build, and Beamer still starts."""
+ try:
+ effects._load()
+ except Exception as exc:
+ return exc
+ return None
+
+
+def style_groups() -> tuple:
+ """(group title, ((style id, name, detail), ...)) in the page's order. An effect's detail is
+ its intensity: quiet, medium or showpiece."""
+ # Glow and Beam's detail is their kind, as an effect's is its intensity; what they do is said
+ # under the preview.
+ groups = [(CLASSIC, tuple((value, name, CLASSIC) for value, name, _blurb in TODAY_STYLES))]
+ if effects_load_error() is not None:
+ return tuple(groups)
+ for _module, title, effect_ids, _packs in effects.DIRECTIONS:
+ found = [effects.effect(effect_id) for effect_id in effect_ids]
+ groups.append((title, tuple((fx.id, fx.name, fx.intensity.capitalize()) for fx in found)))
+ return tuple(groups)
+
+
+def colour_groups() -> tuple:
+ """(group title, ((colour id, name), ...)) in the page's order, grouped as the styles are."""
+ groups = [(CLASSIC, TODAY_COLOURS)]
+ if effects_load_error() is not None:
+ return tuple(groups)
+ for _module, title, _effects, pack_ids in effects.DIRECTIONS:
+ groups.append((title, tuple((pack_id, effects.pack(pack_id)[0]) for pack_id in pack_ids)))
+ return tuple(groups)
+
+
+def is_effect(style: str) -> bool:
+ """Whether `style` is one of the crossing effects, which draw the arrival as well as the push."""
+ return style in effects.EFFECT_IDS
+
+PLACES = {"edge": "the edge", "corner": "a corner"}
+
+
+def preview_place(methods) -> str:
+ """Where the Design page's preview opens: the first of this PC's ways in it can show, Part of
+ the edge shown as the edge, or the edge when the only way in is the shortcut."""
+ chosen = set(methods)
+ if chosen & {"edge", "part"}:
+ return "edge"
+ return "corner" if "corner" in chosen else "edge"
+
+
+def place_note(style: str, place: str, methods) -> str:
+ """The line under Show at: why nothing would cross at `place`, or empty when it does."""
+ ways = {"edge": {"edge", "part"}, "corner": {"corner"}}[place]
+ if set(methods) & ways:
+ return ""
+ return (f"{PLACES[place].capitalize()} is not one of this PC's ways in, so this only shows how it "
+ "would look. Turn it on under Crossing.")
+
+
+
+def part_names(edge):
+ """The names of return_edge.PARTS along `edge`, as the page shows them: top to bottom on a side
+ edge, left to right along the top or bottom."""
+ if edge in ("left", "right"):
+ return {"start": "Top", "middle": "Middle", "end": "Bottom"}
+ return {"start": "Left", "middle": "Middle", "end": "Right"}
+
+
+def parts_phrase(edge, parts):
+ """The chosen thirds in a sentence: "the top and middle of the right edge"."""
+ names = part_names(edge)
+ chosen = [names[part].lower() for part in ("start", "middle", "end") if part in parts] or ["middle"]
+ joined = chosen[0] if len(chosen) == 1 else ", ".join(chosen[:-1]) + " and " + chosen[-1]
+ return f"the {joined} of the {edge} edge"
+
+
+# The Crossing page's ways in, in the page's order. Edge and Part of the edge are two readings of
+# one edge, so choosing either drops the other.
+WAYS = ("shortcut", "edge", "part", "corner")
+EXCLUSIVE_WAYS = ("edge", "part")
+
+
+def toggle_way(methods, way, on) -> list:
+ """`methods` with `way` turned on or off, in WAYS order."""
+ chosen = {method for method in methods if method != way}
+ if on:
+ if way in EXCLUSIVE_WAYS:
+ chosen -= set(EXCLUSIVE_WAYS)
+ chosen.add(way)
+ return [method for method in WAYS if method in chosen]
+
+
+def toggle_part(parts, part, on) -> list:
+ """`parts` with `part` turned on or off, in return_edge.PARTS order. Turning off the last one
+ is refused: Part of the edge with no part would be a wall."""
+ chosen = set(parts) | {part} if on else set(parts) - {part}
+ if not chosen:
+ chosen = set(parts)
+ return [candidate for candidate in ("start", "middle", "end") if candidate in chosen]
+
+
+NOT_LEARNED_EDGE = "Not learned yet: your Mac tells this PC when it first connects, or choose a side."
+
+
+def crossing_state_sentence(paired, mac_heard, sending, connected, armed, paused, full_screen_app) -> str:
+ """The Crossing page's line under Pause: why nothing can cross, first match wins, and only then
+ whether crossing is on, held or paused."""
+ if not paired:
+ return "Not paired yet, so no edge or shortcut moves input until you pair with your Mac above."
+ if not mac_heard:
+ return "Waiting to hear from your Mac. This PC cannot push into it until your Mac has connected once."
+ if not sending:
+ return "This PC drives your Mac is off, so edges and the shortcut do nothing."
+ if not connected:
+ return (
+ "Not connected to your Mac, so edges and the shortcut do nothing yet. "
+ "Check that Windows drives this Mac is on, on your Mac."
+ )
+ if not armed:
+ return "Only the shortcut is switched on; there is nothing to pause."
+ if paused:
+ return "Paused. The edge, part of the edge and corner do nothing until you resume; the shortcut still works."
+ if full_screen_app is not None:
+ return (
+ f"Off while {full_screen_app} is full screen, so the pointer stays put at "
+ "the edges; the shortcut still works."
+ )
+ return "On. Pause it to lean on an edge without switching."
+
+
+def crossing_state_blocked(paired, mac_heard, sending, connected) -> bool:
+ """Whether crossing_state_sentence is giving a reason nothing can cross."""
+ return not (paired and mac_heard and sending and connected)
+
+
+def outward_link_line(connected) -> str:
+ """The Overview's line for this PC's own link to the Mac, which its edges need and the receiver's
+ status above it does not say."""
+ if connected:
+ return "This PC to your Mac: Linked"
+ return "This PC to your Mac: not connected, so pushing an edge does nothing"
+
+
+def crossing_rows(methods) -> frozenset:
+ """Which of the Crossing page's rows the chosen ways use; the rest are hidden."""
+ methods = set(methods)
+ rows = set()
+ # Where the Mac sits, which every way in uses: a crossing lands by it, and this PC's edge facing
+ # the Mac leads there whatever the Mac's own ways in are.
+ rows.add("edge")
+ if "part" in methods:
+ rows.add("parts")
+ if "corner" in methods:
+ rows.add("corner")
+ if methods & {"edge", "part", "corner"}:
+ rows |= {"dragging", "resistance"}
+ if "shortcut" in methods:
+ rows.add("shortcut")
+ return frozenset(rows)
+
+
+# What a switch into this PC plays, as the Design page's Shortcut and menu tiles: the first group
+# stands in for Classic's Glow and Beam, which have no arrival of their own. Named as the Mac's is.
+SIMPLE = "Simple"
+SWITCH_SIMPLE = (
+ ("match", "Same as crossing", "Plays the crossing style"),
+ ("locator", "Ring", "Closes onto the pointer"),
+)
+
+
+def switch_groups() -> tuple:
+ """style_groups() for a switch: SWITCH_SIMPLE in place of Classic, then the same directions."""
+ return ((SIMPLE, SWITCH_SIMPLE),) + style_groups()[1:]
+
+
+# The Crossing page's "Where your Mac is": the value is the edge of this PC that leads to the Mac.
+SIDE_CHOICES = (("left", "Left"), ("right", "Right"), ("top", "Above"), ("bottom", "Below"))
+# The ways in, as their rows read: the pointer's first, then the shortcut.
+WAY_ROWS = (
+ ("edge", "Edge", "One whole side"),
+ ("part", "Part of the edge", "Only the thirds you pick"),
+ ("corner", "Corner", "Push diagonally into a corner"),
+ ("shortcut", "Shortcut", ""),
+)
+CORNER_NAMES = {"top_left": "top-left", "top_right": "top-right", "bottom_left": "bottom-left", "bottom_right": "bottom-right"}
+
+
+def trigger_phrase(key_name: str, style: str) -> str:
+ """The shortcut as the arrangement diagram's key cap line reads it: "Right Ctrl, twice"."""
+ return f"{key_name}, {'held' if style == 'hold' else 'twice'}"
+
+
+def ways_summary(methods, edge, parts, corner, key_name, style) -> str:
+ """The Ways in module's first line: every way input leaves for the Mac, in one sentence."""
+ if not edge:
+ return "Nothing moves input to your Mac until it has connected once and told this PC which side it is on."
+ methods = set(methods)
+ ways = []
+ if "edge" in methods:
+ ways.append(f"push through the whole {edge} edge")
+ if "part" in methods:
+ ways.append(f"push through {parts_phrase(edge, parts)}")
+ if "corner" in methods:
+ ways.append(f"push diagonally into the {CORNER_NAMES.get(corner, corner)} corner")
+ if "shortcut" in methods:
+ ways.append(f"hold {key_name}" if style == "hold" else f"press {key_name} twice")
+ if not ways:
+ return "Nothing moves input to your Mac: choose at least one way below."
+ joined = ways[0] if len(ways) == 1 else ", ".join(ways[:-1]) + " or " + ways[-1]
+ return f"Input moves to your Mac when you {joined}."
+
+
+# The arrangement diagram. Each side of this PC has an angle, and the Mac's screen travels round
+# this PC's between them: through a corner position, never across it.
+SIDE_ANGLE = {"right": 0.0, "top": 90.0, "left": 180.0, "bottom": 270.0}
+
+
+def turn_to(angle: float, side: str) -> float:
+ """The angle to animate to from `angle`, which may be part-way through a turn, to reach `side`
+ the short way round. Half a turn goes over the top from left or right, and round by the left
+ from above or below."""
+ delta = (SIDE_ANGLE[side] - angle) % 360.0
+ if delta > 180.0:
+ delta -= 360.0
+ if delta == 180.0:
+ current = angle % 360.0
+ via = 90.0 if current in (0.0, 180.0) else 180.0
+ delta = 180.0 if (current + 90.0) % 360.0 == via else -180.0
+ return angle + delta
+
+
+def square_point(angle: float) -> tuple:
+ """Where a ray at `angle` degrees meets the unit square's edge, y up: (1, 0) at 0, (1, 1) at 45."""
+ import math
+
+ radians = math.radians(angle)
+ x, y = math.cos(radians), math.sin(radians)
+ scale = max(abs(x), abs(y))
+ return round(x / scale, 9), round(y / scale, 9)
+
+
+def arrangement_rects(width: float, top: float, angle: float, screen: tuple, gap: float) -> tuple:
+ """(this PC's screen, your Mac's screen, the pair's height) as (x, y, w, h) rects, the pair
+ centred across `width` and starting at `top`, the Mac's screen at `angle` from this PC's."""
+ w, h = screen
+ sx, sy = square_point(angle)
+ dx, dy = sx * (w + gap), -sy * (h + gap)
+ pair_h = h + abs(dy)
+ cx, cy = width / 2.0, top + pair_h / 2.0
+ pc = (cx - dx / 2.0 - w / 2.0, cy - dy / 2.0 - h / 2.0, w, h)
+ mac = (cx + dx / 2.0 - w / 2.0, cy + dy / 2.0 - h / 2.0, w, h)
+ return pc, mac, pair_h
+
+
+def side_segment(rect: tuple, side: str, start: float = 0.0, end: float = 1.0, inset: float = 0.0) -> tuple:
+ """The stretch of `rect`'s `side` from `start` to `end` (fractions, top to bottom or left to
+ right, as return_edge's parts run), as a line (x1, y1, x2, y2) `inset` inside the edge."""
+ x, y, w, h = rect
+ if side in ("left", "right"):
+ line_x = x + inset if side == "left" else x + w - inset
+ return line_x, y + h * start, line_x, y + h * end
+ line_y = y + inset if side == "top" else y + h - inset
+ return x + w * start, line_y, x + w * end, line_y
+
+
+PART_SPANS = {"start": (0.0, 1.0 / 3.0), "middle": (1.0 / 3.0, 2.0 / 3.0), "end": (2.0 / 3.0, 1.0)}
+
+
+def corner_box(rect: tuple, corner: str, size: float) -> tuple:
+ """The `size` square in `rect`'s `corner` ("top_left" and so on)."""
+ x, y, w, h = rect
+ vertical, horizontal = corner.split("_")
+ return (x if horizontal == "left" else x + w - size, y if vertical == "top" else y + h - size, size, size)
+
+
+RESISTANCE_MAX = 500
+
+
+def push_depth(resistance: float, track: float) -> float:
+ """How far the push strip's fill reaches from the edge: 0 to RESISTANCE_MAX px across `track`."""
+ return max(0.0, min(1.0, resistance / RESISTANCE_MAX)) * track
+
+
+# An IPv4 address or a hardware address, anywhere in a line of text.
+_ADDRESS = re.compile(r"\b(?:\d{1,3}(?:\.\d{1,3}){3}|[0-9A-Fa-f]{2}(?:[:-][0-9A-Fa-f]{2}){5})\b")
+HIDDEN = "•••"
+
+
+def redact(text: str, hide: bool) -> str:
+ """`text` with every address in it replaced when `hide` is on."""
+ return _ADDRESS.sub(HIDDEN, text) if hide and text else text
diff --git a/win_app/pairing.py b/win_app/pairing.py
index dfd7925..f733d84 100644
--- a/win_app/pairing.py
+++ b/win_app/pairing.py
@@ -12,6 +12,9 @@ Both proofs are HMACs keyed from the six-digit code (scrypt, salted with the pai
the transcript, so each side shows the other that it knows the code. The shared token is
HKDF over the X25519 secret: an eavesdropper who records every datagram cannot derive it.
+Where no broadcast reaches the Mac (another subnet, a VPN), the Mac asks a typed address for its
+beacon with a `find` datagram, and pairing continues exactly as above.
+
What this protects against, and what it does not:
- The token never crosses the wire, and neither does the code. The beacon carries nothing a
@@ -65,6 +68,9 @@ PAIR_ATTEMPTS = 3
MSG_BEACON = "beacon"
MSG_PAIR_REQUEST = "pair_request"
MSG_PAIR_REPLY = "pair_reply"
+# The Mac asking one address for its beacon, for a PC that no broadcast reaches (another subnet,
+# a VPN). The answer is the beacon every listener already hears, so it discloses nothing new.
+MSG_FIND = "find"
ERROR_NOT_PAIRING = "not_pairing"
ERROR_REFUSED = "refused"
@@ -296,11 +302,11 @@ def broadcast_targets(port: int) -> list:
broadcast as a backstop.
⚠ 255.255.255.255 alone is not enough and this is not theoretical: it leaves by the default
- route only, so a PC with a second interface — a Hyper-V vEthernet switch is the common case,
- and the owner's rig has one — announces on whichever the routing table prefers and may never
- reach the LAN the Mac is on. Measured 10-09-2026: the PC beaconed steadily while no beacon
- reached the Mac at all, and the Mac then paired against a stale id from an older beacon that
- had got through, which is what produced `not_pairing`.
+ route only, so a PC with a second interface — a Hyper-V vEthernet switch is the common case —
+ announces on whichever the routing table prefers and may never reach the LAN the Mac is on.
+ Seen in practice: the PC beaconed steadily while no beacon reached the Mac at all, and the Mac
+ then paired against a stale id from an older beacon that had got through, which is what
+ produced `not_pairing`.
The per-interface directed broadcast assumes a /24, because the stdlib exposes no netmask.
A wrong guess costs one datagram that goes nowhere; the limited broadcast is still sent, so
@@ -390,6 +396,11 @@ class Announcer:
self.host.active
return self.host.outcome
+ def _beacon(self) -> bytes:
+ with self._lock:
+ pair_id = self.host.pair_id if self.host.active else None
+ return encode(beacon_msg(self.name, self.port_getter(), pair_id))
+
def _run(self) -> None:
try:
sock = _udp_socket(self.bind_port)
@@ -399,14 +410,13 @@ class Announcer:
return
self.error = None
next_beacon = 0.0
+ answered = {}
try:
while not self._stop.is_set():
now = time.monotonic()
if now >= next_beacon:
next_beacon = now + BEACON_INTERVAL_SECONDS
- with self._lock:
- pair_id = self.host.pair_id if self.host.active else None
- beacon = encode(beacon_msg(self.name, self.port_getter(), pair_id))
+ beacon = self._beacon()
delivered = 0
# Only a caller asking for the limited broadcast wants the per-interface
# fan-out; a named address is honoured exactly, which keeps the tests off
@@ -441,6 +451,17 @@ class Announcer:
message = decode(data)
if message is None:
continue
+ if message.get("type") == MSG_FIND:
+ # At most one answer per address per interval, so the port is no amplifier.
+ if now - answered.get(address[0], -BEACON_INTERVAL_SECONDS) >= BEACON_INTERVAL_SECONDS / 4:
+ if len(answered) > 256:
+ answered.clear()
+ answered[address[0]] = now
+ try:
+ sock.sendto(self._beacon(), address)
+ except OSError as exc:
+ self.logger.warning("beacon to %s not sent: %s", address[0], exc)
+ continue
with self._lock:
reply = self.host.handle(message)
paired, self.host.paired = self.host.paired, None
@@ -476,8 +497,36 @@ class Discovery:
self._stop = threading.Event()
self._thread = None
self._sock = None
+ self._finding = None
+ self._find_serial = 0
+ self._next_find = 0.0
self.error = None
+ def find(self, host: str, port: int = PAIRING_PORT) -> None:
+ """Ask `host` for its beacon, for a PC no broadcast reaches, and keep asking while
+ discovery runs so it stays listed. Returns at once; the PC appears in pcs() when it
+ answers. An empty host stops asking."""
+ host = (host or "").strip()
+ with self._lock:
+ self._find_serial += 1
+ serial = self._find_serial
+ self._finding = None
+ self._next_find = 0.0
+ if host:
+ # A name can take seconds to resolve, and this loop also carries the pairing replies.
+ threading.Thread(target=self._resolve, args=(host, int(port), serial),
+ name="Beamer-find", daemon=True).start()
+
+ def _resolve(self, host: str, port: int, serial: int) -> None:
+ try:
+ address = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_DGRAM)[0][4][0]
+ except (OSError, IndexError) as exc:
+ self.logger.warning("could not resolve %s: %s", host, exc)
+ return
+ with self._lock:
+ if serial == self._find_serial:
+ self._finding = (address, port)
+
def start(self) -> None:
if self._thread is not None:
return
@@ -545,6 +594,7 @@ class Discovery:
self._sock = sock
try:
while not self._stop.is_set():
+ self._send_find(sock)
try:
data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)
except socket.timeout:
@@ -572,6 +622,17 @@ class Discovery:
self._sock = None
sock.close()
+ def _send_find(self, sock) -> None:
+ with self._lock:
+ target = self._finding
+ if target is None or self.clock() < self._next_find:
+ return
+ self._next_find = self.clock() + BEACON_INTERVAL_SECONDS
+ try:
+ sock.sendto(encode({"type": MSG_FIND}), target)
+ except OSError as exc:
+ self.logger.warning("could not ask %s for its beacon: %s", target[0], exc)
+
def _note_beacon(self, message: dict, address) -> None:
name = message.get("name")
port = message.get("port")
diff --git a/win_app/protocol.py b/win_app/protocol.py
index afe05b2..dc86bad 100644
--- a/win_app/protocol.py
+++ b/win_app/protocol.py
@@ -46,7 +46,7 @@ PROTOCOL_VERSION = 4
# handed out below 49152, so the port a user pairs on stays theirs.
DEFAULT_PORT = 24820
PAIRING_PORT = 24821
-# What DEFAULT_PORT was until 20-09-2026. A config still carrying it was never chosen by
+# What DEFAULT_PORT used to be. A config still carrying it was never chosen by
# anyone, so it is migrated rather than honoured; a port a user picked is left alone.
LEGACY_DEFAULT_PORT = 51820
# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing
@@ -58,7 +58,7 @@ KEY_INFO = b"beamy-input-channel"
CLIPBOARD_MAX_BYTES = 256 * 1024
# The clipboard goes out ahead of the focus message on every switch, sealed as one frame and
# buffered whole on both sides, so the image cap is a bound on how late the switch lands, not on
-# bandwidth. A full-screen grab of a 3456x2234 Retina display measured 2.9MB as PNG (09-09-2026);
+# bandwidth. A full-screen grab of a 3456x2234 Retina display measured 2.9MB as PNG;
# 8MB covers that with room for a busier desktop, and as a base64 frame (~10.7MB) it is about
# 0.1s on wired gigabit and half a second on decent Wi-Fi. Beyond it the text still goes.
CLIPBOARD_IMAGE_MAX_BYTES = 8 * 1024 * 1024
@@ -66,7 +66,7 @@ CLIPBOARD_IMAGE_PNG = "png"
# The largest sealed frame either end accepts. It must hold the biggest clipboard message -- an
# 8MB image is ~10.7MB as base64, beside up to 256KB of text -- because the clipboard also travels
# back on the reply stream. A 1MB cap there dropped the link on every return with a screenshot on
-# the clipboard (18-09-2026).
+# the clipboard.
MAX_FRAME_BYTES = 16 * 1024 * 1024
# The first frame each way is a hello or a welcome of a few dozen bytes. Anything larger before
# authentication is not a Beamer, so it is refused before it is read.
diff --git a/win_app/receiver.py b/win_app/receiver.py
index a64691c..cc7b14a 100644
--- a/win_app/receiver.py
+++ b/win_app/receiver.py
@@ -7,7 +7,7 @@ import sys
import threading
import time
from enum import Enum
-from typing import Callable, Optional
+from typing import Callable, Optional, Tuple
import return_edge as crossing
import protocol
@@ -72,7 +72,37 @@ class ProcessedSequence:
return self._latest
-def handle_message(message: dict, injector=None) -> bool:
+class InputScale:
+ """This machine's own speed for the pointer and scroll arriving from the peer. The peer sends
+ what its own acceleration made of the hand's movement, and this machine may accelerate it
+ again, so how fast it feels here is a setting here. Fractions carry over between messages, so
+ a slow movement at a low speed still moves. `reverse` turns the peer's scroll round."""
+
+ MIN, MAX = 0.25, 4.0
+
+ def __init__(self, pointer: float = 1.0, scroll: float = 1.0, reverse: bool = False) -> None:
+ self.pointer = min(self.MAX, max(self.MIN, float(pointer)))
+ self.scroll = min(self.MAX, max(self.MIN, float(scroll)))
+ self.reverse = bool(reverse)
+ self._carry = [0.0, 0.0]
+
+ def move(self, dx: int, dy: int) -> Tuple[int, int]:
+ if self.pointer == 1.0:
+ return dx, dy
+ x = dx * self.pointer + self._carry[0]
+ y = dy * self.pointer + self._carry[1]
+ whole_x, whole_y = int(x), int(y)
+ self._carry = [x - whole_x, y - whole_y]
+ return whole_x, whole_y
+
+ def wheel(self, dy, dx):
+ if self.scroll == 1.0 and not self.reverse:
+ return dy, dx
+ sign = -1.0 if self.reverse else 1.0
+ return dy * self.scroll * sign, dx * self.scroll * sign
+
+
+def handle_message(message: dict, injector=None, scale: Optional[InputScale] = None) -> bool:
"""Inject one input event. `injector` defaults to the real input_injector
module, imported lazily here (not at module load) so receiver.py stays
importable — and its non-injection logic testable — on a machine without
@@ -92,13 +122,21 @@ def handle_message(message: dict, injector=None) -> bool:
elif message_type == protocol.MSG_KEYUP:
injector.inject_key(data["key"], down=False)
elif message_type == protocol.MSG_MOUSEMOVE:
- injector.inject_mouse_move(int(data["dx"]), int(data["dy"]))
+ dx, dy = int(data["dx"]), int(data["dy"])
+ if scale is not None and (dx or dy):
+ dx, dy = scale.move(dx, dy)
+ if not (dx or dy):
+ return True
+ injector.inject_mouse_move(dx, dy)
elif message_type == protocol.MSG_MOUSEDOWN:
injector.inject_mouse_button(data["button"], down=True)
elif message_type == protocol.MSG_MOUSEUP:
injector.inject_mouse_button(data["button"], down=False)
elif message_type == protocol.MSG_SCROLL:
- injector.inject_scroll(data["dy"], data.get("dx", 0), data.get("mode", "line"))
+ dy, dx = data["dy"], data.get("dx", 0)
+ if scale is not None:
+ dy, dx = scale.wheel(dy, dx)
+ injector.inject_scroll(dy, dx, data.get("mode", "line"))
elif message_type == protocol.MSG_GESTURE:
injector.inject_gesture(data["name"])
else:
@@ -114,11 +152,12 @@ class ReceiverServer:
clipboard=None,
unlock=None,
desktop=None,
- pressure_callback: Optional[Callable[[str, float, bool], None]] = None,
+ pressure_callback: Optional[Callable[[str, float, bool, Optional[str]], None]] = None,
injector=None,
focus_callback: Optional[Callable[[str], None]] = None,
peer_callback: Optional[Callable[[str, Optional[str], Optional[int]], None]] = None,
arrangement_callback: Optional[Callable[[str, int], None]] = None,
+ arrival_callback: Optional[Callable[[str, int, int], None]] = None,
self_name: str = "PC",
peer_name: str = "Mac",
self_target: str = "windows",
@@ -136,6 +175,18 @@ class ReceiverServer:
# taken it back, because the peer fails open on its side and the
# message saying so never reaches a dead socket.
self._injector = injector
+ # This machine's speed for the peer's pointer and scroll; the owner replaces it when its
+ # settings change. Read once per message on the session thread.
+ self.input_scale: Optional[InputScale] = None
+ # Whether this machine's edges are held (Pause crossing, a full-screen app). A hold is
+ # about this screen, so it stops the peer's pointer going home through it as well as this
+ # machine's own; the peer's shortcut still switches. Read on the session thread.
+ self.edges_held: Callable[[], bool] = lambda: False
+ # `return_model(edge, resistance)` builds the way home the peer named from this machine's
+ # own ways in: the whole edge, only its chosen thirds, its corner, or None for no way home
+ # by the pointer. The edges on a screen follow that machine's settings, whoever's pointer
+ # pushes; without an owner's answer the whole edge is armed.
+ self.return_model: Optional[Callable[[str, int], Optional[crossing.ReturnEdge]]] = None
self._focus_callback = focus_callback
self._peer_driving = False
# `peer_callback(host, return_edge, resistance_px)` fires once per
@@ -149,6 +200,13 @@ class ReceiverServer:
# change it, so this is how the change arrives at the end that did not
# make it.
self._arrangement_callback = arrangement_callback
+ # `arrival_callback(edge, x, y)` fires on the session thread each time
+ # a crossing lands the pointer here, with the edge it came in by and
+ # where it was placed, in the desktop module's coordinates, and with
+ # edge None and wherever the pointer is when input comes here by a
+ # switch instead. It is how the owner plays its arrival effect; the
+ # owner marshals it.
+ self._arrival_callback = arrival_callback
self._self_name = self_name
self._peer_name = peer_name
self._self_target = self_target
@@ -156,13 +214,20 @@ class ReceiverServer:
self._status_callback = status_callback
# `desktop` defaults to the real desktop_win module, imported lazily for
# the same reason as `clipboard` below. `pressure_callback(edge,
- # pressure, crossed)` is called on the session thread as the pointer
- # is pushed against the return edge; the GUI marshals it to the glow.
+ # pressure, crossed, part)` is called on the session thread as the
+ # pointer is pushed against the return edge, `part` the third or corner
+ # pushed when the way home is only those; the GUI marshals it to the glow.
self._desktop = desktop
self._pressure_callback = pressure_callback
# The way home. Armed by every focus{target:"windows"} the Mac sends,
# which carries the return edge and resistance, and None until then.
self._return_edge: Optional[crossing.ReturnEdge] = None
+ # The edge and resistance that focus named, kept so a settings change can rebuild the way
+ # home (`rearm_return`) without waiting for the next focus.
+ self._named_return: Optional[tuple] = None
+ # Held while the session thread feeds the way home and while a settings change rebuilds it,
+ # so a rebuild never revives a way home that was just pushed through or handed back.
+ self._return_lock = threading.RLock()
# `unlock` defaults to the real unlock_win module, imported lazily for
# the same reason as `clipboard` below.
self._unlock = unlock
@@ -299,8 +364,8 @@ class ReceiverServer:
# TIME_WAIT. On Windows the same option means something else: a
# second bind on a port another listener holds succeeds, and the
# two split the Mac's connections between them, so the held-port
- # wait below never fired for a zombie Beamer (rig, 22-09-2026).
- # Windows does not need it for TIME_WAIT, so it does without.
+ # wait below never fired for a zombie Beamer. Windows does not
+ # need it for TIME_WAIT, so it does without.
if sys.platform != "win32":
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
@@ -399,6 +464,7 @@ class ReceiverServer:
if handshake is None:
return
session, version, hello = handshake
+ self._clipboard_module().forget_sync()
if version != protocol.PROTOCOL_VERSION:
LOGGER.warning(
@@ -502,7 +568,7 @@ class ReceiverServer:
sequence.record(message)
continue
try:
- processed = handle_message(message, self._injector)
+ processed = handle_message(message, self._injector, self.input_scale)
except Exception:
LOGGER.exception("Input event from %s could not be injected", peer)
now = time.monotonic()
@@ -648,15 +714,25 @@ class ReceiverServer:
a return edge is armed; True means the move was consumed — the pointer
was held at the edge, or it broke through and the Mac has been asked
to take input back — and must not be injected."""
- model = self._return_edge
- if model is None or not model.armed:
- return False
data = message.get("data")
if not isinstance(data, dict):
return False
try:
- desktop = self._desktop_module()
- outcome = model.feed(desktop.monitors(), desktop.cursor_position(), float(data["dx"]), float(data["dy"]))
+ with self._return_lock:
+ model = self._return_edge
+ if model is None or not model.armed or self.edges_held():
+ return False
+ desktop = self._desktop_module()
+ monitors, pointer = desktop.monitors(), desktop.cursor_position()
+ outcome = model.feed(monitors, pointer, float(data["dx"]), float(data["dy"]))
+ if outcome.action == crossing.CROSS:
+ self._named_return = None
+ # Which third or corner is being pushed, so the owner lights only that.
+ part = None
+ if isinstance(model, crossing.PartEdge):
+ part = crossing.part_of(crossing.display_fraction(monitors, model.edge, pointer))
+ elif isinstance(model, crossing.CornerPush):
+ part = model.corner
if outcome.action == crossing.HOLD:
desktop.set_cursor_position(*outcome.position)
elif outcome.action == crossing.CROSS:
@@ -666,11 +742,11 @@ class ReceiverServer:
# Logged once, not at 100Hz: the return edge is dropped until the
# Mac's next switch re-arms it, and input keeps flowing normally.
LOGGER.exception("Return edge failed; crossing back is off until the next switch")
- self._return_edge = None
+ self._drop_return()
return False
if outcome.action == crossing.PASS:
return False
- self._notify_pressure(model.edge, outcome.pressure, outcome.action == crossing.CROSS)
+ self._notify_pressure(model.edge, outcome.pressure, outcome.action == crossing.CROSS, part)
return True
def send_arrangement(self, mac_edge: str, set_at: int) -> bool:
@@ -688,17 +764,18 @@ class ReceiverServer:
def send_home(self) -> bool:
"""Send the peer's input back to it from this end, as its own return
edge would. The escape that does not depend on that edge: the owner
- calls it when someone here asks to switch while the peer is driving,
- which was refused outright until the 23-09-2026 afternoon a push
- through the edge never fired and the PC's mouse stayed on the Mac.
- The send runs on its own thread, because the callers are a hook and
- an event tap that must never block on a socket."""
+ calls it when someone here asks to switch while the peer is driving.
+ Earlier versions refused this outright, and a push through the edge
+ that failed to fire could then leave the peer's pointer stuck here
+ with no way back. The send runs on its own thread, because the
+ callers are a hook and an event tap that must never block on a
+ socket."""
with self._lock:
connection = self._client
session = self._session_for(connection)
if not self._peer_driving or connection is None or session is None:
return False
- self._return_edge = None
+ self._drop_return()
LOGGER.info("Switch asked for here; sending input home to the %s", self._peer_name)
threading.Thread(
target=self._send_message,
@@ -755,7 +832,7 @@ class ReceiverServer:
crosses in and back."""
if not self._peer_driving:
return
- self._return_edge = None
+ self._drop_return()
LOGGER.info("%s while its input was here; input returned to this %s", why, self._self_name)
self._release_peer_keys()
self._notify_focus(self._peer_target)
@@ -780,39 +857,88 @@ class ReceiverServer:
except Exception:
LOGGER.exception("Could not release the keys the %s was holding", self._peer_name)
- def _notify_pressure(self, edge: str, pressure: float, crossed: bool) -> None:
+ def _notify_pressure(self, edge: str, pressure: float, crossed: bool, part: Optional[str] = None) -> None:
if self._pressure_callback is None:
return
try:
- self._pressure_callback(edge, pressure, crossed)
+ self._pressure_callback(edge, pressure, crossed, part)
except Exception:
LOGGER.exception("Pressure callback failed")
+ def rearm_return(self) -> None:
+ """Rebuilds the way home from this machine's Crossing settings as they are now, for the
+ edge and resistance the peer last named, so a change applies while the peer's input is
+ here rather than at its next crossing. Nothing happens once that input has gone home, or
+ after the way home has been pushed through."""
+ with self._return_lock:
+ named = self._named_return
+ model = self._return_edge
+ if not self._peer_driving or named is None or (model is not None and not model.armed):
+ return
+ self._arm_return({"return_edge": named[0], "resistance_px": named[1]})
+
+ def _drop_return(self) -> None:
+ """The peer's visit is over, or its way home is spent: nothing may rebuild it."""
+ with self._return_lock:
+ self._return_edge = None
+ self._named_return = None
+
def _arm_return(self, data: dict) -> None:
"""Every switch to Windows says which edge leads home and how hard to
push; an older Mac that says neither gets no return edge, so nothing
it does not expect can fire."""
+ with self._return_lock:
+ self._build_return(data)
+
+ def _build_return(self, data: dict) -> None:
edge = data.get("return_edge")
if edge not in crossing.EDGES:
self._return_edge = None
+ self._named_return = None
return
resistance = data.get("resistance_px", crossing.DEFAULT_RESISTANCE_PX)
# json.loads accepts Infinity and NaN, and int() of either raises, which
# nothing above this catches: a bad number gets the default instead.
if isinstance(resistance, bool) or not isinstance(resistance, (int, float)) or not math.isfinite(resistance):
resistance = crossing.DEFAULT_RESISTANCE_PX
- self._return_edge = crossing.ReturnEdge(edge, int(resistance))
+ self._named_return = (edge, int(resistance))
+ if self.return_model is None:
+ self._return_edge = crossing.ReturnEdge(edge, int(resistance))
+ return
+ try:
+ self._return_edge = self.return_model(edge, int(resistance))
+ except Exception:
+ LOGGER.exception("Could not build the way home through the %s edge", edge)
+ self._return_edge = crossing.ReturnEdge(edge, int(resistance))
def _place_pointer(self, data: dict) -> None:
+ """A crossing names the edge and the fraction along it, and the pointer is placed there. A
+ switch by the shortcut or a menu names neither and leaves the pointer where it was, which
+ the arrival callback gets as edge None, so the owner can show where that is."""
edge = data.get("edge")
offset = data.get("offset")
if edge not in crossing.EDGES or isinstance(offset, bool) or not isinstance(offset, (int, float)):
+ if self._arrival_callback is None:
+ return
+ try:
+ x, y = self._desktop_module().cursor_position()
+ self._arrival_callback(None, x, y)
+ except Exception:
+ LOGGER.exception("Arrival callback for a switch failed")
return
try:
desktop = self._desktop_module()
- desktop.set_cursor_position(*crossing.arrival_position(desktop.monitors(), edge, offset))
+ x, y = crossing.arrival_position(desktop.monitors(), edge, offset)
+ desktop.set_cursor_position(x, y)
except Exception:
LOGGER.exception("Could not place the pointer at the %s edge on arrival", edge)
+ return
+ if self._arrival_callback is None:
+ return
+ try:
+ self._arrival_callback(edge, x, y)
+ except Exception:
+ LOGGER.exception("Arrival callback failed")
def _begin_unlock(self, peer: str, host: str) -> None:
"""Take the console off the lock screen, if it is on one, so the input
@@ -885,7 +1011,7 @@ class ReceiverServer:
# Released before the owner hears input is home: the Mac's tap
# comes back on at that notice, and a modifier still down would
# chord with the first local keystroke.
- self._return_edge = None
+ self._drop_return()
self._release_peer_keys()
self._notify_focus(target)
if target == self._self_target:
@@ -897,7 +1023,7 @@ class ReceiverServer:
return
clipboard = self._clipboard_module()
try:
- text, image = clipboard.get_contents()
+ text, image = clipboard.changed_contents()
except Exception:
LOGGER.exception("Failed to read the local clipboard for %s", peer)
return
diff --git a/win_app/return_edge.py b/win_app/return_edge.py
index d565fdb..643b7b7 100644
--- a/win_app/return_edge.py
+++ b/win_app/return_edge.py
@@ -21,6 +21,18 @@ DECAY_SECONDS = 0.4
# 8 pixels, and the two boundaries are meant to feel like one.
CORNER_PX = 8
CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")
+# The thirds of an edge "Part of the edge" may use, top to bottom or left to right. Both machines'
+# engines read them through in_parts, so a third means the same stretch on each.
+PARTS = ("start", "middle", "end")
+
+
+def part_of(fraction: float) -> str:
+ """Which third of an edge `fraction` of the way along it falls in."""
+ return PARTS[min(2, max(0, int(fraction * 3)))]
+
+
+def in_parts(fraction: float, parts) -> bool:
+ return part_of(fraction) in parts
PASS = "pass"
HOLD = "hold"
@@ -78,6 +90,14 @@ def edge_offset(bounds: Rect, edge: str, pointer: Tuple[int, int]) -> float:
return _clamp((pointer[0] - bounds.x) / max(bounds.width, 1), 0.0, 1.0)
+def display_fraction(monitors: List[Rect], edge: str, pointer: Tuple[int, int]) -> float:
+ """Fraction along `edge` of the display the pointer is on, which is how Part of the edge
+ measures its thirds: against the bounding box, a short display beside a tall one could hold
+ none of the middle third. The bounding box when the pointer is on no display."""
+ home = next((m for m in monitors if _contains(m, pointer)), None) or union(monitors)
+ return edge_offset(home, edge, pointer)
+
+
def owning_monitor(monitors: List[Rect], edge: str) -> Rect:
"""The monitor that reaches the bounding box on `edge`; ties go to the
first enumerated, which on Windows is the primary."""
@@ -90,19 +110,40 @@ def owning_monitor(monitors: List[Rect], edge: str) -> Rect:
return max(monitors, key=lambda r: r.bottom)
+def landing_monitor(monitors: List[Rect], edge: str, along: float) -> Rect:
+ """The monitor a pointer arriving through `edge` at coordinate `along` (y for a side edge, x
+ for the top or bottom) lands on: of those spanning `along`, the outermost on that edge, so two
+ stacked monitors each take their own stretch of it; with none spanning it, a gap in a staggered
+ arrangement, the nearest. Ties go to the first enumerated, which on Windows is the primary."""
+ def span(r: Rect):
+ return (r.y, r.bottom) if edge in ("left", "right") else (r.x, r.right)
+
+ def outer(r: Rect):
+ return {"left": r.x, "right": -r.right, "top": r.y, "bottom": -r.bottom}[edge]
+
+ def distance(r: Rect):
+ low, high = span(r)
+ return max(low - along, along - (high - 1), 0)
+
+ return min(monitors, key=lambda r: (distance(r), outer(r)))
+
+
def arrival_position(monitors: List[Rect], edge: str, offset: float) -> Tuple[int, int]:
- """Where a pointer arriving at `edge`, `offset` of the way along it, lands.
- The fraction is applied against the whole bounding box, then clamped into
- the owning monitor so a staggered arrangement never lands it in a gap."""
+ """Where a pointer arriving at `edge`, `offset` of the way along it, lands. The fraction is
+ applied against the whole bounding box, then placed on the monitor `landing_monitor` picks, so
+ no arrangement lands it in a gap or on the wrong one of two monitors sharing the edge."""
bounds = union(monitors)
- owner = owning_monitor(monitors, edge)
offset = _clamp(float(offset), 0.0, 1.0)
if edge in ("left", "right"):
+ along = int(round(bounds.y + offset * bounds.height))
+ owner = landing_monitor(monitors, edge, along)
x = owner.x if edge == "left" else owner.right
- y = _clamp(int(round(bounds.y + offset * bounds.height)), owner.y, owner.bottom)
+ y = _clamp(along, owner.y, owner.bottom)
else:
+ along = int(round(bounds.x + offset * bounds.width))
+ owner = landing_monitor(monitors, edge, along)
y = owner.y if edge == "top" else owner.bottom
- x = _clamp(int(round(bounds.x + offset * bounds.width)), owner.x, owner.right)
+ x = _clamp(along, owner.x, owner.right)
return x, y
@@ -144,9 +185,9 @@ class ReturnEdge:
def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:
"""On a monitor, with no monitor one pixel beyond it: the pointer is
against a wall. Testing the bounding box instead made the edge of a
- shorter monitor in a staggered arrangement unreachable — on the rig,
- pushing down on the LG, whose bottom stops 204px above the ultrawide's,
- never went home."""
+ shorter monitor in a staggered arrangement unreachable — for example,
+ pushing down on a monitor whose bottom stops above its neighbour's
+ could never reach the edge."""
x, y = pointer
step_x, step_y = {"left": (-1, 0), "right": (1, 0), "top": (0, -1), "bottom": (0, 1)}[self.edge]
beyond = (x + step_x, y + step_y)
@@ -182,6 +223,35 @@ class ReturnEdge:
return Outcome(HOLD, self.pressure, position=position)
+class PartEdge(ReturnEdge):
+ """The edge, but only along the chosen thirds of it: the rest of the edge is a plain wall, so
+ a menu or a dock at one end can sit against it without the pointer ever crossing there. The
+ thirds are measured along the display the pointer is on, by `display_fraction`."""
+
+ def __init__(self, edge: str, parts, resistance_px: int = DEFAULT_RESISTANCE_PX, clock=time.monotonic) -> None:
+ super().__init__(edge, resistance_px, clock)
+ self.parts = frozenset(part for part in parts if part in PARTS)
+
+ def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:
+ return super()._at_edge(monitors, pointer) and in_parts(display_fraction(monitors, self.edge, pointer), self.parts)
+
+
+class SpanEdge(ReturnEdge):
+ """The edge, but only along a stretch of it, in the monitors' own coordinates: a Mac's notch,
+ a fixed stretch of its top edge rather than a third of it. `span()` gives (start, end) or None
+ and is read at every push, so a stretch measured late, or moved by a display change, applies
+ at once."""
+
+ def __init__(self, edge: str, span: Callable[[], Optional[Tuple[float, float]]], resistance_px: int = DEFAULT_RESISTANCE_PX, clock=time.monotonic) -> None:
+ super().__init__(edge, resistance_px, clock)
+ self.span = span
+
+ def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:
+ span = self.span()
+ along = pointer[0] if self.edge in ("top", "bottom") else pointer[1]
+ return span is not None and super()._at_edge(monitors, pointer) and span[0] <= along <= span[1]
+
+
class CornerPush(ReturnEdge):
"""The same pressure model gated to one corner, for a machine whose whole
edge is busy with something else. The push has to be diagonal: travel that
diff --git a/win_app/sender.py b/win_app/sender.py
index f4dbbed..735baa9 100644
--- a/win_app/sender.py
+++ b/win_app/sender.py
@@ -3,7 +3,7 @@ mac_app/bridge.py's link half, talking to the same receiver.py the Mac's
sender talks to, over a second connection this PC opens outwards.
Two links, not one bidirectional socket. The existing Mac-to-Windows link is
-the one Toby uses every day, and its sequence, acknowledgement and watchdog
+the one used every day, and its sequence, acknowledgement and watchdog
bookkeeping is all sender-shaped; threading a second ownership state through
it would put that link at risk for nothing. This one is opened by this PC, to
the Mac's own listener on the same port number, so it needs no inbound
@@ -150,7 +150,7 @@ class MacSender:
self,
status_callback: Callable[[bool, str], None] = None,
redirect_callback: Callable[[bool], None] = None,
- pressure_callback: Callable[[str, float, bool], None] = None,
+ pressure_callback: Callable[[str, float, bool, Optional[str]], None] = None,
arrangement_callback: Callable[[str, int], None] = None,
desktop=None,
clipboard=None,
@@ -159,11 +159,16 @@ class MacSender:
clock=time.monotonic,
wake_sender=wol.send_magic_packet,
mac_lookup=wol.lookup_mac,
+ arrival_callback: Callable[[str, int, int], None] = None,
) -> None:
self._status_callback = status_callback
self._redirect_callback = redirect_callback
self._pressure_callback = pressure_callback
self._arrangement_callback = arrangement_callback
+ # `arrival_callback(edge, x, y)`, as the shared receiver's: the pointer came home through the
+ # Mac's return edge and was placed at desktop pixel (x, y) on `edge` of this PC, or, with
+ # edge None, input came home by a switch and the pointer is at (x, y) where it was left.
+ self._arrival_callback = arrival_callback
self._desktop = desktop
self._clipboard = clipboard
self._socket_factory = socket_factory
@@ -275,7 +280,7 @@ class MacSender:
return
self._receiving = receiving
if receiving and self.redirecting:
- self.set_redirecting(False)
+ self.set_redirecting(False, came_home=False)
self._last_point = None
self._rearm_edge()
@@ -299,7 +304,7 @@ class MacSender:
def stop(self) -> None:
self._stop_event.set()
self._buttons_held.clear()
- self.set_redirecting(False)
+ self.set_redirecting(False, came_home=False)
self._drop_connection()
for thread in self._threads:
thread.join(timeout=2.0)
@@ -338,7 +343,7 @@ class MacSender:
"""Whether input may still be taken from this PC. Deliberately cheap
and lock-light: it is read on the hook thread for every keystroke and
every mouse move, and a hook that cannot answer promptly is a hook
- Windows removes -- with Toby's keyboard inside it."""
+ Windows removes -- with the user's keyboard inside it."""
if self._sock is None:
return False
last = max(self._last_ack_at, self._connected_at)
@@ -454,8 +459,8 @@ class MacSender:
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)."""
+ the Mac with this mouse behind it (ignoring this once left only the
+ Mac's trackpad able to take the pointer back)."""
if not self.connected or self.edges_held:
return
if self._buttons_held and self._setting("block_while_dragging", True) and self._still_dragging():
@@ -483,7 +488,13 @@ class MacSender:
LOGGER.exception("The way out to the Mac failed; crossing out is off until the next reconnect")
self._edge_model = self._corner_model = None
return
- self._notify_pressure(model.edge, outcome.pressure, outcome.action == return_edge.CROSS)
+ part = None
+ if isinstance(model, return_edge.PartEdge):
+ part = return_edge.part_of(return_edge.display_fraction(monitors, model.edge, pointer))
+ elif isinstance(model, return_edge.CornerPush):
+ # The corner's name, so the effects play their corner forms; the glow lights the edge.
+ part = model.corner
+ self._notify_pressure(model.edge, outcome.pressure, outcome.action == return_edge.CROSS, part)
if outcome.action == return_edge.CROSS:
if self._receiving:
# The Mac's input goes home first, over its own link; its
@@ -513,11 +524,17 @@ class MacSender:
# -- switching ----------------------------------------------------------
- def set_redirecting(self, value, arrival_edge=None, offset=None) -> bool:
+ def set_redirecting(self, value, arrival_edge=None, offset=None, came_home=True) -> bool:
"""`arrival_edge` is the Mac edge the pointer arrives at and `offset`
the fraction along it -- the same fraction it left this PC at, which
is what makes one border out of two screens. Both are absent when the
- shortcut moved input rather than a crossing."""
+ shortcut moved input rather than a crossing.
+
+ Input coming home this way is a switch -- the shortcut, the tray, the
+ direction switch or the Mac sending it back -- and is reported to the
+ arrival callback with edge None, for the arrival that shows where the
+ pointer is. `came_home` is False for the two ways back that show their
+ own: a crossing that lands here, and the Mac taking this PC over."""
value = bool(value)
if value == self.redirecting:
return False
@@ -568,6 +585,8 @@ class MacSender:
self._rearm_edge()
self._enqueue_control(protocol.focus_msg("windows"))
LOGGER.info("input returned to this PC")
+ if came_home:
+ self._report_switch_home()
if self._redirect_callback is not None:
try:
self._redirect_callback(value)
@@ -575,6 +594,15 @@ class MacSender:
LOGGER.exception("Redirect callback failed")
return True
+ def _report_switch_home(self) -> None:
+ if self._arrival_callback is None:
+ return
+ try:
+ x, y = self._desktop_module().cursor_position()
+ self._arrival_callback(None, x, y)
+ except Exception:
+ LOGGER.exception("Arrival callback for a switch failed")
+
def toggle(self) -> None:
"""The shortcut's way across and back, for when the pointer is not at
an edge -- or the edge is off."""
@@ -586,15 +614,25 @@ class MacSender:
to."""
if not isinstance(data, dict) or data.get("target") != "windows":
return
- self.set_redirecting(False)
edge = data.get("edge")
offset = data.get("offset")
- if edge in return_edge.EDGES and isinstance(offset, (int, float)) and not isinstance(offset, bool):
+ crossed = edge in return_edge.EDGES and isinstance(offset, (int, float)) and not isinstance(offset, bool)
+ # Without an edge the Mac sent this PC's input home by its own switch: that is a switch
+ # arriving here, and shows where the pointer is.
+ self.set_redirecting(False, came_home=not crossed)
+ if crossed:
try:
desktop = self._desktop_module()
- desktop.set_cursor_position(*return_edge.arrival_position(self._cached_monitors(), edge, offset))
+ x, y = return_edge.arrival_position(self._cached_monitors(), edge, offset)
+ desktop.set_cursor_position(x, y)
except Exception:
LOGGER.exception("Could not place the pointer at the %s edge on arrival", edge)
+ return
+ if self._arrival_callback is not None:
+ try:
+ self._arrival_callback(edge, x, y)
+ except Exception:
+ LOGGER.exception("Arrival callback failed")
# -- the link -----------------------------------------------------------
@@ -662,6 +700,7 @@ class MacSender:
return False
self._sock = sock
self._session = session
+ self._clipboard_module().forget_sync()
now = self._clock()
with self._sequence_lock:
self._last_sent_seq = 0
@@ -786,7 +825,7 @@ class MacSender:
def _send_local_clipboard(self) -> None:
try:
- text, image = self._clipboard_module().get_contents()
+ text, image = self._clipboard_module().changed_contents()
except Exception:
LOGGER.exception("Failed to read the local clipboard for the Mac")
return
@@ -962,6 +1001,8 @@ class MacSender:
self._alert("Input returned to this PC")
self.redirecting = False
self._pin_point = None
+ # The model that crossed disarmed itself; without a fresh one the edge never crosses again.
+ self._rearm_edge()
if self._redirect_callback is not None:
try:
self._redirect_callback(False)
@@ -1018,7 +1059,13 @@ class MacSender:
if self._edge is None:
self._edge_model = self._corner_model = None
return
- self._edge_model = return_edge.ReturnEdge(self._edge, resistance) if "edge" in methods else None
+ if "edge" in methods:
+ self._edge_model = return_edge.ReturnEdge(self._edge, resistance)
+ elif "part" in methods:
+ parts = self._setting("crossing_edge_parts", ("middle",))
+ self._edge_model = return_edge.PartEdge(self._edge, parts, resistance)
+ else:
+ self._edge_model = None
corner = self._setting("crossing_corner", "top_left")
if "corner" in methods and corner in return_edge.CORNERS:
self._corner_model = return_edge.CornerPush(corner, self._edge, resistance)
@@ -1049,10 +1096,10 @@ class MacSender:
return int(self._setting("crossing_resistance_px", return_edge.DEFAULT_RESISTANCE_PX))
def _warp_to_pin(self) -> None:
- """Put the pointer back where it was when input left. Measured on the
- rig, 17-09-2026: SetCursorPos produces no raw input at all -- a
- deliberate 137-pixel warp in a quiet window produced no WM_INPUT -- so
- the pin cannot feed itself back to the Mac as movement nobody made."""
+ """Put the pointer back where it was when input left. Measured: SetCursorPos
+ produces no raw input at all -- a deliberate 137-pixel warp in a quiet
+ window produced no WM_INPUT -- so the pin cannot feed itself back to
+ the Mac as movement nobody made."""
pin = self._pin_point
if pin is None:
return
@@ -1080,11 +1127,11 @@ class MacSender:
import clipboard_win
return clipboard_win
- def _notify_pressure(self, edge, pressure, crossed) -> None:
+ def _notify_pressure(self, edge, pressure, crossed, part=None) -> None:
if self._pressure_callback is None:
return
try:
- self._pressure_callback(edge, pressure, crossed)
+ self._pressure_callback(edge, pressure, crossed, part)
except Exception:
LOGGER.exception("Pressure callback failed")
diff --git a/win_app/tests/fakes.py b/win_app/tests/fakes.py
index a03533f..1cc0e2c 100644
--- a/win_app/tests/fakes.py
+++ b/win_app/tests/fakes.py
@@ -51,6 +51,12 @@ class FakeClipboard:
def get_contents(self):
return self.text, self.image
+ def changed_contents(self):
+ return self.text, self.image
+
+ def forget_sync(self):
+ pass
+
def set_contents(self, text, image):
self.set_calls.append((text, image))
return True
diff --git a/win_app/tests/test_app_config.py b/win_app/tests/test_app_config.py
index 86fdd6f..69a51ec 100644
--- a/win_app/tests/test_app_config.py
+++ b/win_app/tests/test_app_config.py
@@ -8,7 +8,7 @@ import app_config
import protocol
from dataclasses import replace
-from app_config import ConfigError, config_from_dict, config_to_dict, default_config, migrate_legacy_config
+from app_config import ConfigError, config_from_dict, config_to_dict, default_config
BASE = {"host": "192.168.1.3", "port": 51820, "auth_token": "shared-token"}
@@ -25,6 +25,20 @@ class EdgeGlowConfigTests(unittest.TestCase):
with self.assertRaises(ConfigError):
config_from_dict({**BASE, "edge_glow": "yes"})
+ def test_showing_where_the_pointer_lands_is_on_for_an_old_config_and_round_trips_off(self):
+ self.assertTrue(config_from_dict(dict(BASE)).shortcut_arrival)
+ config = config_from_dict({**BASE, "shortcut_arrival": False})
+ self.assertIs(config_to_dict(config)["shortcut_arrival"], False)
+ with self.assertRaises(ConfigError):
+ config_from_dict({**BASE, "shortcut_arrival": "yes"})
+
+ def test_what_a_switch_plays_defaults_to_the_crossing_and_round_trips(self):
+ self.assertEqual(config_from_dict(dict(BASE)).shortcut_arrival_style, "match")
+ config = config_from_dict({**BASE, "shortcut_arrival_style": "discharge"})
+ self.assertEqual(config_to_dict(config)["shortcut_arrival_style"], "discharge")
+ with self.assertRaises(ConfigError):
+ config_from_dict({**BASE, "shortcut_arrival_style": "sparkle"})
+
def test_style_and_colour_default_to_the_original_look_and_round_trip(self):
config = config_from_dict(dict(BASE))
self.assertEqual((config.glow_style, config.glow_colour), ("glow", "signal"))
@@ -32,10 +46,57 @@ class EdgeGlowConfigTests(unittest.TestCase):
saved = config_to_dict(config)
self.assertEqual((saved["glow_style"], saved["glow_colour"]), ("beam", "sunset"))
- def test_colour_choices_are_the_shared_palettes(self):
+ def test_colour_choices_are_the_shared_palettes_then_the_effect_packs(self):
+ import effects
+ import tokens
+
+ self.assertEqual(app_config.GLOW_COLOURS, tuple(tokens.PALETTES) + effects.PACK_IDS)
+
+ def test_every_crossing_effect_and_pack_is_accepted_and_round_trips(self):
+ import effects
+
+ for style in effects.EFFECT_IDS:
+ with self.subTest(style=style):
+ saved = config_to_dict(config_from_dict({**BASE, "glow_style": style}))
+ self.assertEqual(config_from_dict(saved).glow_style, style)
+ for colour in effects.PACK_IDS:
+ with self.subTest(colour=colour):
+ saved = config_to_dict(config_from_dict({**BASE, "glow_colour": colour}))
+ self.assertEqual(config_from_dict(saved).glow_colour, colour)
+
+ def test_any_colour_goes_with_any_style(self):
+ config = config_from_dict({**BASE, "glow_style": "glow", "glow_colour": "ember"})
+ self.assertEqual((config.glow_style, config.glow_colour), ("glow", "ember"))
+ config = config_from_dict({**BASE, "glow_style": "discharge", "glow_colour": "sunset"})
+ self.assertEqual((config.glow_style, config.glow_colour), ("discharge", "sunset"))
+
+ def test_a_colour_resolves_to_todays_palette_else_its_pack(self):
+ import effects
import tokens
- self.assertEqual(app_config.GLOW_COLOURS, tuple(tokens.PALETTES))
+ self.assertEqual(app_config.palette_colours("sunset"), tuple(tokens.PALETTES["sunset"]))
+ self.assertEqual(app_config.palette_colours("forge"), tuple(effects.pack("forge")[1]))
+ self.assertEqual(app_config.palette_colours("tartan"), tuple(tokens.PALETTES["signal"]))
+
+ def test_the_length_defaults_to_normal_and_round_trips(self):
+ self.assertEqual(config_from_dict(dict(BASE)).effect_length, "normal")
+ config = config_from_dict({**BASE, "effect_length": "long"})
+ self.assertEqual(config_to_dict(config)["effect_length"], "long")
+ with self.assertRaises(ConfigError):
+ config_from_dict({**BASE, "effect_length": "forever"})
+
+ def test_a_saved_warp_choice_reads_as_its_stand_in(self):
+ # Warp is offered nowhere for now; a PC that chose it keeps working.
+ config = config_from_dict({**BASE, "glow_style": "light_slit", "glow_colour": "neon",
+ "shortcut_arrival_style": "wormhole"})
+ self.assertEqual((config.glow_style, config.glow_colour, config.shortcut_arrival_style),
+ ("beam", "colourful", "match"))
+ self.assertEqual(config_from_dict({**BASE, "glow_style": "wormhole"}).glow_style, "glow")
+ # Ink likewise.
+ config = config_from_dict({**BASE, "glow_style": "capillary", "glow_colour": "matcha",
+ "shortcut_arrival_style": "sumi_bloom"})
+ self.assertEqual((config.glow_style, config.glow_colour, config.shortcut_arrival_style),
+ ("glow", "colourful", "match"))
def test_rejects_an_unknown_style_or_colour(self):
for key, value in (("glow_style", "sparkle"), ("glow_colour", "tartan")):
@@ -44,34 +105,39 @@ class EdgeGlowConfigTests(unittest.TestCase):
self.assertIn(key, str(caught.exception))
-class MigrateLegacyConfigTests(unittest.TestCase):
- def test_copies_without_touching_the_old_file(self):
- with tempfile.TemporaryDirectory() as directory:
- old_path = Path(directory) / "OpenKB" / "config.json"
- old_path.parent.mkdir()
- old_path.write_text(json.dumps(BASE), encoding="utf-8")
- new_path = Path(directory) / "Beamer" / "config.json"
- with mock.patch.object(app_config, "default_config_path", return_value=new_path), \
- mock.patch.object(app_config, "legacy_config_path", return_value=old_path):
- self.assertTrue(migrate_legacy_config())
- self.assertTrue(old_path.exists())
- self.assertEqual(
- json.loads(new_path.read_text(encoding="utf-8")),
- json.loads(old_path.read_text(encoding="utf-8")),
- )
- # A second run must not overwrite the now-existing new config.
- new_path.write_text(json.dumps({"changed": True}), encoding="utf-8")
- self.assertFalse(migrate_legacy_config())
- self.assertEqual(json.loads(new_path.read_text(encoding="utf-8")), {"changed": True})
-
- def test_is_a_noop_with_no_legacy_file(self):
- with tempfile.TemporaryDirectory() as directory:
- old_path = Path(directory) / "OpenKB" / "config.json"
- new_path = Path(directory) / "Beamer" / "config.json"
- with mock.patch.object(app_config, "default_config_path", return_value=new_path), \
- mock.patch.object(app_config, "legacy_config_path", return_value=old_path):
- self.assertFalse(migrate_legacy_config())
- self.assertFalse(new_path.parent.exists())
+class AppearanceConfigTests(unittest.TestCase):
+ def test_defaults_to_system(self):
+ self.assertEqual(config_from_dict(dict(BASE)).appearance, "system")
+
+ def test_round_trips_light_and_dark(self):
+ for choice in ("light", "dark"):
+ config = config_from_dict({**BASE, "appearance": choice})
+ self.assertEqual(config_to_dict(config)["appearance"], choice)
+
+ def test_a_bad_value_falls_back_to_system_instead_of_erroring(self):
+ self.assertEqual(config_from_dict({**BASE, "appearance": "sepia"}).appearance, "system")
+
+
+
+class HandEditedListsTests(unittest.TestCase):
+ def test_an_unhashable_entry_is_a_config_error_not_a_crash(self):
+ base = {"host": "192.0.2.10", "port": 24820, "auth_token": "synthetic-token-for-tests"}
+ for bad in ([["middle"]], [{}]):
+ with self.subTest(bad=bad), self.assertRaises(ConfigError):
+ config_from_dict(dict(base, crossing_edge_parts=bad))
+ with self.assertRaises(ConfigError):
+ config_from_dict(dict(base, crossing_methods=[["edge"]]))
+
+
+
+class HideAddressesTests(unittest.TestCase):
+ def test_off_by_default_round_trips_and_refuses_a_non_bool(self):
+ base = {"host": "192.0.2.10", "port": 24820, "auth_token": "synthetic-token-for-tests"}
+ self.assertFalse(config_from_dict(base).hide_addresses)
+ config = config_from_dict(dict(base, hide_addresses=True))
+ self.assertTrue(config_to_dict(config)["hide_addresses"])
+ with self.assertRaises(ConfigError):
+ config_from_dict(dict(base, hide_addresses="yes"))
if __name__ == "__main__":
diff --git a/win_app/tests/test_clipboard_win.py b/win_app/tests/test_clipboard_win.py
index b620bb8..91ea2a4 100644
--- a/win_app/tests/test_clipboard_win.py
+++ b/win_app/tests/test_clipboard_win.py
@@ -75,9 +75,9 @@ class DibCodecTests(unittest.TestCase):
# 0xFF -- which makes it impossible for every real alpha byte in the
# image to be zero, so the all-zero-alpha-means-opaque fallback this
# would otherwise suppress was never going to fire anyway. The
- # over-read is real but inert: this pixel, and the whole 1-3px
- # sweep in the verifier's notes, decode identically to a version that
- # reads the correct 3 masks for a size-52 header.
+ # over-read is real but inert: this pixel, and every value across the
+ # small range that could trigger it, decode identically to a version
+ # that reads the correct 3 masks for a size-52 header.
masks = struct.pack("<III", 0x00FF0000, 0x0000FF00, 0x000000FF)
head = header(1, -1, 32, BI_BITFIELDS, size=52)
head = head[:40] + masks
diff --git a/win_app/tests/test_crossing_matrix.py b/win_app/tests/test_crossing_matrix.py
new file mode 100644
index 0000000..5602ebd
--- /dev/null
+++ b/win_app/tests/test_crossing_matrix.py
@@ -0,0 +1,306 @@
+"""This PC's ways in on each arrangement, and the arrangement as both machines hold it. The two-
+machine cases, which need the Mac's code too, are in mac_app/tests/test_crossing_matrix.py; what
+each row proves is written up in docs/crossing-matrix-28-09-2026.md."""
+
+import itertools
+import logging
+import time
+import types
+import unittest
+
+import return_edge
+import sender
+from app_config import Config, default_config
+from fakes import FakeClipboard, FakeDesktop
+from return_edge import CORNERS, EDGES, OPPOSITE, Rect
+
+MONITORS = [Rect(0, 0, 1920, 1080)]
+THIRDS = {"start": 0.17, "middle": 0.5, "end": 0.83}
+LAST_X, LAST_Y = 1919, 1079
+
+
+def side_point(side, third):
+ f = THIRDS[third]
+ return {
+ "left": (0, int(f * LAST_Y)),
+ "right": (LAST_X, int(f * LAST_Y)),
+ "top": (int(f * LAST_X), 0),
+ "bottom": (int(f * LAST_X), LAST_Y),
+ }[side]
+
+
+def outward(side, n=30):
+ return {"left": (-n, 0), "right": (n, 0), "top": (0, -n), "bottom": (0, n)}[side]
+
+
+def corner_point(corner):
+ vertical, horizontal = corner.split("_")
+ return (0 if horizontal == "left" else LAST_X), (0 if vertical == "top" else LAST_Y)
+
+
+def probes():
+ for side in EDGES:
+ for third in THIRDS:
+ x, y = side_point(side, third)
+ yield f"{side}/{third}", x, y, *outward(side), "edge", side, third
+ for corner in CORNERS:
+ vertical, horizontal = corner.split("_")
+ x, y = corner_point(corner)
+ yield f"{corner} diagonal", x, y, outward(horizontal)[0], outward(vertical)[1], "diagonal", corner, None
+ yield f"{corner} along {horizontal}", x, y + (4 if vertical == "top" else -4), *outward(horizontal), "straight", corner, horizontal
+ yield f"{corner} along {vertical}", x + (4 if horizontal == "left" else -4), y, *outward(vertical), "straight", corner, vertical
+
+
+def third_at_corner(corner, side):
+ vertical, horizontal = corner.split("_")
+ if side in ("left", "right"):
+ return "start" if vertical == "top" else "end"
+ return "start" if horizontal == "left" else "end"
+
+
+def make_sender(methods, edge, corner="top_left", parts=("middle",), **more):
+ more.setdefault("crossing_resistance_px", 40)
+ desktop = FakeDesktop(MONITORS)
+ link = sender.MacSender(desktop=desktop, clipboard=FakeClipboard(), is_local=lambda host: False)
+ link.update_config(
+ Config(
+ host="127.0.0.1",
+ port=1,
+ auth_token="matrix-token",
+ mac_host="127.0.0.1",
+ mac_return_edge=edge,
+ crossing_methods=list(methods),
+ crossing_corner=corner,
+ crossing_edge_parts=list(parts),
+ **more,
+ )
+ )
+ link._sock = object()
+ link._connected_at = link._last_ack_at = time.monotonic()
+ return link, desktop
+
+
+def push(methods, edge, probe, corner="top_left", parts=("middle",)):
+ """The focus message a push sends, or None when the push never crosses."""
+ link, desktop = make_sender(methods, edge, corner, parts)
+ _, x, y, dx, dy = probe[:5]
+ desktop.cursor = (x, y)
+ for _ in range(12):
+ link.on_motion(dx, dy)
+ if link.redirecting:
+ break
+ if not link.redirecting:
+ return None
+ return [m for m in list(link._outbound.queue) if m["type"] == "focus"][-1]["data"]
+
+
+def expected(methods, edge, corner, parts, probe):
+ """The Mac edge a push arrives at. Edge is the whole arrangement side and Part of the edge its
+ thirds; Corner is one corner, any of the four, and always arrives by the arrangement side."""
+ _, _, _, _, _, kind, where, third = probe
+
+ def by_edge(side, part):
+ if side != edge:
+ return None
+ return OPPOSITE[edge] if "edge" in methods or ("part" in methods and part in parts) else None
+
+ if kind == "edge":
+ return by_edge(where, third)
+ vertical, horizontal = where.split("_")
+ if kind == "diagonal":
+ if "corner" in methods and where == corner:
+ return OPPOSITE[edge]
+ return by_edge(horizontal, third_at_corner(where, horizontal)) or by_edge(vertical, third_at_corner(where, vertical))
+ return by_edge(third, third_at_corner(where, third))
+
+
+def method_sets():
+ for shortcut, pointer, corner in itertools.product((False, True), ("", "edge", "part"), (False, True)):
+ methods = {name for name, on in (("shortcut", shortcut), (pointer, bool(pointer)), ("corner", corner)) if on and name}
+ if methods:
+ yield frozenset(methods)
+
+
+class PcWaysOutTests(unittest.TestCase):
+ def test_every_way_crosses_where_it_says_and_nowhere_else(self):
+ for methods in method_sets():
+ for edge in EDGES:
+ for corner in CORNERS:
+ for parts in (("middle",), ("start", "end"), ("start", "middle", "end")):
+ for probe in probes():
+ focus = push(methods, edge, probe, corner, parts)
+ arrived = None if focus is None else focus.get("edge")
+ with self.subTest(methods=sorted(methods), mac_is=edge, corner=corner, parts=parts, probe=probe[0]):
+ self.assertEqual(arrived, expected(methods, edge, corner, parts, probe))
+
+ def test_the_shortcut_alone_leaves_every_edge_a_wall(self):
+ for edge in EDGES:
+ for probe in probes():
+ self.assertIsNone(push(("shortcut",), edge, probe), probe[0])
+
+ def test_the_mac_lands_at_the_same_fraction_along_the_far_edge(self):
+ for edge in EDGES:
+ for third, fraction in THIRDS.items():
+ probe = (f"{edge}/{third}", *side_point(edge, third), *outward(edge))
+ focus = push(("edge",), edge, probe)
+ self.assertEqual(focus["edge"], OPPOSITE[edge])
+ self.assertAlmostEqual(focus["offset"], fraction, places=2)
+
+ def test_a_corner_arrives_at_its_position_along_the_arrangement_side_not_along_its_own(self):
+ probe = ("top_left diagonal", 0, 0, -30, -30)
+ self.assertEqual(push(("corner",), "right", probe, corner="top_left")["offset"], 0.0)
+ probe = ("bottom_left diagonal", 0, LAST_Y, -30, 30)
+ self.assertAlmostEqual(push(("corner",), "right", probe, corner="bottom_left")["offset"], 1.0, places=2)
+ probe = ("top_left diagonal", 0, 0, -30, -30)
+ self.assertEqual(push(("corner",), "bottom", probe, corner="top_left")["offset"], 0.0)
+ probe = ("top_right diagonal", LAST_X, 0, 30, -30)
+ self.assertAlmostEqual(push(("corner",), "bottom", probe, corner="top_right")["offset"], 1.0, places=2)
+
+ def test_a_pc_that_holds_no_edge_has_no_way_out(self):
+ for methods in method_sets():
+ for probe in probes():
+ self.assertIsNone(push(methods, "", probe), (methods, probe[0]))
+
+
+class PcWayHomeNamedToTheMacTests(unittest.TestCase):
+ def test_the_hello_and_a_shortcut_switch_name_the_mac_edge_opposite_the_pcs(self):
+ for edge in EDGES:
+ link, _ = make_sender(("shortcut",), edge)
+ self.assertEqual(link._mac_arrival_edge(), OPPOSITE[edge])
+
+ def test_a_crossing_names_the_edge_it_arrived_by(self):
+ for edge in EDGES:
+ probe = ("push", *side_point(edge, "middle"), *outward(edge))
+ focus = push(("edge",), edge, probe)
+ self.assertEqual(focus["return_edge"], focus["edge"])
+ self.assertEqual(focus["resistance_px"], 40)
+
+ def test_the_pcs_resistance_is_what_it_asks_the_mac_for_never_the_macs_own(self):
+ link, _ = make_sender(("edge",), "right", crossing_resistance_px=40)
+ link._config.crossing_resistance_px = 200
+ link.update_config(link._config)
+ self.assertEqual(link._resistance(), 200)
+ link._config.mac_resistance_px = 5
+ self.assertEqual(link._resistance(), 200, "the resistance the Mac reported is never read")
+
+
+class WhatIsSharedTests(unittest.TestCase):
+ def test_the_crossing_page_shares_only_the_side_the_resistance_stays_each_machines_own(self):
+ import pages_win
+
+ line = pages_win.SCOPE["crossing"]
+ self.assertNotIn("Two are shared", line)
+ self.assertIn("Only which side your Mac is on is shared", line)
+
+
+try:
+ import kvm_bridge_win
+except ImportError: # PySide6 is only in the Windows venv
+ kvm_bridge_win = None
+
+
[email protected](kvm_bridge_win is None, "needs PySide6")
+class ArrangementHeldByBothTests(unittest.TestCase):
+ """`_on_arrangement` and `_on_learned` are the two ways a Mac's idea of where the machines are
+ reaches this PC: a stamped message over either link, and the unstamped way home the hello
+ carries."""
+
+ def page(self, edge="right", stamp=0):
+ config = default_config()
+ config.mac_return_edge = edge
+ config.arrangement_set_at = stamp
+ saved = []
+ page = types.SimpleNamespace(
+ _config=config,
+ _persist=lambda: saved.append((config.mac_return_edge, config.arrangement_set_at)) or True,
+ _start_sending=lambda config: None,
+ sender=types.SimpleNamespace(update_config=lambda config: None),
+ edge_choice=types.SimpleNamespace(set_value=lambda value: None),
+ mac_host_readout=types.SimpleNamespace(setText=lambda text: None),
+ _reflect_look=lambda: None,
+ _reflect_ways=lambda: None,
+ )
+ return page, saved
+
+ def arrive(self, page, mac_edge, stamp):
+ kvm_bridge_win.WindowsApplication._on_arrangement(page, mac_edge, stamp)
+
+ def learn(self, page, edge, host="192.168.1.10"):
+ real = kvm_bridge_win.sender.is_this_machine
+ kvm_bridge_win.sender.is_this_machine = lambda h: False
+ try:
+ kvm_bridge_win.WindowsApplication._on_learned(page, host, edge, 40)
+ finally:
+ kvm_bridge_win.sender.is_this_machine = real
+
+ def test_a_newer_arrangement_from_the_mac_is_applied_as_this_pcs_opposite_edge_with_its_stamp(self):
+ page, saved = self.page("right", stamp=100)
+ self.arrive(page, "top", 200)
+ self.assertEqual((page._config.mac_return_edge, page._config.arrangement_set_at), ("bottom", 200))
+
+ def test_the_same_edge_with_a_newer_stamp_leaves_the_stored_stamp_as_the_mac_does(self):
+ page, saved = self.page("left", stamp=100)
+ self.arrive(page, "right", 200)
+ self.assertEqual((page._config.mac_return_edge, page._config.arrangement_set_at), ("left", 100))
+
+ def test_an_older_arrangement_is_ignored(self):
+ page, saved = self.page("right", stamp=200)
+ self.arrive(page, "top", 100)
+ self.assertEqual(page._config.mac_return_edge, "right")
+ self.assertEqual(saved, [])
+
+ def test_the_same_arrangement_over_the_second_link_changes_nothing_and_logs_nothing(self):
+ # One change on the Mac reaches this PC over both links, so the second copy carries the
+ # stamp the first already stored.
+ page, saved = self.page("left", stamp=300)
+ with self.assertNoLogs(kvm_bridge_win.LOGGER, logging.INFO):
+ self.arrive(page, "right", 300)
+ self.assertEqual(saved, [])
+
+ def test_the_macs_hello_names_the_edge_of_a_pc_that_has_none(self):
+ page, saved = self.page("", stamp=0)
+ self.learn(page, "left")
+ self.assertEqual(page._config.mac_return_edge, "left")
+
+ def test_a_change_made_here_with_no_link_is_stored_and_told_to_nobody(self):
+ page, saved = self.page("right", stamp=0)
+ told = []
+ page.sender = types.SimpleNamespace(send_arrangement=lambda *a: told.append(("pc-to-mac", a)) or False, update_config=lambda c: None)
+ page.server = types.SimpleNamespace(send_arrangement=lambda *a: told.append(("mac-to-pc", a)) or False)
+ kvm_bridge_win.WindowsApplication._set_arrangement(page, "top")
+ self.assertEqual(page._config.mac_return_edge, "top")
+ self.assertGreater(page._config.arrangement_set_at, 0)
+ self.assertEqual([who for who, _ in told], ["pc-to-mac", "mac-to-pc"])
+ self.assertEqual(told[0][1][0], "bottom")
+
+ def test_the_macs_hello_replaces_an_edge_set_here_and_leaves_its_stamp_claiming_otherwise(self):
+ # Pinned known gap (G1 in the report): the hello should not win over a newer stamp.
+ # What a PC set up before pairing goes through: the choice made here is stamped, the Mac's
+ # first hello names its own way home, and that is what the PC then holds, under the stamp
+ # of the choice it replaced.
+ page, saved = self.page("top", stamp=5000)
+ self.learn(page, "left")
+ self.assertEqual((page._config.mac_return_edge, page._config.arrangement_set_at), ("left", 5000))
+
+ def test_a_fresh_config_holds_no_edge_though_the_crossing_page_offers_right(self):
+ # Pinned known gap (G3 in the report).
+ self.assertEqual(default_config().mac_return_edge, "")
+
+
+if __name__ == "__main__":
+ unittest.main()
+
+
[email protected](kvm_bridge_win is None, "needs PySide6")
+class WaysReachTheDesignPageTests(unittest.TestCase):
+ def test_changing_a_way_in_moves_the_design_preview(self):
+ config = default_config()
+ looked = []
+ page = types.SimpleNamespace(
+ _config=config, _persist=lambda: True, sender=types.SimpleNamespace(update_config=lambda config: None),
+ _reflect_ways=lambda: None, _reflect_look=lambda: looked.append(tuple(config.crossing_methods)),
+ )
+ kvm_bridge_win.WindowsApplication._ways_changed(page, "corner", True)
+ kvm_bridge_win.WindowsApplication._set_part(page, "start", True)
+ self.assertEqual(len(looked), 2)
+ self.assertIn("corner", looked[0])
diff --git a/win_app/tests/test_edge_glow.py b/win_app/tests/test_edge_glow.py
index 72526f5..df3bb71 100644
--- a/win_app/tests/test_edge_glow.py
+++ b/win_app/tests/test_edge_glow.py
@@ -53,5 +53,182 @@ class PreviewScriptTests(unittest.TestCase):
self.assertEqual(edge_glow.preview_frame(loop + 0.5), edge_glow.preview_frame(0.5))
+
[email protected](edge_glow is None, "PySide6 is not installed")
+class DarkColoursTest(unittest.TestCase):
+ def test_a_dark_pack_is_lifted_on_a_dark_appearance_only(self):
+ from unittest import mock
+
+ import effects
+
+ # Indigo ink, the darkest pack, though Ink is offered nowhere for now.
+ def first(dark):
+ with mock.patch.object(edge_glow.app_config, "palette_colours", return_value=effects.pack("indigo_ink")[1]):
+ stops = edge_glow._colours("indigo_ink", True, 100, dark).stops()
+ return stops[0][1].lightnessF()
+ self.assertLess(first(False), 0.2)
+ self.assertGreater(first(True), 0.4)
+
+
[email protected](edge_glow is None, "PySide6 is not installed")
+class PreviewLoopHoverTests(unittest.TestCase):
+ """Glow and Beam's tiles hold a still; the one the pointer is over plays, from that still."""
+
+ def setUp(self):
+ import os
+
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ from PySide6.QtWidgets import QApplication, QWidget
+
+ self.app = QApplication.instance() or QApplication([])
+ self.parent = QWidget()
+ self.loop = edge_glow.PreviewLoop(self.parent)
+ self.tiles = [edge_glow.GlowPreview(style) for style in ("glow", "beam")]
+ for tile in self.tiles:
+ tile.isVisible = lambda: True
+ tile.visibleRegion = lambda: type("Region", (), {"isEmpty": lambda self: False})()
+ self.loop.add(tile)
+ self.loop.run(True)
+
+ def tearDown(self):
+ self.loop.run(False)
+
+ def test_every_tile_holds_a_still_until_one_is_hovered(self):
+ self.loop._tick()
+ self.assertEqual([tile.state.pressure for tile in self.tiles], [edge_glow.PreviewLoop.HOLD] * 2)
+ self.assertFalse(any(self.loop.playing(tile) for tile in self.tiles))
+
+ def test_a_pointer_passing_over_starts_nothing(self):
+ self.loop.hover(self.tiles[1])
+ self.loop._tick()
+ self.assertFalse(self.loop.playing(self.tiles[1]))
+
+ def test_the_hovered_tile_plays_on_from_its_still_and_settles_back(self):
+ self.loop.hover(self.tiles[1])
+ self.loop._hovered_at -= edge_glow.PreviewLoop.INTENT_S
+ self.loop._tick()
+ self.assertTrue(self.loop.playing(self.tiles[1]))
+ self.assertAlmostEqual(self.tiles[1].state.pressure, edge_glow.PreviewLoop.HOLD, places=2)
+ self.loop.hover(None)
+ self.assertFalse(self.loop.playing(self.tiles[1]))
+ self.assertEqual(self.tiles[1].state.pressure, edge_glow.PreviewLoop.HOLD)
+
+
if __name__ == "__main__":
unittest.main()
+
+
[email protected](edge_glow is None, "PySide6 is not installed")
+class CornerGlowTests(unittest.TestCase):
+ """Glow and Beam in a corner light the corner's two walls, and every window stays above the
+ taskbar."""
+
+ def setUp(self):
+ import os
+
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ from PySide6.QtWidgets import QApplication
+
+ self.app = QApplication.instance() or QApplication([])
+
+ def render(self, corner, style="glow", centre=0.5):
+ from PySide6.QtCore import QRect
+ from PySide6.QtGui import QImage, QPainter, Qt
+
+ size = edge_glow.CORNER_ARM_PX
+ image = QImage(size, size, QImage.Format.Format_ARGB32_Premultiplied)
+ image.fill(Qt.GlobalColor.transparent)
+ state = edge_glow.GlowState()
+ state.push(0.9, False)
+ state.centre = centre
+ painter = QPainter(image)
+ edge_glow.paint_corner(painter, QRect(0, 0, size, size), corner, style, "signal", state)
+ painter.end()
+ return image
+
+ def test_a_corner_lights_both_its_walls_brightest_where_they_meet(self):
+ last = edge_glow.CORNER_ARM_PX - 1
+ for corner, (cx, cy) in (("top_left", (0, 0)), ("top_right", (last, 0)),
+ ("bottom_left", (0, last)), ("bottom_right", (last, last))):
+ image = self.render(corner)
+ alpha = lambda x, y: image.pixelColor(x, y).alpha()
+ far_x = last if cx == 0 else 0
+ far_y = last if cy == 0 else 0
+ step_x = 1 if cx == 0 else -1
+ step_y = 1 if cy == 0 else -1
+ with self.subTest(corner=corner):
+ self.assertGreater(alpha(cx, cy), 150)
+ # A third of the way along each wall is lit, less than the corner itself.
+ self.assertGreater(alpha(cx + step_x * 60, cy), 40)
+ self.assertGreater(alpha(cx, cy + step_y * 60), 40)
+ self.assertLess(alpha(cx + step_x * 60, cy), alpha(cx, cy))
+ # Nothing at the far ends of the walls, nor out in the middle of the square.
+ self.assertLess(alpha(far_x, cy), 8)
+ self.assertLess(alpha(cx, far_y), 8)
+ self.assertEqual(alpha(edge_glow.CORNER_ARM_PX // 2, edge_glow.CORNER_ARM_PX // 2), 0)
+
+ def test_the_beams_comet_runs_in_along_one_wall_and_out_along_the_other(self):
+ last = edge_glow.CORNER_ARM_PX - 1
+ # bottom_right: the bottom wall from its left end to the corner, then up the right wall.
+ early, late = self.render("bottom_right", "beam", 0.15), self.render("bottom_right", "beam", 0.85)
+ on_bottom = lambda image: image.pixelColor(60, last).alpha()
+ on_right = lambda image: image.pixelColor(last, 60).alpha()
+ self.assertGreater(on_bottom(early), on_bottom(late))
+ self.assertGreater(on_right(late), on_right(early))
+
+ def test_a_corner_push_places_the_light_at_that_corner_of_the_display(self):
+ from unittest import mock
+
+ from PySide6.QtCore import QPoint
+
+ glow = edge_glow.EdgeGlow()
+ screen = self.app.primaryScreen().geometry()
+ with mock.patch.object(edge_glow.QCursor, "pos", return_value=QPoint(screen.right() - 2, screen.bottom() - 2)):
+ glow.set_pressure("bottom", 0.5, False, "bottom_right")
+ size = min(edge_glow.CORNER_ARM_PX, screen.width(), screen.height())
+ self.assertEqual((glow.geometry().right(), glow.geometry().bottom()), (screen.right(), screen.bottom()))
+ self.assertEqual((glow.width(), glow.height()), (size, size))
+ glow.hide()
+
+ def test_every_frame_puts_the_window_back_above_the_taskbar(self):
+ from unittest import mock
+
+ glow = edge_glow.EdgeGlow()
+ with mock.patch.object(edge_glow, "keep_on_top") as raised:
+ glow.set_pressure("left", 0.5, False)
+ glow._tick()
+ self.assertEqual(raised.call_count, 2)
+ glow.hide()
+
+
[email protected](edge_glow is None, "PySide6 is not installed")
+class ThirdEndsTests(unittest.TestCase):
+ def setUp(self):
+ import os
+
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ from PySide6.QtWidgets import QApplication
+
+ self.app = QApplication.instance() or QApplication([])
+
+ def test_a_third_of_the_edge_fades_in_and_out_at_its_ends(self):
+ from PySide6.QtCore import QRect
+ from PySide6.QtGui import QImage, QPainter, Qt
+
+ for style in ("glow", "beam"):
+ for taper in (False, True):
+ image = QImage(44, 400, QImage.Format.Format_ARGB32_Premultiplied)
+ image.fill(Qt.GlobalColor.transparent)
+ state = edge_glow.GlowState()
+ state.push(0.9, False)
+ state.flash = 1.0
+ painter = QPainter(image)
+ edge_glow.paint(painter, QRect(0, 0, 44, 400), "right", style, "signal", state, taper=taper)
+ painter.end()
+ end, middle = image.pixelColor(43, 1).alpha(), image.pixelColor(43, 200).alpha()
+ with self.subTest(style=style, taper=taper):
+ self.assertGreater(middle, 100)
+ if taper:
+ self.assertLess(end, 12)
+ else:
+ self.assertGreater(end, 100)
diff --git a/win_app/tests/test_effect_fires.py b/win_app/tests/test_effect_fires.py
new file mode 100644
index 0000000..ead6595
--- /dev/null
+++ b/win_app/tests/test_effect_fires.py
@@ -0,0 +1,197 @@
+"""Traces every crossing-effect "move" from sender.py/receiver.py's pressure and arrival
+callbacks to the call that actually reaches EffectOverlay or EdgeGlow, at the one hop that has no
+test today: kvm_bridge_win.py's WindowsApplication._on_pressure / _on_arrival.
+
+sender.py's MacSender._notify_pressure(edge, pressure, crossed, part) and its arrival_callback --
+an edge push, a Part-of-the-edge push, a corner push, a crossing, a switch home -- are already
+proven by test_sender.py's PushTests, CornerCrossingTests and ArrivalTests. receiver.py's
+pressure_callback and arrival_callback (the return-edge push and its arrival) are proven by
+test_receiver.py's tests around line 716. Neither is repeated here: these tests start from the
+(edge, pressure, crossed, part) / (method, edge, x, y) values those callbacks already produce and
+check where they land.
+
+_on_pressure and _on_arrival read self._effect_overlay() / self._switch_overlay() / self.effects /
+self.glow / self._config, so a SimpleNamespace "owner" stands in for WindowsApplication -- the
+same pattern test_effect_overlay.py's test_the_app_shows_a_switch_only_with_both_switches_on uses
+to call WindowsApplication._switch_overlay directly, without building a whole app (tray icon,
+hooks, Announcer, a real receiver socket). _effect_overlay and _switch_overlay are themselves
+mocked here, at the overlay: what decides whether the chosen style
+counts as "an effect" is config plumbing already covered by test_effect_overlay.py, not this
+file's concern."""
+
+import os
+import unittest
+from types import SimpleNamespace
+from unittest import mock
+
+try:
+ from PySide6.QtWidgets import QApplication
+
+ import effect_overlay
+ import kvm_bridge_win
+except ImportError: # PySide6 is only in the Windows venv
+ kvm_bridge_win = None
+
+
+def _owner(edge_glow=True, glow_style="glow", glow_colour="signal", shortcut_arrival=True,
+ shortcut_arrival_style="match", effects=None, glow=None):
+ config = SimpleNamespace(
+ edge_glow=edge_glow, glow_style=glow_style, glow_colour=glow_colour,
+ shortcut_arrival=shortcut_arrival, shortcut_arrival_style=shortcut_arrival_style, effect_length="normal",
+ )
+ return SimpleNamespace(_closing=False, _config=config, effects=effects, glow=glow)
+
+
[email protected](kvm_bridge_win is None, "needs PySide6")
+class PressureRoutingTest(unittest.TestCase):
+ """The Mac driving this PC and pushing back at the way home (receiver.py's pressure_callback,
+ always with part=None) and this PC's own crossing out (sender.py's, part carrying Part of the
+ edge) both end up on the same bridge.pressure signal and the same _on_pressure -- nothing
+ here tells the two apart, which is why one set of tests covers both directions."""
+
+ def test_an_edge_push_reaches_the_effects_overlay_when_the_style_is_an_effect(self):
+ owner = _owner(glow_style="rupture")
+ overlay = mock.Mock()
+ owner._effect_overlay = mock.Mock(return_value=overlay)
+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 0.4, False)
+ overlay.push.assert_called_once_with("left", 0.4, False, part=None)
+
+ def test_an_edge_push_reaches_edge_glow_when_the_style_is_glow(self):
+ owner = _owner(glow_style="glow", glow_colour="ocean", glow=mock.Mock())
+ owner._effect_overlay = mock.Mock(return_value=None)
+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 0.4, False)
+ owner.glow.configure.assert_called_once_with("glow", "ocean", "normal")
+ owner.glow.set_pressure.assert_called_once_with("left", 0.4, False, None)
+
+ def test_a_beam_style_push_configures_the_glow_as_beam(self):
+ owner = _owner(glow_style="beam", glow=mock.Mock())
+ owner._effect_overlay = mock.Mock(return_value=None)
+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 0.4, False)
+ owner.glow.configure.assert_called_once_with("beam", "signal", "normal")
+
+ def test_an_effect_that_failed_earlier_falls_back_to_plain_glow(self):
+ """_on_pressure's own comment: an effect that failed earlier in the run falls back to
+ today's glow. A style that is neither "glow" nor "beam" (an effect id) still configures
+ EdgeGlow as plain "glow" -- the effect id itself is never passed through."""
+ owner = _owner(glow_style="wormhole", glow_colour="mono", glow=mock.Mock())
+ owner._effect_overlay = mock.Mock(return_value=None)
+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 0.4, False)
+ owner.glow.configure.assert_called_once_with("glow", "mono", "normal")
+
+ def test_a_part_of_the_edge_push_passes_the_part_through_to_the_overlay(self):
+ owner = _owner(glow_style="rupture")
+ overlay = mock.Mock()
+ owner._effect_overlay = mock.Mock(return_value=overlay)
+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "right", 0.5, False, "end")
+ overlay.push.assert_called_once_with("right", 0.5, False, part="end")
+
+ def test_a_part_of_the_edge_push_passes_the_part_through_to_the_glow(self):
+ owner = _owner(glow_style="glow", glow=mock.Mock())
+ owner._effect_overlay = mock.Mock(return_value=None)
+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "right", 0.5, False, "end")
+ owner.glow.set_pressure.assert_called_once_with("right", 0.5, False, "end")
+
+ def test_a_corner_push_reaches_the_overlay_with_its_corner(self):
+ """sender.py names the corner in `part` (test_sender.py's CornerTests), and the overlay
+ plays the corner form from it."""
+ owner = _owner(glow_style="rupture")
+ overlay = mock.Mock()
+ owner._effect_overlay = mock.Mock(return_value=overlay)
+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "top", 1.0, True, "top_left")
+ overlay.push.assert_called_once_with("top", 1.0, True, part="top_left")
+
+ def test_a_crossing_carries_crossed_true_through_to_the_overlay(self):
+ owner = _owner(glow_style="rupture")
+ overlay = mock.Mock()
+ owner._effect_overlay = mock.Mock(return_value=overlay)
+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 1.0, True)
+ overlay.push.assert_called_once_with("left", 1.0, True, part=None)
+
+ def test_a_crossing_carries_crossed_true_through_to_the_glow(self):
+ owner = _owner(glow_style="glow", glow=mock.Mock())
+ owner._effect_overlay = mock.Mock(return_value=None)
+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 1.0, True)
+ owner.glow.set_pressure.assert_called_once_with("left", 1.0, True, None)
+
+ def test_edge_glow_switched_off_in_settings_draws_nothing(self):
+ owner = _owner(edge_glow=False, glow=mock.Mock())
+ owner._effect_overlay = mock.Mock(return_value=None)
+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 0.4, False)
+ owner._effect_overlay.assert_not_called()
+ owner.glow.set_pressure.assert_not_called()
+
+ def test_a_closing_window_draws_nothing(self):
+ owner = _owner(glow_style="rupture")
+ owner._closing = True
+ overlay = mock.Mock()
+ owner._effect_overlay = mock.Mock(return_value=overlay)
+ kvm_bridge_win.WindowsApplication._on_pressure(owner, "left", 0.4, False)
+ overlay.push.assert_not_called()
+
+
[email protected](kvm_bridge_win is None, "needs PySide6")
+class ArrivalRoutingTest(unittest.TestCase):
+ """`method` is decided before _on_arrival ever runs, by the inline lambdas that wire
+ receiver.py's and sender.py's arrival_callback in WindowsApplication.__init__
+ (kvm_bridge_win.py: "notch" if edge == "bottom" else "edge", or "switch" if edge is None, for
+ the receiver around line 240; "switch" if edge is None else "edge" for the sender around line
+ 253 -- the sender has no notch of its own, since only the Mac has one). Neither lambda is a
+ separately callable unit, so it is not unit-tested on its own; these tests start from the
+ method it would have produced and check where _on_arrival sends it."""
+
+ def setUp(self):
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ self.app = QApplication.instance() or QApplication([])
+
+ def test_an_edge_crossing_arrival_reaches_the_effects_overlay_when_wanted(self):
+ owner = _owner(glow_style="rupture")
+ overlay = mock.Mock()
+ owner._effect_overlay = mock.Mock(return_value=overlay)
+ kvm_bridge_win.WindowsApplication._on_arrival(owner, "edge", "left", 10.0, 20.0)
+ expected = effect_overlay.logical_point(10.0, 20.0)
+ overlay.arrive.assert_called_once_with("edge", "left", expected)
+
+ def test_a_notch_crossing_arrival_reaches_the_effects_overlay_with_its_own_method(self):
+ """The Mac's notch always lands on this PC's bottom edge (the receiver arrival lambda's
+ own comment: "The Mac's notch crossing lands on this PC's bottom edge"), remapped to
+ method "notch" before this point -- _on_arrival forwards the method name unchanged."""
+ owner = _owner(glow_style="rupture")
+ overlay = mock.Mock()
+ owner._effect_overlay = mock.Mock(return_value=overlay)
+ kvm_bridge_win.WindowsApplication._on_arrival(owner, "notch", "bottom", 10.0, 20.0)
+ expected = effect_overlay.logical_point(10.0, 20.0)
+ overlay.arrive.assert_called_once_with("notch", "bottom", expected)
+
+ def test_an_arrival_under_glow_only_calls_crossed_in_when_an_overlay_already_exists(self):
+ """Glow and Beam are edge styles with no arrival. crossed_in only makes a waiting switch
+ give way, so with no effects window yet there is nothing to tell (see the next test)."""
+ owner = _owner(glow_style="glow")
+ owner._effect_overlay = mock.Mock(return_value=None)
+ owner.effects = mock.Mock()
+ kvm_bridge_win.WindowsApplication._on_arrival(owner, "edge", "left", 10.0, 20.0)
+ owner.effects.crossed_in.assert_called_once()
+
+ def test_an_arrival_under_glow_with_no_overlay_ever_built_calls_nothing(self):
+ owner = _owner(glow_style="glow")
+ owner._effect_overlay = mock.Mock(return_value=None)
+ owner.effects = None
+ kvm_bridge_win.WindowsApplication._on_arrival(owner, "edge", "left", 10.0, 20.0)
+ self.assertIsNone(owner.effects)
+
+ def test_a_switch_arrival_with_no_edge_reaches_the_switch_overlay(self):
+ owner = _owner(shortcut_arrival=True, shortcut_arrival_style="locator")
+ overlay = mock.Mock()
+ owner._switch_overlay = mock.Mock(return_value=overlay)
+ kvm_bridge_win.WindowsApplication._on_arrival(owner, "switch", "", 10.0, 20.0)
+ expected = effect_overlay.logical_point(10.0, 20.0)
+ overlay.switched.assert_called_once_with(expected, "locator")
+
+ def test_a_switch_arrival_does_nothing_when_the_locator_is_off(self):
+ owner = _owner(shortcut_arrival=False)
+ owner._switch_overlay = mock.Mock(return_value=None)
+ kvm_bridge_win.WindowsApplication._on_arrival(owner, "switch", "", 10.0, 20.0)
+ owner._switch_overlay.assert_called_once()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_effect_layouts.py b/win_app/tests/test_effect_layouts.py
new file mode 100644
index 0000000..db83623
--- /dev/null
+++ b/win_app/tests/test_effect_layouts.py
@@ -0,0 +1,322 @@
+"""Every effect on one display of many: monitor layouts side by side, stacked, staggered, left of or
+above the primary, portrait, mixed sizes and three displays. Each move plays on the display the
+pointer is on and no other, framed as that display alone, and lands where the pointer lands.
+Byte-identical in mac_app and win_app."""
+
+import colorsys
+import unittest
+from types import SimpleNamespace
+
+import effects
+
+PALETTE = ["#ff7828", "#ff3264", "#ffb43c"]
+NOTCH = {"x": 771.5, "y": 0.0, "w": 185.0, "h": 32.0, "r": 10.0}
+
+# Desktop-relative (x, y, w, h), as both overlays hand them to the Player. The first display is the
+# one with the notch, at the top middle of it.
+LAYOUTS = {
+ "one": [(0.0, 0.0, 1728.0, 1117.0)],
+ "side by side": [(0.0, 0.0, 1728.0, 1117.0), (1728.0, 0.0, 2560.0, 1440.0)],
+ "stacked": [(416.0, 1440.0, 1728.0, 1117.0), (0.0, 0.0, 2560.0, 1440.0)],
+ "staggered": [(0.0, 400.0, 1728.0, 1117.0), (1728.0, 0.0, 1920.0, 1080.0)],
+ "left of the primary": [(1920.0, 0.0, 1728.0, 1117.0), (0.0, 300.0, 1920.0, 1080.0)],
+ "portrait": [(0.0, 300.0, 1728.0, 1117.0), (1728.0, 0.0, 1080.0, 1920.0)],
+ "three": [(1920.0, 200.0, 1728.0, 1117.0), (0.0, 0.0, 1920.0, 1080.0), (3648.0, 0.0, 1280.0, 1024.0)],
+ "150% beside 100%": [(0.0, 0.0, 2560.0, 1440.0), (2560.0, 0.0, 1706.67, 960.0)],
+}
+
+
+def box(displays):
+ return (max(x + w for x, _y, w, _h in displays), max(y + h for _x, y, _w, h in displays))
+
+
+def notch_on(displays):
+ x, y, _w, _h = displays[0]
+ return dict(NOTCH, x=x + NOTCH["x"], y=y)
+
+
+def edge_region(display, edge, desktop=None):
+ """The engine's strip for `edge` of `display`; `desktop` stretches it along the whole box, as
+ the Mac's engine measures an edge."""
+ x, y, w, h = display
+ if desktop is not None and edge in ("left", "right"):
+ y, h = 0.0, desktop[1]
+ if desktop is not None and edge in ("top", "bottom"):
+ x, w = 0.0, desktop[0]
+ strips = {"left": (x, y, 1.0, h), "right": (x + w - 1.0, y, 1.0, h), "top": (x, y, w, 1.0), "bottom": (x, y + h - 1.0, w, 1.0)}
+ rx, ry, rw, rh = strips[edge]
+ return {"kind": "edge", "edge": edge, "x": rx, "y": ry, "w": rw, "h": rh}
+
+
+def corner_region(display, corner):
+ x, y, w, h = display
+ vertical, horizontal = corner.split("_")
+ return {"kind": "corner", "edge": horizontal, "corner": corner, "x": x if horizontal == "left" else x + w - 8.0,
+ "y": y if vertical == "top" else y + h - 8.0, "w": 8.0, "h": 8.0}
+
+
+def corner_point(display, corner):
+ x, y, w, h = display
+ vertical, horizontal = corner.split("_")
+ return (x if horizontal == "left" else x + w - 1.0, y if vertical == "top" else y + h - 1.0)
+
+
+def moves(display, desktop, first):
+ """(name, a function that feeds a Player at `now`) for every move on `display`."""
+ x, y, w, h = display
+ out = []
+ for edge in ("left", "right", "top", "bottom"):
+ region = edge_region(display, edge, desktop)
+ own = edge_region(display, edge)
+ for along in (0.0, 0.5, 1.0):
+ at = (own["x"] + own["w"] * along if edge in ("top", "bottom") else own["x"],
+ own["y"] + own["h"] * along if edge in ("left", "right") else own["y"])
+ at = (min(at[0], x + w - 1.0), min(at[1], y + h - 1.0))
+ out.append((f"push {edge} {along}", lambda p, now, region=region, at=at: p.push(now, "edge", region, at, 0.6, 2, display=display)))
+ out.append((f"cross {edge} {along}", lambda p, now, region=region, at=at: (p.push(now, "edge", region, at, 1.0, display=display), p.cross(now))))
+ out.append((f"arrive {edge} {along}", lambda p, now, at=at, edge=edge: p.arrive(now, "edge", at, edge, display)))
+ third = dict(own)
+ if edge in ("left", "right"):
+ third.update(y=y + 2.0 * h / 3.0, h=h / 3.0)
+ at = (own["x"], y + 5.0 * h / 6.0)
+ else:
+ third.update(x=x + 2.0 * w / 3.0, w=w / 3.0)
+ at = (x + 5.0 * w / 6.0, own["y"])
+ out.append((f"part {edge}", lambda p, now, third=third, at=at: p.push(now, "edge", third, at, 0.6, 2, display=display)))
+ for corner in ("top_left", "top_right", "bottom_left", "bottom_right"):
+ region, at = corner_region(display, corner), corner_point(display, corner)
+ out.append((f"corner {corner}", lambda p, now, region=region, at=at: (p.push(now, "corner", region, at, 1.0, display=display), p.cross(now))))
+ out.append((f"switch near {corner}", lambda p, now, at=at: p.switched(now - effects.SWITCH_SETTLE_S, at, "left", None, display)))
+ if first:
+ region = {"kind": "notch", "edge": "top", "x": x + NOTCH["x"], "y": y, "w": NOTCH["w"], "h": 1.0}
+ at = (x + NOTCH["x"] + NOTCH["w"] / 2.0, y)
+ out.append(("notch", lambda p, now, region=region, at=at: (p.push(now, "notch", region, at, 1.0, display=display), p.cross(now))))
+ out.append(("arrive under the notch", lambda p, now, at=(x + w / 2.0, y + 2.0): p.arrive(now, "edge", at, "top", display)))
+ return out
+
+
+def inside(box_, display):
+ x, y, w, h = display
+ return box_[0] >= x and box_[1] >= y and box_[2] <= x + w and box_[3] <= y + h
+
+
+class EveryLayoutTests(unittest.TestCase):
+ def test_every_move_draws_only_on_the_pointers_display(self):
+ styles = [effects.effect(effect_id) for effect_id in effects.EFFECT_IDS] + [effects.LOCATOR]
+ for layout, displays in LAYOUTS.items():
+ desktop = box(displays)
+ notch = notch_on(displays)
+ for index, display in enumerate(displays):
+ edge = (display[0], display[1], display[0] + display[2], display[1] + display[3])
+ for name, feed in moves(display, desktop, index == 0):
+ for fx in styles:
+ if fx is effects.LOCATOR and not name.startswith("switch"):
+ continue
+ with self.subTest(layout=layout, display=index, move=name, effect=fx.id):
+ player = effects.Player()
+ feed(player, 10.0)
+ drawn = 0
+ for step in (0, 14, 35):
+ for pen in player.frames(10.0 + step / 60.0, fx, (desktop[0], desktop[1], "mac"),
+ PALETTE, False, True, notch):
+ drawn += 1
+ self.assertEqual(pen.clip, edge)
+ self.assertTrue(inside(pen.bounds, display), pen.bounds)
+ self.assertGreater(drawn, 0)
+
+ def test_an_effect_is_framed_as_its_display_alone(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append((s.screen.w, s.screen.h, s.point.x, s.point.y, s.edge)), 0.0, 0.5)
+ player = effects.Player()
+ player.arrive(0.0, "edge", (1730.0, 500.0), "left", (1728.0, 0.0, 1920.0, 1080.0))
+ player.frames(0.1, fx, (3648.0, 1517.0, "mac"), PALETTE, False, True)
+ self.assertEqual(seen, [(1920.0, 1080.0, 2.0, 500.0, "left")])
+
+ def test_an_edge_strip_along_the_whole_desktop_is_cut_to_the_display(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: seen.append(vars(s.region)),
+ lambda pen, s: None, 0.5, 0.0)
+ player = effects.Player()
+ display = (1728.0, 0.0, 1920.0, 1080.0)
+ player.push(0.0, "edge", {"kind": "edge", "edge": "right", "x": 3647.0, "y": 0.0, "w": 1.0, "h": 1517.0},
+ (3647.0, 500.0), 0.5, display=display)
+ player.frames(0.0, fx, (3648.0, 1517.0, "mac"), PALETTE, False, True)
+ self.assertEqual((seen[0]["x"], seen[0]["y"], seen[0]["h"]), (1919.0, 0.0, 1080.0))
+
+ def test_the_notch_is_only_seen_on_its_own_display(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append(getattr(s, "notch", None)), 0.0, 0.5)
+ displays = LAYOUTS["left of the primary"]
+ for display in displays:
+ player = effects.Player()
+ player.arrive(0.0, "edge", (display[0] + display[2] / 2.0, display[1] + 2.0), "top", display)
+ player.frames(0.1, fx, (3648.0, 1380.0, "mac"), PALETTE, False, True, notch_on(displays))
+ self.assertEqual((seen[0].x, seen[0].y), (NOTCH["x"], 0.0))
+ self.assertIsNone(seen[1])
+
+
+class AuditFindingTests(unittest.TestCase):
+ def test_a_departure_carries_no_tick_from_its_push(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: seen.append(s.tick), lambda pen, s: None, 0.5, 0.0)
+ player = effects.Player()
+ region = edge_region((0.0, 0.0, 1728.0, 1117.0), "right")
+ player.push(0.0, "edge", region, (1727.0, 500.0), 0.8, 3)
+ player.frames(0.01, fx, (1728.0, 1117.0, "mac"), PALETTE, False, True)
+ player.cross(0.02)
+ player.frames(0.05, fx, (1728.0, 1117.0, "mac"), PALETTE, False, True)
+ self.assertEqual((seen[0].index, seen[1]), (3, None))
+
+ def test_a_push_draining_between_events_stays_on_its_display(self):
+ player = effects.Player()
+ display = (1728.0, 0.0, 1920.0, 1080.0)
+ region = edge_region(display, "right")
+ player.push(0.0, "edge", region, (3647.0, 500.0), 0.6, display=display)
+ player.push(0.1, "edge", region, (3647.0, 500.0), 0.4)
+ self.assertEqual(player.depart["display"], display)
+
+ def test_a_gauge_switch_near_a_corner_draws_no_corner_register(self):
+ def ops(at):
+ s = effects.state(1728.0, 1117.0, "mac", "switch", PALETTE, point=effects.point(*at),
+ edge=effects.nearest_edge(at[0], at[1], 1728.0, 1117.0), since=0.2)
+ return len(effects.draw(effects.effect("gauge"), "arrive", s).ops)
+ self.assertEqual(ops((5.0, 5.0)), ops((800.0, 500.0)))
+
+
+class LegibleColourTests(unittest.TestCase):
+ @staticmethod
+ def lightness(colour):
+ r, g, b, _a = effects.parse_colour(colour)
+ return colorsys.rgb_to_hls(r, g, b)[1]
+
+ def test_dark_colours_are_lifted_on_dark_and_keep_their_hue(self):
+ ink = effects.pack("indigo_ink")[1]
+ lifted = effects.legible(ink, True, effects.effect("flint"))
+ self.assertTrue(all(self.lightness(c) >= effects.DARK_FLOOR - 0.01 for c in lifted))
+ before = colorsys.rgb_to_hls(*effects.parse_colour(ink[0])[:3])[0]
+ after = colorsys.rgb_to_hls(*effects.parse_colour(lifted[0])[:3])[0]
+ self.assertAlmostEqual(before, after, delta=0.02)
+ self.assertEqual(lifted[-1], ink[-1])
+
+ def test_pale_colours_come_down_on_light_only_for_effects_that_draw_them_as_given(self):
+ pearl = effects.pack("pearl")[1]
+ for effect_id in ("hyperdrive", "capillary"):
+ drawn = effects.legible(pearl, False, effects.effect(effect_id))
+ self.assertTrue(all(self.lightness(c) <= effects.LIGHT_CEILING + 0.01 for c in drawn))
+ for effect_id in ("film", "flint", "gauge"):
+ self.assertEqual(effects.legible(pearl, False, effects.effect(effect_id)), list(pearl))
+
+
+class DisplayForTests(unittest.TestCase):
+ DISPLAYS = LAYOUTS["staggered"]
+
+ def test_a_point_on_a_display_stays_where_it_is(self):
+ self.assertEqual(effects.display_for((1800.0, 20.0), self.DISPLAYS), (self.DISPLAYS[1], (1800.0, 20.0)))
+
+ def test_a_point_on_no_display_lands_on_the_nearest(self):
+ # Above the shorter display, where an arrival along the staggered desktop's top edge lands.
+ display, at = effects.display_for((500.0, 2.0), self.DISPLAYS)
+ self.assertEqual((display, at), (self.DISPLAYS[0], (500.0, 400.0)))
+
+ def test_the_far_edge_is_inside(self):
+ display, at = effects.display_for((5000.0, 5000.0), self.DISPLAYS)
+ self.assertEqual((display, at), (self.DISPLAYS[1], (3647.0, 1079.0)))
+
+
+class InkCornerTests(unittest.TestCase):
+ def test_every_corner_draws_on_screen(self):
+ w, h = 1728.0, 1117.0
+ for effect_id in ("capillary", "viscous_drop", "sumi_bloom"):
+ for corner in ("top_left", "top_right", "bottom_left", "bottom_right"):
+ for reduced in (False, True):
+ with self.subTest(effect=effect_id, corner=corner, reduced=reduced):
+ display = (0.0, 0.0, w, h)
+ region = corner_region(display, corner)
+ s = effects.state(w, h, "mac", "corner", PALETTE, reduced=reduced, region=SimpleNamespace(**region),
+ point=effects.point(*corner_point(display, corner)), along=0.0, pressure=0.8,
+ tick=None, since=None)
+ pen = effects.draw(effects.effect(effect_id), "depart", s)
+ points = [(seg[-2], seg[-1]) for op in pen.ops for seg in op[1] if len(seg) > 1]
+ on = [p for p in points if -1.0 <= p[0] <= w + 1.0 and -1.0 <= p[1] <= h + 1.0]
+ self.assertGreater(len(on) / len(points), 0.9)
+
+
+class CornerSideTests(unittest.TestCase):
+ def test_a_corner_draws_the_same_whichever_of_its_sides_leads_to_the_other_machine(self):
+ # The region's edge is the side the other machine is on: the corner's horizontal side on
+ # a machine beside it, its vertical side on one above or below.
+ w, h = 2560.0, 1440.0
+ display = (0.0, 0.0, w, h)
+ for effect_id in effects.EFFECT_IDS:
+ for corner in ("top_left", "top_right", "bottom_left", "bottom_right"):
+ sizes = []
+ for side in corner.split("_"):
+ region = dict(corner_region(display, corner), edge=side)
+ s = effects.state(w, h, "windows", "corner", PALETTE, region=SimpleNamespace(**region),
+ point=effects.point(*corner_point(display, corner)), along=0.0, pressure=0.8,
+ tick=None, since=None)
+ b = effects.draw(effects.effect(effect_id), "depart", s).bounds
+ sizes.append((round(min(b[2], w) - max(b[0], 0.0)), round(min(b[3], h) - max(b[1], 0.0))))
+ with self.subTest(effect=effect_id, corner=corner):
+ self.assertEqual(sizes[0], sizes[1])
+
+
+class ClassicPreviewTests(unittest.TestCase):
+ def test_glow_and_beam_play_at_every_place_the_preview_shows(self):
+ for style in ("glow", "beam"):
+ fx = effects.preview_effect(style)
+ for method in ("edge", "corner"):
+ with self.subTest(style=style, method=method):
+ pushing = effects.preview_scene(fx, 1.8, method, PALETTE)
+ through = effects.preview_scene(fx, 2.3, method, PALETTE)
+ self.assertTrue(pushing["pens"])
+ self.assertTrue(through["pens"])
+ # The Mac's notch style plays at the notch instead.
+ self.assertFalse(effects.preview_scene(fx, 1.8, "notch", PALETTE)["pens"])
+
+ def test_a_corner_lights_both_its_walls_on_the_mac_screen(self):
+ fx = effects.preview_effect("glow")
+ pen = effects.preview_scene(fx, 2.0, "corner", PALETTE)["pens"][0]
+ w, h = effects.PREVIEW_SCREEN
+ self.assertLess(pen.bounds[0], w - effects.CLASSIC_ARM + 10)
+ self.assertGreater(pen.bounds[3], effects.CLASSIC_ARM - 10)
+ self.assertLessEqual(pen.bounds[2], w + 4)
+
+ def test_only_the_styles_have_a_preview(self):
+ self.assertIsNone(effects.preview_effect("nonsense"))
+ self.assertEqual(effects.preview_effect("flint").id, "flint")
+
+
+class LengthTests(unittest.TestCase):
+ def test_a_longer_length_plays_the_crossing_and_the_landing_for_longer(self):
+ fx = effects.effect("rupture")
+ region = {"kind": "edge", "edge": "right", "x": 1727.0, "y": 0.0, "w": 1.0, "h": 1117.0}
+ lasted = {}
+ for length in ("short", "normal", "long"):
+ player = effects.Player(effects.pace(length))
+ player.push(0.0, "edge", region, (1727.0, 500.0), 0.9)
+ player.cross(0.0)
+ player.arrive(0.0, "edge", (1.0, 500.0), "left")
+ t = 0.0
+ while player.frames(t, fx, (1728.0, 1117.0, "mac"), PALETTE, False, True) and t < 5.0:
+ t += 1 / 60
+ lasted[length] = t
+ self.assertLess(lasted["short"], lasted["normal"])
+ self.assertLess(lasted["normal"], lasted["long"])
+ self.assertAlmostEqual(lasted["long"] / lasted["normal"], 1.5, delta=0.1)
+
+ def test_the_push_follows_the_hand_whatever_the_length(self):
+ fx = effects.effect("flint")
+ region = {"kind": "edge", "edge": "right", "x": 1727.0, "y": 0.0, "w": 1.0, "h": 1117.0}
+ drawn = []
+ for length in ("short", "long"):
+ player = effects.Player(effects.pace(length))
+ player.push(0.0, "edge", region, (1727.0, 500.0), 0.6)
+ drawn.append(player.frames(0.2, fx, (1728.0, 1117.0, "mac"), PALETTE, False, True)[0].bounds)
+ self.assertEqual(drawn[0], drawn[1])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_effect_overlay.py b/win_app/tests/test_effect_overlay.py
new file mode 100644
index 0000000..84ace05
--- /dev/null
+++ b/win_app/tests/test_effect_overlay.py
@@ -0,0 +1,366 @@
+"""The crossing effects' replay into QPainter, against a fake painter that records what it was asked
+to draw and in what state, and the overlay window's attributes."""
+
+import math
+import os
+import unittest
+from dataclasses import replace
+from types import SimpleNamespace
+
+import effects
+from return_edge import Rect
+
+try:
+ from PySide6.QtCore import QPointF, QRect, Qt
+ from PySide6.QtGui import QConicalGradient, QLinearGradient, QPainter, QPainterPath, QRadialGradient
+
+ import effect_overlay
+except ImportError: # PySide6 is only in the Windows venv
+ effect_overlay = None
+
+
+class FakePainter:
+ """Records every draw with the opacity and composition it was made in, and keeps save/restore
+ as QPainter does."""
+
+ def __init__(self):
+ self.opacity = 1.0
+ self.mode = "source-over-at-start"
+ self._stack = []
+ self.draws = []
+ self.clips = []
+
+ def setClipRect(self, rect):
+ self.clips.append((rect.x(), rect.y(), rect.width(), rect.height()))
+
+ def save(self):
+ self._stack.append((self.opacity, self.mode))
+
+ def restore(self):
+ self.opacity, self.mode = self._stack.pop()
+
+ def setOpacity(self, value):
+ self.opacity = value
+
+ def setCompositionMode(self, mode):
+ self.mode = mode
+
+ def fillPath(self, path, brush):
+ self.draws.append(("fill", path, brush, self.opacity, self.mode))
+
+ def strokePath(self, path, pen):
+ self.draws.append(("stroke", path, pen, self.opacity, self.mode))
+
+
+def gradient(kind, geometry, stops=((0.0, (1, 0, 0, 1)), (1.0, (0, 0, 1, 1)))):
+ out = effects.Gradient(kind, geometry)
+ for offset, colour in stops:
+ out.addColorStop(offset, colour)
+ return out
+
+
+def elements(path):
+ return [(path.elementAt(i).type, round(path.elementAt(i).x, 3), round(path.elementAt(i).y, 3))
+ for i in range(path.elementCount())]
+
+
[email protected](effect_overlay is None, "needs PySide6")
+class ReplayTests(unittest.TestCase):
+ def setUp(self):
+ from PySide6.QtWidgets import QApplication
+
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ self.app = QApplication.instance() or QApplication([])
+
+ def pen_of(self, ops):
+ pen = effects.Pen()
+ pen.ops = list(ops)
+ return pen
+
+ def test_every_op_restores_opacity_and_composition(self):
+ linear = gradient("linear", (0, 0, 10, 0))
+ ops = [
+ ("fill", [("M", 0, 0), ("L", 10, 0), ("L", 10, 10), ("Z",)], (1, 0, 0, 1), 0.5, "lighter", "nonzero"),
+ ("stroke", [("M", 0, 0), ("L", 10, 10)], linear, 0.25, "source-over", 3.0, "round", "bevel"),
+ ("fill", [("M", 0, 0), ("L", 5, 0), ("L", 5, 5), ("Z",)], (0, 1, 0, 1), 1.0, "source-over", "evenodd"),
+ ]
+ painter = FakePainter()
+ effect_overlay.replay(painter, [self.pen_of(ops)])
+ self.assertEqual((painter.opacity, painter.mode), (1.0, "source-over-at-start"))
+ self.assertEqual(painter._stack, [])
+ self.assertEqual([d[0] for d in painter.draws], ["fill", "stroke", "fill"])
+ self.assertEqual([d[3] for d in painter.draws], [0.5, 0.25, 1.0])
+ self.assertEqual(painter.draws[0][4], QPainter.CompositionMode.CompositionMode_Plus)
+ self.assertEqual(painter.draws[1][4], QPainter.CompositionMode.CompositionMode_SourceOver)
+ self.assertEqual(painter.draws[0][1].fillRule(), Qt.FillRule.WindingFill)
+ self.assertEqual(painter.draws[2][1].fillRule(), Qt.FillRule.OddEvenFill)
+
+ def test_a_stroke_carries_width_cap_and_join(self):
+ for cap, join, qcap, qjoin in (
+ ("butt", "miter", Qt.PenCapStyle.FlatCap, Qt.PenJoinStyle.MiterJoin),
+ ("round", "round", Qt.PenCapStyle.RoundCap, Qt.PenJoinStyle.RoundJoin),
+ ("square", "bevel", Qt.PenCapStyle.SquareCap, Qt.PenJoinStyle.BevelJoin),
+ ):
+ painter = FakePainter()
+ op = ("stroke", [("M", 0, 0), ("L", 4, 4)], (1, 1, 1, 1), 1.0, "source-over", 2.5, cap, join)
+ effect_overlay.replay(painter, [self.pen_of([op])])
+ stroke = painter.draws[0][2]
+ self.assertEqual((stroke.widthF(), stroke.capStyle(), stroke.joinStyle()), (2.5, qcap, qjoin))
+
+ def test_every_path_segment(self):
+ path = effect_overlay.qpath([("M", 1, 2), ("L", 3, 4), ("Q", 5, 6, 7, 8), ("C", 9, 10, 11, 12, 13, 14), ("Z",)])
+ kinds = [kind for kind, _x, _y in elements(path)]
+ Move, Line, Curve, Data = (QPainterPath.ElementType.MoveToElement, QPainterPath.ElementType.LineToElement,
+ QPainterPath.ElementType.CurveToElement, QPainterPath.ElementType.CurveToDataElement)
+ # Qt stores a quad as a cubic; the close is a line back to the start.
+ self.assertEqual(kinds, [Move, Line, Curve, Data, Data, Curve, Data, Data, Line])
+ self.assertEqual(elements(path)[-2][1:], (13.0, 14.0))
+ self.assertEqual(elements(path)[-1][1:], (1.0, 2.0))
+
+ def test_a_line_after_a_close_carries_on_from_the_subpath_start(self):
+ path = effect_overlay.qpath([("M", 5, 5), ("L", 10, 5), ("Z",), ("L", 5, 10)])
+ self.assertEqual(elements(path)[-2][1:], (5.0, 5.0))
+ self.assertEqual(elements(path)[-1][1:], (5.0, 10.0))
+
+ def test_every_paint_kind(self):
+ colour = (0.2, 0.4, 0.6, 0.8)
+ linear = gradient("linear", (0, 0, 10, 0))
+ radial = gradient("radial", (1, 2, 3, 4, 5, 6))
+ conic = gradient("conic", (math.pi / 2, 7, 8))
+ ops = [("fill", [("M", 0, 0), ("L", 1, 1), ("L", 0, 1), ("Z",)], paint, 1.0, "source-over", "nonzero")
+ for paint in (colour, linear, radial, conic)]
+ painter = FakePainter()
+ effect_overlay.replay(painter, [self.pen_of(ops)])
+ brushes = [draw[2] for draw in painter.draws]
+ self.assertEqual(tuple(round(v, 4) for v in brushes[0].color().getRgbF()), colour)
+ self.assertIsInstance(brushes[1].gradient(), QLinearGradient)
+ self.assertEqual((brushes[1].gradient().start(), brushes[1].gradient().finalStop()), (QPointF(0, 0), QPointF(10, 0)))
+ radial_q = brushes[2].gradient()
+ self.assertIsInstance(radial_q, QRadialGradient)
+ # canvas's first circle is Qt's focal circle; its second is Qt's centre circle.
+ self.assertEqual((radial_q.focalPoint(), radial_q.focalRadius()), (QPointF(1, 2), 3))
+ self.assertEqual((radial_q.center(), radial_q.centerRadius()), (QPointF(4, 5), 6))
+ conic_q = brushes[3].gradient()
+ self.assertIsInstance(conic_q, QConicalGradient)
+ self.assertEqual(conic_q.center(), QPointF(7, 8))
+ self.assertAlmostEqual(conic_q.angle() % 360.0, 270.0)
+ # Reversed: canvas's last stop is Qt's first.
+ self.assertEqual([round(p, 6) for p, _c in conic_q.stops()], [0.0, 1.0])
+ self.assertEqual(conic_q.stops()[0][1].getRgbF(), (0.0, 0.0, 1.0, 1.0))
+
+ def test_one_qt_gradient_per_gradient_per_frame(self):
+ shared = gradient("linear", (0, 0, 10, 0))
+ op = ("fill", [("M", 0, 0), ("L", 1, 1), ("L", 0, 1), ("Z",)], shared, 1.0, "source-over", "nonzero")
+ painter = FakePainter()
+ effect_overlay.replay(painter, [self.pen_of([op, op]), self.pen_of([op])])
+ self.assertEqual(len({id(draw[2]) for draw in painter.draws}), 1)
+
+ def test_a_hard_stop_keeps_both_colours(self):
+ stops = effect_overlay._stops([(0.0, "a"), (0.5, "b"), (0.5, "c"), (1.0, "d")])
+ self.assertEqual([colour for _o, colour in stops], ["a", "b", "c", "d"])
+ self.assertLess(stops[1][0], stops[2][0])
+
+ def test_a_real_effect_replays_into_a_real_painter(self):
+ from PySide6.QtGui import QImage
+
+ image = QImage(900, 500, QImage.Format.Format_ARGB32_Premultiplied)
+ image.fill(0)
+ painter = QPainter(image)
+ for effect_id in effects.EFFECT_IDS:
+ for t in (1.2, 2.5):
+ scene = effects.preview_scene(effects.effect(effect_id), t, "edge", ["#ff0000", "#00ff00"])
+ effect_overlay.replay(painter, scene["pens"])
+ painter.end()
+
+
[email protected](effect_overlay is None, "needs PySide6")
+class GeometryTests(unittest.TestCase):
+ def test_union_of_bounds(self):
+ a, b = effects.Pen(), effects.Pen()
+ a.bounds, b.bounds = (0, 5, 10, 20), (-3, 8, 4, 30)
+ self.assertEqual(effect_overlay.union_bounds([a, b, effects.Pen()]), (-3, 5, 10, 30))
+ self.assertIsNone(effect_overlay.union_bounds([]))
+
+ def test_the_region_is_the_owning_displays_edge_relative_to_the_desktop(self):
+ rects = [Rect(-1920, 0, 1920, 1080), Rect(0, -200, 2560, 1440)]
+ origin = (-1920, -200)
+ self.assertEqual(effect_overlay.edge_region("left", rects, origin),
+ {"kind": "edge", "edge": "left", "x": 0.0, "y": 200.0, "w": 1.0, "h": 1080.0})
+ self.assertEqual(effect_overlay.edge_region("right", rects, origin),
+ {"kind": "edge", "edge": "right", "x": 4479.0, "y": 0.0, "w": 1.0, "h": 1440.0})
+ self.assertEqual(effect_overlay.edge_region("top", rects, origin)["y"], 0.0)
+ self.assertEqual(effect_overlay.edge_region("bottom", rects, origin)["y"], 1439.0)
+
+ def test_a_push_on_a_shorter_displays_exposed_edge_lights_that_display(self):
+ # Side by side, the 1080-high display's bottom edge crosses too, 360 points above the
+ # desktop's bottom; the effect belongs there, not on the taller display beside it.
+ rects = [Rect(0, 0, 1920, 1080), Rect(1920, 0, 2560, 1440)]
+ region = effect_overlay.edge_region("bottom", rects, (0, 0), (100, 1079))
+ self.assertEqual((region["x"], region["y"], region["w"]), (0.0, 1079.0, 1920.0))
+
+ def test_part_of_the_edge_lights_only_the_third_being_pushed(self):
+ rects = [Rect(0, 0, 1920, 1080)]
+ region = effect_overlay.edge_region("right", rects, (0, 0), (1919, 900), "end")
+ self.assertEqual((region["x"], region["y"], region["h"]), (1919.0, 720.0, 360.0))
+ region = effect_overlay.edge_region("top", rects, (0, 0), (900, 0), "middle")
+ self.assertEqual((region["x"], region["w"]), (640.0, 640.0))
+
+ def test_a_third_is_the_display_under_the_pointers_own(self):
+ # Stacked, each display's left edge has its own thirds, as PartEdge measures them.
+ rects = [Rect(0, 0, 1920, 1080), Rect(0, 1080, 1920, 1080)]
+ region = effect_overlay.edge_region("left", rects, (0, 0), (0, 1500), "middle")
+ self.assertEqual((region["y"], region["h"]), (1440.0, 360.0))
+ region = effect_overlay.edge_region("left", rects, (0, 0), (0, 100), "end")
+ self.assertEqual((region["y"], region["h"]), (720.0, 360.0))
+
+
[email protected](effect_overlay is None, "needs PySide6")
+class OverlayTests(unittest.TestCase):
+ def setUp(self):
+ from PySide6.QtWidgets import QApplication
+
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ self.app = QApplication.instance() or QApplication([])
+
+ def test_the_window_never_takes_input_focus_or_a_taskbar_button(self):
+ overlay = effect_overlay.EffectOverlay()
+ flags = overlay.windowFlags()
+ for flag in (Qt.WindowType.Tool, Qt.WindowType.FramelessWindowHint, Qt.WindowType.WindowStaysOnTopHint,
+ Qt.WindowType.WindowTransparentForInput, Qt.WindowType.WindowDoesNotAcceptFocus):
+ self.assertTrue(flags & flag, flag)
+ self.assertTrue(overlay.testAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating))
+ self.assertTrue(overlay.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground))
+
+ def test_a_failing_effect_logs_once_and_turns_the_effects_off(self):
+ failures = []
+ overlay = effect_overlay.EffectOverlay(on_failure=lambda: failures.append(1))
+ overlay.configure("skin", "signal")
+
+ def boom(pen, s):
+ raise RuntimeError("design bug")
+
+ overlay._fx = effects.Effect("boom", "Boom", "quiet", "", boom, boom, 0.5, 0.5)
+ with self.assertLogs(effect_overlay.LOGGER, "ERROR") as logged:
+ overlay.push("right", 0.6, False, QPointF(10, 10))
+ overlay._tick()
+ self.assertEqual(len(logged.records), 1)
+ self.assertIn("skin", logged.output[0])
+ self.assertTrue(overlay.failed)
+ self.assertEqual(failures, [1])
+ self.assertTrue(overlay.isHidden())
+ overlay.push("right", 0.6, False, QPointF(10, 10))
+ self.assertFalse(overlay.player.busy)
+
+ def test_effects_that_cannot_load_turn_themselves_off(self):
+ failures = []
+ overlay = effect_overlay.EffectOverlay(on_failure=lambda: failures.append(1))
+ real = effects.effect
+
+ def missing(_effect_id):
+ raise ImportError("No module named 'fx_membrane'")
+
+ effects.effect = missing
+ try:
+ with self.assertLogs(effect_overlay.LOGGER, "ERROR"):
+ overlay.configure("skin", "signal")
+ finally:
+ effects.effect = real
+ self.assertTrue(overlay.failed)
+ self.assertEqual(failures, [1])
+ overlay.push("right", 0.6, False, QPointF(10, 10))
+ self.assertFalse(overlay.player.busy)
+
+ def test_a_switch_with_glow_or_beam_plays_the_locator_where_the_pointer_is(self):
+ for style in ("glow", "beam"):
+ with self.subTest(style=style):
+ overlay = effect_overlay.EffectOverlay()
+ overlay.configure(style, "sunset")
+ self.assertIs(overlay._fx, effects.LOCATOR)
+ overlay.switched(QPointF(300, 200))
+ arrival = overlay.player.arrival
+ self.assertTrue(arrival["switch"])
+ desk = overlay._desk
+ self.assertEqual(arrival["at"], (300 - desk.x(), 200 - desk.y()))
+ overlay.stop()
+
+ def test_a_switch_with_an_effect_plays_that_effect(self):
+ overlay = effect_overlay.EffectOverlay()
+ overlay.configure("rupture", "neon")
+ overlay.switched(QPointF(300, 200))
+ self.assertEqual(overlay._fx.id, "rupture")
+ self.assertEqual(overlay.player.arrival["method"], "switch")
+ overlay.stop()
+
+ def test_the_app_shows_a_switch_only_with_both_switches_on(self):
+ import app_config
+ import kvm_bridge_win
+
+ def overlay_for(**change):
+ config = replace(app_config.default_config(), glow_style="glow", **change)
+ owner = SimpleNamespace(_closing=False, _config=config, effects=None, _on_effects_failed=lambda: None)
+ return kvm_bridge_win.WindowsApplication._switch_overlay(owner)
+
+ self.assertIsNotNone(overlay_for())
+ self.assertIsNone(overlay_for(shortcut_arrival=False))
+ self.assertIsNone(overlay_for(edge_glow=False))
+
+ def test_the_window_margin_stops_at_a_pens_display(self):
+ pen = effects.Pen()
+ pen.fillRect(100, 100, 50, 50)
+ pen.bounds, pen.clip = (100.0, 100.0, 150.0, 150.0), (100.0, 0.0, 400.0, 400.0)
+ self.assertEqual(effect_overlay.union_bounds([pen], 2.0), (100.0, 98.0, 152.0, 152.0))
+
+ def test_a_pen_that_names_its_display_is_drawn_inside_it(self):
+ pen = effects.Pen()
+ pen.fillRect(0, 0, 50, 50)
+ pen.clip = (10.0, 20.0, 110.0, 220.0)
+ painter = FakePainter()
+ effect_overlay.replay(painter, [pen])
+ self.assertEqual(painter.clips, [(10.0, 20.0, 100.0, 200.0)])
+ self.assertEqual(painter._stack, [])
+
+ def test_each_event_plays_on_the_display_under_the_pointer(self):
+ overlay = effect_overlay.EffectOverlay()
+ overlay.configure("skin", "signal")
+ overlay.arrive("edge", "left", QPointF(10, 10))
+ # A 150% display beside a 100% one, as Qt's logical geometry has them.
+ overlay._displays = [(0.0, 0.0, 2560.0, 1440.0), (2560.0, 0.0, 1706.0, 960.0)]
+ overlay._desk = QRect(0, 0, 4266, 1440)
+ overlay.arrive("edge", "left", QPointF(3000, 1300))
+ arrival = overlay.player.arrival
+ overlay.stop()
+ self.assertEqual((arrival["display"], arrival["at"]), ((2560.0, 0.0, 1706.0, 960.0), (3000.0, 959.0)))
+
+ def test_the_event_that_starts_an_effect_draws_its_first_frame(self):
+ overlay = effect_overlay.EffectOverlay()
+ overlay.configure("rupture", "neon")
+ overlay.arrive("edge", "left", QPointF(2, 200))
+ drawn = bool(overlay._pens)
+ overlay.stop()
+ self.assertTrue(drawn)
+
+ def test_a_corner_push_plays_the_corner_form_on_its_display(self):
+ overlay = effect_overlay.EffectOverlay()
+ overlay.configure("hyperdrive", "neon")
+ overlay.push("left", 0.5, False, QPointF(1, 1), part="top_left")
+ depart = overlay.player.depart
+ overlay.stop()
+ self.assertEqual((depart["method"], depart["region"]["kind"], depart["region"]["corner"]),
+ ("corner", "corner", "top_left"))
+ self.assertEqual((depart["region"]["w"], depart["region"]["h"]), (8.0, 8.0))
+
+ def test_a_push_ticks_each_quarter_once(self):
+ overlay = effect_overlay.EffectOverlay()
+ overlay.configure("skin", "signal")
+ seen = []
+ real_push = overlay.player.push
+ overlay.player.push = lambda now, method, region, at, pressure, tick=None, display=None: (
+ seen.append(tick), real_push(now, method, region, at, pressure, tick, display))
+ for pressure in (0.1, 0.3, 0.3, 0.55, 0.8, 0.9):
+ overlay.push("right", pressure, False, QPointF(10, 10))
+ overlay.stop()
+ self.assertEqual([tick for tick in seen if tick], [1, 2, 3])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_firewall_first.py b/win_app/tests/test_firewall_first.py
new file mode 100644
index 0000000..ade0fe0
--- /dev/null
+++ b/win_app/tests/test_firewall_first.py
@@ -0,0 +1,60 @@
+import sys
+import unittest
+from types import SimpleNamespace
+from unittest import mock
+
+
[email protected](sys.platform == "win32", "the app module needs Windows")
+class RulesBeforeListeningTests(unittest.TestCase):
+ """A listener Windows has no rule for makes it ask, and Allow there opens every network."""
+
+ def owner(self, events):
+ import kvm_bridge_win
+
+ owner = SimpleNamespace(
+ update_checker=SimpleNamespace(start=lambda: None),
+ _firewall_target=lambda: ("C:\\Beamer\\Beamer.exe", 24820),
+ bridge=SimpleNamespace(rules_ready=SimpleNamespace(emit=lambda: events.append("listen"))),
+ _listen=lambda: events.append("listen"),
+ )
+ owner._rules_then_listen = lambda: kvm_bridge_win.WindowsApplication._rules_then_listen(owner)
+ return kvm_bridge_win, owner
+
+ def status(self, allowed=False, blocked=False, error=""):
+ return SimpleNamespace(allowed=allowed, blocked=blocked, error=error)
+
+ def test_missing_rules_are_added_before_anything_listens(self):
+ events = []
+ module, owner = self.owner(events)
+ with mock.patch.object(module.firewall_win, "status", return_value=self.status()), \
+ mock.patch.object(module.firewall_win, "repair", side_effect=lambda *a: events.append("rules")):
+ owner._rules_then_listen()
+ self.assertEqual(events, ["rules", "listen"])
+
+ def test_an_existing_rule_or_a_block_is_left_alone(self):
+ for existing in (self.status(allowed=True), self.status(blocked=True), self.status(error="no PowerShell")):
+ events = []
+ module, owner = self.owner(events)
+ with self.subTest(existing=existing), \
+ mock.patch.object(module.firewall_win, "status", return_value=existing), \
+ mock.patch.object(module.firewall_win, "repair", side_effect=lambda *a: events.append("rules")):
+ owner._rules_then_listen()
+ self.assertEqual(events, ["listen"])
+
+ def test_a_failure_still_listens(self):
+ events = []
+ module, owner = self.owner(events)
+ with mock.patch.object(module.firewall_win, "status", side_effect=OSError("denied")):
+ owner._rules_then_listen()
+ self.assertEqual(events, ["listen"])
+
+ def test_without_elevation_it_listens_at_once(self):
+ events = []
+ module, owner = self.owner(events)
+ with mock.patch.object(module.firewall_win, "is_elevated", return_value=False):
+ module.WindowsApplication.start(owner)
+ self.assertEqual(events, ["listen"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_firewall_win.py b/win_app/tests/test_firewall_win.py
index 78e3fd1..9866b05 100644
--- a/win_app/tests/test_firewall_win.py
+++ b/win_app/tests/test_firewall_win.py
@@ -122,8 +122,8 @@ class InterpretTests(unittest.TestCase):
self.assertFalse(interpret(payload([rule(profile=4)]), EXE, PORT).covered)
def test_public_hyper_v_switch_beside_private_wifi_is_not_the_lan(self):
- # The owner's machine today: Wi-Fi Private with Internet, a vEthernet switch Public with none.
- networks = [network(), network("Public", alias="vEthernet (AI-Hub-Switch)", index=31, ipv4="NoTraffic")]
+ # A common setup: Wi-Fi Private with Internet, a vEthernet switch Public with none.
+ networks = [network(), network("Public", alias="vEthernet (Hyper-V Switch)", index=31, ipv4="NoTraffic")]
status = interpret(payload([rule(), pairing_rule()], networks), EXE, PORT)
self.assertEqual(status.active_profiles, ("Private", "Public"))
self.assertEqual(status.lan_profiles, ("Private",))
diff --git a/win_app/tests/test_hide_addresses_win.py b/win_app/tests/test_hide_addresses_win.py
new file mode 100644
index 0000000..4e0da36
--- /dev/null
+++ b/win_app/tests/test_hide_addresses_win.py
@@ -0,0 +1,45 @@
+"""Hide addresses in the real window, built offscreen as tools/readme_shots_win.py builds it, which
+starts no receiver, hooks or announcer."""
+
+import json
+import os
+import tempfile
+import unittest
+from pathlib import Path
+
+try:
+ from PySide6.QtWidgets import QApplication, QLineEdit
+
+ import kvm_bridge_win
+ import theme
+except ImportError: # PySide6 is only in the Windows venv
+ kvm_bridge_win = None
+
+
[email protected](kvm_bridge_win is None, "needs PySide6")
+class HideAddressesWindowTest(unittest.TestCase):
+ def setUp(self):
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ self.app = QApplication.instance() or QApplication([])
+ theme.init_fonts()
+ self.config = Path(tempfile.mkdtemp()) / "config.json"
+ self.raw = {"host": "192.0.2.20", "port": 24820, "auth_token": "synthetic", "paired_with": "MacBook Pro",
+ "mac_host": "192.0.2.10", "mac_return_edge": "left"}
+ self.config.write_text(json.dumps(self.raw))
+ self.window = kvm_bridge_win.WindowsApplication(self.config)
+
+ def tearDown(self):
+ self.window.deleteLater()
+
+ def test_a_reload_that_turns_it_on_hides_this_pcs_address(self):
+ # The final bug pass, 28-09-2026: the tray's Reload configuration set the switch on but left
+ # the address field readable, as the switch's handler never ran.
+ self.assertEqual(self.window.host_entry.echoMode(), QLineEdit.EchoMode.Normal)
+ self.config.write_text(json.dumps(dict(self.raw, hide_addresses=True)))
+ self.window.reload_config()
+ self.assertTrue(self.window.hide_switch.isChecked())
+ self.assertEqual(self.window.host_entry.echoMode(), QLineEdit.EchoMode.Password)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_ignored_inputs.py b/win_app/tests/test_ignored_inputs.py
index ba80c68..637650c 100644
--- a/win_app/tests/test_ignored_inputs.py
+++ b/win_app/tests/test_ignored_inputs.py
@@ -138,7 +138,7 @@ class CaptureTests(unittest.TestCase):
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)
- # How Qt 6 reports them on the rig: the extended prefix, not the bit.
+ # How Qt 6 reports them: the extended prefix, not the bit.
self.assertEqual(capture_win.hook_vk(0x11, 0xE01D), 0xA3)
self.assertEqual(capture_win.hook_vk(0x12, 0xE038), 0xA5)
self.assertEqual(capture_win.hook_vk(0x10, 0x2A), 0xA0)
diff --git a/win_app/tests/test_ignored_page.py b/win_app/tests/test_ignored_page.py
index 012a09a..15f77f7 100644
--- a/win_app/tests/test_ignored_page.py
+++ b/win_app/tests/test_ignored_page.py
@@ -72,7 +72,7 @@ class RecorderTests(unittest.TestCase):
self.recorder.eventFilter(self.recorder, event)
def test_right_ctrl_is_recorded_as_right_ctrl(self):
- # Qt 6 on the rig: nativeVirtualKey 0x11, nativeScanCode 0xE01D.
+ # What Qt 6 reports for Right Ctrl: nativeVirtualKey 0x11, nativeScanCode 0xE01D.
self.key(True, 0x11, 0xE01D)
self.assertEqual(self.recorded, [("key", 0xA3)])
diff --git a/win_app/tests/test_input_injector.py b/win_app/tests/test_input_injector.py
index d192a4d..c3c3113 100644
--- a/win_app/tests/test_input_injector.py
+++ b/win_app/tests/test_input_injector.py
@@ -383,6 +383,15 @@ class InjectSideButtonTests(unittest.TestCase):
self.assertEqual((sent[1].dwFlags, sent[1].mouseData), (input_injector.MOUSEEVENTF_XUP, 2))
+
+class FractionalWheelTests(unittest.TestCase):
+ def test_half_clicks_add_up_to_whole_ones(self):
+ accum = [0.0, 0.0]
+ units = [input_injector.plan_scroll_units(0.5, 0.0, "line", accum)[0] for _ in range(4)]
+ self.assertEqual(sum(units), 240)
+ self.assertEqual(input_injector.plan_scroll_units(2, 0, "line", [0.0, 0.0]), (240, 0))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/win_app/tests/test_motion.py b/win_app/tests/test_motion.py
new file mode 100644
index 0000000..41fc342
--- /dev/null
+++ b/win_app/tests/test_motion.py
@@ -0,0 +1,95 @@
+import os
+import unittest
+
+try:
+ from PySide6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
+except ImportError: # PySide6 is only in the Windows venv
+ QApplication = None
+
+
[email protected](QApplication is None, "needs PySide6")
+class MotionTest(unittest.TestCase):
+ def setUp(self):
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ self.app = QApplication.instance() or QApplication([])
+ import motion
+
+ self.motion = motion
+ self.real_reduced = motion.reduced
+ motion.reduced = lambda: False
+ self.window = QWidget()
+ column = QVBoxLayout(self.window)
+ self.row = QWidget()
+ inner = QVBoxLayout(self.row)
+ inner.addWidget(QLabel("A row that slides"))
+ column.addWidget(self.row)
+ column.addStretch(1)
+ self.window.resize(300, 200)
+
+ def tearDown(self):
+ self.motion.reduced = self.real_reduced
+ self.window.close()
+
+ def finish(self, owner, key):
+ animation = self.motion._runs(owner).get(key)
+ self.assertIsNotNone(animation)
+ animation.setCurrentTime(animation.duration())
+
+ def test_nothing_moves_while_the_window_is_hidden(self):
+ self.motion.set_shown(self.row, False)
+ self.assertTrue(self.row.isHidden())
+ self.assertFalse(self.motion.running(self.row, "shown"))
+
+ def test_nothing_moves_under_reduced_motion(self):
+ self.window.show()
+ self.motion.reduced = lambda: True
+ self.motion.set_shown(self.row, False)
+ self.assertTrue(self.row.isHidden())
+ self.assertIsNone(self.row.graphicsEffect())
+
+ def test_a_row_slides_shut_and_its_cap_comes_off(self):
+ self.window.show()
+ self.motion.set_shown(self.row, False)
+ self.assertFalse(self.row.isHidden(), "still on its way out")
+ self.assertFalse(self.motion.target_shown(self.row))
+ self.finish(self.row, "shown")
+ self.assertTrue(self.row.isHidden())
+ self.assertEqual(self.row.maximumHeight(), self.motion.QWIDGETSIZE_MAX)
+ self.assertTrue(self.row.layout().isEnabled())
+ self.assertIsNone(self.row.graphicsEffect())
+
+ def test_a_change_of_mind_turns_the_row_round(self):
+ self.window.show()
+ self.motion.set_shown(self.row, False)
+ self.motion.set_shown(self.row, True)
+ self.finish(self.row, "shown")
+ self.assertFalse(self.row.isHidden())
+ self.assertEqual(self.row.maximumHeight(), self.motion.QWIDGETSIZE_MAX)
+
+ def test_the_ring_slides_to_the_new_choice(self):
+ first, second = QWidget(self.window), QWidget(self.window)
+ first.setGeometry(10, 10, 40, 40)
+ second.setGeometry(100, 10, 40, 40)
+ ring = self.motion.Ring(self.window, lambda widget: widget.rect(), "#ffffff", 4)
+ ring.follow(first)
+ self.window.show()
+ ring.follow(second)
+ self.assertEqual(ring.current().x(), 10)
+ self.finish(ring, "ring")
+ self.assertEqual(ring.current().x(), 100)
+
+ def test_the_diagram_lands_on_its_side_at_once_before_the_window_opens(self):
+ import diagram
+
+ picture = diagram.ArrangementDiagram(self.window)
+ picture.set_state("left", ["edge"], [], "top_left", "Right Ctrl", "hold")
+ picture.set_state("top", ["edge", "shortcut"], [], "top_left", "Right Ctrl", "hold")
+ self.assertEqual(picture._angle, 90.0)
+ self.assertEqual(picture._marks[("edge", "top")], 1.0)
+ self.assertEqual(picture._marks[("edge", "left")], 0.0)
+ self.assertEqual(picture._marks[("cap",)], 1.0)
+ self.assertIn("hold Right Ctrl", picture.accessibleDescription())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_pages_win.py b/win_app/tests/test_pages_win.py
index 1322268..c8a511a 100644
--- a/win_app/tests/test_pages_win.py
+++ b/win_app/tests/test_pages_win.py
@@ -1,12 +1,30 @@
+import os
import unittest
+from types import SimpleNamespace
+import app_config
+import effects
import pages_win
+try:
+ import widgets
+except ImportError: # PySide6 is only in the Windows venv
+ widgets = None
+
class PagesWinTest(unittest.TestCase):
def test_keys_match_pages_in_order(self):
self.assertEqual(pages_win.KEYS, tuple(page[0] for page in pages_win.PAGES))
+ def test_the_sidebar_runs_in_setup_order(self):
+ self.assertEqual(pages_win.KEYS,
+ ("overview", "crossing", "keyboard", "design", "connection"))
+
+ def test_the_footer_drops_apply_as_you_go_on_connection(self):
+ self.assertEqual(pages_win.footer("design"),
+ "Changes apply as you make them. Closing this window keeps Beamer running in the tray.")
+ self.assertEqual(pages_win.footer("connection"), "Closing this window keeps Beamer running in the tray.")
+
def test_every_page_has_a_name_and_purpose(self):
for key, name, purpose in pages_win.PAGES:
self.assertTrue(name)
@@ -24,16 +42,402 @@ class PagesWinTest(unittest.TestCase):
def test_config_error_marks_connection(self):
self.assertEqual(pages_win.dots(True, None), {"connection": "fault"})
- def test_firewall_amber_marks_firewall(self):
- self.assertEqual(pages_win.dots(False, "note-amber"), {"firewall": "amber"})
+ def test_firewall_amber_marks_connection(self):
+ self.assertEqual(pages_win.dots(False, "note-amber"), {"connection": "amber"})
+
+ def test_firewall_fault_marks_connection(self):
+ self.assertEqual(pages_win.dots(False, "note-fault"), {"connection": "fault"})
+
+ def test_a_fault_outranks_a_firewall_amber(self):
+ self.assertEqual(pages_win.dots(True, "note-amber"), {"connection": "fault"})
+
+
+class DesignGroupsTest(unittest.TestCase):
+ def test_the_preview_opens_where_the_pointer_crosses(self):
+ self.assertEqual(pages_win.preview_place(["shortcut", "corner"]), "corner")
+ self.assertEqual(pages_win.preview_place(["part", "corner"]), "edge")
+ self.assertEqual(pages_win.preview_place(["shortcut"]), "edge")
+
+ def test_every_place_plays_every_style_and_says_why_when_it_differs(self):
+ self.assertEqual(pages_win.place_note("glow", "corner", ["corner"]), "")
+ self.assertIn("not one of this PC's ways in", pages_win.place_note("beam", "edge", ["corner"]))
+
+ def test_glow_and_beam_tiles_read_as_the_effects_do(self):
+ today = pages_win.style_groups()[0][1]
+ self.assertEqual([detail for _value, _name, detail in today], ["Classic", "Classic"])
+
+ def test_styles_are_classic_then_each_direction_in_order(self):
+ groups = pages_win.style_groups()
+ self.assertEqual([title for title, _items in groups],
+ ["Classic", "Membrane", "Sparks", "Instrument"])
+ self.assertEqual([style for style, _n, _d in groups[0][1]], ["glow", "beam"])
+ effect_ids = tuple(style for _title, items in groups[1:] for style, _n, _d in items)
+ self.assertEqual(effect_ids, effects.EFFECT_IDS)
+
+ def test_every_effect_tile_names_its_intensity(self):
+ for _title, items in pages_win.style_groups()[1:]:
+ self.assertEqual([detail for _s, _n, detail in items], ["Quiet", "Medium", "Showpiece"])
+ for _style, name, _detail in items:
+ self.assertTrue(name)
+
+ def test_colours_are_grouped_as_the_styles_are(self):
+ groups = pages_win.colour_groups()
+ self.assertEqual([title for title, _items in groups], [title for title, _items in pages_win.style_groups()])
+ self.assertEqual(tuple(value for _t, items in groups for value, _name in items), app_config.GLOW_COLOURS)
+
+ def test_effects_that_cannot_load_leave_only_the_classic_choices(self):
+ real = effects._load
+
+ def missing():
+ raise ImportError("No module named 'fx_membrane'")
+
+ effects._load = missing
+ try:
+ styles, colours = pages_win.style_groups(), pages_win.colour_groups()
+ finally:
+ effects._load = real
+ self.assertEqual([title for title, _items in styles], ["Classic"])
+ self.assertEqual([title for title, _items in colours], ["Classic"])
+
+ def test_only_the_new_effects_count_as_effects(self):
+ self.assertFalse(pages_win.is_effect("glow"))
+ self.assertFalse(pages_win.is_effect("beam"))
+ self.assertTrue(all(pages_win.is_effect(style) for style in effects.EFFECT_IDS))
+
- def test_firewall_fault_marks_firewall(self):
- self.assertEqual(pages_win.dots(False, "note-fault"), {"firewall": "fault"})
+class CrossingWaysTest(unittest.TestCase):
+ def test_edge_and_part_of_the_edge_exclude_each_other(self):
+ self.assertEqual(pages_win.toggle_way(["shortcut", "edge"], "part", True), ["shortcut", "part"])
+ self.assertEqual(pages_win.toggle_way(["part", "corner"], "edge", True), ["edge", "corner"])
+ self.assertEqual(pages_win.toggle_way(["edge"], "edge", False), [])
+ self.assertEqual(pages_win.toggle_way(["corner"], "shortcut", True), ["shortcut", "corner"])
- def test_both_problems_mark_both_pages(self):
+ def test_turning_on_a_way_already_on_keeps_one_copy(self):
+ self.assertEqual(pages_win.toggle_way(["edge", "edge"], "edge", True), ["edge"])
+
+ def test_any_parts_can_be_on_but_never_none(self):
+ self.assertEqual(pages_win.toggle_part(["middle"], "start", True), ["start", "middle"])
+ self.assertEqual(pages_win.toggle_part(["start", "end"], "start", False), ["end"])
+ self.assertEqual(pages_win.toggle_part(["end"], "end", False), ["end"])
+
+ def test_the_parts_are_named_along_the_edge(self):
+ self.assertEqual([pages_win.part_names("right")[p] for p in ("start", "middle", "end")], ["Top", "Middle", "Bottom"])
+ self.assertEqual([pages_win.part_names("bottom")[p] for p in ("start", "middle", "end")], ["Left", "Middle", "Right"])
+ self.assertEqual(pages_win.parts_phrase("left", ["end", "start"]), "the top and bottom of the left edge")
+
+ def test_no_parts_reads_as_the_middle_rather_than_failing(self):
+ self.assertEqual(pages_win.parts_phrase("right", []), "the middle of the right edge")
+ self.assertEqual(pages_win.parts_phrase("top", ["nowhere"]), "the middle of the top edge")
+
+ def test_each_row_shows_for_the_ways_that_use_it(self):
+ rows = pages_win.crossing_rows
+ # Where the Mac sits shows whatever the ways: it is where this PC's edge leads.
+ self.assertEqual(rows([]), {"edge"})
+ self.assertEqual(rows(["shortcut"]), {"edge", "shortcut"})
+ self.assertEqual(rows(["edge"]), {"edge", "dragging", "resistance"})
+ self.assertEqual(rows(["part"]), {"edge", "parts", "dragging", "resistance"})
+ self.assertEqual(rows(["corner"]), {"edge", "corner", "dragging", "resistance"})
+ self.assertEqual(rows(["shortcut", "part", "corner"]),
+ {"shortcut", "edge", "parts", "corner", "dragging", "resistance"})
+
+ def test_the_keyboard_page_no_longer_claims_the_switch_key(self):
+ purposes = {key: purpose for key, _name, purpose in pages_win.PAGES}
+ self.assertNotIn("key that", purposes["keyboard"])
+ self.assertNotIn("shortcut", pages_win.SCOPE["keyboard"].lower())
+ self.assertIn("a key moves input", purposes["crossing"])
+
+ def test_the_mac_is_placed_left_right_above_or_below(self):
+ self.assertEqual(pages_win.SIDE_CHOICES,
+ (("left", "Left"), ("right", "Right"), ("top", "Above"), ("bottom", "Below")))
+
+ def test_the_summary_names_every_way_in_one_sentence(self):
+ summary = pages_win.ways_summary
+ self.assertEqual(summary(["edge"], "right", [], "top_left", "Right Ctrl", "double_tap"),
+ "Input moves to your Mac when you push through the whole right edge.")
self.assertEqual(
- pages_win.dots(True, "note-amber"), {"connection": "fault", "firewall": "amber"}
+ summary(["shortcut", "part", "corner"], "left", ["start"], "bottom_right", "Right Ctrl", "hold"),
+ "Input moves to your Mac when you push through the top of the left edge, push diagonally into "
+ "the bottom-right corner or hold Right Ctrl.")
+ self.assertIn("choose at least one way", summary([], "left", [], "top_left", "F13", "hold"))
+
+ def test_the_key_cap_line_says_how_the_key_is_pressed(self):
+ self.assertEqual(pages_win.trigger_phrase("Right Ctrl", "double_tap"), "Right Ctrl, twice")
+ self.assertEqual(pages_win.trigger_phrase("Right Ctrl", "hold"), "Right Ctrl, held")
+
+
+class ArrangementGeometryTest(unittest.TestCase):
+ SCREEN = (120.0, 75.0)
+
+ def test_the_mac_sits_on_the_chosen_side_of_this_pc(self):
+ for side, check in (
+ ("right", lambda pc, mac: mac[0] == pc[0] + 134 and mac[1] == pc[1]),
+ ("left", lambda pc, mac: mac[0] == pc[0] - 134 and mac[1] == pc[1]),
+ ("top", lambda pc, mac: mac[1] == pc[1] - 89 and mac[0] == pc[0]),
+ ("bottom", lambda pc, mac: mac[1] == pc[1] + 89 and mac[0] == pc[0]),
+ ):
+ pc, mac, _height = pages_win.arrangement_rects(400.0, 0.0, pages_win.SIDE_ANGLE[side], self.SCREEN, 14.0)
+ self.assertTrue(check(pc, mac), (side, pc, mac))
+
+ def test_the_pair_is_centred_and_only_as_tall_as_it_needs(self):
+ pc, mac, height = pages_win.arrangement_rects(400.0, 10.0, 0.0, self.SCREEN, 14.0)
+ self.assertEqual(height, 75.0)
+ self.assertEqual((pc[0] + mac[0] + mac[2]) / 2.0, 200.0)
+ self.assertEqual(pc[1], 10.0)
+ _pc, _mac, stacked = pages_win.arrangement_rects(400.0, 0.0, 90.0, self.SCREEN, 14.0)
+ self.assertEqual(stacked, 164.0)
+
+ def test_the_mac_goes_round_this_pc_never_through_it(self):
+ for angle in range(0, 360, 5):
+ pc, mac, _height = pages_win.arrangement_rects(400.0, 0.0, float(angle), self.SCREEN, 14.0)
+ apart_x = mac[0] >= pc[0] + pc[2] or mac[0] + mac[2] <= pc[0]
+ apart_y = mac[1] >= pc[1] + pc[3] or mac[1] + mac[3] <= pc[1]
+ self.assertTrue(apart_x or apart_y, angle)
+
+ def test_a_turn_takes_the_short_way_and_half_turns_go_round_the_top(self):
+ turn = pages_win.turn_to
+ self.assertEqual(turn(0.0, "top"), 90.0)
+ self.assertEqual(turn(0.0, "bottom"), -90.0)
+ self.assertEqual(turn(0.0, "left"), 180.0)
+ self.assertEqual(turn(180.0, "right"), 0.0)
+ self.assertEqual(turn(90.0, "bottom"), 270.0)
+ self.assertEqual(turn(270.0, "top"), 90.0)
+ self.assertEqual(turn(45.0, "right"), 0.0)
+
+ def test_the_lit_marks_sit_on_the_side_that_leads_to_the_mac(self):
+ rect = (0.0, 0.0, 120.0, 90.0)
+ self.assertEqual(pages_win.side_segment(rect, "right"), (120.0, 0.0, 120.0, 90.0))
+ self.assertEqual(pages_win.side_segment(rect, "top", *pages_win.PART_SPANS["end"]), (80.0, 0.0, 120.0, 0.0))
+ self.assertEqual(pages_win.corner_box(rect, "bottom_left", 10.0), (0.0, 80.0, 10.0, 10.0))
+
+ def test_the_push_strip_fills_to_the_resistance(self):
+ self.assertEqual(pages_win.push_depth(0, 300.0), 0.0)
+ self.assertEqual(pages_win.push_depth(250, 300.0), 150.0)
+ self.assertEqual(pages_win.push_depth(900, 300.0), 300.0)
+
+
+class SwitchGroupsTest(unittest.TestCase):
+ def test_the_switch_tiles_offer_exactly_the_switch_styles(self):
+ values = [value for _title, items in pages_win.switch_groups() for value, _n, _d in items]
+ self.assertEqual(sorted(values), sorted(effects.SWITCH_STYLES))
+ self.assertEqual(len(values), len(set(values)))
+
+ def test_simple_comes_first_then_the_crossing_directions(self):
+ groups = pages_win.switch_groups()
+ self.assertEqual(groups[0], ("Simple", (("match", "Same as crossing", "Plays the crossing style"),
+ ("locator", "Ring", "Closes onto the pointer"))))
+ self.assertEqual(groups[1:], pages_win.style_groups()[1:])
+
+
[email protected](widgets is None, "needs PySide6")
+class DesignControlsTest(unittest.TestCase):
+ def setUp(self):
+ from PySide6.QtWidgets import QApplication, QWidget
+
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ self.app = QApplication.instance() or QApplication([])
+ self.QWidget = QWidget
+
+ def test_one_style_across_every_group(self):
+ chosen = []
+ groups = [(title, [(style, name, detail, self.QWidget()) for style, name, detail in items])
+ for title, items in pages_win.style_groups()]
+ tiles = widgets.TileGroups(groups, "glow", on_change=chosen.append)
+ tiles.groups["Sparks"]._chosen("discharge")
+ self.assertEqual((tiles.value, chosen), ("discharge", ["discharge"]))
+ self.assertEqual(tiles.groups["Classic"].value, "discharge")
+ tiles.set_value("skin")
+ self.assertEqual(chosen, ["discharge"], "set_value must not report a change")
+ self.assertTrue(all(group.value == "skin" for group in tiles.groups.values()))
+
+ def test_one_colour_across_every_row(self):
+ import effect_previews # noqa: F401 -- the page's pictures import cleanly
+
+ chosen = []
+ groups = [(title, [(value, name, app_config.palette_colours(value)) for value, name in items])
+ for title, items in pages_win.colour_groups()]
+ swatches = widgets.SwatchGroups(groups, "signal", on_change=chosen.append)
+ swatches._swatches["ember"].click()
+ self.assertEqual((swatches.value, chosen), ("ember", ["ember"]))
+ self.assertFalse(swatches._swatches["signal"].isChecked())
+ swatches.set_value("mono")
+ self.assertEqual((swatches.value, chosen), ("mono", ["ember"]))
+
+ def test_every_tile_draws_its_style_at_the_chosen_place_and_length(self):
+ import effect_previews
+ from PySide6.QtGui import QImage
+
+ for style in ("glow", "beam", "rupture", "gauge"):
+ still = effect_previews.EffectStill(style, ("#ff0000", "#0000ff"))
+ still.resize(180, effect_previews.STILL_HEIGHT)
+ pictures = []
+ for place in ("edge", "corner"):
+ still.set_place(place)
+ still.set_pace(1.5)
+ with self.subTest(style=style, place=place):
+ image = still.grab().toImage().convertToFormat(QImage.Format.Format_RGB32)
+ pictures.append(bytes(image.constBits()))
+ self.assertEqual(len(set(pictures)), 2, style)
+
+ def test_a_switch_tile_plays_at_the_chosen_length(self):
+ import effect_previews
+
+ still = effect_previews.SwitchStill("match", "rupture", ("#ff0000",))
+ still.resize(180, effect_previews.STILL_HEIGHT)
+ still.set_pace(0.75)
+ still.playing_since = 0.0
+ still.grab()
+ self.assertIsNotNone(still.playing_since)
+
+ def test_a_switch_still_follows_the_crossing_style(self):
+ import effect_previews
+
+ still = effect_previews.SwitchStill("match", "glow", ("#ffffff",))
+ still.resize(160, effect_previews.STILL_HEIGHT)
+ still.grab()
+ drawn = still._image
+ still.set_crossing_style("rupture")
+ self.assertIsNone(still._image)
+ still.grab()
+ self.assertIsNot(still._image, drawn)
+
+
[email protected](widgets is None, "needs PySide6")
+class CrossingPageTest(unittest.TestCase):
+ """The Crossing page's rows and chips, set from the config without building the whole window."""
+
+ def setUp(self):
+ from types import SimpleNamespace
+
+ from PySide6.QtWidgets import QApplication, QCheckBox, QPushButton, QWidget
+
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ self.app = QApplication.instance() or QApplication([])
+ import diagram
+ import kvm_bridge_win
+
+ self.reflect = kvm_bridge_win.WindowsApplication._reflect_ways
+ self.host = QWidget()
+ self.page = SimpleNamespace(
+ _config=app_config.default_config(),
+ way_boxes={way: QCheckBox(way) for way in pages_win.WAYS},
+ part_buttons={part: QPushButton() for part in ("start", "middle", "end")},
+ parts_note=widgets.label("", "note"),
+ # Inside a window that is never shown, as on a page before the window opens.
+ crossing_rows={key: QWidget(self.host) for key in ("edge", "parts", "corner", "dragging")},
+ resistance_module=QWidget(self.host),
+ shortcut_module=QWidget(self.host),
+ pause_row=QWidget(self.host),
+ ways_summary=widgets.label("", "note"),
+ edge_unlearned=QWidget(self.host),
+ arrangement_diagram=diagram.ArrangementDiagram(),
+ resistance_strip=diagram.PushStrip(),
)
+ for button in self.page.part_buttons.values():
+ button.setCheckable(True)
+
+ def shown(self):
+ page = self.page
+ rows = {key for key, row in page.crossing_rows.items() if not row.isHidden()}
+ rows |= {"resistance"} - ({"resistance"} if page.resistance_module.isHidden() else set())
+ rows |= {"shortcut"} - ({"shortcut"} if page.shortcut_module.isHidden() else set())
+ return rows
+
+ def test_rows_hide_and_come_back_with_the_ways(self):
+ self.page._config.crossing_methods = ["shortcut"]
+ self.reflect(self.page)
+ self.assertEqual(self.shown(), {"edge", "shortcut"})
+ self.page._config.crossing_methods = ["part"]
+ self.reflect(self.page)
+ self.assertEqual(self.shown(), {"edge", "parts", "dragging", "resistance"})
+ self.assertTrue(self.page.way_boxes["part"].isChecked())
+ self.assertFalse(self.page.way_boxes["shortcut"].isChecked())
+
+ def test_the_chips_are_named_for_the_current_edge(self):
+ self.page._config.mac_return_edge = "right"
+ self.page._config.crossing_edge_parts = ["start", "end"]
+ self.reflect(self.page)
+ buttons = self.page.part_buttons
+ self.assertEqual([buttons[p].text() for p in ("start", "middle", "end")], ["Top", "Middle", "Bottom"])
+ self.assertEqual([buttons[p].isChecked() for p in ("start", "middle", "end")], [True, False, True])
+ self.page._config.mac_return_edge = "top"
+ self.reflect(self.page)
+ self.assertEqual([buttons[p].text() for p in ("start", "middle", "end")], ["Left", "Middle", "Right"])
+
+ def test_an_edge_learned_from_the_mac_renames_the_chips(self):
+ import kvm_bridge_win
+
+ page = self.page
+ page._config.crossing_methods = ["part"]
+ page._config.mac_return_edge = "right"
+ self.reflect(page)
+ page._persist = lambda: True
+ page._start_sending = lambda config: None
+ page._reflect_look = lambda: None
+ page._reflect_ways = lambda: self.reflect(page)
+ page.sender = SimpleNamespace(update_config=lambda config: None)
+ page.mac_host_readout = widgets.label("", "readout")
+ page.edge_choice = SimpleNamespace(set_value=lambda value: None)
+ real = kvm_bridge_win.sender.is_this_machine
+ kvm_bridge_win.sender.is_this_machine = lambda host: False
+ try:
+ kvm_bridge_win.WindowsApplication._on_learned(page, "192.168.1.10", "top", 120)
+ finally:
+ kvm_bridge_win.sender.is_this_machine = real
+ buttons = page.part_buttons
+ self.assertEqual([buttons[p].text() for p in ("start", "middle", "end")], ["Left", "Middle", "Right"])
+ self.assertIn("top edge", page.parts_note.text())
+
+ def test_unticking_the_last_part_leaves_it_on(self):
+ import kvm_bridge_win
+
+ page = self.page
+ page._config.crossing_edge_parts = ["middle"]
+ page._persist = lambda: True
+ page.sender = SimpleNamespace(update_config=lambda config: None)
+ page._reflect_ways = lambda: self.reflect(page)
+ page._reflect_look = lambda: None
+ page.part_buttons["middle"].setChecked(False)
+ kvm_bridge_win.WindowsApplication._set_part(page, "middle", False)
+ self.assertEqual(page._config.crossing_edge_parts, ["middle"])
+ self.assertTrue(page.part_buttons["middle"].isChecked())
+
+ def test_the_crossing_line_gives_the_first_reason_nothing_can_cross(self):
+ line = pages_win.crossing_state_sentence
+ self.assertTrue(line(False, False, False, False, True, False, None).startswith("Not paired yet"))
+ self.assertTrue(line(True, False, True, False, True, False, None).startswith("Waiting to hear from your Mac"))
+ self.assertTrue(line(True, True, False, False, True, False, None).startswith("This PC drives your Mac is off"))
+ self.assertTrue(line(True, True, True, False, True, False, None).startswith("Not connected to your Mac"))
+ self.assertTrue(line(True, True, True, True, False, False, None).startswith("Only the shortcut"))
+ self.assertTrue(line(True, True, True, True, True, True, None).startswith("Paused."))
+ self.assertTrue(line(True, True, True, True, True, False, "Keynote").startswith("Off while Keynote"))
+ self.assertEqual(line(True, True, True, True, True, False, None), "On. Pause it to lean on an edge without switching.")
+
+ def test_a_reason_shows_even_when_only_the_shortcut_is_on(self):
+ self.assertTrue(pages_win.crossing_state_blocked(False, True, True, True))
+ self.assertTrue(pages_win.crossing_state_blocked(True, False, True, True))
+ self.assertTrue(pages_win.crossing_state_blocked(True, True, False, True))
+ self.assertTrue(pages_win.crossing_state_blocked(True, True, True, False))
+ self.assertFalse(pages_win.crossing_state_blocked(True, True, True, True))
+
+ def test_the_overview_says_whether_this_pcs_own_link_is_up(self):
+ self.assertEqual(pages_win.outward_link_line(True), "This PC to your Mac: Linked")
+ self.assertEqual(pages_win.outward_link_line(False),
+ "This PC to your Mac: not connected, so pushing an edge does nothing")
+
+ def test_no_learned_edge_is_not_described_as_the_right_edge(self):
+ summary = pages_win.ways_summary(["edge"], "", ["middle"], "top_right", "Right Ctrl", "double_tap")
+ self.assertNotIn("right edge", summary)
+ self.assertTrue(summary.startswith("Nothing moves input to your Mac until"))
+ self.assertIn("the whole right edge", pages_win.ways_summary(["edge"], "right", ["middle"], "top_right", "Right Ctrl", "double_tap"))
+
+
+
+class RedactTests(unittest.TestCase):
+ def test_hides_ip_and_hardware_addresses_only_when_asked(self):
+ line = "MacBook Pro at 192.168.1.10:24820, woken by 02-1A-2B-3C-0D-4E"
+ self.assertEqual(pages_win.redact(line, False), line)
+ self.assertEqual(pages_win.redact(line, True), "MacBook Pro at •••:24820, woken by •••")
+ self.assertEqual(pages_win.redact("Ready on TCP port 24820", True), "Ready on TCP port 24820")
if __name__ == "__main__":
diff --git a/win_app/tests/test_parity.py b/win_app/tests/test_parity.py
index 4d4e75e..e2d209e 100644
--- a/win_app/tests/test_parity.py
+++ b/win_app/tests/test_parity.py
@@ -1,6 +1,6 @@
-"""What the PC gained so each machine offers the same control as the other (27-09-2026 parity
-audit, docs/parity-audit-27-09-2026.md): a recorded trigger key, the modifier style, Pause
-crossing, the full-screen hold, never crossing while dragging, alerts, and waking the Mac."""
+"""What the PC gained so each machine offers the same control as the other: a recorded
+trigger key, the modifier style, Pause crossing, the full-screen hold, never crossing
+while dragging, alerts, and waking the Mac."""
import time
import unittest
diff --git a/win_app/tests/test_receiver.py b/win_app/tests/test_receiver.py
index 80c39f1..40db3ec 100644
--- a/win_app/tests/test_receiver.py
+++ b/win_app/tests/test_receiver.py
@@ -707,13 +707,14 @@ class ReceiverCrossingTests(unittest.TestCase):
MONITORS = [Rect(0, 0, 2560, 1440), Rect(-1920, 200, 1920, 1080)]
- def _session(self, desktop, pressures=None):
+ def _session(self, desktop, pressures=None, arrivals=None):
statuses = []
server = ReceiverServer(
lambda state, detail: statuses.append((state, detail)),
clipboard=FakeClipboard(text=""),
desktop=desktop,
pressure_callback=None if pressures is None else (lambda *args: pressures.append(args)),
+ arrival_callback=None if arrivals is None else (lambda *args: arrivals.append(args)),
)
client, connection, address = connected_socket_pair()
stop_event = threading.Event()
@@ -748,15 +749,29 @@ class ReceiverCrossingTests(unittest.TestCase):
finally:
self._teardown(client, connection, stop_event, thread)
+ def test_arrival_callback_gets_the_edge_and_where_the_pointer_landed(self):
+ desktop = FakeDesktop(self.MONITORS, cursor=(500, 500))
+ arrivals = []
+ server, client, connection, stop_event, thread = self._session(desktop, arrivals=arrivals)
+ try:
+ client.send(self._focus_windows(edge="left", offset=0.5, return_edge="left", resistance_px=100))
+ wait_for_calls(arrivals, minimum=1)
+ self.assertEqual(arrivals, [("left", -1920, 720)])
+ finally:
+ self._teardown(client, connection, stop_event, thread)
+
def test_shortcut_switch_arms_without_moving_the_pointer(self):
desktop = FakeDesktop(self.MONITORS, cursor=(500, 500))
- server, client, connection, stop_event, thread = self._session(desktop)
+ arrivals = []
+ server, client, connection, stop_event, thread = self._session(desktop, arrivals=arrivals)
try:
client.send(self._focus_windows(return_edge="top", resistance_px=120))
client.send(protocol.ping_msg())
client.settimeout(1.0)
self.assertEqual(client.recv(), protocol.ack_msg(0))
self.assertEqual(desktop.set_calls, [])
+ # A switch, reported with no edge and wherever the pointer was left, to show where it is.
+ self.assertEqual(arrivals, [(None, 500, 500)])
self.assertEqual(server.return_edge, "top")
finally:
self._teardown(client, connection, stop_event, thread)
@@ -779,11 +794,11 @@ class ReceiverCrossingTests(unittest.TestCase):
self.assertEqual(desktop.set_calls, [(-1920, 723)])
inject.assert_not_called()
# The receiver sends the switch before it reports the breakthrough pressure, so
- # the second entry can land after recv() returns: 2 in 15 runs failed on the rig.
+ # the second entry can land after recv() returns: this was flaky without the wait.
wait_for_calls(pressures, minimum=2)
- self.assertEqual([edge for edge, _, _ in pressures], ["left", "left"])
+ self.assertEqual([entry[0] for entry in pressures], ["left", "left"])
self.assertAlmostEqual(pressures[0][1], 0.6)
- self.assertEqual(pressures[1][1:], (1.0, True))
+ self.assertEqual(pressures[1][1:], (1.0, True, None))
# Disarmed after the crossing: the next move injects normally.
client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})
wait_for_calls(inject.call_args_list, minimum=1)
@@ -791,6 +806,121 @@ class ReceiverCrossingTests(unittest.TestCase):
finally:
self._teardown(client, connection, stop_event, thread)
+ def test_pause_on_this_machine_holds_the_way_home_too(self):
+ desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 720))
+ with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(
+ input_injector, "inject_mouse_move"
+ ) as inject:
+ server, client, connection, stop_event, thread = self._session(desktop)
+ server.edges_held = lambda: True
+ try:
+ client.send(self._focus_windows(return_edge="left", resistance_px=100))
+ for _ in range(4):
+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})
+ wait_for_calls(inject.call_args_list, minimum=4)
+ # Every push went through as an ordinary move; nothing was held or sent home.
+ self.assertEqual(desktop.set_calls, [])
+ self.assertTrue(server._return_edge.armed)
+ finally:
+ self._teardown(client, connection, stop_event, thread)
+
+ def test_the_way_home_follows_this_machines_own_thirds(self):
+ # This PC has Part of the edge with only the top third: a push lower down is a wall.
+ desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 1100))
+ pressures = []
+ with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(
+ input_injector, "inject_mouse_move"
+ ) as inject:
+ server, client, connection, stop_event, thread = self._session(desktop, pressures)
+ server.return_model = lambda edge, resistance: receiver.crossing.PartEdge(edge, ("start",), resistance)
+ try:
+ client.send(self._focus_windows(return_edge="left", resistance_px=100))
+ for _ in range(3):
+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})
+ wait_for_calls(inject.call_args_list, minimum=3)
+ self.assertEqual(pressures, [])
+ desktop.cursor = (-1920, 300)
+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})
+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})
+ client.settimeout(1.0)
+ self.assertEqual(client.recv()["type"], protocol.MSG_SWITCH)
+ wait_for_calls(pressures, minimum=1)
+ self.assertEqual(pressures[0][3], "start")
+ finally:
+ self._teardown(client, connection, stop_event, thread)
+
+ def test_a_crossing_setting_changed_mid_visit_applies_at_once(self):
+ # Toby, 28-09-2026: a change to Part of the edge applied only after crossing out and back.
+ desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 1100))
+ settings = {"parts": ("start",)}
+ with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(
+ input_injector, "inject_mouse_move"
+ ) as inject:
+ server, client, connection, stop_event, thread = self._session(desktop, [])
+ server.return_model = lambda edge, resistance: receiver.crossing.PartEdge(edge, settings["parts"], resistance)
+ # Both apps pass one; it is what records that the peer is driving.
+ server._focus_callback = lambda target: None
+ try:
+ client.send(self._focus_windows(return_edge="left", resistance_px=100))
+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})
+ wait_for_calls(inject.call_args_list, minimum=1)
+ self.assertEqual(server._return_edge.parts, frozenset({"start"}))
+ settings["parts"] = ("end",)
+ server.rearm_return()
+ self.assertEqual(server._return_edge.parts, frozenset({"end"}))
+ self.assertEqual((server.return_edge, server.return_resistance), ("left", 100))
+ finally:
+ self._teardown(client, connection, stop_event, thread)
+
+ def test_rearming_does_nothing_once_input_has_gone_home(self):
+ server = receiver.ReceiverServer(lambda *args: None)
+ server.return_model = lambda edge, resistance: receiver.crossing.ReturnEdge(edge, resistance)
+ server.rearm_return()
+ self.assertIsNone(server._return_edge)
+
+ def test_rearming_never_revives_a_way_home_that_was_handed_back(self):
+ # Codex on 74e8e96: send_home drops the way home while the peer still counts as driving,
+ # until its focus arrives; a settings save in between must not arm it again.
+ server = receiver.ReceiverServer(lambda *args: None, focus_callback=lambda target: None)
+ server.return_model = lambda edge, resistance: receiver.crossing.ReturnEdge(edge, resistance)
+ server._notify_focus(server._self_target)
+ server._arm_return({"return_edge": "left", "resistance_px": 100})
+ server._drop_return()
+ server.rearm_return()
+ self.assertIsNone(server._return_edge)
+
+ def test_rearming_never_revives_a_way_home_already_pushed_through(self):
+ desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 300))
+ with mock.patch.object(receiver, "ACK_IDLE_SECONDS", 1000.0), mock.patch.object(input_injector, "inject_mouse_move"):
+ server, client, connection, stop_event, thread = self._session(desktop, [])
+ server.return_model = lambda edge, resistance: receiver.crossing.ReturnEdge(edge, resistance)
+ server._focus_callback = lambda target: None
+ try:
+ client.send(self._focus_windows(return_edge="left", resistance_px=100))
+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})
+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})
+ client.settimeout(1.0)
+ self.assertEqual(client.recv()["type"], protocol.MSG_SWITCH)
+ server.rearm_return()
+ self.assertFalse(server._return_edge is not None and server._return_edge.armed)
+ finally:
+ self._teardown(client, connection, stop_event, thread)
+
+ def test_no_way_home_by_the_pointer_when_this_machine_has_none(self):
+ desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 720))
+ with mock.patch.object(input_injector, "inject_mouse_move") as inject:
+ server, client, connection, stop_event, thread = self._session(desktop)
+ server.return_model = lambda edge, resistance: None
+ try:
+ client.send(self._focus_windows(return_edge="left", resistance_px=100))
+ for _ in range(4):
+ client.send({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": -60, "dy": 0}})
+ wait_for_calls(inject.call_args_list, minimum=4)
+ self.assertIsNone(server.return_edge)
+ self.assertEqual(desktop.set_calls, [])
+ finally:
+ self._teardown(client, connection, stop_event, thread)
+
def test_moves_inject_normally_when_no_return_edge_is_armed(self):
desktop = FakeDesktop(self.MONITORS, cursor=(-1920, 720))
with mock.patch.object(input_injector, "inject_mouse_move") as inject:
@@ -806,8 +936,8 @@ class ReceiverCrossingTests(unittest.TestCase):
class ReceiverHandBackTests(unittest.TestCase):
"""The peer's input is here and the link that brought it ends. The peer
fails open on its own side, but the focus saying so dies with the socket,
- so the receiver raises it: otherwise the owner keeps treating the peer as
- driving and its own edge and shortcut stay dead."""
+ so the receiver raises it: otherwise this machine keeps treating the peer
+ as driving and its own edge and shortcut stay dead."""
def _session(self, focuses):
server = ReceiverServer(
@@ -846,7 +976,7 @@ class ReceiverHandBackTests(unittest.TestCase):
connection.close()
def test_send_home_while_driving_sends_the_peer_its_input(self):
- # The escape that does not depend on the return edge: 23-09-2026, the
+ # The escape that does not depend on the return edge: without it, the
# PC's mouse stayed on the Mac after a push through the edge never fired.
focuses = []
server, client, connection, thread = self._session(focuses)
@@ -981,5 +1111,33 @@ class ReceiverBindTests(unittest.TestCase):
self.assertIn(f"port {port}", detail)
+
+class InputScaleTests(unittest.TestCase):
+ def test_a_slower_pointer_carries_its_fractions(self):
+ scale = receiver.InputScale(pointer=0.5)
+ moves = [scale.move(1, 1) for _ in range(4)]
+ self.assertEqual(moves, [(0, 0), (1, 1), (0, 0), (1, 1)])
+
+ def test_a_faster_pointer_multiplies(self):
+ self.assertEqual(receiver.InputScale(pointer=2.0).move(3, -4), (6, -8))
+
+ def test_speeds_are_held_to_their_range(self):
+ scale = receiver.InputScale(pointer=99, scroll=0)
+ self.assertEqual((scale.pointer, scale.scroll), (4.0, 0.25))
+
+ def test_scroll_speed_and_reverse(self):
+ self.assertEqual(receiver.InputScale(scroll=2.0).wheel(3, 1), (6.0, 2.0))
+ self.assertEqual(receiver.InputScale(reverse=True).wheel(3, -1), (-3.0, 1.0))
+ self.assertEqual(receiver.InputScale().wheel(3, 1), (3, 1))
+
+ def test_handle_message_applies_the_scale_and_drops_a_move_that_rounds_to_nothing(self):
+ injector = FakeInjector()
+ scale = receiver.InputScale(pointer=0.5)
+ handle_message({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 1, "dy": 0}}, injector, scale)
+ handle_message({"type": protocol.MSG_MOUSEMOVE, "data": {"dx": 1, "dy": 0}}, injector, scale)
+ handle_message({"type": protocol.MSG_SCROLL, "data": {"dy": 2, "dx": 0}}, injector, receiver.InputScale(reverse=True))
+ self.assertEqual(injector.calls, [("mouse_move", (1, 0)), ("scroll", (-2.0, -0.0, "line"))])
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/win_app/tests/test_return_edge.py b/win_app/tests/test_return_edge.py
index aab26e5..b162e7b 100644
--- a/win_app/tests/test_return_edge.py
+++ b/win_app/tests/test_return_edge.py
@@ -34,15 +34,15 @@ class GeometryTests(unittest.TestCase):
self.assertEqual(edge_offset(BOUNDS, "right", (2559, 99999)), 1.0)
def test_arrival_lands_on_the_monitor_owning_each_edge(self):
- # left: the monitor with the smallest x, offset against the whole box
- # then clamped into that monitor's own span.
+ # The offset is taken against the whole box, and lands on the outermost monitor spanning
+ # that point: the left monitor for most of the left edge, the primary above it, where the
+ # primary's own left edge is the wall.
self.assertEqual(arrival_position(ARRANGEMENT, "left", 0.5), (-1920, 720))
- self.assertEqual(arrival_position(ARRANGEMENT, "left", 0.0), (-1920, 200))
+ self.assertEqual(arrival_position(ARRANGEMENT, "left", 0.0), (0, 0))
# right: the primary, at its last pixel column.
self.assertEqual(arrival_position(ARRANGEMENT, "right", 0.5), (2559, 720))
- # top: the primary is the only monitor reaching y=0; 10% of 4480 from
- # x=-1920 is in the left monitor's column range, so it clamps to x=0.
- self.assertEqual(arrival_position(ARRANGEMENT, "top", 0.1), (0, 0))
+ # top: 10% of 4480 from x=-1920 is over the left monitor, whose top is exposed at y=200.
+ self.assertEqual(arrival_position(ARRANGEMENT, "top", 0.1), (-1472, 200))
self.assertEqual(arrival_position(ARRANGEMENT, "top", 0.75), (1440, 0))
# bottom: the primary reaches y=1439; the left monitor stops at 1279.
self.assertEqual(arrival_position(ARRANGEMENT, "bottom", 1.0), (2559, 1439))
@@ -120,5 +120,59 @@ class PressureTests(unittest.TestCase):
ReturnEdge("sideways")
+
+class PartEdgeTests(unittest.TestCase):
+ def test_only_the_chosen_thirds_cross(self):
+ from return_edge import PartEdge
+
+ # Thirds are the pointer's own display's: the left monitor spans 200 to 1280, so they
+ # break at 560 and 920.
+ for y, crosses in ((300, False), (700, True), (1100, False)):
+ with self.subTest(y=y):
+ model = PartEdge("left", ("middle",), resistance_px=40, clock=FakeClock())
+ outcome = None
+ for _ in range(5):
+ outcome = model.feed(ARRANGEMENT, (-1920, y), -20, 0)
+ if outcome.action == CROSS:
+ break
+ self.assertEqual(outcome.action == CROSS, crosses)
+
+ def test_a_short_display_beside_a_tall_one_keeps_every_third(self):
+ # Measured on the 1440-tall bounding box, the 900-tall display's end third would start at
+ # 960 and most of it would not exist.
+ from return_edge import display_fraction
+
+ short, tall = Rect(0, 0, 1440, 900), Rect(-2560, 0, 2560, 1440)
+ self.assertAlmostEqual(display_fraction([tall, short], "right", (1439, 800)), 800 / 900)
+
+ def test_parts_are_named_by_thirds(self):
+ from return_edge import in_parts, part_of
+
+ self.assertEqual([part_of(f) for f in (0.0, 0.34, 0.99, 1.0)], ["start", "middle", "end", "end"])
+ self.assertFalse(in_parts(0.1, ("middle",)))
+
+
+class LandingMonitorTests(unittest.TestCase):
+ def test_two_stacked_monitors_each_take_their_own_stretch_of_the_edge(self):
+ stacked = [Rect(0, 0, 1920, 1080), Rect(0, 1080, 1920, 1080)]
+ self.assertEqual(arrival_position(stacked, "left", 0.2), (0, 432))
+ self.assertEqual(arrival_position(stacked, "left", 0.8), (0, 1728))
+
+ def test_side_by_side_monitors_share_the_bottom_edge(self):
+ side = [Rect(0, 0, 1920, 1080), Rect(1920, 0, 1920, 1080)]
+ self.assertEqual(arrival_position(side, "bottom", 0.75)[0], 2880)
+
+ def test_a_staggered_arrangement_lands_on_whichever_edge_is_the_wall(self):
+ staggered = [Rect(0, 0, 1920, 1080), Rect(1920, 300, 1280, 720)]
+ # Past the short monitor's bottom, the tall one's right edge is the wall.
+ self.assertEqual(arrival_position(staggered, "right", 0.95), (1919, 1026))
+ self.assertEqual(arrival_position(staggered, "right", 0.5), (3199, 540))
+
+ def test_a_monitor_left_of_and_above_the_primary(self):
+ monitors = [Rect(0, 0, 1728, 1117), Rect(-2560, -200, 2560, 1440)]
+ self.assertEqual(arrival_position(monitors, "left", 0.0), (-2560, -200))
+ self.assertEqual(arrival_position(monitors, "right", 0.5)[0], 1727)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/win_app/tests/test_sender.py b/win_app/tests/test_sender.py
index ef58353..49b2f85 100644
--- a/win_app/tests/test_sender.py
+++ b/win_app/tests/test_sender.py
@@ -58,16 +58,93 @@ class EdgeTests(unittest.TestCase):
# 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.link.sender._pressure_callback = lambda edge, pressure, crossed, part: seen.append((edge, crossed))
self.push(4)
self.assertTrue(seen, "a push against the edge reported no pressure")
self.assertTrue(all(edge == "left" for edge, _ in seen))
self.assertEqual(seen[-1][1], True)
+ def test_part_of_the_edge_lights_only_the_third_it_is_pushing(self):
+ seen = []
+ self.link.sender.update_config(make_config(crossing_methods=["part"], crossing_edge_parts=["middle", "end"]))
+ self.link.sender._pressure_callback = lambda edge, pressure, crossed, part: seen.append((edge, part))
+ self.desktop.cursor = (0, 900)
+ self.push(4)
+ self.assertTrue(seen, "a push along a chosen third reported no pressure")
+ self.assertEqual(set(seen), {("left", "end")})
+
+ def test_the_third_is_measured_on_the_pointers_own_display(self):
+ # The left display runs 200 to 1280 of a 1440-tall desktop: 1000 is its end third, though
+ # on the desktop as a whole it would be the middle one.
+ desktop = FakeDesktop([Rect(0, 200, 1920, 1080), Rect(1920, 0, 2560, 1440)], cursor=(0, 1000))
+ link = MacSenderWithLink(desktop=desktop)
+ self.addCleanup(link.close)
+ seen = []
+ link.sender.update_config(make_config(crossing_methods=["part"], crossing_edge_parts=["end"]))
+ link.sender._pressure_callback = lambda edge, pressure, crossed, part: seen.append(part)
+ for _ in range(4):
+ link.sender.on_motion(-20, 0)
+ self.assertEqual(set(seen), {"end"})
+
+ def test_the_whole_edge_names_no_third(self):
+ seen = []
+ self.link.sender._pressure_callback = lambda edge, pressure, crossed, part: seen.append(part)
+ self.push(4)
+ self.assertEqual(set(seen), {None})
+
+ def test_coming_home_reports_where_the_pointer_landed(self):
+ # The crossing effects play their arrival where the pointer is placed.
+ arrivals = []
+ self.link.sender._arrival_callback = lambda edge, x, y: arrivals.append((edge, x, y))
+ self.link.sender._handle_switch({"target": "windows", "edge": "left", "offset": 0.5})
+ self.assertEqual(arrivals, [("left",) + self.desktop.set_calls[-1]])
+
+ def test_a_raising_arrival_callback_only_logs(self):
+ def boom(edge, x, y):
+ raise RuntimeError("effect fell over")
+
+ self.link.sender._arrival_callback = boom
+ with self.assertLogs(sender.LOGGER, "ERROR"):
+ self.link.sender._handle_switch({"target": "windows", "edge": "left", "offset": 0.5})
+ self.assertTrue(self.desktop.set_calls)
+
+ def test_a_switch_without_an_edge_while_already_home_reports_no_arrival(self):
+ arrivals = []
+ self.link.sender._arrival_callback = lambda edge, x, y: arrivals.append(edge)
+ self.link.sender._handle_switch({"target": "windows"})
+ self.assertEqual(arrivals, [])
+
+ def _home_by(self, action):
+ """Input on the Mac, then brought home by `action`; what the arrival callback heard."""
+ arrivals = []
+ self.link.sender._arrival_callback = lambda edge, x, y: arrivals.append((edge, x, y))
+ self.link.sender.redirecting = True
+ action()
+ self.assertFalse(self.link.sender.redirecting)
+ return arrivals
+
+ def test_the_shortcut_home_reports_where_the_pointer_is(self):
+ self.assertEqual(self._home_by(self.link.sender.toggle), [(None, 0, 500)])
+
+ def test_the_mac_sending_input_home_by_its_switch_reports_it(self):
+ arrivals = self._home_by(lambda: self.link.sender._handle_switch({"target": "windows"}))
+ self.assertEqual(arrivals, [(None, 0, 500)])
+
+ def test_a_crossing_home_reports_only_its_own_arrival(self):
+ arrivals = self._home_by(
+ lambda: self.link.sender._handle_switch({"target": "windows", "edge": "left", "offset": 0.5}))
+ self.assertEqual([edge for edge, _x, _y in arrivals], ["left"])
+
+ def test_the_mac_taking_this_pc_over_is_not_a_switch_home(self):
+ self.assertEqual(self._home_by(lambda: self.link.sender.set_receiving(True)), [])
+
+ def test_a_dropped_link_shows_nothing(self):
+ self.assertEqual(self._home_by(lambda: self.link.sender._force_local("The Mac stopped responding")), [])
+
def test_this_pcs_own_mouse_pushing_out_while_the_mac_drives_takes_the_pointer_across(self):
- # 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.
+ # Before this, the Mac's trackpad could cross to the PC but the PC's own mouse could not
+ # push back out. The Mac's injected moves carry INJECTED_MARK and never reach on_motion,
+ # so a push here is the hand's: the Mac gets its input back and this mouse follows it across.
sent_home = []
self.link.sender.send_peer_home = lambda: sent_home.append(True) or True
self.link.sender.set_receiving(True)
@@ -130,6 +207,14 @@ class CornerTests(unittest.TestCase):
self.link.sender.on_motion(-20, -20)
self.assertTrue(self.link.sender.redirecting)
+ def test_the_push_names_its_corner_for_the_effects(self):
+ seen = []
+ self.link.sender._pressure_callback = lambda edge, pressure, crossed, part: seen.append((edge, part))
+ for _ in range(4):
+ self.link.sender.on_motion(-20, -20)
+ self.assertTrue(seen)
+ self.assertEqual(set(part for _edge, part in seen), {"top_left"})
+
def test_a_straight_push_along_the_edge_does_not(self):
for _ in range(10):
self.link.sender.on_motion(-20, 0)
@@ -352,5 +437,24 @@ def wait_for(predicate, timeout=5.0):
return False
+
+class LinkDropTests(unittest.TestCase):
+ def test_the_edge_crosses_again_after_the_link_dropped_while_redirecting(self):
+ desktop = FakeDesktop(MONITORS, cursor=(0, 500))
+ link = MacSenderWithLink(desktop=desktop)
+ self.addCleanup(link.close)
+ sender = link.sender
+ for _ in range(4):
+ sender.on_motion(-20, 0)
+ self.assertTrue(sender.redirecting)
+ sender._force_local("the link to the Mac went quiet")
+ sender._sock = object()
+ sender._connected_at = sender._last_ack_at = time.monotonic()
+ desktop.cursor = (0, 500)
+ for _ in range(6):
+ sender.on_motion(-20, 0)
+ self.assertTrue(sender.redirecting)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/win_app/tests/test_shared_copies.py b/win_app/tests/test_shared_copies.py
index 6fb648c..ec5e1ad 100644
--- a/win_app/tests/test_shared_copies.py
+++ b/win_app/tests/test_shared_copies.py
@@ -1,6 +1,7 @@
"""The files both apps share are kept byte-identical, not merely similar.
-`ignored.py`, `pairing.py`, `protocol.py`, `receiver.py`, `return_edge.py` and `wol.py` each exist once in mac_app
+`effects.py` and its `fx_*.py`, `ignored.py`, `pairing.py`, `protocol.py`, `receiver.py`, `return_edge.py`
+and `wol.py` each exist once in mac_app
and once in win_app because neither app can import across the other's
directory -- both are packaged as self-contained bundles. Everything
platform-shaped in them is injected at construction instead, so there is no
@@ -19,8 +20,11 @@ import unittest
_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))
-SHARED_MODULES = ("ignored.py", "pairing.py", "protocol.py", "receiver.py", "return_edge.py", "wol.py")
-SHARED_TESTS = ("test_ignored.py", "test_shared_copies.py")
+SHARED_MODULES = (
+ "effects.py", "fx_ink.py", "fx_instrument.py", "fx_membrane.py", "fx_sparks.py", "fx_warp.py",
+ "ignored.py", "pairing.py", "protocol.py", "receiver.py", "return_edge.py", "updates.py", "wol.py",
+)
+SHARED_TESTS = ("test_ignored.py", "test_shared_copies.py", "test_switch_arrival.py", "test_updates.py")
def _digest(path):
diff --git a/win_app/tests/test_stuck_modifier_on_drop.py b/win_app/tests/test_stuck_modifier_on_drop.py
index 620a145..eda60af 100644
--- a/win_app/tests/test_stuck_modifier_on_drop.py
+++ b/win_app/tests/test_stuck_modifier_on_drop.py
@@ -39,7 +39,7 @@ class PeerKeysReleasedTests(unittest.TestCase):
def test_input_going_home_releases_what_the_peer_held(self):
injector = FakeInjector()
server = self._server(injector)
- server._clipboard = type("C", (), {"get_contents": staticmethod(lambda: (None, None))})
+ server._clipboard = type("C", (), {"changed_contents": staticmethod(lambda: (None, None))})
server._handle_focus({"type": "focus", "data": {"target": "mac"}}, None, None, "peer", "192.168.1.5")
self.assertIn(("release_all",), injector.calls)
diff --git a/win_app/tests/test_style_for.py b/win_app/tests/test_style_for.py
new file mode 100644
index 0000000..b881757
--- /dev/null
+++ b/win_app/tests/test_style_for.py
@@ -0,0 +1,53 @@
+"""The Design page's Style for switch shows the tiles it names, in the real window: built offscreen
+from a synthetic config as tools/readme_shots_win.py builds it, which starts no receiver, hooks or
+announcer."""
+
+import json
+import os
+import tempfile
+import unittest
+from pathlib import Path
+
+try:
+ from PySide6.QtWidgets import QApplication
+
+ import kvm_bridge_win
+ import theme
+except ImportError: # PySide6 is only in the Windows venv
+ kvm_bridge_win = None
+
+
[email protected](kvm_bridge_win is None, "needs PySide6")
+class StyleForTest(unittest.TestCase):
+ def setUp(self):
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ self.app = QApplication.instance() or QApplication([])
+ theme.init_fonts()
+ config = Path(tempfile.mkdtemp()) / "config.json"
+ config.write_text(json.dumps({
+ "host": "192.168.1.20", "port": 24820, "auth_token": "synthetic", "paired_with": "MacBook Pro",
+ "mac_host": "192.168.1.10", "mac_return_edge": "left", "shortcut_arrival": True,
+ }))
+ self.window = kvm_bridge_win.WindowsApplication(config)
+ self.window._select_page("design")
+ self.window._refresh_window()
+
+ def tearDown(self):
+ self.window.deleteLater()
+
+ def shown(self):
+ return {name for name, choice in (("crossing", self.window.glow_style_choice),
+ ("switch", self.window.switch_style_choice))
+ if not choice.view.isHidden()}
+
+ def test_each_choice_shows_its_own_tiles_every_time(self):
+ self.assertEqual(self.shown(), {"crossing"})
+ for choice in ("switch", "crossing", "switch", "crossing"):
+ self.window.design_mode_choice._buttons[choice].click()
+ self.app.processEvents()
+ self.assertEqual(self.window.design_mode_choice.value, choice)
+ self.assertEqual(self.shown(), {choice})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_switch_arrival.py b/win_app/tests/test_switch_arrival.py
new file mode 100644
index 0000000..532b99c
--- /dev/null
+++ b/win_app/tests/test_switch_arrival.py
@@ -0,0 +1,189 @@
+"""What plays when input arrives by the shortcut, a menu or a switch rather than a crossing: the
+Player's switch arrival, the locator Glow and Beam get, and every effect's arrival away from an
+edge. Byte-identical in mac_app and win_app."""
+
+import math
+import unittest
+
+import effects
+
+SCREEN = (1728.0, 1117.0, "mac")
+MID = (700.0, 460.0)
+PALETTE = ["#ff7828", "#ff3264", "#ffb43c"]
+
+
+def frames(player, now, fx=None, reduced=False, dark=True):
+ return player.frames(now, fx or effects.LOCATOR, SCREEN, PALETTE, reduced, dark)
+
+
+def arrival_state(fx, since, reduced=False, dark=True, palette=PALETTE):
+ x, y = MID
+ edge = effects.nearest_edge(x, y, SCREEN[0], SCREEN[1])
+ return effects.state(SCREEN[0], SCREEN[1], "mac", "switch", palette, reduced=reduced, dark=dark,
+ point=effects.point(x, y), edge=edge, since=since)
+
+
+class PlayerSwitchTests(unittest.TestCase):
+ def test_a_switch_waits_for_the_settle_then_plays_at_the_pointer(self):
+ player = effects.Player()
+ player.switched(10.0, MID, "top")
+ self.assertEqual(frames(player, 10.0 + effects.SWITCH_SETTLE_S / 2), [])
+ self.assertTrue(player.busy)
+ pens = frames(player, 10.0 + effects.SWITCH_SETTLE_S + 0.1)
+ self.assertEqual(len(pens), 1)
+ left, top, right, bottom = pens[0].bounds
+ self.assertTrue(left < MID[0] < right and top < MID[1] < bottom)
+
+ def test_a_switch_plays_out_and_ends(self):
+ player = effects.Player()
+ player.switched(10.0, MID, "top")
+ self.assertEqual(frames(player, 10.0 + effects.SWITCH_SETTLE_S + 1.0), [])
+ self.assertFalse(player.busy)
+
+ def test_a_crossing_arriving_during_the_settle_is_the_one_that_plays(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append(s.method) or pen.fillRect(0, 0, 4, 4), 0.1, 0.5)
+ player = effects.Player()
+ player.switched(10.0, MID, "top")
+ player.arrive(10.05, "edge", (2.0, 300.0), "left")
+ for step in range(10):
+ frames(player, 10.05 + step * 0.05, fx)
+ self.assertEqual(set(seen), {"edge"})
+
+ def test_a_switch_just_after_a_crossing_arrival_gives_way_to_it(self):
+ player = effects.Player()
+ player.arrive(10.0, "edge", (2.0, 300.0), "left")
+ player.switched(10.0 + effects.SWITCH_SETTLE_S / 2, MID, "top")
+ self.assertFalse(player.arrival["switch"])
+ self.assertEqual(player.arrival["at"], (2.0, 300.0))
+
+ def test_a_crossing_drawn_elsewhere_still_cancels_a_waiting_switch(self):
+ # Glow and Beam draw a crossing themselves and never tell the Player about it.
+ player = effects.Player()
+ player.switched(10.0, MID, "top")
+ player.crossed_in(10.05)
+ self.assertEqual(frames(player, 10.0 + effects.SWITCH_SETTLE_S + 0.1), [])
+ self.assertFalse(player.busy)
+ player.switched(10.1, MID, "top")
+ self.assertIsNone(player.arrival)
+
+ def test_a_later_switch_replaces_an_old_crossing_arrival(self):
+ player = effects.Player()
+ player.arrive(10.0, "edge", (2.0, 300.0), "left")
+ player.switched(10.5, MID, "top")
+ self.assertTrue(player.arrival["switch"])
+ self.assertEqual(player.arrival["at"], MID)
+
+ def test_a_switch_is_not_told_about_the_notch(self):
+ seen = []
+ fx = effects.Effect("probe", "Probe", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append(getattr(s, "notch", None)), 0.1, 0.5)
+ player = effects.Player()
+ player.switched(10.0, (860.0, 40.0), "top")
+ notch = {"x": 771, "y": 0, "w": 185, "h": 32, "r": 10}
+ player.frames(10.0 + effects.SWITCH_SETTLE_S + 0.1, fx, SCREEN, PALETTE, False, True, notch)
+ self.assertEqual(seen, [None])
+
+
+class SwitchStyleTests(unittest.TestCase):
+ def test_same_as_crossing_follows_the_crossing_style(self):
+ self.assertIs(effects.switch_effect("match", "glow"), effects.LOCATOR)
+ self.assertIs(effects.switch_effect("match", "beam"), effects.LOCATOR)
+ self.assertEqual(effects.switch_effect("match", "rupture").id, "rupture")
+
+ def test_a_chosen_style_wins_over_the_crossing_style(self):
+ self.assertIs(effects.switch_effect("locator", "rupture"), effects.LOCATOR)
+ self.assertEqual(effects.switch_effect("discharge", "glow").id, "discharge")
+
+ def test_the_picker_offers_every_choice_once(self):
+ offered = [value for _title, items in effects.switch_style_groups() for value, _name in items]
+ self.assertEqual(sorted(offered), sorted(effects.SWITCH_STYLES))
+ self.assertEqual(offered[:2], ["match", "locator"])
+
+ def test_a_switch_plays_its_own_effect_beside_the_crossing_one(self):
+ seen = []
+ own = effects.Effect("own", "Own", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append("own") or pen.fillRect(0, 0, 4, 4), 0.1, 0.5)
+ crossing_fx = effects.Effect("crossing", "Crossing", "quiet", "", lambda pen, s: None,
+ lambda pen, s: seen.append("crossing"), 0.1, 0.5)
+ player = effects.Player()
+ player.switched(10.0, MID, "top", own)
+ frames(player, 10.0 + effects.SWITCH_SETTLE_S + 0.1, crossing_fx)
+ self.assertEqual(seen, ["own"])
+
+
+class SwitchPreviewTests(unittest.TestCase):
+ def test_the_loop_rests_then_plays_round_the_pointer(self):
+ for fx in (effects.LOCATOR, effects.effect("rupture")):
+ with self.subTest(fx=fx.id):
+ self.assertEqual(effects.preview_switch_scene(fx, 0.1, PALETTE)["pens"], [])
+ scene = effects.preview_switch_scene(fx, 0.55, PALETTE)
+ self.assertTrue(scene["pens"])
+ self.assertEqual(len(scene["screens"]), 1)
+ self.assertEqual(effects.preview_size("switch"), effects.PREVIEW_SCREEN)
+
+
+class NearestEdgeTests(unittest.TestCase):
+ def test_each_side(self):
+ self.assertEqual(effects.nearest_edge(10, 500, 1000, 1000), "left")
+ self.assertEqual(effects.nearest_edge(990, 500, 1000, 1000), "right")
+ self.assertEqual(effects.nearest_edge(500, 10, 1000, 1000), "top")
+ self.assertEqual(effects.nearest_edge(500, 990, 1000, 1000), "bottom")
+
+
+class LocatorTests(unittest.TestCase):
+ def _bounds(self, since, reduced):
+ pen = effects.draw(effects.LOCATOR, "arrive", arrival_state(effects.LOCATOR, since, reduced))
+ return None if pen is None else pen.bounds
+
+ def test_it_is_never_more_than_260pt_across(self):
+ for reduced in (False, True):
+ for step in range(0, 80):
+ box = self._bounds(step / 100.0, reduced)
+ if box is None:
+ continue
+ with self.subTest(since=step / 100.0, reduced=reduced):
+ # The Pen pads its bounds by the stroke and two points each side.
+ self.assertLessEqual(box[2] - box[0], 260.0 + 12.0)
+ self.assertLessEqual(box[3] - box[1], 260.0 + 12.0)
+
+ def test_it_closes_onto_the_pointer(self):
+ start, end = self._bounds(0.05, False), self._bounds(0.45, False)
+ self.assertGreater(start[2] - start[0], 3 * (end[2] - end[0]))
+ for box in (start, end):
+ self.assertAlmostEqual((box[0] + box[2]) / 2, MID[0], delta=1.0)
+ self.assertAlmostEqual((box[1] + box[3]) / 2, MID[1], delta=1.0)
+
+ def test_reduce_motion_holds_its_size(self):
+ early, late = self._bounds(0.15, True), self._bounds(0.4, True)
+ self.assertAlmostEqual(early[2] - early[0], late[2] - late[0], delta=0.5)
+
+ def test_it_is_over_within_0_8s(self):
+ self.assertLessEqual(effects.LOCATOR.arrive_seconds, 0.8)
+ self.assertIsNone(self._bounds(effects.LOCATOR.arrive_seconds + 0.06, False))
+
+ def test_one_colour_and_many_both_draw(self):
+ for palette in (["#5fd4f4"], PALETTE):
+ with self.subTest(palette=palette):
+ pen = effects.draw(effects.LOCATOR, "arrive", arrival_state(effects.LOCATOR, 0.2, palette=palette))
+ self.assertTrue(pen.ops)
+
+
+class EveryEffectAwayFromAnEdgeTests(unittest.TestCase):
+ def test_each_arrival_plays_round_the_pointer(self):
+ for effect_id in effects.EFFECT_IDS:
+ fx = effects.effect(effect_id)
+ for reduced in (False, True):
+ for dark in (True, False):
+ with self.subTest(effect=effect_id, reduced=reduced, dark=dark):
+ pen = effects.draw(fx, "arrive", arrival_state(fx, 0.12, reduced, dark))
+ self.assertIsNotNone(pen, "drew nothing")
+ left, top, right, bottom = pen.bounds
+ centre = ((left + right) / 2, (top + bottom) / 2)
+ # Centred on the pointer, not left at the nearest edge 460pt away.
+ self.assertLess(math.dist(centre, MID), 60.0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_theme.py b/win_app/tests/test_theme.py
new file mode 100644
index 0000000..729dcd8
--- /dev/null
+++ b/win_app/tests/test_theme.py
@@ -0,0 +1,47 @@
+import unittest
+
+try:
+ import theme
+ import tokens
+except ImportError: # PySide6 is only in the Windows build venv
+ theme = None
+
+
[email protected](theme is None, "PySide6 is not installed")
+class SetDarkTests(unittest.TestCase):
+ def tearDown(self):
+ theme.set_dark(True)
+
+ def test_swaps_the_palette_and_back(self):
+ theme.set_dark(True)
+ self.assertEqual(theme.P, tokens.PALETTE)
+ self.assertTrue(theme.is_dark())
+ theme.set_dark(False)
+ self.assertEqual(theme.P, tokens.PALETTE_LIGHT)
+ self.assertFalse(theme.is_dark())
+ theme.set_dark(True)
+ self.assertEqual(theme.P, tokens.PALETTE)
+ self.assertTrue(theme.is_dark())
+
+ def test_stylesheet_carries_the_light_palette_when_light(self):
+ theme.set_dark(False)
+ self.assertIn(tokens.PALETTE_LIGHT["ground"], theme.stylesheet())
+ theme.set_dark(True)
+ self.assertIn(tokens.PALETTE["ground"], theme.stylesheet())
+
+
[email protected](theme is None, "PySide6 is not installed")
+class WantsDarkTests(unittest.TestCase):
+ def test_dark_and_light_are_absolute(self):
+ self.assertTrue(theme.wants_dark("dark", False))
+ self.assertFalse(theme.wants_dark("light", True))
+
+ def test_system_and_anything_unrecognised_follow_the_system(self):
+ self.assertTrue(theme.wants_dark("system", True))
+ self.assertFalse(theme.wants_dark("system", False))
+ self.assertTrue(theme.wants_dark("sepia", True))
+ self.assertFalse(theme.wants_dark("sepia", False))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_updates.py b/win_app/tests/test_updates.py
new file mode 100644
index 0000000..d41ddfb
--- /dev/null
+++ b/win_app/tests/test_updates.py
@@ -0,0 +1,91 @@
+import json
+import os
+import sys
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import updates
+
+
+def release(tag, **extra):
+ return dict({"tag_name": tag, "html_url": f"https://github.com/kalkman-code/beamer/releases/tag/{tag}",
+ "draft": False, "prerelease": False}, **extra)
+
+
+class NewerReleaseTests(unittest.TestCase):
+ def test_a_patch_release_is_quiet_unless_its_notes_announce_it(self):
+ self.assertIsNone(updates.newer_release("1.4.0", release("v1.4.1", body="Small fixes.")))
+ self.assertIsNone(updates.newer_release("1.4.0", release("v1.4.1")))
+ self.assertIsNotNone(updates.newer_release("1.4.0", release("v1.4.1", body="Fixes a crash.\n<!-- announce -->")))
+
+ def test_a_quiet_patch_still_offers_the_minor_version_someone_is_behind(self):
+ self.assertIsNotNone(updates.newer_release("1.4.2", release("v1.5.1", body="Small fixes.")))
+ self.assertIsNotNone(updates.newer_release("1.9.0", release("v2.0.1")))
+
+ def test_a_newer_tag_is_offered_with_its_page(self):
+ self.assertEqual(updates.newer_release("1.3.3", release("v1.4.0")),
+ ("1.4.0", "https://github.com/kalkman-code/beamer/releases/tag/v1.4.0"))
+
+ def test_the_same_or_an_older_tag_is_not(self):
+ self.assertIsNone(updates.newer_release("1.4.0", release("v1.4.0")))
+ self.assertIsNone(updates.newer_release("1.4.0", release("v1.3.9")))
+
+ def test_versions_compare_as_numbers(self):
+ self.assertIsNotNone(updates.newer_release("1.9.0", release("v1.10.0")))
+ self.assertIsNone(updates.newer_release("1.4", release("v1.4.1")))
+
+ def test_drafts_prereleases_and_odd_tags_never_count(self):
+ self.assertIsNone(updates.newer_release("1.3.3", release("v2.0.0", prerelease=True)))
+ self.assertIsNone(updates.newer_release("1.3.3", release("v2.0.0", draft=True)))
+ self.assertIsNone(updates.newer_release("1.3.3", release("v2.0.0-beta")))
+ self.assertIsNone(updates.newer_release("1.3.3", {"message": "rate limited"}))
+ self.assertIsNone(updates.newer_release("1.3.3", ["not", "a", "dict"]))
+
+ def test_a_dev_build_is_never_told_to_update(self):
+ self.assertIsNone(updates.newer_release("dev", release("v9.0.0")))
+
+ def test_a_page_outside_the_project_is_replaced_by_the_releases_page(self):
+ found = updates.newer_release("1.3.3", release("v1.4.0", html_url="https://example.com/beamer.exe"))
+ self.assertEqual(found, ("1.4.0", updates.RELEASES_PAGE))
+
+
+class CheckerTests(unittest.TestCase):
+ def make(self, payload=None, enabled=True, error=None):
+ results = []
+
+ def fetcher():
+ if error:
+ raise error
+ return json.dumps(payload).encode("utf-8")
+
+ checker = updates.Checker("1.3.3", lambda: enabled, results.append, fetcher=fetcher,
+ logger=updates.logging.getLogger("test-updates"))
+ return checker, results
+
+ def test_reports_a_newer_release(self):
+ checker, results = self.make(release("v1.4.0"))
+ checker.check_once()
+ self.assertEqual(results, [("1.4.0", "https://github.com/kalkman-code/beamer/releases/tag/v1.4.0")])
+
+ def test_reports_none_when_current(self):
+ checker, results = self.make(release("v1.3.3"))
+ checker.check_once()
+ self.assertEqual(results, [None])
+
+ def test_switched_off_it_asks_nothing(self):
+ checker, results = self.make(error=AssertionError("fetched while switched off"), enabled=False)
+ checker.check_once()
+ self.assertEqual(results, [])
+
+ def test_a_failed_check_keeps_the_last_answer(self):
+ checker, results = self.make(release("v1.4.0"))
+ checker.check_once()
+ checker.fetcher = lambda: (_ for _ in ()).throw(OSError("offline"))
+ checker.check_once()
+ self.assertEqual(checker.latest[0], "1.4.0")
+ self.assertEqual(len(results), 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_way_home.py b/win_app/tests/test_way_home.py
new file mode 100644
index 0000000..a72c657
--- /dev/null
+++ b/win_app/tests/test_way_home.py
@@ -0,0 +1,34 @@
+import sys
+import unittest
+from types import SimpleNamespace
+
+
[email protected](sys.platform == "win32", "the app module needs Windows")
+class WayHomeFollowsThisPcTests(unittest.TestCase):
+ """The Mac's pointer comes home through this PC's edge as this PC's own settings say."""
+
+ def model(self, methods, parts=("middle",), corner="bottom_left", edge="bottom"):
+ import kvm_bridge_win
+
+ config = SimpleNamespace(crossing_methods=list(methods), crossing_edge_parts=list(parts), crossing_corner=corner)
+ return kvm_bridge_win.WindowsApplication._return_model(SimpleNamespace(_config=config), edge, 120)
+
+ def test_part_of_the_edge_arms_only_its_thirds(self):
+ import return_edge
+
+ armed = self.model(["part", "shortcut"], parts=("start", "end"))
+ self.assertIsInstance(armed, return_edge.PartEdge)
+ self.assertEqual(armed.parts, frozenset({"start", "end"}))
+
+ def test_a_corner_on_that_edge_and_none_elsewhere(self):
+ import return_edge
+
+ self.assertIsInstance(self.model(["corner"], corner="bottom_left"), return_edge.CornerPush)
+ self.assertIsNone(self.model(["corner"], corner="top_left"))
+
+ def test_the_shortcut_alone_leaves_no_way_home_by_the_pointer(self):
+ self.assertIsNone(self.model(["shortcut"]))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/theme.py b/win_app/theme.py
index 971b35e..49915e6 100644
--- a/win_app/theme.py
+++ b/win_app/theme.py
@@ -1,4 +1,4 @@
-"""Vernier theming for the Windows receiver, built from tokens.py.
+"""Vernier theming for the Windows receiver, built from tokens.py, light and dark.
Widgets opt into a component with a `vernier` property set before the stylesheet is applied, or
re-polished with `repolish(widget)` after it changes. QSS cannot express letter spacing, so the
@@ -14,7 +14,10 @@ import sys
import titlebar
import tokens
-P = tokens.PALETTE
+# Swapped in place by set_dark(), never reassigned, so a widget that took a reference to P (the
+# stylesheet template's `values = dict(P)` included) sees the new palette without being rebuilt.
+P = dict(tokens.PALETTE)
+_dark = True
TYPE = tokens.TYPE
RADIUS = tokens.RADIUS
@@ -22,8 +25,7 @@ _sans = "Segoe UI"
_mono = "Consolas"
# Derived here because tokens.py has no value for them: the heading size inside a module (the
-# mock sets the Windows status word at 22px, between body and status_word_narrow), and the
-# countdown numeral (30px in the mock).
+# Windows status word, 22px, between body and status_word_narrow), and the countdown numeral.
HEADING = 22.0
COUNT = 30.0
@@ -33,9 +35,9 @@ COUNT = 30.0
# 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
-# pairing card) does not fit that row at 640 wide, so this page uses its own smaller size.
+# The pairing code sits beside the countdown and the Pair button, in a page narrowed by the
+# sidebar -- tokens.TYPE["code"] (92px, shared with the Mac's own pairing card) does not fit
+# that row at 640 wide, so this page uses its own smaller size.
PAIRING_CODE = 48.0
# One tone per receiver state, shared by the LED, the tray dot and the heading.
@@ -82,6 +84,65 @@ def colour(name: str) -> str:
return P[name]
+def set_dark(dark: bool) -> None:
+ """Swaps every colour `colour()`/`P` hands out to the dark or light palette, in place."""
+ global _dark
+ _dark = dark
+ P.clear()
+ P.update(tokens.PALETTE if dark else tokens.PALETTE_LIGHT)
+
+
+def is_dark() -> bool:
+ return _dark
+
+
+def wants_dark(choice: str, system_dark: bool) -> bool:
+ """What the `appearance` setting means for `set_dark`: "dark" and "light" are absolute,
+ "system" and anything unrecognised follow the system."""
+ if choice == "dark":
+ return True
+ if choice == "light":
+ return False
+ return system_dark
+
+
+def system_dark() -> bool:
+ """The system's own light/dark choice. AppsUseLightTheme, not the taskbar's
+ SystemUsesLightTheme, which Windows lets disagree with it -- this window is an app."""
+ try:
+ import winreg
+
+ with winreg.OpenKey(
+ winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"
+ ) as key:
+ return winreg.QueryValueEx(key, "AppsUseLightTheme")[0] == 0
+ except (ImportError, OSError):
+ pass
+ from PySide6.QtGui import QGuiApplication
+
+ app = QGuiApplication.instance()
+ if app is None:
+ return True
+ from PySide6.QtCore import Qt
+
+ return app.styleHints().colorScheme() == Qt.ColorScheme.Dark
+
+
+def watch_system(callback) -> None:
+ """Calls `callback()` whenever Windows' own light/dark choice changes, for "system" to follow
+ it live. A no-op with no QGuiApplication yet, or on a PySide6 old enough to predate
+ colorSchemeChanged (6.5) -- the guard costs nothing and the pin in requirements-win.txt may
+ move under us."""
+ from PySide6.QtGui import QGuiApplication
+
+ app = QGuiApplication.instance()
+ if app is None:
+ return
+ hints = app.styleHints()
+ if hasattr(hints, "colorSchemeChanged"):
+ hints.colorSchemeChanged.connect(lambda _scheme: callback())
+
+
def state_tone(state: str) -> str:
return STATE_TONE.get(state, "off")
@@ -163,6 +224,7 @@ QLabel[vernier="note"] {{ color: {ink_2}; font-size: {note}px; }}
QLabel[vernier="note-amber"] {{ color: {amber}; font-size: {note}px; }}
QLabel[vernier="note-fault"] {{ color: {fault}; font-size: {note}px; }}
QLabel[vernier="note-live"] {{ color: {signal}; font-size: {note}px; }}
+QLabel[vernier="note-quiet"] {{ color: {ink_3}; font-size: {note}px; }}
QLabel[vernier="key"] {{ color: {ink_2}; font-size: {note}px; }}
QLabel[vernier="mono"] {{ color: {ink_2}; font-family: "{mono}"; font-size: {note}px; }}
QLabel[vernier="readout"] {{ color: {ink}; font-family: "{mono}"; font-size: {note}px; font-weight: 700; }}
@@ -246,9 +308,8 @@ QLabel[vernier="tile-name"] {{ color: {ink}; font-size: {body}px; font-weight: 6
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"] {{ background: {ground}; border: 1px solid {edge}; 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;
@@ -310,6 +371,6 @@ QMenu::separator {{ height: 1px; background: {rule}; margin: 4px 6px; }}
def apply_titlebar(hwnd: int) -> None:
- """Paints the native title bar at hwnd in the Vernier ground, so it stops following the
- user's accent colour."""
- titlebar.apply_caption(hwnd, P)
+ """Paints the native title bar at hwnd in Vernier's current ground, light or dark, so it stops
+ following the user's accent colour."""
+ titlebar.apply_caption(hwnd, P, is_dark())
diff --git a/win_app/titlebar.py b/win_app/titlebar.py
index 365512f..fc9a5bf 100644
--- a/win_app/titlebar.py
+++ b/win_app/titlebar.py
@@ -26,10 +26,10 @@ def _colorref(hex_colour: str) -> int:
return (b << 16) | (g << 8) | r
-def apply_caption(hwnd: int, palette: dict) -> None:
+def apply_caption(hwnd: int, palette: dict, dark: bool = True) -> None:
"""Paints hwnd's native title bar with Vernier's ground, ink and rule from `palette`
- (tokens.PALETTE), replacing the Windows accent colour. Vernier is dark only, so this pins the
- native caption to dark mode too. Cosmetic only: any failure (older Windows, missing dwmapi, a
+ (theme.P), replacing the Windows accent colour, and toggles the native caption theme so the
+ caption buttons' glyphs follow. Cosmetic only: any failure (older Windows, missing dwmapi, a
bad hwnd) is swallowed so the caller's window still opens."""
if sys.platform != "win32":
return
@@ -37,9 +37,9 @@ def apply_caption(hwnd: int, palette: dict) -> None:
import ctypes
dwmapi = ctypes.windll.dwmapi
- dark = ctypes.c_int(1)
+ dark_mode = ctypes.c_int(1 if dark else 0)
for attribute in (DWMWA_USE_IMMERSIVE_DARK_MODE, 19): # 19 is the pre-20H1 alias
- if dwmapi.DwmSetWindowAttribute(hwnd, attribute, ctypes.byref(dark), ctypes.sizeof(dark)) == 0:
+ if dwmapi.DwmSetWindowAttribute(hwnd, attribute, ctypes.byref(dark_mode), ctypes.sizeof(dark_mode)) == 0:
break
caption = ctypes.c_int(_colorref(palette["ground"]))
dwmapi.DwmSetWindowAttribute(hwnd, DWMWA_CAPTION_COLOR, ctypes.byref(caption), ctypes.sizeof(caption))
diff --git a/win_app/tokens.py b/win_app/tokens.py
index 83c7627..dbb5b81 100644
--- a/win_app/tokens.py
+++ b/win_app/tokens.py
@@ -1,15 +1,18 @@
-"""Beamer's design tokens: the Vernier direction, chosen 10-09-2026.
+"""Beamer's design tokens: the Vernier direction.
-The mock is docs/designs/claude-2-vernier.html and its reasoning docs/designs/claude-2-vernier-notes.md.
This file is the one home for every colour, size, face and spring both apps draw with. The Mac app
reads it through the root theme.py; win_app/tokens.py is a byte-identical copy because PyInstaller
only bundles what sits under the app, and win_app's tests fail if the two drift. Edit this one, then
copy it across.
-Dark only. `signal` is the one colour that means something is happening: the link is up, input is on
-Windows, pressure is building, a permission is granted. The mock used lime; it was swapped for
-cockpit cyan at build time because lime on near-black is the stock developer-tool look, and B612
-Mono is a cockpit face. Reverting is this one value and `signal_dim`.
+`signal` is the one colour that means something is happening: the link is up, input is on Windows,
+pressure is building, a permission is granted. The mock used lime; it was swapped for cockpit cyan
+at build time because lime on near-black is the stock developer-tool look, and B612 Mono is a
+cockpit face. Reverting is this one value and `signal_dim`, in both palettes.
+
+PALETTE is the dark settings window and PALETTE_LIGHT the light one, the same names in the same
+roles, chosen by the `appearance` setting. The crossing effects and PALETTES take the dark `signal`
+whatever the window shows: they draw on the desktop, not on the window.
"""
PALETTE = {
@@ -32,6 +35,31 @@ PALETTE = {
# panel 5.5, edge on panel 3.5 (control boundaries), signal on panel 10.4, ground on signal 11.1,
# amber on panel 9.8, fault on panel 7.1.
+# Paper rather than the dark palette turned over: modules are lighter than the window, as in the dark
+# one, so a module still lifts off the ground and a well still sets a control apart from its module.
+# signal keeps its hue but drops to a depth that carries text on paper and a ground-coloured glyph on
+# itself. Measured WCAG ratios: ink on panel 16.4, ink_2 on panel 9.1 and on well 7.5, ink_3 on
+# panel 5.6 and on well 4.6, edge on panel 3.9 and on well 3.2, signal on panel 5.9 and on ground 5.4,
+# ground on signal 5.4, ink on signal_dim 12.3, amber on panel 5.4, fault on panel 5.8.
+PALETTE_LIGHT = {
+ "ground": "#f1f0ea",
+ "panel": "#fbfaf6",
+ "well": "#e5e4dc",
+ "rule": "#dcdbd3",
+ "edge": "#7f7e74",
+ "ink": "#1b1c18",
+ "ink_2": "#46463f",
+ "ink_3": "#66655c",
+ "signal": "#006a88",
+ "signal_dim": "#bfe0ea",
+ "amber": "#8f5c00",
+ "fault": "#b53522",
+ "off": "#aeada3",
+}
+
+# The `appearance` setting on both apps: follow the system, or keep one palette.
+APPEARANCES = ("system", "light", "dark")
+
UI_FAMILY = "Hanken Grotesk"
MONO_FAMILY = "B612 Mono"
FONT_FILES = (
diff --git a/win_app/touchpad_injector.py b/win_app/touchpad_injector.py
index 54f1dad..851b58d 100644
--- a/win_app/touchpad_injector.py
+++ b/win_app/touchpad_injector.py
@@ -4,8 +4,8 @@ decide what it does -- Task View for three fingers up, desktop switching for
four fingers sideways, with the same animation real fingers get.
Uses CreateSyntheticPointerDevice2 / InjectSyntheticPointerInput with
-PT_TOUCHPAD (Windows 11; documented 28-03-2026 with a pre-release banner,
-present on build 26200). Every entry point returns False rather than
+PT_TOUCHPAD (Windows 11; documented with a pre-release banner, present on
+build 26200). Every entry point returns False rather than
raising when the API is missing or refuses, so the caller can fall back to
a keyboard shortcut. Importable on macOS for the tests: nothing touches
user32 until a swipe is asked for.
diff --git a/win_app/unlock_win.py b/win_app/unlock_win.py
index 4c28899..49fa8bf 100644
--- a/win_app/unlock_win.py
+++ b/win_app/unlock_win.py
@@ -6,22 +6,22 @@ only reaches the desktop its calling thread is attached to. Running elevated
clears UIPI, not desktop access -- which is why an admin Beamer still cannot
touch a locked machine.
-So this module does not inject into the lock screen. It asks Room Deck's
-credential provider to take the machine *off* the lock screen, after which
-the console is back on the Default desktop and the ordinary
-input_injector.py path works unchanged.
-
-The provider (Room-Deck/room-deck-agent/provider) is a COM DLL that LogonUI
-loads as SYSTEM. It waits on an auto-reset event and, when signalled,
-submits the password stored in a machine-DPAPI blob. Its event's DACL grants
-Authenticated Users EVENT_MODIFY_STATE, so an unelevated Beamer can signal it
-and no Beamer process ever holds a password.
-
-Room Deck owns the provider; Beamer only knocks. Shipping a second provider
-would put two waiters on one auto-reset event, and losing that race is the
-exact bug that cost Room Deck a day (see its 28-08-2026 doc). If the
-provider is not installed, every call here fails cleanly and Beamer behaves
-as it did before.
+So this module does not inject into the lock screen. It asks an external
+unlock credential provider to take the machine *off* the lock screen, after
+which the console is back on the Default desktop and the ordinary
+input_injector.py path works unchanged. That provider is optional and not
+part of this repository.
+
+The provider is a COM DLL that LogonUI loads as SYSTEM. It waits on an
+auto-reset event and, when signalled, submits the password stored in a
+machine-DPAPI blob. Its event's DACL grants Authenticated Users
+EVENT_MODIFY_STATE, so an unelevated Beamer can signal it and no Beamer
+process ever holds a password.
+
+The provider owns the unlock; Beamer only knocks. Shipping a second
+provider would put two waiters on one auto-reset event, which is a real way
+to lose the signal. If the provider is not installed, every call here fails
+cleanly and Beamer behaves as it did before.
Guarded like clipboard_win.py and input_injector.py so it stays importable,
and its orchestration testable, on a machine without ctypes.windll.
@@ -40,10 +40,11 @@ _IS_WINDOWS = sys.platform == "win32"
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) if _IS_WINDOWS else None
-# Named by the provider as Global\RoomDeckUnlock.<its own session id>. Global
-# rather than Local because an RDP round trip leaves the agent and the console
-# in different sessions; the session suffix restores the per-session isolation
-# that stops a stale lock screen elsewhere swallowing the auto-reset signal.
+# The name is fixed by the provider: Global\RoomDeckUnlock.<its own session
+# id>. Global rather than Local because an RDP round trip leaves the
+# provider and the console in different sessions; the session suffix
+# restores the per-session isolation that stops a stale lock screen
+# elsewhere swallowing the auto-reset signal.
UNLOCK_EVENT_PREFIX = "Global\\RoomDeckUnlock."
EVENT_MODIFY_STATE = 0x0002
@@ -144,7 +145,7 @@ def signal_unlock(mem32=None) -> bool:
handle = mem32.OpenEventW(EVENT_MODIFY_STATE, False, name)
if not handle:
LOGGER.warning(
- "Could not open %s -- is the Room Deck unlock provider registered?", name
+ "Could not open %s -- is the unlock provider registered?", name
)
return False
try:
@@ -182,7 +183,7 @@ def ensure_unlocked(
LOGGER.info("Console unlocked after %.1fs", timeout - deadline)
return True
LOGGER.error(
- "Console still locked after %.0fs -- see C:\\ProgramData\\RoomDeck\\provider.log",
+ "Console still locked after %.0fs -- see the unlock provider's own log",
timeout,
)
return False
diff --git a/win_app/updates.py b/win_app/updates.py
new file mode 100644
index 0000000..21bfc57
--- /dev/null
+++ b/win_app/updates.py
@@ -0,0 +1,134 @@
+"""Whether a newer Beamer has been released, shared by mac_app and win_app (two identical copies;
+test_shared_copies checks they match).
+
+One HTTPS request to GitHub's public releases API when the app starts and once a day after, sending
+nothing but the request itself, and only while the `check_updates` setting is on. A newer release
+is shown quietly in the window and the menu; nothing downloads or installs, and nothing pops up.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+import sys
+import threading
+
+LATEST_URL = "https://api.github.com/repos/kalkman-code/beamer/releases/latest"
+RELEASES_PAGE = "https://github.com/kalkman-code/beamer/releases/latest"
+CHECK_EVERY_SECONDS = 24 * 60 * 60
+TIMEOUT_SECONDS = 10.0
+MAX_BYTES = 256 * 1024
+
+LOGGER = logging.getLogger(__name__)
+_VERSION = re.compile(r"^v?(\d+)\.(\d+)(?:\.(\d+))?$")
+
+
+def parse_version(text):
+ """(major, minor, patch) for "1.4", "1.4.0" or "v1.4.0", else None: a local "dev" build or a
+ tag in any other shape never reads as older or newer than anything."""
+ match = _VERSION.match(str(text or "").strip())
+ if not match:
+ return None
+ return tuple(int(part or 0) for part in match.groups())
+
+
+# In a release's notes, where GitHub renders nothing, it offers a patch release as an update too.
+ANNOUNCE = "<!-- announce -->"
+
+
+def newer_release(current, payload):
+ """(version text, page url) when `payload`, the API's JSON, names a release worth offering over
+ `current`, else None. A new minor or major version always is; a patch release (1.4.0 to 1.4.1)
+ only when its notes carry ANNOUNCE, so frequent small releases do not nag. Drafts and
+ prereleases never count."""
+ if not isinstance(payload, dict) or payload.get("draft") or payload.get("prerelease"):
+ return None
+ tag = payload.get("tag_name")
+ theirs, ours = parse_version(tag), parse_version(current)
+ if theirs is None or ours is None or theirs <= ours:
+ return None
+ body = payload.get("body")
+ if theirs[:2] == ours[:2] and not (isinstance(body, str) and ANNOUNCE in body):
+ return None
+ url = payload.get("html_url")
+ if not isinstance(url, str) or not url.startswith("https://github.com/kalkman-code/beamer/"):
+ url = RELEASES_PAGE
+ return (str(tag).lstrip("v"), url)
+
+
+def fetch(url=LATEST_URL):
+ """The response body as bytes. The Mac goes through Foundation, which trusts the system's
+ certificates; a bundled Python has no certificate store of its own there."""
+ if sys.platform == "darwin":
+ import Foundation
+
+ request = Foundation.NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_(
+ Foundation.NSURL.URLWithString_(url), Foundation.NSURLRequestReloadIgnoringLocalCacheData, TIMEOUT_SECONDS)
+ request.setValue_forHTTPHeaderField_("application/vnd.github+json", "Accept")
+ data, response, error = Foundation.NSURLConnection.sendSynchronousRequest_returningResponse_error_(
+ request, None, None)
+ if data is None or error is not None or response is None or response.statusCode() != 200:
+ raise OSError(f"update check failed: {error or (response.statusCode() if response else 'no response')}")
+ return bytes(data)[:MAX_BYTES]
+ import urllib.request
+
+ request = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json"})
+ with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
+ return response.read(MAX_BYTES)
+
+
+class Checker:
+ """Checks now and every CHECK_EVERY_SECONDS on its own thread while `enabled()` says so, and
+ calls `on_result((version, url) or None)` on that thread after each check that got an answer;
+ the owner marshals it. A failed check keeps the last answer and logs once."""
+
+ def __init__(self, current, enabled, on_result, fetcher=fetch, logger=None):
+ self.current = current
+ self.enabled = enabled
+ self.on_result = on_result
+ self.fetcher = fetcher
+ self.logger = logger or LOGGER
+ self.latest = None
+ self._wake = threading.Event()
+ self._stop = threading.Event()
+ self._thread = None
+ self._failed = False
+
+ def start(self):
+ if self._thread is None:
+ self._thread = threading.Thread(target=self._run, name="Beamer-updates", daemon=True)
+ self._thread.start()
+
+ def check_now(self):
+ """After the setting is switched on, rather than waiting a day."""
+ self._wake.set()
+
+ def stop(self):
+ self._stop.set()
+ self._wake.set()
+
+ def check_once(self):
+ if parse_version(self.current) is None or not self.enabled():
+ return
+ try:
+ payload = json.loads(self.fetcher().decode("utf-8"))
+ except Exception as exc:
+ if not self._failed:
+ self.logger.info("could not check for a newer Beamer: %s", exc)
+ self._failed = True
+ return
+ self._failed = False
+ self.latest = newer_release(self.current, payload)
+ if self.latest:
+ self.logger.info("Beamer %s is available", self.latest[0])
+ try:
+ self.on_result(self.latest)
+ except Exception:
+ self.logger.exception("update result callback failed")
+
+ def _run(self):
+ while not self._stop.is_set():
+ self.check_once()
+ self._wake.wait(CHECK_EVERY_SECONDS)
+ self._wake.clear()
diff --git a/win_app/widgets.py b/win_app/widgets.py
index 0960fa9..b5fd4dc 100644
--- a/win_app/widgets.py
+++ b/win_app/widgets.py
@@ -3,10 +3,11 @@ LED, the 60-segment countdown and the switch."""
from __future__ import annotations
-from PySide6.QtCore import QEvent, QRectF, QSize, Qt
-from PySide6.QtGui import QColor, QLinearGradient, QPainter, QPen
+from PySide6.QtCore import QEvent, QRect, QRectF, QSize, Qt
+from PySide6.QtGui import QColor, QFontMetrics, QLinearGradient, QPainter, QPen
from PySide6.QtWidgets import (
QApplication,
+ QButtonGroup,
QCheckBox,
QFrame,
QGraphicsOpacityEffect,
@@ -15,14 +16,18 @@ from PySide6.QtWidgets import (
QLabel,
QPushButton,
QSizePolicy,
+ QSlider,
QVBoxLayout,
QWidget,
)
+import motion
import theme
import tokens
LEFT_CTRL_VK = 0xA2
+# The smallest a Segmented cell or small button is drawn, so each is a fair target.
+MIN_TARGET = 28
def label(text: str, role: str, wrap: bool = False) -> QLabel:
@@ -38,6 +43,18 @@ def set_role(widget: QWidget, role: str) -> None:
theme.repolish(widget)
+def refresh_colours(root: QWidget) -> None:
+ """Re-paints every colour under `root` after theme.set_dark() swaps the palette: `update()`
+ for a widget that reads theme.colour() at paint time (nearly all of them), plus that widget's
+ own `refresh_colours()` for one that instead baked a colour into a stylesheet or rich text at
+ construction."""
+ for widget in (root, *root.findChildren(QWidget)):
+ own_refresh = getattr(widget, "refresh_colours", None)
+ if callable(own_refresh):
+ own_refresh()
+ widget.update()
+
+
class Eyebrow(QLabel):
def __init__(self, text: str, parent: QWidget | None = None) -> None:
super().__init__(text, parent)
@@ -137,6 +154,7 @@ class Choice:
button.setCheckable(True)
button.setAutoExclusive(True)
button.setCursor(Qt.CursorShape.PointingHandCursor)
+ button.setMinimumHeight(MIN_TARGET)
button.setChecked(value == current)
if on_change is not None:
button.clicked.connect(lambda _checked=False, v=value: on_change(v))
@@ -148,14 +166,26 @@ class Choice:
return next((value for value, button in self._buttons.items() if button.isChecked()), None)
def set_value(self, value) -> None:
+ """A value that is not a choice selects nothing."""
button = self._buttons.get(value)
- if button is not None and not button.isChecked():
+ if button is None:
+ for other in self._buttons.values():
+ if other.isChecked():
+ other.setAutoExclusive(False)
+ other.setChecked(False)
+ other.setAutoExclusive(True)
+ elif not button.isChecked():
button.setChecked(True)
def set_enabled(self, enabled: bool) -> None:
for button in self._buttons.values():
button.setEnabled(enabled)
+ def set_names(self, prefix: str) -> None:
+ """Each cell's accessible name leads with what the row chooses: "Where your Mac is, Left"."""
+ for button in self._buttons.values():
+ button.setAccessibleName(f"{prefix}, {button.text()}")
+
class _Tile(QFrame):
"""One tile of ChoiceTiles: the whole tile is the control, by click or by Space from Tab."""
@@ -181,8 +211,9 @@ class _Tile(QFrame):
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`."""
+ what it is. The chosen tile is ringed by the TileGroups it sits in, in ink, outside the tile, so
+ the signal focus border inside it still shows. `on_change(value)` fires only on a real choice,
+ never on `set_value`."""
def __init__(self, items, current, on_change=None, parent: QWidget | None = None) -> None:
self.on_change = on_change
@@ -193,9 +224,12 @@ class ChoiceTiles:
row.setContentsMargins(0, 0, 0, 0)
row.setSpacing(10)
self._tiles: dict = {}
+ self._titles: dict = {}
for value, title, detail, preview in items:
tile = _Tile(lambda v=value: self._chosen(v))
+ self._titles[value] = title
tile.setAccessibleName(title)
+ tile.setAccessibleDescription(detail)
column = QVBoxLayout(tile)
column.setContentsMargins(8, 8, 8, 12)
column.setSpacing(6)
@@ -212,6 +246,11 @@ class ChoiceTiles:
self.value = value
for candidate, tile in self._tiles.items():
set_role(tile, "tile-on" if candidate == value else "tile")
+ title = self._titles[candidate]
+ tile.setAccessibleName(f"{title}, selected" if candidate == value else title)
+
+ def tile(self, value):
+ return self._tiles.get(value)
def set_enabled(self, enabled: bool) -> None:
# Faded whole, previews included, as the Mac's tiles are.
@@ -230,7 +269,12 @@ class ChoiceTiles:
class _Swatch(QPushButton):
+ """A colour chip over its name. The name wraps onto a second line rather than widen the grid:
+ at the window's minimum width five chips a row have about 65px each."""
+
CHIP = 24
+ MIN_WIDTH = 44
+ NAME_GAP = 4
def __init__(self, colours, title: str, parent: QWidget | None = None) -> None:
super().__init__(title, parent)
@@ -239,59 +283,161 @@ class _Swatch(QPushButton):
self.setAutoExclusive(True)
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setAccessibleName(title)
- self.setFixedHeight(self.CHIP + 24)
- self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+ policy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
+ policy.setHeightForWidth(True)
+ self.setSizePolicy(policy)
+
+ def _face(self, chosen: bool):
+ return theme.font(tokens.TYPE["small"], 600 if chosen else 400)
+
+ def _name_height(self, width: int) -> int:
+ # Measured at the heavier weight so choosing a colour never re-wraps its name.
+ metrics = QFontMetrics(self._face(True))
+ return metrics.boundingRect(QRect(0, 0, max(1, width), 1000), int(Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignHCenter),
+ self.text()).height()
+
+ def hasHeightForWidth(self) -> bool:
+ return True
+
+ def heightForWidth(self, width: int) -> int:
+ return 3 + self.CHIP + self.NAME_GAP + self._name_height(width) + 2
def sizeHint(self) -> QSize:
- return QSize(max(56, self.fontMetrics().horizontalAdvance(self.text()) + 8), self.CHIP + 24)
+ width = max(56, QFontMetrics(self._face(True)).horizontalAdvance(self.text()) + 8)
+ return QSize(width, self.heightForWidth(width))
+
+ def minimumSizeHint(self) -> QSize:
+ return QSize(self.MIN_WIDTH, self.heightForWidth(self.MIN_WIDTH))
+
+ def chip_rect(self) -> QRectF:
+ return QRectF(3, 3, self.width() - 6, self.CHIP)
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)
+ chip = self.chip_rect()
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)
+ # The chosen chip's ink ring is SwatchGroups', outside the chip; focus is this signal
+ # border on the chip itself, so the two can be told apart when they fall on one chip.
if self.hasFocus():
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.drawRoundedRect(chip.adjusted(1, 1, -1, -1), radius, radius)
+ else:
+ painter.setPen(QPen(QColor(theme.colour("rule")), 1))
+ painter.drawRoundedRect(chip.adjusted(0.5, 0.5, -0.5, -0.5), radius, radius)
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.setFont(self._face(chosen))
painter.drawText(
- QRectF(0, chip.bottom() + 4, self.width(), self.height() - chip.bottom() - 4),
- Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop,
+ QRectF(0, chip.bottom() + self.NAME_GAP, self.width(), self.height() - chip.bottom() - self.NAME_GAP),
+ Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop | Qt.TextFlag.TextWordWrap,
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."""
+class TileGroups:
+ """ChoiceTiles in titled groups with one value across all of them: `groups` is (title, items)
+ with ChoiceTiles' items. `on_change(value)` fires only on a real choice. One ring marks the
+ chosen tile and slides to the next, across groups."""
- def __init__(self, items, current, on_change=None, parent: QWidget | None = None) -> None:
+ RING_OUTSET = 3
+
+ def __init__(self, groups, current, on_change=None, parent: QWidget | None = None) -> None:
+ self.on_change = on_change
+ self.value = current
self.view = QWidget(parent)
self.view.setProperty("vernier", "plain")
- row = QHBoxLayout(self.view)
- row.setContentsMargins(0, 0, 0, 0)
- row.setSpacing(8)
+ column = QVBoxLayout(self.view)
+ # Room for the ring outside the outermost tiles.
+ room = self.RING_OUTSET + 1
+ column.setContentsMargins(room, room, room, room)
+ column.setSpacing(6)
+ self.groups: dict = {}
+ for index, (title, items) in enumerate(groups):
+ if index:
+ column.addSpacing(8)
+ column.addWidget(label(title, "key"))
+ tiles = ChoiceTiles(items, current, on_change=self._chosen)
+ column.addWidget(tiles.view)
+ self.groups[title] = tiles
+ outset = self.RING_OUTSET
+ self.ring = motion.Ring(
+ self.view,
+ lambda tile: QRectF(tile.rect()).adjusted(-outset + 0.5, -outset + 0.5, outset - 0.5, outset - 0.5),
+ lambda: theme.colour("ink"),
+ tokens.RADIUS["button"] + outset,
+ )
+ self.ring.follow(self.tile(current))
+
+ def tile(self, value):
+ return next((tile for tiles in self.groups.values() if (tile := tiles.tile(value)) is not None), None)
+
+ def set_value(self, value) -> None:
+ self.value = value
+ for tiles in self.groups.values():
+ tiles.set_value(value)
+ self.ring.follow(self.tile(value))
+
+ def set_enabled(self, enabled: bool) -> None:
+ for tiles in self.groups.values():
+ tiles.set_enabled(enabled)
+
+ def _chosen(self, value) -> None:
+ self.set_value(value)
+ if self.on_change is not None:
+ self.on_change(value)
+
+
+class SwatchGroups:
+ """One colour of several in titled rows, each group's name over its chips as the style tiles'
+ are: `groups` is (title, ((value, name, colours), ...)). The chips share one exclusive group
+ across the rows and line up in equal columns, so a row of three sits under the first three of
+ a row of five. One ink ring marks the chosen chip and slides to the next.
+
+ The names sit over the chips, not in a column beside them: beside, the widest name plus five
+ chips outgrew the page at the window's minimum width and clipped the whole Design page."""
+
+ def __init__(self, groups, current, on_change=None, parent: QWidget | None = None) -> None:
+ self.view = QWidget(parent)
+ self.view.setProperty("vernier", "plain")
+ grid = QGridLayout(self.view)
+ grid.setContentsMargins(0, 0, 0, 0)
+ grid.setHorizontalSpacing(6)
+ grid.setVerticalSpacing(2)
+ self._group = QButtonGroup(self.view)
+ self._group.setExclusive(True)
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
+ widest = max(len(items) for _title, items in groups)
+ for row, (title, items) in enumerate(groups):
+ heading = label(title, "key")
+ if row:
+ heading.setContentsMargins(0, 8, 0, 0)
+ grid.addWidget(heading, row * 2, 0, 1, widest)
+ for index, (value, name, colours) in enumerate(items):
+ swatch = _Swatch(colours, name)
+ swatch.setAutoExclusive(False)
+ self._group.addButton(swatch)
+ swatch.setChecked(value == current)
+ swatch.toggled.connect(lambda on, s=swatch: on and self.ring.follow(s))
+ if on_change is not None:
+ swatch.clicked.connect(lambda _checked=False, v=value: on_change(v))
+ grid.addWidget(swatch, row * 2 + 1, index)
+ self._swatches[value] = swatch
+ for index in range(widest):
+ grid.setColumnStretch(index, 1)
+ self.ring = motion.Ring(
+ self.view,
+ lambda swatch: swatch.chip_rect().adjusted(-2.5, -2.5, 2.5, 2.5),
+ lambda: theme.colour("ink"),
+ tokens.RADIUS["field"] + 2.5,
+ )
+ self.ring.follow(self._swatches.get(current))
@property
def value(self):
@@ -322,8 +468,11 @@ class InputRecorder(QPushButton):
Qt.MouseButton.ForwardButton: "forward",
}
- def __init__(self, title: str, on_record, hook_vk, parent: QWidget | None = None, keys_only: bool = False) -> None:
+ def __init__(self, title: str, on_record, hook_vk, parent: QWidget | None = None, keys_only: bool = False,
+ name: str = "", mono: bool = True) -> None:
super().__init__(parent)
+ # What the recorder is, before what it shows: "Shortcut key, Right Ctrl".
+ self.name = name
self.title = title
self.on_record = on_record
self.hook_vk = hook_vk
@@ -333,13 +482,13 @@ class InputRecorder(QPushButton):
self.left_ctrl_held = False
self.setProperty("vernier", "keycap")
self.setCursor(Qt.CursorShape.PointingHandCursor)
- self.setAccessibleName(title)
- self.setFixedHeight(42)
+ self.setAccessibleName(self._spoken(title))
+ self.setFixedHeight(42 if mono else 36)
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.key.setFont(theme.mono_font(tokens.TYPE["field_mono"]) if mono else theme.font(tokens.TYPE["body"]))
self.hint = label(self.HINT, "small")
for part in (self.key, self.hint):
part.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
@@ -350,10 +499,13 @@ class InputRecorder(QPushButton):
def set_title(self, title: str) -> None:
"""What the keycap says while it is not recording: the trigger recorder shows its key."""
self.title = title
- self.setAccessibleName(title)
+ self.setAccessibleName(self._spoken(title))
if not self.armed:
self.key.setText(title)
+ def _spoken(self, title: str) -> str:
+ return f"{self.name}, {title}" if self.name else title
+
def cancel(self) -> None:
self.left_ctrl_held = False
if not self.armed:
@@ -387,7 +539,7 @@ class InputRecorder(QPushButton):
if vk == LEFT_CTRL_VK:
# AltGr arrives as a Left Ctrl Windows makes up, then the Right Alt pressed, so a
# Left Ctrl waits: let go, it is what was pressed; followed by another key, that
- # key is (proved on the rig 27-09-2026, where AltGr recorded as Left Ctrl).
+ # key is what was pressed (without this wait, AltGr records as Left Ctrl).
self.left_ctrl_held = True
return True
self.cancel()
@@ -445,7 +597,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, foot: str = "", on_foot=None, parent: QWidget | None = None) -> None:
+ def __init__(self, pages, on_select, foot: str = "", on_foot=None, foot_tip: str = "", parent: QWidget | None = None) -> None:
super().__init__(parent)
self.setProperty("vernier", "sidebar")
outer = QVBoxLayout(self)
@@ -481,7 +633,8 @@ class Sidebar(QWidget):
self.foot = QPushButton(foot)
self.foot.setProperty("vernier", "foot")
self.foot.setCursor(Qt.CursorShape.PointingHandCursor)
- self.foot.setToolTip("Open in your browser")
+ self.foot.setToolTip(foot_tip or "Open in your browser")
+ self.foot.setAccessibleName(foot.replace("\n", ", "))
if on_foot is not None:
self.foot.clicked.connect(on_foot)
outer.addWidget(self.foot)
@@ -501,6 +654,28 @@ class Sidebar(QWidget):
button.set_dot(marks.get(key))
+class Ruler(QSlider):
+ """A horizontal ruler, named for screen readers, stepping 10 on the arrow keys and 1 with Alt
+ held, as the Mac's steps 1 with Option."""
+
+ STEP = 10
+
+ def __init__(self, name: str, maximum: int, minimum: int = 0, parent: QWidget | None = None) -> None:
+ super().__init__(Qt.Orientation.Horizontal, parent)
+ self.setRange(minimum, maximum)
+ self.setSingleStep(self.STEP)
+ self.setPageStep(self.STEP * 5)
+ self.setAccessibleName(name)
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
+
+ def keyPressEvent(self, event) -> None:
+ steps = {Qt.Key.Key_Left: -1, Qt.Key.Key_Down: -1, Qt.Key.Key_Right: 1, Qt.Key.Key_Up: 1}
+ if event.modifiers() & Qt.KeyboardModifier.AltModifier and event.key() in steps:
+ self.setValue(self.value() + steps[event.key()])
+ return
+ super().keyPressEvent(event)
+
+
class Switch(QCheckBox):
"""A QCheckBox drawn as Vernier's switch: label left, track right."""
@@ -521,6 +696,8 @@ class Switch(QCheckBox):
def paintEvent(self, _event) -> None:
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ if not self.isEnabled():
+ painter.setOpacity(0.45)
on = self.isChecked()
track = QRectF(
self.width() - self.TRACK.width() - 2.5,