Skip to content

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

Beamer 1.5.0-beta.1

Toby Kalkman1ec7cbe4ece4
diff --git a/PAIRING.md b/PAIRING.md
index f620105..8054515 100644
--- a/PAIRING.md
+++ b/PAIRING.md
@@ -1,8 +1,8 @@
# Pairing
How two machines running Beamer agree a token from the six-digit code, exactly enough to write
-a second implementation. The code is `mac_app/pairing.py` (and its byte-identical copy in
-`win_app`); `mac_app/tests/pairing_vectors.json` holds test vectors for every step. What
+a second implementation. The code is `core/pairing.py`, which both apps
+import; `core/tests/pairing_vectors.json` holds test vectors for every step. What
pairing protects and what it does not is in [SECURITY.md](SECURITY.md).
Pairing is CPace, a password-authenticated key exchange, with the code as the password:
diff --git a/README.md b/README.md
index 5afb69d..c091690 100644
--- a/README.md
+++ b/README.md
@@ -395,9 +395,10 @@ A local Mac build is signed with the release's Developer ID identity when the lo
reach it, so privacy grants carry between local builds and releases, and ad-hoc otherwise (over
SSH), under the hardened runtime either way. It is not notarised.
-Files shared by both apps (`receiver.py`, `return_edge.py`, `pairing.py`, `ignored.py`, `tokens.py`
-and others) are byte-identical copies, because each app bundles only what sits under it; a test
-fails if a pair drifts. `Beamer.svg` is the master of the mark, and `Beamer.ico`, `Beamer.png` and
+What both apps run the same way (`protocol.py`, `pairing.py`, `receiver.py`, `return_edge.py`, the
+crossing effects and others) lives once in `core/`, which both apps import and both packagers
+bundle; `core/tests` runs inside each app's suite. `tokens.py` is still copied into `win_app`, and a
+test fails if the two drift. `Beamer.svg` is the master of the mark, and `Beamer.ico`, `Beamer.png` and
`Beamer.icns` are rendered from it.
</details>
diff --git a/VERSION b/VERSION
index 428b770..591650a 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.4.3
+1.5.0-beta.1
diff --git a/core/__init__.py b/core/__init__.py
new file mode 100644
index 0000000..64bd7f9
--- /dev/null
+++ b/core/__init__.py
@@ -0,0 +1,7 @@
+"""What both apps run the same way: the wire protocol and its pairing, the receiver, the crossing
+effects and their arithmetic, the settings both machines share, update checks and Wake-on-LAN.
+
+One copy, imported by mac_app, win_app and anything later, from the repository root (the apps put
+it on sys.path when run from source; both packagers bundle it). Everything platform-shaped is
+injected at construction, so nothing in here may import an app module at the top level.
+"""
diff --git a/mac_app/effects.py b/core/effects.py
similarity index 99%
rename from mac_app/effects.py
rename to core/effects.py
index ab4ac74..e5bc1fc 100644
--- a/mac_app/effects.py
+++ b/core/effects.py
@@ -9,8 +9,6 @@ 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
@@ -442,7 +440,7 @@ def _load():
import importlib
effects, packs = {}, {}
for module_name, _name, effect_ids, pack_ids in ALL_DIRECTIONS:
- module = importlib.import_module(module_name)
+ module = importlib.import_module(f"{__package__}.{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]
diff --git a/mac_app/fx_ink.py b/core/fx_ink.py
similarity index 99%
rename from mac_app/fx_ink.py
rename to core/fx_ink.py
index d0e587f..96c9471 100644
--- a/mac_app/fx_ink.py
+++ b/core/fx_ink.py
@@ -4,7 +4,7 @@ blooming into fluid wash on arrival.
import math
-import effects
+from . import effects
def _colour_at(pal, i):
diff --git a/mac_app/fx_instrument.py b/core/fx_instrument.py
similarity index 99%
rename from mac_app/fx_instrument.py
rename to core/fx_instrument.py
index 84bbc5a..5a2eb12 100644
--- a/mac_app/fx_instrument.py
+++ b/core/fx_instrument.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import math
from types import SimpleNamespace
-from effects import Effect, clamp, lerp
+from .effects import Effect, clamp, lerp
PI = math.pi
TAU = PI * 2.0
diff --git a/win_app/fx_membrane.py b/core/fx_membrane.py
similarity index 99%
rename from win_app/fx_membrane.py
rename to core/fx_membrane.py
index 8f2c89b..b348601 100644
--- a/win_app/fx_membrane.py
+++ b/core/fx_membrane.py
@@ -6,7 +6,7 @@ healing behind you.
import math
from types import SimpleNamespace
-import effects
+from . import effects
TAU = effects.TAU
clamp = effects.clamp
diff --git a/mac_app/fx_sparks.py b/core/fx_sparks.py
similarity index 99%
rename from mac_app/fx_sparks.py
rename to core/fx_sparks.py
index b60128f..2cc7df0 100644
--- a/mac_app/fx_sparks.py
+++ b/core/fx_sparks.py
@@ -6,8 +6,8 @@ from __future__ import annotations
import math
from types import SimpleNamespace
-import effects
-from effects import TAU, clamp, lerp
+from . import effects
+from .effects import TAU, clamp, lerp
INWARD = {"right": (-1, 0), "left": (1, 0), "top": (0, 1), "bottom": (0, -1)}
diff --git a/mac_app/fx_warp.py b/core/fx_warp.py
similarity index 99%
rename from mac_app/fx_warp.py
rename to core/fx_warp.py
index 2adb36c..9bc829b 100644
--- a/mac_app/fx_warp.py
+++ b/core/fx_warp.py
@@ -4,7 +4,7 @@ the pointer's trail into speed lines, arriving as a streak that decelerates into
import math
-import effects
+from . import effects
PACKS = {
"neon": ("Neon", ["#ff0055", "#00ffcc", "#ffcc00"]),
diff --git a/mac_app/ignored.py b/core/ignored.py
similarity index 98%
rename from mac_app/ignored.py
rename to core/ignored.py
index 5bc01a5..b7135a4 100644
--- a/mac_app/ignored.py
+++ b/core/ignored.py
@@ -6,7 +6,7 @@ other's list.
Each entry is a string: `key:<code>` for a key in the platform's own numbering, `button:<name>`
for a mouse button, and `media:<name>` for a Mac media key, which arrives as a system event rather
-than a key. Byte-identical in both apps.
+than a key.
"""
import re
diff --git a/win_app/pairing.py b/core/pairing.py
similarity index 99%
rename from win_app/pairing.py
rename to core/pairing.py
index fb0c916..52196d6 100644
--- a/win_app/pairing.py
+++ b/core/pairing.py
@@ -59,7 +59,7 @@ import time
from nacl.bindings import crypto_scalarmult
from nacl.exceptions import CryptoError
-import protocol
+from . import protocol
# One home for the port, in the module both apps share byte-for-byte.
PAIRING_PORT = protocol.PAIRING_PORT
@@ -199,12 +199,6 @@ def _x25519(scalar: bytes, point: bytes) -> bytes:
return product
-def _hkdf(key_material: bytes, salt: bytes, info: bytes) -> bytes:
- """HKDF-SHA256 (RFC 5869) for one 32-byte block."""
- extracted = hmac.new(salt, key_material, hashlib.sha256).digest()
- return hmac.new(extracted, info + b"\x01", hashlib.sha256).digest()
-
-
def _session_id(pair_id: str, nonce: bytes) -> bytes:
# Random bytes from both ends, as the draft recommends for sid: the host's in the pairing
# id, the requester's in its nonce.
@@ -230,7 +224,7 @@ def _keys(sid: bytes, shared: bytes, ya: bytes, ada: bytes, yb: bytes, adb: byte
def tag(message: bytes) -> bytes:
return hmac.new(mac_key, message, hashlib.sha512).digest()
- return _b64(_hkdf(isk, sid, TOKEN_INFO)), tag(_lv_cat(ya, ada)), tag(_lv_cat(yb, adb)), tag(_lv_cat(DONE_LABEL))
+ return _b64(protocol.hkdf_sha256(isk, sid, TOKEN_INFO)), tag(_lv_cat(ya, ada)), tag(_lv_cat(yb, adb)), tag(_lv_cat(DONE_LABEL))
def _failure(kind: str, pair_id: str, error: str) -> dict:
diff --git a/win_app/protocol.py b/core/protocol.py
similarity index 87%
rename from win_app/protocol.py
rename to core/protocol.py
index 3168324..426f286 100644
--- a/win_app/protocol.py
+++ b/core/protocol.py
@@ -25,6 +25,8 @@ secrecy: anyone who later learns the token can read a recording made before.
import base64
import binascii
+import hashlib
+import hmac
import json
import os
import socket
@@ -32,10 +34,12 @@ import struct
import threading
import time
-from cryptography.exceptions import InvalidTag
-from cryptography.hazmat.primitives import hashes
-from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
-from cryptography.hazmat.primitives.kdf.hkdf import HKDF
+from nacl.bindings import (
+ crypto_aead_chacha20poly1305_ietf_ABYTES,
+ crypto_aead_chacha20poly1305_ietf_decrypt,
+ crypto_aead_chacha20poly1305_ietf_encrypt,
+)
+from nacl.exceptions import CryptoError
HEADER_SIZE = 4
COUNTER_SIZE = 4
@@ -94,6 +98,7 @@ MSG_FOCUS = "focus"
MSG_GESTURE = "gesture"
MSG_SWITCH = "switch"
MSG_ARRANGEMENT = "arrangement"
+MSG_SETTINGS = "settings"
# System trackpad gestures. The Mac classifies one at the end of the movement and sends a
# single message; the name is the finger motion, not its meaning, so the receiver decides
@@ -141,13 +146,17 @@ class VersionMismatch(ProtocolError):
self.peer_version = peer_version
+def hkdf_sha256(key_material: bytes, salt: bytes, info: bytes) -> bytes:
+ """HKDF-SHA256 (RFC 5869) for one 32-byte block, the only length either key needs."""
+ extracted = hmac.new(salt, key_material, hashlib.sha256).digest()
+ return hmac.new(extracted, info + b"\x01", hashlib.sha256).digest()
+
+
def derive_key(token: str, sender_prefix: bytes, receiver_prefix: bytes) -> bytes:
"""The key for the frames one side seals and the other opens, on one
connection only: both prefixes are drawn fresh per connection, and their
order is the direction."""
- return HKDF(
- algorithm=hashes.SHA256(), length=32, salt=KEY_SALT, info=KEY_INFO + sender_prefix + receiver_prefix
- ).derive(token.encode("utf-8"))
+ return hkdf_sha256(token.encode("utf-8"), KEY_SALT, KEY_INFO + bytes(sender_prefix) + bytes(receiver_prefix))
class SecureSession:
@@ -166,9 +175,9 @@ class SecureSession:
raise ValueError("nonce prefix must be 8 bytes")
self.send_lock = threading.RLock()
self._send_counter = 0
- self._send_cipher = None
+ self._send_key = None
self.peer_prefix = None
- self._recv_cipher = None
+ self._recv_key = None
self._recv_counter = 0
def preamble(self) -> bytes:
@@ -187,33 +196,41 @@ class SecureSession:
if peer_prefix == self.prefix:
raise ProtocolError("peer echoed this side's nonce prefix")
with self.send_lock:
- self._send_cipher = ChaCha20Poly1305(derive_key(self._token, self.prefix, peer_prefix))
- self._recv_cipher = ChaCha20Poly1305(derive_key(self._token, peer_prefix, self.prefix))
- self.peer_prefix = peer_prefix
+ self._send_key = derive_key(self._token, self.prefix, peer_prefix)
+ self._recv_key = derive_key(self._token, peer_prefix, self.prefix)
+ self.peer_prefix = bytes(peer_prefix)
def seal(self, msg: dict) -> bytes:
body = json.dumps(msg).encode("utf-8")
with self.send_lock:
- if self._send_cipher is None:
+ if self._send_key is None:
raise ProtocolError("nothing is sealed before the peer's preamble")
if self._send_counter >= MAX_COUNTER:
raise ProtocolError("frame counter exhausted; reconnect")
self._send_counter += 1
counter = struct.pack(">I", self._send_counter)
- ciphertext = self._send_cipher.encrypt(self.prefix + counter, body, None)
+ ciphertext = crypto_aead_chacha20poly1305_ietf_encrypt(body, None, self.prefix + counter, self._send_key)
return struct.pack(">I", COUNTER_SIZE + len(ciphertext)) + counter + ciphertext
def open(self, body: bytes) -> dict:
- if self._recv_cipher is None:
+ if self._recv_key is None:
raise ProtocolError("frame received before the peer's preamble")
if len(body) <= COUNTER_SIZE:
raise ProtocolError("frame too short")
+ # PyNaCl takes bytes only; any other buffer is copied, and a non-buffer is a TypeError as it
+ # always was, never a tag failure.
+ body = bytes(memoryview(body))
(counter,) = struct.unpack(">I", body[:COUNTER_SIZE])
if counter != self._recv_counter + 1:
raise ProtocolError("frame counter did not advance; replay rejected")
+ sealed = body[COUNTER_SIZE:]
+ # Shorter than a tag cannot authenticate, and PyNaCl would fail to size its output
+ # buffer with a ValueError rather than refuse it, so it is refused here first.
+ if len(sealed) < crypto_aead_chacha20poly1305_ietf_ABYTES:
+ raise AuthenticationError() from None
try:
- plain = self._recv_cipher.decrypt(self.peer_prefix + body[:COUNTER_SIZE], body[COUNTER_SIZE:], None)
- except InvalidTag:
+ plain = crypto_aead_chacha20poly1305_ietf_decrypt(sealed, None, self.peer_prefix + body[:COUNTER_SIZE], self._recv_key)
+ except CryptoError:
raise AuthenticationError() from None
self._recv_counter = counter
try:
@@ -284,8 +301,9 @@ def hello_msg(return_edge: str = None, resistance_px: int = None) -> dict:
first crossing rather than after it -- which is what lets the receiver's
own machine push back across that same border unprompted. Both are
omitted when None and unknown keys are ignored, so this needs no version
- bump."""
- data = {"version": PROTOCOL_VERSION}
+ bump. `settings` says this end keeps settings in step (settings_sync), so an end
+ holding the switch on can tell an older peer that never will."""
+ data = {"version": PROTOCOL_VERSION, "settings": 1}
if return_edge is not None:
data["return_edge"] = return_edge
if resistance_px is not None:
@@ -296,8 +314,8 @@ def hello_msg(return_edge: str = None, resistance_px: int = None) -> dict:
def welcome_msg(error: str = None) -> dict:
"""Sent by the receiver to confirm authentication and protocol version.
`error` (e.g. "version_mismatch") is set when the sender's declared version
- is not supported."""
- data = {"version": PROTOCOL_VERSION}
+ is not supported. `settings` is the hello's: this end keeps settings in step."""
+ data = {"version": PROTOCOL_VERSION, "settings": 1}
if error is not None:
data["error"] = error
return {"type": MSG_WELCOME, "data": data}
@@ -457,6 +475,18 @@ def arrangement_wins(theirs: int, mine: int) -> bool:
return int(theirs or 0) > int(mine or 0)
+def settings_msg(data: dict) -> dict:
+ """Same on both machines: whether it is on, its stamp and, while on, the shared values, as
+ settings_sync.message_data builds them. Sent on every change while on and announced on every
+ new connection; an older Beamer ignores the type."""
+ return {"type": MSG_SETTINGS, "data": dict(data)}
+
+
+def keeps_settings(data) -> bool:
+ """Whether a hello's or welcome's data says the peer keeps settings in step."""
+ return isinstance(data, dict) and data.get("settings") == 1
+
+
def gesture_msg(name: str) -> dict:
"""One completed system gesture (a GESTURE_* name). Unknown message types are
ignored by the receiver, so this needs no protocol version bump."""
diff --git a/win_app/receiver.py b/core/receiver.py
similarity index 96%
rename from win_app/receiver.py
rename to core/receiver.py
index ea1a8af..a59483f 100644
--- a/win_app/receiver.py
+++ b/core/receiver.py
@@ -9,8 +9,8 @@ import time
from enum import Enum
from typing import Callable, Optional, Tuple
-import return_edge as crossing
-import protocol
+from . import return_edge as crossing
+from . import protocol
LOGGER = logging.getLogger(__name__)
@@ -164,8 +164,7 @@ class ReceiverServer:
self_target: str = "windows",
peer_target: str = "mac",
) -> None:
- # One module serves both machines: this file is byte-identical in
- # win_app and mac_app, which test_receiver_parity enforces. Everything
+ # One module serves both machines. Everything
# platform-shaped is handed in -- the injector, clipboard, desktop
# geometry and unlock modules, the two names that appear in status
# text, and the two wire target words -- so nothing below knows which
@@ -201,6 +200,14 @@ class ReceiverServer:
# change it, so this is how the change arrives at the end that did not
# make it.
self._arrangement_callback = arrangement_callback
+ # Same on both machines (settings_sync). `settings_callback(data)` fires on the session
+ # thread for each settings message; `announce()` returns the messages this end sends the
+ # moment a peer has authenticated -- its stamped arrangement and its settings -- so a
+ # change made while nobody was connected still reaches the other end; `peer_settings` is
+ # whether the latest peer's hello said it keeps settings in step, None before any.
+ self.settings_callback: Optional[Callable[[dict], None]] = None
+ self.announce: Callable[[], list] = lambda: []
+ self.peer_settings: Optional[bool] = None
# `arrival_callback(edge, x, y)` fires on the session thread each time
# a crossing lands the pointer here, with the edge it came in by and
# where it was placed, in the desktop module's coordinates, and with
@@ -512,8 +519,16 @@ class ReceiverServer:
# A peer that has just connected has its input at home, whatever the
# session it replaced was in the middle of.
self._hand_back(f"{self._peer_name} reconnected")
+ self.peer_settings = protocol.keeps_settings(hello)
self._notify_peer(address[0], hello)
self._set_status(ServerState.CONNECTED, f"Connected to {address[0]}")
+ try:
+ announcements = list(self.announce())
+ except Exception:
+ LOGGER.exception("Announce failed")
+ announcements = []
+ for announcement in announcements:
+ self._send_message(connection, session, announcement)
client_stop = threading.Event()
ack_due = threading.Event()
@@ -566,6 +581,10 @@ class ReceiverServer:
# Never recorded or acked as an input event, like ping.
self._handle_arrangement(message)
continue
+ if message_type == protocol.MSG_SETTINGS:
+ # Never recorded or acked as an input event, like ping.
+ self._handle_settings(message)
+ continue
if self._unlocking.is_set():
# Dropped, not queued: see _begin_unlock. Still recorded so
# the ACK sequence stays continuous and the Mac's watchdog
@@ -803,6 +822,15 @@ class ReceiverServer:
return False
return self._send_message(connection, session, protocol.arrangement_msg(mac_edge, set_at))
+ def send_settings(self, data: dict) -> bool:
+ """Tell the peer this end's settings state, over the connection it opened to this one."""
+ with self._lock:
+ connection = self._client
+ session = self._session_for(connection)
+ if connection is None or session is None:
+ return False
+ return self._send_message(connection, session, protocol.settings_msg(data))
+
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
@@ -839,6 +867,14 @@ class ReceiverServer:
except Exception:
LOGGER.exception("Arrangement callback failed")
+ def _handle_settings(self, message: dict) -> None:
+ if self.settings_callback is None or not isinstance(message.get("data"), dict):
+ return
+ try:
+ self.settings_callback(message["data"])
+ except Exception:
+ LOGGER.exception("Settings callback failed")
+
def _notify_peer(self, host: str, hello: dict) -> None:
if self._peer_callback is None:
return
diff --git a/mac_app/return_edge.py b/core/return_edge.py
similarity index 100%
rename from mac_app/return_edge.py
rename to core/return_edge.py
diff --git a/core/settings_sync.py b/core/settings_sync.py
new file mode 100644
index 0000000..689821a
--- /dev/null
+++ b/core/settings_sync.py
@@ -0,0 +1,226 @@
+"""Same on both machines: the Crossing and Design settings the Mac and the PC keep in step.
+
+Pure, with no AppKit and no Qt.
+Off by default. While it is on, a change to a shared setting at either end is sent to the other;
+on every new connection each end announces its own state and the newer `set_at` stands, as the
+arrangement does. Turning it on at one end turns it on at the other and carries this end's values
+across; turning it off turns it off at both and leaves each end with what it has.
+
+The wire speaks the Mac's names. The PC's settings are flat fields with a `crossing_` prefix on
+some, so each end has an adapter here: `mac_values`/`apply_mac` read and write the Mac's raw
+settings dict, `pc_values`/`apply_pc` the PC's Config. A corner names a place on the leaving
+machine's screen, and the two machines face each other, so it crosses the wire in the Mac's frame
+and the PC mirrors it across the border between them.
+
+Never shared, whatever the switch says: the Mac's notch way in and notch look, the haptics,
+whether crossings animate on each screen, the arrangement (it has its own stamped message, which
+also reaches an older Beamer), and anything outside the Crossing and Design pages.
+"""
+
+from . import effects
+from . import return_edge
+
+# The ways in both machines have; the notch is the Mac's alone, and a received set keeps the
+# receiver's own notch.
+WAYS = ("shortcut", "edge", "part", "corner")
+CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")
+TRIGGER_STYLES = ("double_tap", "hold")
+GLOW_STYLES = ("glow", "beam") + effects.EFFECT_IDS
+GLOW_COLOURS = ("signal", "colourful", "ocean", "sunset", "mono") + effects.PACK_IDS
+LENGTHS = tuple(value for value, _name in effects.LENGTHS)
+
+CROSSING_KEYS = ("methods", "edge_parts", "corner", "resistance_px", "block_while_dragging",
+ "trigger_key", "trigger_style", "double_tap_ms")
+DESIGN_KEYS = ("glow_style", "glow_colour", "effect_length", "shortcut_arrival", "shortcut_arrival_style")
+
+# The PC's field for each wire key; the PC's corner also needs mirroring (see pc_values).
+PC_FIELDS = {
+ "methods": "crossing_methods", "edge_parts": "crossing_edge_parts", "corner": "crossing_corner",
+ "resistance_px": "crossing_resistance_px", "block_while_dragging": "block_while_dragging",
+ "trigger_key": "trigger_key", "trigger_style": "trigger_style", "double_tap_ms": "double_tap_ms",
+ "glow_style": "glow_style", "glow_colour": "glow_colour", "effect_length": "effect_length",
+ "shortcut_arrival": "shortcut_arrival", "shortcut_arrival_style": "shortcut_arrival_style",
+}
+# The Mac keeps the shortcut at the top of its settings and the rest in `crossing`.
+MAC_TOP_LEVEL = ("trigger_key", "trigger_style", "double_tap_ms")
+
+
+def mirror_corner(corner, edge):
+ """`corner` as the machine across `edge` names the same place: the two screens face each other,
+ so the corner flips across the border and keeps its place along it. Its own inverse."""
+ vertical, horizontal = corner.split("_")
+ if edge in ("top", "bottom"):
+ vertical = "bottom" if vertical == "top" else "top"
+ else:
+ horizontal = "right" if horizontal == "left" else "left"
+ return f"{vertical}_{horizontal}"
+
+
+def _whole(value, low, high):
+ return not isinstance(value, bool) and isinstance(value, int) and low <= value <= high
+
+
+def _valid(key, value, trigger_keys):
+ if key == "methods":
+ return isinstance(value, list) and all(way in WAYS for way in value)
+ if key == "edge_parts":
+ return isinstance(value, list) and bool(value) and all(part in return_edge.PARTS for part in value)
+ if key == "corner":
+ return value in CORNERS
+ if key == "resistance_px":
+ return _whole(value, 0, 500)
+ if key in ("block_while_dragging", "shortcut_arrival"):
+ return isinstance(value, bool)
+ if key == "trigger_key":
+ return isinstance(value, str) and value in trigger_keys
+ if key == "trigger_style":
+ return value in TRIGGER_STYLES
+ if key == "double_tap_ms":
+ return _whole(value, 50, 2000)
+ if key == "glow_style":
+ return value in GLOW_STYLES
+ if key == "glow_colour":
+ return value in GLOW_COLOURS
+ if key == "effect_length":
+ return value in LENGTHS
+ if key == "shortcut_arrival_style":
+ return value in effects.SWITCH_STYLES
+ return False
+
+
+def message_data(on, set_at, values=None):
+ """What a `settings` message carries: whether it is on, when that or a shared value last
+ changed, and while on, the values."""
+ data = {"on": bool(on), "set_at": int(set_at)}
+ if on and values is not None:
+ data["crossing"] = {key: values[key] for key in CROSSING_KEYS if key in values}
+ data["design"] = {key: values[key] for key in DESIGN_KEYS if key in values}
+ return data
+
+
+def read(data, trigger_keys):
+ """(on, set_at, values) from a `settings` message's data, or None when it is not one. A value
+ this end cannot hold -- a key it does not have, an effect it does not know -- is left out
+ rather than failing the rest. Never raises: a malformed message must not take a link down."""
+ if not isinstance(data, dict) or not isinstance(data.get("on"), bool):
+ return None
+ set_at = data.get("set_at")
+ if isinstance(set_at, bool) or not isinstance(set_at, (int, float)):
+ return None
+ values = {}
+ for group, keys in (("crossing", CROSSING_KEYS), ("design", DESIGN_KEYS)):
+ section = data.get(group)
+ if not isinstance(section, dict):
+ continue
+ for key in keys:
+ if key in section and _valid(key, section[key], trigger_keys):
+ values[key] = list(section[key]) if isinstance(section[key], list) else section[key]
+ return data["on"], int(set_at), values
+
+
+def wins(theirs, mine):
+ """Whether the peer's state replaces this end's: the newer stamp stands, and a tie changes
+ nothing, so the copy that arrives over the second link is a no-op."""
+ return int(theirs or 0) > int(mine or 0)
+
+
+def next_stamp(held, now):
+ """The stamp for a change made here: now, or one past the stamp held if that is not older.
+ Two changes in one second would otherwise tie and the second be ignored at the other end, and
+ a peer whose clock runs ahead would win every time."""
+ return max(int(now), int(held or 0) + 1)
+
+
+def arrived(data, set_at_here, trigger_keys, held=None):
+ """What to do with a `settings` message that arrived: (on, set_at, values) to take in place of
+ this end's state, or None to keep it -- malformed, or no newer than what is held here.
+
+ Two ends that each changed something in the same second while apart meet with equal stamps
+ and different values. The Mac's stands: the PC passes `held`, its own (on, values), and takes a
+ tie that differs from it; the Mac never takes a tie, so nothing goes back and forth."""
+ read_back = read(data, trigger_keys)
+ if read_back is None:
+ return None
+ on, set_at, values = read_back
+ if wins(set_at, set_at_here):
+ return read_back
+ if held is not None and int(set_at) == int(set_at_here or 0) and set_at:
+ held_on, held_values = held
+ if on != held_on or (on and changed(held_values, {**held_values, **values})):
+ return read_back
+ return None
+
+
+def _in_order(values):
+ """The ways and thirds in one fixed order, as sets are: the windows build them in tile order,
+ and a saved list in another order is not a change."""
+ values["methods"] = [way for way in WAYS if way in (values.get("methods") or [])]
+ values["edge_parts"] = [part for part in return_edge.PARTS if part in (values.get("edge_parts") or [])]
+ return values
+
+
+def mac_values(raw):
+ """The shared values in the Mac's raw settings dict (settings_store.config_to_raw)."""
+ crossing = raw.get("crossing", {})
+ values = {key: raw[key] if key in MAC_TOP_LEVEL else crossing.get(key)
+ for key in CROSSING_KEYS + DESIGN_KEYS}
+ return _in_order(values)
+
+
+def apply_mac(raw, values):
+ """A copy of the Mac's raw settings with `values` in place. The notch stays in `methods` if it
+ was there: it is this Mac's own way in."""
+ raw = dict(raw)
+ crossing = dict(raw.get("crossing", {}))
+ for key, value in values.items():
+ if key in MAC_TOP_LEVEL:
+ raw[key] = value
+ elif key == "methods":
+ crossing[key] = list(value) + (["notch"] if "notch" in crossing.get("methods", []) else [])
+ else:
+ crossing[key] = list(value) if isinstance(value, list) else value
+ raw["crossing"] = crossing
+ return raw
+
+
+def pc_values(config):
+ """The shared values in the PC's Config, the corner in the Mac's frame. A PC that has not
+ learned where the Mac is mirrors as if it were on the right, the PC's own default."""
+ values = {key: getattr(config, field) for key, field in PC_FIELDS.items()}
+ values["corner"] = mirror_corner(values["corner"], config.mac_return_edge or "right")
+ return _in_order(values)
+
+
+def apply_pc(config, values):
+ """Sets `values` on the PC's Config in place; the corner arrives in the Mac's frame."""
+ for key, value in values.items():
+ if key == "corner":
+ value = mirror_corner(value, config.mac_return_edge or "right")
+ setattr(config, PC_FIELDS[key], list(value) if isinstance(value, list) else value)
+
+
+def changed(before, after):
+ """Whether any shared value differs between two value dicts."""
+ return any(before.get(key) != after.get(key) for key in CROSSING_KEYS + DESIGN_KEYS)
+
+
+# What the window says. `peer` is "PC" on the Mac and "Mac" on the PC.
+SHARED_PAGES = ("crossing", "design")
+
+
+def scope(page, peer, on, own):
+ """The line under a page's purpose: `own` (the page's usual "for this machine only") unless
+ the page is kept in step and the switch is on."""
+ if on and page in SHARED_PAGES:
+ return f"Kept the same as your {peer}. Change it on either machine."
+ return own
+
+
+def switch_note(peer, on, peer_too_old):
+ """The note under Overview's Same on both machines switch."""
+ if peer_too_old:
+ return f"Your {peer}'s Beamer is too old to keep settings in step. Update it to turn this on."
+ if on:
+ return f"The Crossing and Design pages match your {peer}'s. A change on either machine reaches the other."
+ return (f"Off: the Crossing and Design pages are this machine's own. On, they match your {peer}'s, "
+ "and a change on either reaches the other.")
diff --git a/core/tests/__init__.py b/core/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/mac_app/tests/pairing_vectors.json b/core/tests/pairing_vectors.json
similarity index 100%
rename from mac_app/tests/pairing_vectors.json
rename to core/tests/pairing_vectors.json
diff --git a/win_app/tests/test_ignored.py b/core/tests/test_ignored.py
similarity index 98%
rename from win_app/tests/test_ignored.py
rename to core/tests/test_ignored.py
index 244af59..b7db42c 100644
--- a/win_app/tests/test_ignored.py
+++ b/core/tests/test_ignored.py
@@ -2,7 +2,7 @@
import unittest
-import ignored
+from core import ignored
class GateTests(unittest.TestCase):
diff --git a/core/tests/test_no_copies.py b/core/tests/test_no_copies.py
new file mode 100644
index 0000000..240967c
--- /dev/null
+++ b/core/tests/test_no_copies.py
@@ -0,0 +1,38 @@
+"""What both apps share lives once, in core/. Until 1.5.0 each shared module was two byte-identical
+copies, one in mac_app/ and one in win_app/, kept in step by a test; a copy creeping back into
+either app would shadow nothing (the apps import `core.x`) but would drift unseen.
+
+This fails if any app folder, or its tests, holds a file named like one of core's.
+"""
+
+import os
+import unittest
+
+_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
+_CORE = os.path.dirname(_TESTS_DIR)
+_REPO_ROOT = os.path.dirname(_CORE)
+_APPS = ("mac_app", "win_app")
+
+
+def _files(folder, keep):
+ return {name for name in os.listdir(folder) if keep(name)}
+
+
+class NoCopiesTests(unittest.TestCase):
+ def test_no_app_holds_a_copy_of_a_core_module(self):
+ modules = _files(_CORE, lambda name: name.endswith(".py") and name != "__init__.py")
+ self.assertIn("protocol.py", modules)
+ for app in _APPS:
+ with self.subTest(app=app):
+ self.assertEqual(modules & _files(os.path.join(_REPO_ROOT, app), lambda name: name.endswith(".py")), set())
+
+ def test_no_app_holds_a_copy_of_a_core_test(self):
+ tests = _files(_TESTS_DIR, lambda name: name != "__init__.py" and not name.startswith("__"))
+ self.assertIn("pairing_vectors.json", tests)
+ for app in _APPS:
+ with self.subTest(app=app):
+ self.assertEqual(tests & _files(os.path.join(_REPO_ROOT, app, "tests"), lambda name: True), set())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_pairing_cpace.py b/core/tests/test_pairing_cpace.py
similarity index 99%
rename from win_app/tests/test_pairing_cpace.py
rename to core/tests/test_pairing_cpace.py
index 078bbd6..d7f8780 100644
--- a/win_app/tests/test_pairing_cpace.py
+++ b/core/tests/test_pairing_cpace.py
@@ -8,8 +8,8 @@ import json
import os
import unittest
-import pairing
-from pairing import PairingClient, PairingError, PairingHost, encode
+from core import pairing
+from core.pairing import PairingClient, PairingError, PairingHost, encode
_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
@@ -97,7 +97,7 @@ class PublishedVectorTests(unittest.TestCase):
def test_hkdf_matches_rfc_5869(self):
# Test case 1, whose first 32 bytes are the single block this HKDF produces.
- block = pairing._hkdf(bytes([0x0B]) * 22, bytes(range(13)), bytes(range(0xF0, 0xFA)))
+ block = pairing.protocol.hkdf_sha256(bytes([0x0B]) * 22, bytes(range(13)), bytes(range(0xF0, 0xFA)))
self.assertEqual(block.hex(), "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf")
diff --git a/core/tests/test_settings_sync.py b/core/tests/test_settings_sync.py
new file mode 100644
index 0000000..16c2018
--- /dev/null
+++ b/core/tests/test_settings_sync.py
@@ -0,0 +1,158 @@
+"""Same on both machines, without AppKit or Qt: the message, the merge and the window's words."""
+
+import unittest
+from types import SimpleNamespace
+
+from core import settings_sync
+
+KEYS = {"alt_r", "cmd_r", "f13"}
+
+
+def mac_raw(**crossing):
+ base = {
+ "methods": ["shortcut", "edge", "notch"], "edge": "right", "edge_parts": ["middle"],
+ "corner": "top_right", "resistance_px": 120, "block_while_dragging": True, "glow": True,
+ "glow_style": "glow", "glow_colour": "signal", "effect_length": "normal", "shortcut_arrival": True,
+ "shortcut_arrival_style": "match", "notch_style": "beam", "notch_after_ms": 1200, "haptics": True,
+ "hold_full_screen": False,
+ }
+ base.update(crossing)
+ return {"trigger_key": "alt_r", "trigger_style": "double_tap", "double_tap_ms": 300,
+ "appearance": "dark", "crossing": base}
+
+
+def pc_config(**fields):
+ base = dict(
+ crossing_methods=["edge", "shortcut"], crossing_edge_parts=["middle"], crossing_corner="top_left",
+ crossing_resistance_px=120, block_while_dragging=True, trigger_key="cmd_r", trigger_style="double_tap",
+ double_tap_ms=300, glow_style="glow", glow_colour="signal", effect_length="normal",
+ shortcut_arrival=True, shortcut_arrival_style="match", mac_return_edge="left", edge_glow=True,
+ appearance="light",
+ )
+ base.update(fields)
+ return SimpleNamespace(**base)
+
+
+class CornerTests(unittest.TestCase):
+ def test_a_corner_flips_across_the_border_and_keeps_its_place_along_it(self):
+ self.assertEqual(settings_sync.mirror_corner("top_right", "right"), "top_left")
+ self.assertEqual(settings_sync.mirror_corner("bottom_left", "left"), "bottom_right")
+ self.assertEqual(settings_sync.mirror_corner("top_right", "top"), "bottom_right")
+
+ def test_mirroring_is_its_own_inverse(self):
+ for corner in settings_sync.CORNERS:
+ for edge in ("left", "right", "top", "bottom"):
+ self.assertEqual(settings_sync.mirror_corner(settings_sync.mirror_corner(corner, edge), edge), corner)
+
+
+class MessageTests(unittest.TestCase):
+ def test_off_carries_no_values(self):
+ data = settings_sync.message_data(False, 50, settings_sync.mac_values(mac_raw()))
+ self.assertEqual(data, {"on": False, "set_at": 50})
+
+ def test_on_carries_crossing_and_design_and_never_the_notch_or_this_machines_own(self):
+ data = settings_sync.message_data(True, 50, settings_sync.mac_values(mac_raw()))
+ self.assertEqual(set(data["crossing"]), set(settings_sync.CROSSING_KEYS))
+ self.assertEqual(set(data["design"]), set(settings_sync.DESIGN_KEYS))
+ self.assertEqual(data["crossing"]["methods"], ["shortcut", "edge"])
+ flat = {**data["crossing"], **data["design"]}
+ for own in ("notch_style", "notch_after_ms", "haptics", "glow", "appearance", "edge", "hold_full_screen"):
+ self.assertNotIn(own, flat)
+
+ def test_a_round_trip_reads_back_what_was_sent(self):
+ values = settings_sync.mac_values(mac_raw())
+ on, set_at, read = settings_sync.read(settings_sync.message_data(True, 7, values), KEYS)
+ self.assertEqual((on, set_at), (True, 7))
+ self.assertEqual(read, values)
+
+ def test_a_value_this_end_cannot_hold_is_left_out_and_the_rest_kept(self):
+ data = settings_sync.message_data(True, 7, settings_sync.mac_values(mac_raw()))
+ data["crossing"]["trigger_key"] = "hyper"
+ data["crossing"]["resistance_px"] = 9000
+ data["design"]["glow_style"] = "from-the-future"
+ data["crossing"]["methods"] = ["edge", "notch"]
+ _on, _set_at, values = settings_sync.read(data, KEYS)
+ for dropped in ("trigger_key", "resistance_px", "glow_style", "methods"):
+ self.assertNotIn(dropped, values)
+ self.assertEqual(values["corner"], "top_right")
+
+ def test_malformed_data_is_not_a_message(self):
+ for data in (None, [], {}, {"on": "yes", "set_at": 1}, {"on": True}, {"on": True, "set_at": True}):
+ self.assertIsNone(settings_sync.read(data, KEYS))
+
+ def test_a_change_here_always_stamps_newer_than_what_is_held(self):
+ self.assertEqual(settings_sync.next_stamp(0, 1000.7), 1000)
+ self.assertEqual(settings_sync.next_stamp(1000, 1000.2), 1001)
+ # A peer's clock ahead of this one's: the change made here still wins.
+ self.assertEqual(settings_sync.next_stamp(5000, 1000), 5001)
+
+ def test_a_tie_goes_to_the_mac_and_only_when_it_differs(self):
+ mac = settings_sync.message_data(True, 100, settings_sync.mac_values(mac_raw(glow_style="beam")))
+ pc_same = (True, settings_sync.mac_values(mac_raw(glow_style="beam")))
+ pc_other = (True, settings_sync.mac_values(mac_raw(glow_style="glow")))
+ self.assertIsNone(settings_sync.arrived(mac, 100, KEYS))
+ self.assertIsNone(settings_sync.arrived(mac, 100, KEYS, pc_same))
+ self.assertEqual(settings_sync.arrived(mac, 100, KEYS, pc_other)[2]["glow_style"], "beam")
+ self.assertIsNone(settings_sync.arrived(settings_sync.message_data(False, 0), 0, KEYS, (True, {})))
+
+ def test_only_a_newer_stamp_wins(self):
+ self.assertTrue(settings_sync.wins(2, 1))
+ self.assertFalse(settings_sync.wins(1, 1))
+ self.assertFalse(settings_sync.wins(0, 0))
+
+
+class AdapterTests(unittest.TestCase):
+ def test_the_mac_keeps_its_notch_and_its_own_rows(self):
+ raw = mac_raw()
+ values = settings_sync.mac_values(mac_raw(methods=["corner"], glow_style="beam", resistance_px=40))
+ values["trigger_key"] = "f13"
+ applied = settings_sync.apply_mac(raw, values)
+ self.assertEqual(applied["crossing"]["methods"], ["corner", "notch"])
+ self.assertEqual((applied["crossing"]["glow_style"], applied["crossing"]["resistance_px"]), ("beam", 40))
+ self.assertEqual(applied["trigger_key"], "f13")
+ for own in ("notch_style", "notch_after_ms", "haptics", "glow", "edge"):
+ self.assertEqual(applied["crossing"][own], raw["crossing"][own])
+ self.assertEqual(applied["appearance"], "dark")
+ self.assertEqual(raw["crossing"]["methods"], ["shortcut", "edge", "notch"])
+
+ def test_a_mac_without_the_notch_gains_none(self):
+ applied = settings_sync.apply_mac(mac_raw(methods=["edge"]), {"methods": ["corner"]})
+ self.assertEqual(applied["crossing"]["methods"], ["corner"])
+
+ def test_the_pc_sends_its_corner_in_the_macs_frame_and_takes_one_back_in_its_own(self):
+ config = pc_config(crossing_corner="top_left", mac_return_edge="left")
+ self.assertEqual(settings_sync.pc_values(config)["corner"], "top_right")
+ settings_sync.apply_pc(config, {"corner": "bottom_right"})
+ self.assertEqual(config.crossing_corner, "bottom_left")
+
+ def test_values_from_the_mac_land_on_the_pcs_fields_and_leave_its_own(self):
+ config = pc_config()
+ values = settings_sync.mac_values(mac_raw(glow_colour="ocean", edge_parts=["start", "end"]))
+ settings_sync.apply_pc(config, values)
+ self.assertEqual(config.crossing_methods, ["shortcut", "edge"])
+ self.assertEqual(config.crossing_edge_parts, ["start", "end"])
+ self.assertEqual((config.glow_colour, config.trigger_key), ("ocean", "alt_r"))
+ self.assertEqual((config.edge_glow, config.appearance, config.mac_return_edge), (True, "light", "left"))
+
+ def test_a_change_is_seen_only_in_a_shared_value(self):
+ before = settings_sync.mac_values(mac_raw())
+ self.assertFalse(settings_sync.changed(before, settings_sync.mac_values(mac_raw(notch_style="island", glow=False))))
+ self.assertTrue(settings_sync.changed(before, settings_sync.mac_values(mac_raw(effect_length="long"))))
+
+
+class WordsTests(unittest.TestCase):
+ def test_a_shared_page_says_so_only_while_on(self):
+ own = "For this Mac only; the PC keeps its own."
+ self.assertEqual(settings_sync.scope("crossing", "PC", False, own), own)
+ self.assertEqual(settings_sync.scope("design", "PC", True, own),
+ "Kept the same as your PC. Change it on either machine.")
+ self.assertEqual(settings_sync.scope("keyboard", "Mac", True, own), own)
+
+ def test_the_switch_note_names_both_pages_and_an_old_peer(self):
+ self.assertIn("Crossing and Design", settings_sync.switch_note("Mac", True, False))
+ self.assertIn("Crossing and Design", settings_sync.switch_note("Mac", False, False))
+ self.assertIn("too old", settings_sync.switch_note("PC", True, True))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_switch_arrival.py b/core/tests/test_switch_arrival.py
similarity index 99%
rename from win_app/tests/test_switch_arrival.py
rename to core/tests/test_switch_arrival.py
index 532b99c..62020a7 100644
--- a/win_app/tests/test_switch_arrival.py
+++ b/core/tests/test_switch_arrival.py
@@ -5,7 +5,7 @@ edge. Byte-identical in mac_app and win_app."""
import math
import unittest
-import effects
+from core import effects
SCREEN = (1728.0, 1117.0, "mac")
MID = (700.0, 460.0)
diff --git a/mac_app/tests/test_updates.py b/core/tests/test_updates.py
similarity index 67%
rename from mac_app/tests/test_updates.py
rename to core/tests/test_updates.py
index d41ddfb..02e2b6e 100644
--- a/mac_app/tests/test_updates.py
+++ b/core/tests/test_updates.py
@@ -1,11 +1,7 @@
import json
-import os
-import sys
import unittest
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-import updates
+from core import updates
def release(tag, **extra):
@@ -50,6 +46,37 @@ class NewerReleaseTests(unittest.TestCase):
self.assertEqual(found, ("1.4.0", updates.RELEASES_PAGE))
+class BetaTests(unittest.TestCase):
+ def test_a_beta_reads_its_own_version(self):
+ self.assertIsNotNone(updates.parse_version("1.5.0-beta.1"))
+ self.assertIsNone(updates.parse_version("1.5.0-beta"))
+ self.assertIsNone(updates.parse_version("1.5.0-rc.1"))
+
+ def test_the_public_release_is_offered_to_a_beta_without_an_announce(self):
+ self.assertEqual(updates.newer_release("1.5.0-beta.1", release("v1.5.0"))[0], "1.5.0")
+ self.assertEqual(updates.newer_release("1.5.0-beta.1", release("v1.5.1"))[0], "1.5.1")
+ self.assertEqual(updates.newer_release("1.5.0-beta.3", release("v1.6.0"))[0], "1.6.0")
+
+ def test_an_older_release_is_not_offered_to_a_beta(self):
+ self.assertIsNone(updates.newer_release("1.5.0-beta.1", release("v1.4.3")))
+ self.assertIsNone(updates.newer_release("1.5.0-beta.1", release("v1.4.9", body="<!-- announce -->")))
+
+ def test_a_beta_is_never_offered_to_anyone(self):
+ self.assertIsNone(updates.newer_release("1.4.3", release("v1.5.0-beta.2")))
+ self.assertIsNone(updates.newer_release("1.4.3", release("v1.5.0-beta.2", prerelease=True)))
+ self.assertIsNone(updates.newer_release("1.5.0-beta.1", release("v1.5.0-beta.2")))
+ self.assertIsNone(updates.newer_release("1.5.0-beta.1", release("v1.5.0-beta.2", prerelease=True)))
+ self.assertIsNone(updates.newer_release("1.4.3", release("v1.5.0", prerelease=True)))
+
+ def test_a_beta_checks_for_updates_like_any_install(self):
+ results = []
+ checker = updates.Checker("1.5.0-beta.1", lambda: True, results.append,
+ fetcher=lambda: json.dumps(release("v1.5.0")).encode("utf-8"),
+ logger=updates.logging.getLogger("test-updates"))
+ checker.check_once()
+ self.assertEqual([r[0] for r in results], ["1.5.0"])
+
+
class CheckerTests(unittest.TestCase):
def make(self, payload=None, enabled=True, error=None):
results = []
diff --git a/core/tests/test_wire_vectors.py b/core/tests/test_wire_vectors.py
new file mode 100644
index 0000000..b82ad05
--- /dev/null
+++ b/core/tests/test_wire_vectors.py
@@ -0,0 +1,224 @@
+"""The link's crypto against the committed v5 vectors in tools/phone_vectors.json, byte for byte.
+
+The vectors were written by the cryptography-backed protocol.py of 1.4.x and are never
+regenerated: libsodium through PyNaCl has to reproduce them exactly, in both directions, or a
+1.5 app cannot talk to a 1.4 one or to the phone apps built against the same file. Each vector is
+checked twice, once through protocol.py and once through the raw primitives with no protocol.py
+in the way, so a mistake in the module and a mistake in the primitives cannot cancel out.
+
+Also here: the failures are refused the way callers expect (AuthenticationError, and the
+counter not spent), the pairing section's low-order shares are still refused, and no module of
+either app imports cryptography, whose macOS wheels no longer run on Intel Macs.
+"""
+
+import ast
+import hashlib
+import hmac
+import json
+import os
+import struct
+import unittest
+
+from nacl.bindings import crypto_aead_chacha20poly1305_ietf_decrypt, crypto_aead_chacha20poly1305_ietf_encrypt
+
+from core import pairing
+from core import protocol
+
+_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
+_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))
+
+with open(os.path.join(_REPO_ROOT, "tools", "phone_vectors.json"), encoding="utf-8") as _handle:
+ VECTORS = json.load(_handle)
+
+
+def _hkdf_sha256(key_material, salt, info):
+ """RFC 5869 by hand, for one 32-byte block: an independent check on the module's HKDF."""
+ extracted = hmac.new(salt, key_material, hashlib.sha256).digest()
+ return hmac.new(extracted, info + b"\x01", hashlib.sha256).digest()
+
+
+def _frame_parts(frame_hex):
+ frame = bytes.fromhex(frame_hex)
+ (length,) = struct.unpack(">I", frame[:protocol.HEADER_SIZE])
+ body = frame[protocol.HEADER_SIZE:]
+ assert length == len(body)
+ return body[:protocol.COUNTER_SIZE], body[protocol.COUNTER_SIZE:]
+
+
+class DeriveKeyVectorTests(unittest.TestCase):
+ def test_the_salt_and_info_are_the_ones_in_the_file(self):
+ vector = VECTORS["derive_key"]
+ self.assertEqual(vector["salt_ascii"].encode("ascii"), protocol.KEY_SALT)
+ self.assertEqual(vector["info_label_ascii"].encode("ascii"), protocol.KEY_INFO)
+ self.assertEqual(VECTORS["protocol_version"], protocol.PROTOCOL_VERSION)
+
+ def test_the_module_derives_the_committed_key(self):
+ vector = VECTORS["derive_key"]
+ sender, receiver = bytes.fromhex(vector["sender_prefix_hex"]), bytes.fromhex(vector["receiver_prefix_hex"])
+ self.assertEqual(protocol.derive_key(vector["token"], sender, receiver).hex(), vector["key_hex"])
+
+ def test_hmac_by_hand_derives_the_committed_key(self):
+ vector = VECTORS["derive_key"]
+ info = vector["info_label_ascii"].encode("ascii") + bytes.fromhex(vector["sender_prefix_hex"]) + bytes.fromhex(vector["receiver_prefix_hex"])
+ key = _hkdf_sha256(vector["token"].encode("utf-8"), vector["salt_ascii"].encode("ascii"), info)
+ self.assertEqual(key.hex(), vector["key_hex"])
+
+ def test_the_two_directions_have_different_keys(self):
+ vector = VECTORS["derive_key"]
+ sender, receiver = bytes.fromhex(vector["sender_prefix_hex"]), bytes.fromhex(vector["receiver_prefix_hex"])
+ self.assertNotEqual(protocol.derive_key(vector["token"], sender, receiver), protocol.derive_key(vector["token"], receiver, sender))
+
+ def test_the_preamble_is_the_committed_one(self):
+ vector = VECTORS["preamble"]
+ session = protocol.SecureSession("any token", prefix=bytes.fromhex(vector["nonce_prefix_hex"]))
+ self.assertEqual(session.preamble().hex(), vector["preamble_hex"])
+
+
+class FrameVectorTests(unittest.TestCase):
+ """Five frames of one link, alternating direction, each side counting from 1."""
+
+ def setUp(self):
+ vector = VECTORS["frames"]
+ self.token = vector["token"]
+ self.prefix_a = bytes.fromhex(vector["sender_prefix_hex"])
+ self.prefix_b = bytes.fromhex(vector["receiver_prefix_hex"])
+ self.frames = vector["frames"]
+ self.assertEqual({frame["direction"] for frame in self.frames}, {"a_to_b", "b_to_a"})
+
+ def _pair(self):
+ side_a = protocol.SecureSession(self.token, prefix=self.prefix_a)
+ side_b = protocol.SecureSession(self.token, prefix=self.prefix_b)
+ side_a.accept_preamble(side_b.preamble())
+ side_b.accept_preamble(side_a.preamble())
+ return side_a, side_b
+
+ def _ends(self, direction):
+ """(sender prefix, receiver prefix) for one direction."""
+ return (self.prefix_a, self.prefix_b) if direction == "a_to_b" else (self.prefix_b, self.prefix_a)
+
+ def test_the_module_seals_every_frame_to_the_committed_bytes(self):
+ side_a, side_b = self._pair()
+ for frame in self.frames:
+ with self.subTest(direction=frame["direction"], counter=frame["counter"]):
+ sender = side_a if frame["direction"] == "a_to_b" else side_b
+ self.assertEqual(sender.seal(frame["plaintext"]).hex(), frame["frame_hex"])
+
+ def test_the_module_opens_every_committed_frame(self):
+ side_a, side_b = self._pair()
+ for frame in self.frames:
+ with self.subTest(direction=frame["direction"], counter=frame["counter"]):
+ receiver = side_b if frame["direction"] == "a_to_b" else side_a
+ body = bytes.fromhex(frame["frame_hex"])[protocol.HEADER_SIZE:]
+ self.assertEqual(receiver.open(body), frame["plaintext"])
+
+ def test_libsodium_by_hand_seals_and_opens_every_committed_frame(self):
+ for frame in self.frames:
+ with self.subTest(direction=frame["direction"], counter=frame["counter"]):
+ sender, receiver = self._ends(frame["direction"])
+ key = _hkdf_sha256(self.token.encode("utf-8"), protocol.KEY_SALT, protocol.KEY_INFO + sender + receiver)
+ counter, sealed = _frame_parts(frame["frame_hex"])
+ self.assertEqual(struct.unpack(">I", counter)[0], frame["counter"])
+ plaintext = json.dumps(frame["plaintext"]).encode("utf-8")
+ self.assertEqual(crypto_aead_chacha20poly1305_ietf_encrypt(plaintext, None, sender + counter, key), sealed)
+ self.assertEqual(crypto_aead_chacha20poly1305_ietf_decrypt(sealed, None, sender + counter, key), plaintext)
+
+ def _refused(self, receiver, body):
+ # Opened while another exception is being handled, as a caller's reader loop may be:
+ # nothing about the failure is carried out, as before, neither a library error nor that one.
+ with self.assertRaises(protocol.AuthenticationError) as caught:
+ try:
+ raise RuntimeError("handled elsewhere")
+ except RuntimeError:
+ receiver.open(body)
+ self.assertIsNone(caught.exception.__cause__)
+ self.assertTrue(caught.exception.__suppress_context__)
+
+ def test_a_flipped_bit_anywhere_after_the_counter_is_refused_and_spends_nothing(self):
+ frame = self.frames[0]
+ body = bytes.fromhex(frame["frame_hex"])[protocol.HEADER_SIZE:]
+ for index in range(protocol.COUNTER_SIZE, len(body)):
+ with self.subTest(byte=index):
+ _, side_b = self._pair()
+ tampered = bytearray(body)
+ tampered[index] ^= 0x01
+ self._refused(side_b, bytes(tampered))
+ self.assertEqual(side_b.open(body), frame["plaintext"])
+
+ def test_a_frame_shorter_than_its_tag_is_refused_as_a_tag_failure(self):
+ body = bytes.fromhex(self.frames[0]["frame_hex"])[protocol.HEADER_SIZE:]
+ for keep in (1, 8, 15, 16):
+ with self.subTest(sealed_bytes=keep):
+ _, side_b = self._pair()
+ self._refused(side_b, body[:protocol.COUNTER_SIZE + keep])
+
+ def test_a_body_that_is_not_bytes_like_is_a_type_error_not_a_tag_failure(self):
+ body = bytes.fromhex(self.frames[0]["frame_hex"])[protocol.HEADER_SIZE:]
+ _, side_b = self._pair()
+ with self.assertRaises(TypeError):
+ side_b.open(list(body))
+ self.assertEqual(side_b.open(bytearray(body)), self.frames[0]["plaintext"])
+
+ def test_a_frame_sealed_under_another_token_is_refused(self):
+ stranger = protocol.SecureSession("another token", prefix=self.prefix_a)
+ stranger.accept_preamble(protocol.SecureSession("another token", prefix=self.prefix_b).preamble())
+ _, side_b = self._pair()
+ self._refused(side_b, stranger.seal(self.frames[0]["plaintext"])[protocol.HEADER_SIZE:])
+
+ def test_a_side_s_own_frame_reflected_back_is_refused(self):
+ side_a, _ = self._pair()
+ own = bytes.fromhex(self.frames[0]["frame_hex"])[protocol.HEADER_SIZE:]
+ self._refused(side_a, own)
+
+ def test_a_connection_recorded_under_other_prefixes_is_refused(self):
+ _, side_b = self._pair()
+ replayer = protocol.SecureSession(self.token, prefix=self.prefix_a)
+ replayer.accept_preamble(protocol.SecureSession(self.token, prefix=bytes(8)).preamble())
+ self._refused(side_b, replayer.seal(self.frames[0]["plaintext"])[protocol.HEADER_SIZE:])
+
+
+class PairingShareVectorTests(unittest.TestCase):
+ """Pairing moved to libsodium in 1.4.3; its low-order shares, from the same file."""
+
+ def test_low_order_and_all_zero_shares_are_refused(self):
+ low = VECTORS["pairing"]["low_order_shares"]
+ scalar = bytes.fromhex(low["scalar_hex"])
+ self.assertIn(bytes(32).hex(), low["must_refuse"])
+ for share in low["must_refuse"]:
+ with self.subTest(share=share):
+ with self.assertRaises(pairing.PairingError):
+ pairing._x25519(scalar, bytes.fromhex(share))
+ for vector in low["must_give"]:
+ with self.subTest(share=vector["share_hex"]):
+ self.assertEqual(pairing._x25519(scalar, bytes.fromhex(vector["share_hex"])).hex(), vector["product_hex"])
+
+
+class NoCryptographyTests(unittest.TestCase):
+ """cryptography 49 dropped x86_64 macOS wheels, so no module of either app may import it."""
+
+ def test_no_module_imports_cryptography(self):
+ offenders = []
+ for top in ("mac_app", "win_app", "core", "tools"):
+ for folder, dirs, files in os.walk(os.path.join(_REPO_ROOT, top)):
+ dirs[:] = [name for name in dirs if not name.startswith(".") and name not in ("build", "dist", "__pycache__")]
+ for name in files:
+ if not name.endswith(".py"):
+ continue
+ path = os.path.join(folder, name)
+ with open(path, encoding="utf-8") as handle:
+ tree = ast.parse(handle.read(), path)
+ for node in ast.walk(tree):
+ modules = [alias.name for alias in node.names] if isinstance(node, ast.Import) else [node.module or ""] if isinstance(node, ast.ImportFrom) else []
+ if any(module == "cryptography" or module.startswith("cryptography.") for module in modules):
+ offenders.append(f"{os.path.relpath(path, _REPO_ROOT)}:{node.lineno}")
+ self.assertEqual(offenders, [])
+
+ def test_neither_requirements_file_asks_for_it(self):
+ for path in ("mac_app/requirements-mac.txt", "win_app/requirements-win.txt"):
+ with self.subTest(path=path):
+ with open(os.path.join(_REPO_ROOT, path), encoding="utf-8") as handle:
+ names = [line.split("#")[0].strip().lower() for line in handle]
+ self.assertFalse([name for name in names if name.startswith("cryptography")])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/updates.py b/core/updates.py
similarity index 81%
rename from mac_app/updates.py
rename to core/updates.py
index 21bfc57..a4788fe 100644
--- a/mac_app/updates.py
+++ b/core/updates.py
@@ -1,5 +1,4 @@
-"""Whether a newer Beamer has been released, shared by mac_app and win_app (two identical copies;
-test_shared_copies checks they match).
+"""Whether a newer Beamer has been released, for both apps.
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
@@ -21,16 +20,23 @@ TIMEOUT_SECONDS = 10.0
MAX_BYTES = 256 * 1024
LOGGER = logging.getLogger(__name__)
-_VERSION = re.compile(r"^v?(\d+)\.(\d+)(?:\.(\d+))?$")
+_VERSION = re.compile(r"^v?(\d+)\.(\d+)(?:\.(\d+))?(?:-beta\.(\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."""
+def _parse(text):
+ """((major, minor, patch), is_beta) or None."""
match = _VERSION.match(str(text or "").strip())
if not match:
return None
- return tuple(int(part or 0) for part in match.groups())
+ return tuple(int(part or 0) for part in match.groups()[:3]), match.group(4) is not None
+
+
+def parse_version(text):
+ """(major, minor, patch) for "1.4", "1.4.0", "v1.4.0" or a beta such as "1.5.0-beta.1" (which
+ reads as its release), else None: a local "dev" build or a tag in any other shape never reads as
+ older or newer than anything."""
+ parsed = _parse(text)
+ return parsed[0] if parsed else None
# In a release's notes, where GitHub renders nothing, it offers a patch release as an update too.
@@ -41,15 +47,19 @@ 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."""
+ prereleases never count, nor does a tag that names a beta. A beta install is offered its own
+ release (1.5.0-beta.1 to 1.5.0) and anything newer without the announce, never an older one."""
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:
+ theirs, ours = _parse(tag), _parse(current)
+ if theirs is None or ours is None or theirs[1]:
+ return None
+ theirs, (ours, beta) = theirs[0], ours
+ if theirs < ours or (theirs == ours and not beta):
return None
body = payload.get("body")
- if theirs[:2] == ours[:2] and not (isinstance(body, str) and ANNOUNCE in body):
+ if not beta and 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/"):
diff --git a/mac_app/wol.py b/core/wol.py
similarity index 100%
rename from mac_app/wol.py
rename to core/wol.py
diff --git a/mac_app/bridge.py b/mac_app/bridge.py
index 307b03c..17592c2 100644
--- a/mac_app/bridge.py
+++ b/mac_app/bridge.py
@@ -19,10 +19,10 @@ import crossing
import desktop_mac
from input_injector_mac import INJECTED_MARK
import gestures
-import ignored
+from core import ignored
import keyboard_layout
import media_keys
-import protocol
+from core import protocol
from key_codes import (
KEY_NAME_TO_CODE,
MODIFIER_KEY_CODES,
@@ -514,6 +514,12 @@ class KVMController:
# Set by the app: called when Windows says the two machines have moved
# in relation to each other.
self.on_arrangement = None
+ # Same on both machines, as the receiver's: `on_settings(data)` for each settings message
+ # from Windows, `announce()` for what to send the moment the link is up, `peer_settings`
+ # whether Windows's welcome said it keeps settings in step.
+ self.on_settings = None
+ self.announce = lambda: []
+ self.peer_settings = None
self.threads = []
self.started = False
self.capture_lock = threading.Lock()
@@ -570,13 +576,25 @@ class KVMController:
# remembers cannot survive a restart; full_screen_app is the name of the frontmost app
# while it is full screen, measured by the app on the main thread like notch_range.
self.crossing_paused = False
- self.full_screen_app = None
+ self._full_screen_app = None
# Round trip: (seq, sent at) for every input event still unacknowledged, oldest first,
# and the last few measured trips. Both under sequence_lock.
self._unacked_sent_at = collections.deque()
self._round_trips = collections.deque(maxlen=ROUND_TRIP_SAMPLES)
self._round_trip_at = 0.0
+ @property
+ def full_screen_app(self):
+ """The full-screen app holding the edges, or None: also None while this Mac's own setting
+ has the hold off, read here so every reader of the hold agrees and a change applies at once."""
+ if self.cfg.crossing.get("hold_full_screen", True):
+ return self._full_screen_app
+ return None
+
+ @full_screen_app.setter
+ def full_screen_app(self, name):
+ self._full_screen_app = name
+
@property
def connected(self):
with self.socket_lock:
@@ -1480,6 +1498,7 @@ class KVMController:
raise _HandshakeError(f"Windows rejected the connection: {error}")
if welcome_data.get("version") != protocol.PROTOCOL_VERSION:
raise _HandshakeError(OLD_RECEIVER_STATUS)
+ self.peer_settings = protocol.keeps_settings(welcome_data)
sock.settimeout(SOCKET_IO_TIMEOUT_SECONDS)
except _HandshakeError as exc:
self.redirecting = False
@@ -1534,6 +1553,13 @@ class KVMController:
else:
self.connection_status = f"Connected to {host}:{port}"
self.logger.info("connected to Windows at %s:%s", host, port)
+ try:
+ announcements = list(self.announce())
+ except Exception:
+ self.logger.exception("announce failed")
+ announcements = []
+ for announcement in announcements:
+ self._send_raw(announcement)
return True
def _connect_via_ssh_fallback(self):
@@ -1716,6 +1742,14 @@ class KVMController:
if message_type == protocol.MSG_ARRANGEMENT:
self._handle_arrangement(message.get("data", {}))
return
+ if message_type == protocol.MSG_SETTINGS:
+ data = message.get("data")
+ if isinstance(data, dict) and self.on_settings is not None:
+ try:
+ self.on_settings(data)
+ except Exception:
+ self.logger.exception("settings handler failed")
+ return
self.logger.debug("ignoring inbound message of type %r", message_type)
def _handle_arrangement(self, data):
@@ -1735,6 +1769,10 @@ class KVMController:
whether or not input is currently redirected."""
return self._send_raw(protocol.arrangement_msg(mac_edge, int(set_at)))
+ def send_settings(self, data):
+ """Tell Windows this Mac's settings state, straight out like the arrangement."""
+ return self._send_raw(protocol.settings_msg(data))
+
def _apply_inbound_clipboard(self, data):
if not isinstance(data, dict):
return
diff --git a/mac_app/build_dmg.sh b/mac_app/build_dmg.sh
index a5a8e17..ef4a008 100755
--- a/mac_app/build_dmg.sh
+++ b/mac_app/build_dmg.sh
@@ -1,9 +1,9 @@
#!/bin/bash
-# Builds Beamer.app and Beamer.dmg.
+# Builds Beamer.app (arm64 and x86_64 in one bundle) and Beamer.dmg.
#
# ./build_dmg.sh local build in mac_app/dist, signed with the same Developer ID identity
# ./build_dmg.sh --release Developer ID, notarised and stapled, written to
-# docs/beamer-releases/<version>/ beside the repository, with nothing left in dist
+# docs/beamer-releases/<version>/ beside the repository as Beamer-<version>.dmg, with nothing left in dist
#
# The version is the repo-root VERSION file and the build number is the commit count, so a release
# rebuilt from the same commit carries the same numbers. Nothing here uploads anywhere but Apple's
@@ -71,7 +71,31 @@ rm -rf "$SCRIPT_DIR/build" "$SCRIPT_DIR/dist"
PYTHONDONTWRITEBYTECODE=1 .venv/bin/python3 -B setup.py py2app
PY2APP_DIR="$(.venv/bin/python3 -c 'from pathlib import Path; import py2app; print(Path(py2app.__file__).parent)')"
-clang -O2 -arch arm64 -mmacosx-version-min=13.0 "$PY2APP_DIR/apptemplate/src/main.c" -framework Cocoa -o "$APP/Contents/MacOS/Beamer"
+clang -O2 -arch arm64 -arch x86_64 -mmacosx-version-min=13.0 "$PY2APP_DIR/apptemplate/src/main.c" -framework Cocoa -o "$APP/Contents/MacOS/Beamer"
+
+# cffi ships no universal2 wheel, so the extension pip installed for this Mac is single-architecture.
+# The other half comes from cffi's own wheel for the other architecture, and lipo fuses the two.
+# Everything else in the bundle (Python itself, PyObjC, PyNaCl) ships universal2 and is checked below.
+HOST_ARCH="$(uname -m)"
+[ "$HOST_ARCH" = arm64 ] && OTHER_ARCH=x86_64 || OTHER_ARCH=arm64
+CFFI_VERSION="$(.venv/bin/python3 -c 'import importlib.metadata as m; print(m.version("cffi"))')"
+PY_TAG="$(.venv/bin/python3 -c 'import sys; print(f"{sys.version_info[0]}{sys.version_info[1]}")')"
+mkdir -p "$STAGING_DIR/cffi-other"
+if [ "$OTHER_ARCH" = x86_64 ]; then
+ OTHER_PLATFORMS="--platform macosx_10_13_x86_64 --platform macosx_10_15_x86_64 --platform macosx_11_0_x86_64 --platform macosx_13_0_x86_64"
+else
+ OTHER_PLATFORMS="--platform macosx_11_0_arm64 --platform macosx_13_0_arm64"
+fi
+.venv/bin/python3 -m pip download -q --no-deps --only-binary=:all: --python-version "$PY_TAG" \
+ $OTHER_PLATFORMS "cffi==$CFFI_VERSION" -d "$STAGING_DIR/cffi-other"
+unzip -q -o "$STAGING_DIR"/cffi-other/cffi-*.whl '_cffi_backend*.so' -d "$STAGING_DIR/cffi-other/x"
+for ours in $(find "$APP/Contents" -name '_cffi_backend*.so'); do
+ theirs="$(ls "$STAGING_DIR"/cffi-other/x/_cffi_backend*.so)"
+ if [ "$(lipo -archs "$ours" | wc -w)" -lt 2 ]; then
+ lipo -create "$ours" "$theirs" -output "$STAGING_DIR/cffi-fused.so"
+ cp "$STAGING_DIR/cffi-fused.so" "$ours"
+ fi
+done
xattr -cr "$APP"
@@ -82,7 +106,7 @@ for archive in "$APP"/Contents/Resources/lib/python3*.zip; do
zip -q -d "$archive" '*.dSYM/*' || [ $? -eq 12 ]
done
-# The packages py2app copies whole (rumps, cryptography, cffi, setuptools) arrive with the
+# The packages py2app copies whole (rumps, cffi, nacl, 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. A shipped build once carried both. The
# caches go, inside the zip too, where zipimport never reads a __pycache__ anyway; the loose packages
@@ -95,6 +119,21 @@ for packages in "$APP"/Contents/Resources/lib/python3.*/; do
.venv/bin/python3 -m compileall -q -d "lib/$(basename "$packages")" "$packages" >/dev/null
done
/usr/libexec/PlistBuddy -c 'Delete :PythonInfoDict:PythonExecutable' "$APP/Contents/Info.plist"
+# Every Mach-O in the bundle must carry both architectures, or an Intel Mac (or an Apple silicon one
+# under Rosetta) fails on the one file that does not, at first use rather than at launch.
+find "$APP/Contents" -type f -print0 | xargs -0 file | grep 'Mach-O' | grep -v '(for architecture' \
+ | cut -d: -f1 > "$STAGING_DIR/machos.txt"
+single=0
+while IFS= read -r binary; do
+ archs="$(lipo -archs "$binary")"
+ if [ "$(printf '%s\n' $archs | grep -cx -e x86_64 -e arm64)" -ne 2 ]; then
+ echo "single-architecture Mach-O ($archs): ${binary#$APP/}" >&2
+ single=$((single + 1))
+ fi
+done < "$STAGING_DIR/machos.txt"
+[ "$single" -eq 0 ] || { echo "$single Mach-O files in the app lack arm64 or x86_64" >&2; exit 1; }
+echo "$(wc -l < "$STAGING_DIR/machos.txt" | tr -d ' ') Mach-O files in the app, every one arm64 and x86_64"
+
# Anything still naming this Mac's home folder, in a file or inside the zipped stdlib, stops the build.
.venv/bin/python3 - "$APP" "$HOME" <<'EOF'
import pathlib, sys, zipfile
@@ -116,7 +155,7 @@ EOF
if [ "$RELEASE" -eq 1 ]; then TIMESTAMP="--timestamp"; else TIMESTAMP="--timestamp=none"; fi
# Inside-out rather than --deep: every nested Mach-O (the Python framework, the extension modules,
-# cryptography's _rust, the helper python) is signed on its own, then the framework, then the bundle,
+# PyNaCl's _sodium, the helper python) is signed on its own, then the framework, then the bundle,
# whose signature seals the lot. --identifier pins the bundle id, which must never change - the
# privacy grants are keyed to it.
sign_app() {
@@ -124,12 +163,14 @@ sign_app() {
find "$APP/Contents" -type f ! -path "$APP/Contents/MacOS/Beamer" -print0 \
| xargs -0 file | grep 'Mach-O' | grep -v '(for architecture' | cut -d: -f1 > "$STAGING_DIR/nested.txt"
while IFS= read -r binary; do
- codesign --force --sign "$identity" --options runtime $TIMESTAMP "$binary" || return 1
+ local entitle=()
+ [ "$binary" = "$APP/Contents/MacOS/python" ] && entitle=(--entitlements "$SCRIPT_DIR/entitlements.plist")
+ codesign --force --sign "$identity" --options runtime $TIMESTAMP ${entitle[@]+"${entitle[@]}"} "$binary" || return 1
done < "$STAGING_DIR/nested.txt"
codesign --force --sign "$identity" --options runtime $TIMESTAMP \
"$APP/Contents/Frameworks/Python.framework/Versions/"[0-9]* || return 1
codesign --force --sign "$identity" --options runtime $TIMESTAMP \
- --identifier uk.co.kalkman.beamer "$APP" || return 1
+ --entitlements "$SCRIPT_DIR/entitlements.plist" --identifier uk.co.kalkman.beamer "$APP" || return 1
}
# A real identity is stable across rebuilds, so macOS keeps the Accessibility and Input Monitoring
@@ -157,6 +198,13 @@ codesign -dvv "$APP" 2>&1 | grep -E '^(Identifier|Signature|Authority|Timestamp|
# entitlement fails here rather than at a user's first launch.
env -i HOME="$HOME" PATH=/usr/bin:/bin PYTHONHOME="$APP/Contents/Resources" \
"$APP/Contents/MacOS/python" "$PROJECT_DIR/tools/runtime_probe.py"
+# The same probe as an Intel Mac would run it, where Rosetta is here to run it.
+if /usr/bin/arch -x86_64 /usr/bin/true 2>/dev/null; then
+ env -i HOME="$HOME" PATH=/usr/bin:/bin PYTHONHOME="$APP/Contents/Resources" \
+ /usr/bin/arch -x86_64 "$APP/Contents/MacOS/python" "$PROJECT_DIR/tools/runtime_probe.py"
+else
+ echo "Rosetta is not installed here: the x86_64 half of the bundle was not run" >&2
+fi
notarise() {
local result="$STAGING_DIR/notary.json" id status
@@ -195,8 +243,8 @@ if [ "$RELEASE" -eq 1 ]; then
spctl -a -vv "$APP"
spctl -a -vv -t install "$DMG"
mkdir -p "$RELEASE_DIR"
- cp "$DMG" "$RELEASE_DIR/Beamer.dmg"
- echo "Released Beamer $VERSION ($BEAMER_BUILD) at $RELEASE_DIR/Beamer.dmg"
+ cp "$DMG" "$RELEASE_DIR/Beamer-$VERSION.dmg"
+ echo "Released Beamer $VERSION ($BEAMER_BUILD) at $RELEASE_DIR/Beamer-$VERSION.dmg"
else
echo "Built Beamer $VERSION ($BEAMER_BUILD) at $DMG"
fi
diff --git a/mac_app/config.py b/mac_app/config.py
index 44daa3d..07bc8da 100644
--- a/mac_app/config.py
+++ b/mac_app/config.py
@@ -4,7 +4,7 @@ import json
import os
from dataclasses import dataclass, field
-import effects
+from core import effects
from crossing import DEFAULT_CROSSING
DEFAULT_CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
@@ -75,6 +75,10 @@ class Config:
check_updates: bool = True
# Every address the window shows is hidden; see pages.redact.
hide_addresses: bool = False
+ # Same on both machines: the Crossing and Design pages kept in step with the PC's, and the unix
+ # seconds of the last change to that or to a shared value; see settings_sync.
+ same_on_both: bool = False
+ same_set_at: int = 0
# How the PC's pointer and scroll feel on this Mac; see receiver.InputScale.
pointer_speed: float = 1.0
scroll_speed: float = 1.0
@@ -84,6 +88,11 @@ class Config:
ignored_inputs: list = field(default_factory=list)
+def _stamp(value) -> int:
+ """A saved unix-seconds stamp, or 0 for anything that is not one."""
+ return int(value) if not isinstance(value, bool) and isinstance(value, (int, float)) and value > 0 else 0
+
+
def key_map_style(key_map):
"""The name of a key_map when it is one of the two offered styles, else None."""
for name, mapping in KEY_MAP_STYLES.items():
@@ -154,6 +163,8 @@ def load_config(path: str = None) -> Config:
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,
+ same_on_both=raw.get("same_on_both", False) is True,
+ same_set_at=_stamp(raw.get("same_set_at", 0)),
pointer_speed=raw.get("pointer_speed", 1.0),
scroll_speed=raw.get("scroll_speed", 1.0),
reverse_scroll=raw.get("reverse_scroll", False),
diff --git a/mac_app/crossing.py b/mac_app/crossing.py
index 3dd6b86..07cb677 100644
--- a/mac_app/crossing.py
+++ b/mac_app/crossing.py
@@ -13,7 +13,7 @@ mechanism is what keeps a slow lean against the edge from ever building a switch
from dataclasses import dataclass
-import return_edge
+from core import return_edge
EDGES = ("left", "right", "top", "bottom")
CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")
@@ -40,6 +40,8 @@ DEFAULT_CROSSING = {
"glow_style": "glow",
"glow_colour": "signal",
"block_while_dragging": True,
+ # A full-screen app in front holds this Mac's edges. This Mac's own choice, never shared.
+ "hold_full_screen": 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.
diff --git a/mac_app/desktop_mac.py b/mac_app/desktop_mac.py
index 9fc524a..5ce11fb 100644
--- a/mac_app/desktop_mac.py
+++ b/mac_app/desktop_mac.py
@@ -13,7 +13,7 @@ on a machine without it.
from typing import List, Tuple
-from return_edge import Rect
+from core.return_edge import Rect
try:
import Quartz
diff --git a/mac_app/effects_overlay.py b/mac_app/effects_overlay.py
index fbdbaf7..b3bc4d1 100644
--- a/mac_app/effects_overlay.py
+++ b/mac_app/effects_overlay.py
@@ -21,7 +21,7 @@ import rumps
import crossing
import desktop_mac
-import effects
+from core import effects
import notch_beam
import notch_island
diff --git a/mac_app/entitlements.plist b/mac_app/entitlements.plist
new file mode 100644
index 0000000..7c83a0f
--- /dev/null
+++ b/mac_app/entitlements.plist
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- Under Rosetta, libffi (every PyObjC callback) cannot map executable memory inside the hardened
+ runtime without this, and `import Foundation` never finishes. Native arm64 needs nothing. -->
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
+ <true/>
+</dict>
+</plist>
diff --git a/mac_app/fx_membrane.py b/mac_app/fx_membrane.py
deleted file mode 100644
index 8f2c89b..0000000
--- a/mac_app/fx_membrane.py
+++ /dev/null
@@ -1,546 +0,0 @@
-"""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/gestures.py b/mac_app/gestures.py
index 0f64d0a..55031c6 100644
--- a/mac_app/gestures.py
+++ b/mac_app/gestures.py
@@ -34,7 +34,7 @@ AppKit or Quartz -- `ns_event` only has to expose `.magnification`,
import logging
-import protocol
+from core import protocol
GESTURE_TYPE = 29
MAGNIFY_TYPE = 30
diff --git a/mac_app/ignored_titles.py b/mac_app/ignored_titles.py
index 261055a..c1d5028 100644
--- a/mac_app/ignored_titles.py
+++ b/mac_app/ignored_titles.py
@@ -2,7 +2,7 @@
out of the AppKit recorder in widgets.py so both are testable without it.
"""
-import ignored
+from core import ignored
import media_keys
from bridge import NX_DEVICE_MODIFIER_BITS, WIRE_OTHER_BUTTONS
import keyboard_layout
diff --git a/mac_app/kvm_bridge_app.py b/mac_app/kvm_bridge_app.py
index 1c44900..3d8d58e 100644
--- a/mac_app/kvm_bridge_app.py
+++ b/mac_app/kvm_bridge_app.py
@@ -23,9 +23,9 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import config as config_module
import crossing
-import return_edge
+from core import return_edge
import desktop_mac
-import effects
+from core import effects
import effects_overlay
import gestures
import ignored_titles
@@ -41,9 +41,10 @@ from key_codes import KEY_NAME_TO_CODE
import link_state
import login_item
import pages
-import updates
-import protocol
-import pairing
+from core import updates
+from core import protocol
+from core import pairing
+from core import settings_sync
from settings_store import (
SettingsError,
SettingsStore,
@@ -54,6 +55,7 @@ import theme
from wake import WakingController, lookup_mac
import widgets
from windows_input import WindowsInput
+from core.receiver import ServerState
LOG_DIRECTORY = Path.home() / "Library" / "Logs" / "Beamer"
@@ -1029,6 +1031,9 @@ class ControlWindow(AppKit.NSObject):
widgets.add(pane, self._commit())
self.page_titles = []
+ # Same on both machines: each shared page's scope line, and the notes on this Mac's own rows.
+ self.scope_labels = {}
+ self.own_notes = []
self.page_paddings = []
self.pages = {}
builders = {
@@ -1040,7 +1045,7 @@ class ControlWindow(AppKit.NSObject):
"permissions": self._permissions_page,
}
for key, name, _symbol, purpose in pages.PAGES:
- scroll, body = self._page(name, purpose, pages.SCOPE.get(key))
+ scroll, body = self._page(name, purpose, pages.SCOPE.get(key), key)
host.addSubview_(scroll)
widgets.pin(scroll, host)
scroll.setHidden_(True)
@@ -1138,12 +1143,8 @@ class ControlWindow(AppKit.NSObject):
self.token_field.setStringValue_(str(raw["auth_token"]))
self.token_plain.setStringValue_(str(raw["auth_token"]))
self._say_pairing("Choose a PC, then type the code it shows.")
- self.key_recorder.set_value(raw["trigger_key"])
self.ignored_entries = list(raw["ignored_inputs"])
self._render_ignored()
- self.style_select.value = raw["trigger_style"]
- self.double_tap_ruler.value = raw["double_tap_ms"]
- self.double_tap_numeral.set(str(raw["double_tap_ms"]))
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))
@@ -1154,21 +1155,33 @@ class ControlWindow(AppKit.NSObject):
self.updates_switch.value = raw["check_updates"]
self.modifier_select.value = raw["key_map"] if isinstance(raw["key_map"], str) else "custom"
crossing_raw = raw["crossing"]
+ self.edge_select.value = crossing_raw["edge"]
+ self.haptics_box.value = crossing_raw["haptics"]
+ self.glow_box.value = crossing_raw["glow"]
+ self.notch_style_select.value = crossing_raw["notch_style"]
+ self.notch_after_select.value = crossing_raw["notch_after_ms"]
+ self.tick_steps_select.value = crossing_raw["haptic_steps"]
+ self.hold_box.value = crossing_raw["hold_full_screen"]
+ self._load_shared(raw)
+
+ @objc.python_method
+ def _load_shared(self, raw):
+ """The controls Same on both machines keeps in step, and nothing else: settings arriving
+ from the PC must not reset a half-typed address or the pairing card."""
+ self.key_recorder.set_value(raw["trigger_key"])
+ self.style_select.value = raw["trigger_style"]
+ self.double_tap_ruler.value = raw["double_tap_ms"]
+ self.double_tap_numeral.set(str(raw["double_tap_ms"]))
+ crossing_raw = raw["crossing"]
for name, tile in self.method_boxes.items():
tile.value = name in crossing_raw["methods"]
for name, tile in self.part_boxes.items():
tile.value = name in crossing_raw["edge_parts"]
- self.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_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"]
@@ -1378,6 +1391,13 @@ class ControlWindow(AppKit.NSObject):
self.double_tap_numeral.set(str(value))
self._changed()
+ @objc.python_method
+ def _hold_changed(self, value):
+ # The controller reads this at every crossing, so it must not wait out the debounce; the
+ # controller's config is the one the pending save builds on.
+ self.controller.cfg.crossing["hold_full_screen"] = value
+ self._changed()
+
@objc.python_method
def _changed(self, *_ignored):
"""Every control outside the Connection page calls this. The settings are written and
@@ -1410,7 +1430,7 @@ class ControlWindow(AppKit.NSObject):
return widgets.hug(figure.view), figure
@objc.python_method
- def _page(self, title, purpose, scope=None):
+ def _page(self, title, purpose, scope=None, key=None):
"""One page: a vertical scroller holding the title, the sentence saying what the page is
for, `scope` saying whose settings they are where that needs saying, then the modules the
builder adds to the returned body. Returns (scroll, body)."""
@@ -1429,9 +1449,17 @@ class ControlWindow(AppKit.NSObject):
padding = [
body.topAnchor().constraintEqualToAnchor_constant_(page.topAnchor(), top),
body.leadingAnchor().constraintEqualToAnchor_constant_(page.leadingAnchor(), leading),
- page.bottomAnchor().constraintEqualToAnchor_constant_(body.bottomAnchor(), bottom),
+ page.bottomAnchor().constraintGreaterThanOrEqualToAnchor_constant_(body.bottomAnchor(), bottom),
page.trailingAnchor().constraintEqualToAnchor_constant_(body.trailingAnchor(), trailing),
]
+ # The page ends where its body does, unless motion props it up with the floor while a
+ # module folds away, so the scroll offset eases down rather than snapping. Only the
+ # page is pulled short; pulling the body would stretch a module into the held space.
+ page.floor = page.heightAnchor().constraintGreaterThanOrEqualToConstant_(0.0)
+ page.floor.setActive_(True)
+ shrink = page.heightAnchor().constraintEqualToConstant_(0.0)
+ shrink.setPriority_(1)
+ shrink.setActive_(True)
AppKit.NSLayoutConstraint.activateConstraints_(padding)
self.page_paddings.append(padding)
scroll.setDocumentView_(page)
@@ -1454,6 +1482,7 @@ class ControlWindow(AppKit.NSObject):
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)
+ self.scope_labels[key] = scope_label
widgets.add(body, header)
body.setCustomSpacing_afterView_(32, header)
return scroll, body
@@ -1466,6 +1495,7 @@ class ControlWindow(AppKit.NSObject):
widgets.add(body, self._status_module().view)
widgets.add(body, self._keyboard_module().view)
widgets.add(body, self._directions_module().view)
+ widgets.add(body, self._same_module().view)
widgets.add(body, self._paired_module().view)
widgets.add(body, self._login_module().view)
widgets.add(body, self._updates_module().view)
@@ -1500,6 +1530,106 @@ class ControlWindow(AppKit.NSObject):
if switch.value != bool(value):
switch.value = value
+ @objc.python_method
+ def _same_module(self):
+ module = widgets.Module(spacing=10)
+ module.add(widgets.eyebrow("Settings"))
+ self.same_switch = widgets.Switch("Same on both machines", on_change=self._set_same)
+ module.add(self.same_switch.view)
+ self.same_note = widgets.note()
+ module.add(self.same_note.view)
+ return module
+
+ @objc.python_method
+ def _own_note(self, text=pages.OWN_ROW):
+ """A note on a row this Mac keeps to itself, shown only while the pages are kept in step."""
+ note = widgets.note(text)
+ note.view.setHidden_(True)
+ self.own_notes.append(note)
+ return note.view
+
+ @objc.python_method
+ def _peer_too_old(self):
+ """Whether a link is up to a PC whose Beamer does not keep settings in step."""
+ links = [(self.controller.connected, getattr(self.controller, "peer_settings", None))]
+ if self.windows_input is not None:
+ links.append((self.windows_input.state == ServerState.CONNECTED, self.windows_input.server.peer_settings))
+ return any(up and known is False for up, known in links)
+
+ @objc.python_method
+ def _show_same(self):
+ cfg = self.controller.cfg
+ old = self._peer_too_old()
+ on = cfg.same_on_both and not old
+ if self.same_switch.value != on:
+ self.same_switch.value = on
+ self.same_switch.set_enabled(not old)
+ self.same_note.set(settings_sync.switch_note("PC", cfg.same_on_both, old), ink="amber" if old else "ink_2")
+ for key, label in self.scope_labels.items():
+ text = settings_sync.scope(key, "PC", on, pages.SCOPE.get(key))
+ if label.text != text:
+ label.set(text)
+ for note in self.own_notes:
+ if note.view.isHidden() == on:
+ motion.set_hidden(note.view, not on)
+
+ @objc.python_method
+ def _set_same(self, on):
+ """Turning it on carries this Mac's Crossing and Design across; off, each end keeps what it
+ has. Either way the PC follows, now if a link is up, else when one next comes up."""
+ raw = config_to_raw(self.controller.cfg)
+ raw["same_on_both"] = bool(on)
+ raw["same_set_at"] = settings_sync.next_stamp(raw["same_set_at"], time.time())
+ try:
+ cfg = self.settings_store.save(raw)
+ except SettingsError as exc:
+ self.logger.warning("Same on both machines not saved: %s", exc)
+ return
+ self.controller.apply_settings(cfg)
+ self._send_same()
+ self._show_same()
+
+ @objc.python_method
+ def same_state(self):
+ """This Mac's settings message, for a change here and for announcing on a new link. Called
+ from the links' threads as well, so it reads the settings once."""
+ cfg = self.controller.cfg
+ return settings_sync.message_data(cfg.same_on_both, cfg.same_set_at,
+ settings_sync.mac_values(config_to_raw(cfg)))
+
+ @objc.python_method
+ def _send_same(self):
+ data = self.same_state()
+ self.controller.send_settings(data)
+ if self.windows_input is not None:
+ self.windows_input.server.send_settings(data)
+
+ @objc.python_method
+ def apply_same(self, data):
+ """The PC's settings message, over either link, on the main thread. Its state stands only
+ when it is newer than this Mac's; then its values replace the shared ones here."""
+ cfg = self.controller.cfg
+ taken = settings_sync.arrived(data, cfg.same_set_at, KEY_NAME_TO_CODE)
+ if taken is None:
+ return
+ on, set_at, values = taken
+ raw = config_to_raw(cfg)
+ raw["same_on_both"] = on
+ raw["same_set_at"] = set_at
+ if on:
+ raw = settings_sync.apply_mac(raw, values)
+ try:
+ cfg = self.settings_store.save(raw)
+ except (SettingsError, TypeError, ValueError):
+ self.logger.exception("could not save the settings the PC sent")
+ return
+ self.controller.apply_settings(cfg)
+ if self.previews is not None:
+ self.previews.repaint()
+ self.logger.info("settings from the PC applied (same on both machines %s)", "on" if on else "off")
+ self._load_shared(config_to_raw(cfg))
+ self.refresh()
+
@objc.python_method
def _login_module(self):
module = widgets.Module(spacing=10)
@@ -1610,6 +1740,7 @@ class ControlWindow(AppKit.NSObject):
above are what the page is for."""
module = widgets.Module()
module.add(widgets.eyebrow("Appearance"))
+ module.add(self._own_note())
self.appearance_select = widgets.Segmented(
[("system", "System"), ("light", "Light"), ("dark", "Dark")], on_change=self._appearance_chosen
)
@@ -1731,6 +1862,13 @@ class ControlWindow(AppKit.NSObject):
widgets.add(self.pause_row, self.crossing_state.view)
module.add(self.pause_row)
module.body.setCustomSpacing_afterView_(14, self.toggle_button.view)
+ self.hold_box = widgets.Switch("Hold the edges while an app is full screen", on_change=self._hold_changed)
+ module.add(self.hold_box.view)
+ module.add(self._own_note())
+ module.add(widgets.note(
+ "Off, your pointer can leave a full-screen game or video, and the PC's pointer can come home "
+ "through this Mac's edge. Useful if your keyboard has no key for the shortcut."
+ ).view)
return module
@objc.python_method
@@ -1771,6 +1909,7 @@ class ControlWindow(AppKit.NSObject):
for way, title, detail in ways
}
module.add(widgets.grid([tile.view for tile in self.method_boxes.values()], 2))
+ module.add(self._own_note(pages.OWN_NOTCH))
# The values are the side of this Mac the PC is on, which is also the edge that crosses.
self.edge_select = widgets.Segmented(
[("left", "Left"), ("right", "Right"), ("top", "Above"), ("bottom", "Below")], on_change=self._changed
@@ -1926,6 +2065,7 @@ class ControlWindow(AppKit.NSObject):
module.add(widgets.eyebrow("On screen"))
self.glow_box = widgets.Switch("Animate crossings on this Mac", on_change=self._changed)
module.add(self.glow_box.view)
+ module.add(self._own_note())
module.add(widgets.note(
"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."
@@ -1975,6 +2115,7 @@ class ControlWindow(AppKit.NSObject):
[(600, "0.6 s"), (1200, "1.2 s"), (2000, "2 s"), (3000, "3 s")], on_change=self._changed
)
widgets.add(row, widgets.field_row("Keep animating", self.notch_after_select.view)[0])
+ widgets.add(row, self._own_note())
self.notch_note = widgets.note()
widgets.add(row, self.notch_note.view)
return row
@@ -2111,6 +2252,7 @@ class ControlWindow(AppKit.NSObject):
def _trackpad_module(self):
module = widgets.Module()
module.add(widgets.eyebrow("Trackpad"))
+ module.add(self._own_note())
self.haptics_box = widgets.Switch("Tick as the push builds", on_change=self._changed)
module.add(self.haptics_box.view)
self.tick_steps_select = widgets.Segmented(
@@ -2471,8 +2613,13 @@ class ControlWindow(AppKit.NSObject):
"glow_colour": self.glow_colour_select.value,
"effect_length": self.length_select.value or "normal",
"block_while_dragging": self.dragging_box.value,
+ "hold_full_screen": self.hold_box.value,
"arrangement_set_at": self.controller.cfg.crossing.get("arrangement_set_at", 0),
}
+ shared = self.controller.cfg.same_on_both and settings_sync.changed(
+ settings_sync.mac_values(config_to_raw(self.controller.cfg)), settings_sync.mac_values(raw))
+ if shared:
+ raw["same_set_at"] = settings_sync.next_stamp(self.controller.cfg.same_set_at, time.time())
moved = raw["crossing"]["edge"] != self.controller.cfg.crossing.get("edge")
if moved:
# The edge is half of a value Windows holds too, so a change
@@ -2495,6 +2642,8 @@ class ControlWindow(AppKit.NSObject):
self.windows_input.send_arrangement(
cfg.crossing["edge"], cfg.crossing.get("arrangement_set_at", 0)
)
+ if shared:
+ self._send_same()
self._say("Saved. Changes apply as you make them.", "ink_2")
@objc.python_method
@@ -2596,6 +2745,7 @@ class ControlWindow(AppKit.NSObject):
@objc.python_method
def _say_pairing(self, message, ink="ink_2"):
+ self._pair_ink = ink
self.pair_status.set(message, ink=ink)
@objc.python_method
@@ -2605,11 +2755,21 @@ class ControlWindow(AppKit.NSObject):
discovery = self.discovery
pcs = discovery.pcs() if discovery is not None else []
chosen = self.chosen_pc["address"] if self.chosen_pc is not None else None
- key = (chosen, tuple((pc["name"], pc["address"], pc["port"], pc["pair_id"] is not None) for pc in pcs))
+ key = (chosen, tuple(tuple(sorted(pc.items())) for pc in pcs))
if key == self._pcs_key:
return
self._pcs_key = key
self._pcs = pcs
+ # The chosen row is the PC's beacon at the moment of the click; a PC that starts,
+ # renews or stops its code after that must move the hint with it, not leave it stale.
+ current = next((pc for pc in pcs if pc["address"] == chosen), None)
+ if current is not None and current != self.chosen_pc:
+ showed = self.chosen_pc["pair_id"]
+ self.chosen_pc = current
+ # A refusal or a failed save stays up until the PC offers a fresh code.
+ fault = getattr(self, "_pair_ink", None) == "fault"
+ if current["pair_id"] != showed and not self._pairing and (current["pair_id"] or not fault):
+ self._say_choice()
self._find_answered(pcs)
for view in list(self.pc_list.arrangedSubviews()):
self.pc_list.removeArrangedSubview_(view)
@@ -2654,12 +2814,16 @@ class ControlWindow(AppKit.NSObject):
self.chosen_pc = self._pcs[index]
self.code_boxes.clear()
self.code_boxes.view.setAccessibilityLabel_(f"Code shown on {self.chosen_pc['name']}")
+ self._say_choice()
+ self._refresh_pcs()
+ self.code_boxes.focus(self.window)
+
+ @objc.python_method
+ def _say_choice(self):
if self.chosen_pc["pair_id"] is None:
self._say_pairing(f"{self.chosen_pc['name']} is not showing a code yet. Start pairing in Beamer on it first.")
else:
self._say_pairing("Six digits, as shown on the PC.")
- 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()
@@ -2818,6 +2982,7 @@ class ControlWindow(AppKit.NSObject):
def refresh(self):
controller = self.controller
self._show_directions()
+ self._show_same()
access = accessibility_granted()
listening = input_monitoring_granted()
self._permission(self.access_status, self.access_button, access)
@@ -2990,6 +3155,12 @@ class TrayApp(rumps.App):
arrival_callback=self._driven_arrival,
)
self.control_window.windows_input = self.windows_input
+ # Same on both machines, over either link: applied on the main thread, and announced
+ # with the arrangement the moment either link comes up.
+ for link in (self.windows_input.server, controller):
+ link.announce = self._announce
+ self.windows_input.server.settings_callback = self._settings
+ controller.on_settings = self._settings
self.windows_input.sync(controller.cfg)
self.discovery = pairing.Discovery(logger=logger)
self.control_window.discovery = self.discovery
@@ -3063,6 +3234,17 @@ class TrayApp(rumps.App):
LOG_DIRECTORY.mkdir(parents=True, exist_ok=True, mode=0o700)
AppKit.NSWorkspace.sharedWorkspace().openURL_(AppKit.NSURL.fileURLWithPath_(str(LOG_DIRECTORY)))
+ def _announce(self):
+ """What this Mac tells the PC on every new link: where the machines are, even never
+ changed (an unstamped arrangement from the Mac fills a PC that holds only what a hello
+ told it), and its settings state. On the link's own thread."""
+ crossing_cfg = self.controller.cfg.crossing
+ return [protocol.arrangement_msg(crossing_cfg["edge"], crossing_cfg.get("arrangement_set_at", 0)),
+ protocol.settings_msg(self.control_window.same_state())]
+
+ def _settings(self, data):
+ AppHelper.callAfter(self.control_window.apply_same, data)
+
def _arrangement(self, mac_edge, set_at):
"""An arrangement from the PC, over either link, applied on the main
thread -- it writes the settings file and redraws the window."""
diff --git a/mac_app/motion.py b/mac_app/motion.py
index 5d35f6a..245633c 100644
--- a/mac_app/motion.py
+++ b/mac_app/motion.py
@@ -59,6 +59,55 @@ def _relayout(view):
window.contentView().layoutSubtreeIfNeeded()
+def _now(changes):
+ """Runs `changes` unanimated, even inside a group, and stops any animation of what it sets."""
+ def run(context):
+ context.setDuration_(0.0)
+ context.setAllowsImplicitAnimation_(False)
+ changes()
+
+ AppKit.NSAnimationContext.runAnimationGroup_completionHandler_(run, None)
+
+
+def _collapse(view):
+ """Hides `view` inside a running group. On a scrolling page with a `floor` constraint (its
+ height at least the constant), the page gives up the space as the rows slide, not at once:
+ a page left shorter than its scroll offset has the clip view clamp in a single frame, dropping
+ everything on screen by the difference while the rows are still moving."""
+ scroll = view.enclosingScrollView()
+ page = scroll.documentView() if scroll is not None else None
+ floor = getattr(page, "floor", None)
+ if floor is None:
+ view.setHidden_(True)
+ _relayout(view)
+ return
+ clip = scroll.contentView()
+ height, origin = page.frame().size.height, clip.bounds().origin
+ _now(lambda: floor.setConstant_(0.0))
+ view.setHidden_(True)
+ _relayout(view)
+ natural = page.frame().size.height
+ if natural >= height:
+ return
+
+ def hold():
+ floor.setConstant_(height)
+ _relayout(view)
+ clip.scrollToPoint_(origin)
+ scroll.reflectScrolledClipView_(clip)
+
+ _now(hold)
+ key = objc.pyobjc_id(page)
+ serial = _serials.get(key, (0, None))[0] + 1
+ _serials[key] = (serial, None)
+
+ def eased():
+ if _serials.get(key, (None,))[0] == serial:
+ _now(lambda: floor.setConstant_(0.0))
+
+ _group(DURATION, lambda: floor.animator().setConstant_(natural), eased)
+
+
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."""
@@ -108,7 +157,7 @@ def set_hidden(view, hidden, done=None):
def collapse():
if _serials.get(key, (None,))[0] != serial:
return
- _group(DURATION, lambda: (view.setHidden_(True), _relayout(view)), collapsed)
+ _group(DURATION, lambda: _collapse(view), collapsed)
_group(FADE_OUT, lambda: view.animator().setAlphaValue_(0.0), collapse)
return
diff --git a/mac_app/notch_beam.py b/mac_app/notch_beam.py
index d4cc7ac..243e455 100644
--- a/mac_app/notch_beam.py
+++ b/mac_app/notch_beam.py
@@ -29,7 +29,7 @@ import time
import AppKit
import Quartz
-import effects
+from core import effects
import tokens
from notch_island import (
NOTCH_FALLBACK_HEIGHT,
diff --git a/mac_app/pages.py b/mac_app/pages.py
index 74670a9..69d98bf 100644
--- a/mac_app/pages.py
+++ b/mac_app/pages.py
@@ -8,7 +8,7 @@ from __future__ import annotations
import re
-import effects
+from core 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.
@@ -37,6 +37,9 @@ SCOPE = {
"design": "For this Mac's screen only; the PC keeps its own.",
"keyboard": "For this Mac's keyboard only; the PC keeps its own.",
}
+# With Same on both machines on, under each row of the shared pages that stays this Mac's own.
+OWN_ROW = "This Mac only."
+OWN_NOTCH = "The notch is this Mac only."
# The window's footer, and the pages where its first sentence would be untrue.
FOOTER_APPLIES = "Changes apply as you make them."
FOOTER_RUNNING = "Closing this window keeps Beamer running in the menu bar."
diff --git a/mac_app/pairing.py b/mac_app/pairing.py
deleted file mode 100644
index fb0c916..0000000
--- a/mac_app/pairing.py
+++ /dev/null
@@ -1,1009 +0,0 @@
-"""LAN discovery and pairing, shared by mac_app and win_app (two identical copies; the Mac
-test suite checks they match byte for byte).
-
-The host (the PC) broadcasts a small UDP beacon -- hostname, Beamer TCP port, and a random
-pairing id while a code is on screen -- and the requester (the Mac) lists what it hears. Pairing
-is then a PAKE with the six-digit code as its password: CPace, draft-irtf-cfrg-cpace-21, suite
-CPACE-X25519-SHA512 with initiator and responder roles, followed by the explicit key
-confirmation of the draft's section 10.4. Four datagrams:
-
- requester -> host pair_start {pair, v, nonce, share: Ya, name, id}
- host -> requester pair_answer {pair, ok, share: Yb, tag: Tb, name, id}
- requester -> host pair_confirm {pair, tag: Ta}
- host -> requester pair_done {pair, ok, tag: Td}
-
-Both shares are X25519 public values over a generator derived from the code, so neither says
-anything about the code to someone who does not already know it. The shared token is HKDF over
-CPace's session key. The full specification is PAIRING.md at the repository root;
-tests/pairing_vectors.json holds vectors for every step.
-
-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
- token or key could be derived from.
-- Nothing on the wire can be tested against a list of codes offline, recorded or live. Whoever
- takes part without the code gets one guess against each side: a host answers only the first
- pair_start a code receives, a requester judges only the first pair_answer to its share, and
- it does not send a code again once an answer to it has failed. These rules are what keep an
- attacker to a guess a side, two chances in a million for a code, so none may be relaxed.
-- A wrong code fails closed. The requester checks the host's tag before it sends its own, and
- the host stores a token only after the requester's tag checks out. A fresh code needs a person
- at the PC to press Pair a Mac again, and that is the rate limit. Codes expire after
- CODE_LIFETIME_SECONDS.
-- Anyone on the LAN can still stop a pairing: a junk pair_start uses up the code. That is a
- denial, not a compromise.
-- The host's address and port still come from the beacon, which nothing authenticates. That
- can point the Mac at the wrong address; it cannot read or forge the link.
-- The generator is mapped to the curve in Python integers, which are not constant time. The
- code it depends on is single-use and lives a minute, so there is one computation to time per
- code on the PC and one per attempt on the Mac, and the PC's answer leaves a fixed time after
- the request whatever that computation took.
-"""
-
-from __future__ import annotations
-
-import base64
-import hashlib
-import hmac
-import json
-import logging
-import queue
-import secrets
-import socket
-import threading
-import time
-
-from nacl.bindings import crypto_scalarmult
-from nacl.exceptions import CryptoError
-
-import protocol
-
-# One home for the port, in the module both apps share byte-for-byte.
-PAIRING_PORT = protocol.PAIRING_PORT
-BEACON_VERSION = 1
-# The pairing exchange's own version, in every beacon and every pair_start. 1 was the
-# scrypt-keyed HMAC proof of 1.4.2 and earlier, which carried no number. There is no fallback
-# to it: a version that does not match ends the attempt with ERROR_VERSION.
-PAIRING_VERSION = 2
-BEACON_INTERVAL_SECONDS = 2.0
-# Three missed beacons: long enough to ride out Wi-Fi hiccups, short enough that a PC that
-# went to sleep leaves the list before anyone tries it.
-BEACON_STALE_SECONDS = 7.0
-# More PCs than any one network shows, and a ceiling on what forged beacons can make a Mac hold.
-MAX_SEEN_HOSTS = 64
-# A good pair_answer leaves this long after its pair_start arrived, however long it took to
-# make. The generator's arithmetic is not constant time, and this keeps its duration out of
-# the one thing a stranger can time: the answer.
-PAIR_ANSWER_SECONDS = 0.05
-CODE_LIFETIME_SECONDS = 60.0
-# How long a requester will not send a code again after an answer to it failed: past the code's
-# own life, after which a guess at it is worth nothing.
-FAILED_CODE_SECONDS = 2 * CODE_LIFETIME_SECONDS
-CODE_DIGITS = 6
-MAX_DATAGRAM_BYTES = 1024
-PAIR_REPLY_TIMEOUT_SECONDS = 1.5
-PAIR_ATTEMPTS = 3
-NONCE_BYTES = 16
-SHARE_BYTES = 32
-TAG_BYTES = 64
-# A name is bound into the exchange as sent, so it is cut before it is sent, never after. 48
-# characters keep the largest datagram under MAX_DATAGRAM_BYTES even when JSON escapes each one.
-MAX_NAME_CHARS = 48
-MAX_IDENTITY_BYTES = 32
-# A pairing id is 32 hex characters; 1.4.2's was 8. Anything longer or not ASCII is not one.
-MAX_PAIR_ID_CHARS = 64
-
-MSG_BEACON = "beacon"
-MSG_PAIR_START = "pair_start"
-MSG_PAIR_ANSWER = "pair_answer"
-MSG_PAIR_CONFIRM = "pair_confirm"
-MSG_PAIR_DONE = "pair_done"
-# The 1.4.2 exchange's two datagrams. A host still answers the request, with a refusal, so an
-# older Mac is told something rather than left to time out.
-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"
-ERROR_VERSION = "version"
-_ERRORS = (ERROR_NOT_PAIRING, ERROR_REFUSED, ERROR_VERSION)
-
-# What the exchange binds besides the code. The two roles are fixed by who shows the code; the
-# identities are parameters, empty until machines have ids of their own (wire v6), so a later
-# version changes what is fed in and nothing else.
-ROLE_REQUESTER = b"requester"
-ROLE_HOST = b"host"
-CHANNEL = b"beamer-pair-v2"
-TOKEN_INFO = b"beamer-pair-token-v2"
-DONE_LABEL = b"beamer-pair-done"
-
-_DSI = b"CPace255"
-_FIELD_PRIME = 2**255 - 19
-_CURVE_A = 486662
-_SHA512_BLOCK_BYTES = 128
-
-
-class PairingError(Exception):
- pass
-
-
-def new_code() -> str:
- return "".join(secrets.choice("0123456789") for _ in range(CODE_DIGITS))
-
-
-def _b64(data: bytes) -> str:
- return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
-
-
-def _unb64(text: str) -> bytes:
- if not isinstance(text, str):
- raise PairingError("expected base64 text")
- try:
- data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
- except ValueError as exc:
- raise PairingError("bad base64") from exc
- # The decoder skips what it does not know, so several spellings give the same bytes. Only
- # the one _b64 writes is taken: a field then has one form on the wire on every platform.
- if _b64(data) != text:
- raise PairingError("bad base64")
- return data
-
-
-def _prepend_len(data: bytes) -> bytes:
- """The draft's prepend_len: the length as LEB128, then the bytes."""
- length = len(data)
- encoded = bytearray()
- while True:
- encoded.append(length & 0x7F if length < 128 else (length & 0x7F) | 0x80)
- length >>= 7
- if length == 0:
- return bytes(encoded) + data
-
-
-def _lv_cat(*parts: bytes) -> bytes:
- return b"".join(_prepend_len(part) for part in parts)
-
-
-def _elligator2(r: int) -> int:
- """The u coordinate Elligator 2 maps a field element to on Curve25519 (RFC 9380 6.7.1 with
- Z = 2, as the draft's appendix A.5 repeats it)."""
- p = _FIELD_PRIME
- v = -_CURVE_A * pow(1 + 2 * r * r, p - 2, p) % p
- square = pow((v * v * v + _CURVE_A * v * v + v) % p, (p - 1) // 2, p) == 1
- return v if square else (-v - _CURVE_A) % p
-
-
-def _generator(prs: bytes, channel: bytes, sid: bytes) -> bytes:
- """The draft's calculate_generator for G_X25519 with SHA-512 (sections 8.1 and 8.2)."""
- padding = bytes(max(0, _SHA512_BLOCK_BYTES - 1 - len(_prepend_len(prs)) - len(_prepend_len(_DSI))))
- digest = hashlib.sha512(_lv_cat(_DSI, prs, padding, channel, sid)).digest()[:SHARE_BYTES]
- r = int.from_bytes(digest, "little") & ((1 << 255) - 1)
- return _elligator2(r).to_bytes(SHARE_BYTES, "little")
-
-
-def _x25519(scalar: bytes, point: bytes) -> bytes:
- """X25519 (RFC 7748), refusing a point that lands on the neutral element: the draft's
- scalar_mult_vfy, which MUST abort there. libsodium reports exactly that case as an error."""
- try:
- product = crypto_scalarmult(scalar, point)
- except CryptoError as exc:
- raise PairingError(ERROR_REFUSED) from exc
- if product == bytes(SHARE_BYTES):
- raise PairingError(ERROR_REFUSED)
- return product
-
-
-def _hkdf(key_material: bytes, salt: bytes, info: bytes) -> bytes:
- """HKDF-SHA256 (RFC 5869) for one 32-byte block."""
- extracted = hmac.new(salt, key_material, hashlib.sha256).digest()
- return hmac.new(extracted, info + b"\x01", hashlib.sha256).digest()
-
-
-def _session_id(pair_id: str, nonce: bytes) -> bytes:
- # Random bytes from both ends, as the draft recommends for sid: the host's in the pairing
- # id, the requester's in its nonce.
- return _lv_cat(pair_id.encode("utf-8"), nonce)
-
-
-def _party(role: bytes, identity: bytes, name: str) -> bytes:
- """One side's associated data: CPace's ADa or ADb. The role comes first, so the two sides'
- can never be equal, which is what stops a tag being reflected back at its sender."""
- return _lv_cat(role, identity, name.encode("utf-8"))
-
-
-def _share(code: str, sid: bytes, scalar: bytes) -> bytes:
- return _x25519(scalar, _generator(code.encode("utf-8"), CHANNEL, sid))
-
-
-def _keys(sid: bytes, shared: bytes, ya: bytes, ada: bytes, yb: bytes, adb: bytes) -> tuple:
- """(token, Ta, Tb, Td) for one exchange, from the secret the two shares agree. Ta and Tb are
- the draft's tags over each side's own message; Td is the host's receipt."""
- isk = hashlib.sha512(_lv_cat(_DSI + b"_ISK", sid, shared) + _lv_cat(ya, ada) + _lv_cat(yb, adb)).digest()
- mac_key = hashlib.sha512(b"CPaceMac" + sid + isk).digest()
-
- def tag(message: bytes) -> bytes:
- return hmac.new(mac_key, message, hashlib.sha512).digest()
-
- return _b64(_hkdf(isk, sid, TOKEN_INFO)), tag(_lv_cat(ya, ada)), tag(_lv_cat(yb, adb)), tag(_lv_cat(DONE_LABEL))
-
-
-def _failure(kind: str, pair_id: str, error: str) -> dict:
- return {"type": kind, "pair": pair_id, "ok": False, "error": error}
-
-
-def _error_of(reply: dict) -> str:
- error = reply.get("error")
- return error if error in _ERRORS else ERROR_REFUSED
-
-
-def encode(message: dict) -> bytes:
- # The "beamy" key is a wire constant, deliberately kept as the pre-rename name: changing it
- # would break an existing pairing and a mixed-version pair for no gain.
- return json.dumps({"beamy": BEACON_VERSION, **message}, separators=(",", ":")).encode("utf-8")
-
-
-def decode(data: bytes):
- """The dict a Beamer datagram carries, or None for anything else on the port."""
- if len(data) > MAX_DATAGRAM_BYTES:
- return None
- try:
- message = json.loads(data.decode("utf-8"))
- except (UnicodeDecodeError, ValueError, RecursionError):
- # RecursionError is what a datagram of nothing but brackets raises on some Pythons, and
- # left uncaught it would end the socket loop that called this.
- return None
- if not isinstance(message, dict) or message.get("beamy") != BEACON_VERSION:
- return None
- return message
-
-
-def beacon_msg(name: str, port: int, pair_id: str = None) -> dict:
- message = {"type": MSG_BEACON, "name": name, "port": int(port), "pairing": PAIRING_VERSION}
- if pair_id:
- message["pair"] = pair_id
- return message
-
-
-class PairingHost:
- """The PC's half: holds at most one live code and answers the exchange. Pure -- the
- Announcer owns the socket, and the clock and the randomness are injected for the tests and
- the vectors."""
-
- def __init__(self, clock=time.monotonic, name: str = "", identity: bytes = b"", entropy=secrets.token_bytes):
- self.clock = clock
- self.name = name[:MAX_NAME_CHARS]
- self.identity = identity
- self._entropy = entropy
- self.code = None
- self.pair_id = None
- self.expires_at = 0.0
- # The one pair_start this code answered, as a dict; None until it arrives.
- self._bound = None
- self._last = None
- # True once a pair_answer has just been worked out from the code, until the caller that
- # sends it takes note. A retransmit's answer comes from memory and leaves it False.
- self.fresh_answer = False
- self.paired = None
- # How the last code ended -- "paired", "refused", "version" or "expired" -- for the
- # window to say so; None while a code is live or after a deliberate cancel.
- self.outcome = None
-
- @property
- def active(self) -> bool:
- if self.code is None:
- return False
- if self.clock() >= self.expires_at:
- self.cancel()
- self.outcome = "expired"
- return False
- return True
-
- @property
- def seconds_left(self) -> int:
- return max(0, int(self.expires_at - self.clock())) if self.active else 0
-
- def begin(self) -> str:
- self.code = new_code()
- self.pair_id = self._entropy(16).hex()
- self.expires_at = self.clock() + CODE_LIFETIME_SECONDS
- self._bound = None
- self._last = None
- self.fresh_answer = False
- self.outcome = None
- return self.code
-
- def cancel(self) -> None:
- self.code = None
- self.pair_id = None
- self.expires_at = 0.0
- self._bound = None
- self.outcome = None
-
- def handle(self, message: dict):
- """The reply to one datagram, or None when it deserves no answer. A successful pairing
- leaves the token in `self.paired` as (token, requester_name); the caller stores it."""
- kind = message.get("type")
- pair_id = message.get("pair")
- # Every reply echoes the pairing id, so one that is not shaped like an id gets none: a
- # reply is then never much larger than the datagram that drew it.
- if not isinstance(pair_id, str) or not pair_id.isascii() or not 0 < len(pair_id) <= MAX_PAIR_ID_CHARS:
- return None
- if kind == MSG_PAIR_START:
- return self._start(message, pair_id)
- if kind == MSG_PAIR_CONFIRM:
- return self._confirm(message, pair_id)
- if kind == MSG_PAIR_REQUEST:
- return self._outdated(pair_id)
- return None
-
- def _start(self, message: dict, pair_id: str) -> dict:
- sent = [message.get(field) for field in ("pair", "v", "nonce", "share", "name", "id")]
- if self._last is not None and self._last[0] == sent:
- # A lost reply makes the requester send the same datagram again; answer it the same
- # way, so a retransmit is not read as a second attempt.
- return self._last[1]
- if not self.active or pair_id != self.pair_id:
- return _failure(MSG_PAIR_ANSWER, pair_id, ERROR_NOT_PAIRING)
- if self._bound is not None:
- if self._bound["sent"] == sent:
- return self._bound["answer"]
- # One code answers one share. A second answer would hand whoever sent it a second
- # guess at the code, so it is refused, and the exchange already under way is left
- # alone rather than cancelled by a stranger's datagram.
- return _failure(MSG_PAIR_ANSWER, pair_id, ERROR_REFUSED)
- if message.get("v") != PAIRING_VERSION:
- return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_VERSION, "version")
- try:
- nonce = _unb64(message.get("nonce"))
- share = _unb64(message.get("share"))
- identity = _unb64(message.get("id"))
- name = message.get("name")
- if (
- len(nonce) != NONCE_BYTES
- or len(share) != SHARE_BYTES
- or len(identity) > MAX_IDENTITY_BYTES
- or not isinstance(name, str)
- or len(name) > MAX_NAME_CHARS
- ):
- raise PairingError(ERROR_REFUSED)
- sid = _session_id(pair_id, nonce)
- scalar = self._entropy(SHARE_BYTES)
- requester = _party(ROLE_REQUESTER, identity, name)
- host = _party(ROLE_HOST, self.identity, self.name)
- # Everything that can refuse this datagram is settled before the code is touched:
- # a refusal goes back at once, and must not carry the time the generator took.
- shared = _x25519(scalar, share)
- except (PairingError, UnicodeError):
- return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_REFUSED, "refused")
- try:
- own = _share(self.code, sid, scalar)
- except PairingError:
- return self._end(MSG_PAIR_ANSWER, sent, pair_id, ERROR_REFUSED, "refused")
- token, requester_tag, host_tag, done_tag = _keys(sid, shared, share, requester, own, host)
- self.fresh_answer = True
- answer = {
- "type": MSG_PAIR_ANSWER,
- "pair": pair_id,
- "ok": True,
- "share": _b64(own),
- "tag": _b64(host_tag),
- "name": self.name,
- "id": _b64(self.identity),
- }
- self._bound = {
- "sent": sent,
- "answer": answer,
- "requester_tag": requester_tag,
- "done_tag": done_tag,
- "token": token,
- "name": name,
- }
- return answer
-
- def _confirm(self, message: dict, pair_id: str) -> dict:
- sent = [pair_id, message.get("tag")]
- if self._last is not None and self._last[0] == sent:
- return self._last[1]
- if not self.active or pair_id != self.pair_id or self._bound is None:
- return _failure(MSG_PAIR_DONE, pair_id, ERROR_NOT_PAIRING)
- bound = self._bound
- try:
- tag = _unb64(message.get("tag"))
- except PairingError:
- tag = b""
- if not hmac.compare_digest(tag, bound["requester_tag"]):
- return self._end(MSG_PAIR_DONE, sent, pair_id, ERROR_REFUSED, "refused")
- self.paired = (bound["token"], bound["name"])
- reply = {"type": MSG_PAIR_DONE, "pair": pair_id, "ok": True, "tag": _b64(bound["done_tag"])}
- self._last = (sent, reply)
- self.cancel()
- self.outcome = "paired"
- return reply
-
- def _outdated(self, pair_id: str) -> dict:
- """A 1.4.2 Mac's request. It is answered in the datagram that Mac reads, and the code
- goes, because its window then says the PC cancelled it."""
- if self.active and pair_id == self.pair_id and self._bound is None:
- self.cancel()
- self.outcome = "version"
- return _failure(MSG_PAIR_REPLY, pair_id, ERROR_REFUSED)
- return _failure(MSG_PAIR_REPLY, pair_id, ERROR_REFUSED if self.active else ERROR_NOT_PAIRING)
-
- def _end(self, kind: str, sent: list, pair_id: str, error: str, outcome: str) -> dict:
- reply = _failure(kind, pair_id, error)
- self._last = (sent, reply)
- self.cancel()
- self.outcome = outcome
- return reply
-
-
-class PairingClient:
- """The Mac's half of one attempt: builds the start, checks the answer, confirms, and yields
- the token once the host says it has stored it."""
-
- def __init__(self, pair_id: str, code: str, name: str, identity: bytes = b"", entropy=secrets.token_bytes):
- self.pair_id = pair_id
- self.name = name[:MAX_NAME_CHARS]
- self.identity = identity
- self._nonce = entropy(NONCE_BYTES)
- self._sid = _session_id(pair_id, self._nonce)
- self._scalar = entropy(SHARE_BYTES)
- self._share = _share(code, self._sid, self._scalar)
- self._answered = False
- self._token = None
- self._done_tag = None
- # The host's name and identity as the exchange bound them; None until its tag checks out.
- self.host_name = None
- self.host_identity = None
-
- def start(self) -> dict:
- return {
- "type": MSG_PAIR_START,
- "pair": self.pair_id,
- "v": PAIRING_VERSION,
- "nonce": _b64(self._nonce),
- "share": _b64(self._share),
- "name": self.name,
- "id": _b64(self.identity),
- }
-
- def accept(self, answer: dict) -> dict:
- """The pair_confirm to send back, or PairingError naming why not. It judges one answer
- and no more: each answer it judged would be another guess at the code for whoever is
- answering."""
- if answer.get("type") != MSG_PAIR_ANSWER or answer.get("pair") != self.pair_id:
- raise PairingError("not a reply to this attempt")
- if self._answered:
- raise PairingError(ERROR_REFUSED)
- self._answered = True
- if answer.get("ok") is not True:
- raise PairingError(_error_of(answer))
- try:
- share = _unb64(answer.get("share"))
- tag = _unb64(answer.get("tag"))
- identity = _unb64(answer.get("id"))
- name = answer.get("name")
- if len(share) != SHARE_BYTES or len(identity) > MAX_IDENTITY_BYTES or not isinstance(name, str) or len(name) > MAX_NAME_CHARS:
- raise PairingError(ERROR_REFUSED)
- requester = _party(ROLE_REQUESTER, self.identity, self.name)
- host = _party(ROLE_HOST, identity, name)
- shared = _x25519(self._scalar, share)
- token, requester_tag, host_tag, done_tag = _keys(self._sid, shared, self._share, requester, share, host)
- except (PairingError, UnicodeError) as exc:
- raise PairingError(ERROR_REFUSED) from exc
- if not hmac.compare_digest(tag, host_tag):
- raise PairingError(ERROR_REFUSED)
- self._token = token
- self._done_tag = done_tag
- self.host_name = name
- self.host_identity = identity
- return {"type": MSG_PAIR_CONFIRM, "pair": self.pair_id, "tag": _b64(requester_tag)}
-
- def abort(self) -> dict:
- """What to send a host whose answer failed: a confirmation that cannot pass, so the PC
- drops the code and says a wrong one was entered instead of showing it for the rest of
- its minute."""
- return {"type": MSG_PAIR_CONFIRM, "pair": self.pair_id, "tag": ""}
-
- def finish(self, done: dict) -> str:
- """The agreed token, once the host's pair_done proves it stored the same one."""
- if done.get("type") != MSG_PAIR_DONE or done.get("pair") != self.pair_id or self._token is None:
- raise PairingError("not a reply to this attempt")
- if done.get("ok") is not True:
- raise PairingError(_error_of(done))
- try:
- tag = _unb64(done.get("tag"))
- except PairingError as exc:
- raise PairingError(ERROR_REFUSED) from exc
- if not hmac.compare_digest(tag, self._done_tag):
- raise PairingError(ERROR_REFUSED)
- return self._token
-
-
-def _udp_socket(bind_port: int) -> socket.socket:
- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- if hasattr(socket, "SO_REUSEPORT"):
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
- sock.bind(("", bind_port))
- sock.settimeout(0.5)
- return sock
-
-
-def local_address_towards(host: str) -> str:
- """This machine's address on the interface that reaches `host`; nothing is sent."""
- probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- try:
- probe.connect((host, 9))
- return probe.getsockname()[0]
- finally:
- probe.close()
-
-
-def broadcast_targets(port: int) -> list:
- """Every address worth sending a beacon to, one per local IPv4 interface plus the limited
- broadcast as a backstop.
-
- ⚠ 255.255.255.255 alone is not enough and this is not theoretical: it leaves by the default
- route only, so a PC with a second interface — a Hyper-V vEthernet switch is the common case —
- 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
- this can only add delivery, never remove it."""
- targets = [("255.255.255.255", port)]
- seen = {"255.255.255.255"}
- for address in _local_ipv4_addresses():
- parts = address.split(".")
- if len(parts) != 4:
- continue
- directed = ".".join(parts[:3] + ["255"])
- if directed not in seen:
- seen.add(directed)
- targets.append((directed, port))
- return targets
-
-
-def _local_ipv4_addresses() -> list:
- found = []
- try:
- for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):
- address = info[4][0]
- if not address.startswith("127.") and address not in found:
- found.append(address)
- except OSError:
- pass
- return found
-
-
-def machine_name() -> str:
- return socket.gethostname().split(".", 1)[0] or "This machine"
-
-
-class Announcer:
- """The PC's socket loop: broadcasts the beacon and answers pairing requests on one socket.
- `port_getter` returns the current TCP port, so a changed listen port is announced without a
- restart. `on_paired(token, mac_name, mac_address)` is called on this thread."""
-
- def __init__(self, port_getter, on_paired, logger=None, bind_port=PAIRING_PORT, announce_to=("255.255.255.255", PAIRING_PORT), name=None):
- self.port_getter = port_getter
- self.on_paired = on_paired
- self.logger = logger or logging.getLogger("Beamer")
- self.bind_port = bind_port
- self.announce_to = announce_to
- self.name = name or machine_name()
- self.host = PairingHost(name=self.name)
- self._lock = threading.Lock()
- self._stop = threading.Event()
- self._thread = None
- self.error = None
-
- def start(self) -> None:
- if self._thread is not None:
- return
- self._stop.clear()
- self._thread = threading.Thread(target=self._run, name="Beamer-announcer", daemon=True)
- self._thread.start()
-
- def stop(self) -> None:
- self._stop.set()
- thread = self._thread
- if thread is not None and thread is not threading.current_thread():
- thread.join(timeout=2.0)
- self._thread = None
-
- def begin_pairing(self) -> str:
- with self._lock:
- return self.host.begin()
-
- def cancel_pairing(self) -> None:
- with self._lock:
- self.host.cancel()
-
- @property
- def code(self):
- with self._lock:
- return self.host.code if self.host.active else None
-
- @property
- def seconds_left(self) -> int:
- with self._lock:
- return self.host.seconds_left
-
- @property
- def outcome(self):
- with self._lock:
- self.host.active
- return self.host.outcome
-
- def _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))
-
- @staticmethod
- def _due(last: dict, host: str, now: float) -> bool:
- """Whether `host` may be sent another datagram of a rationed kind, noting it if so."""
- interval = BEACON_INTERVAL_SECONDS / 4
- if now - last.get(host, -BEACON_INTERVAL_SECONDS) < interval:
- return False
- if len(last) > 256:
- # Only what has lapsed is forgotten. Emptying the table would let a burst from
- # made-up addresses wipe the record of the one being aimed at.
- for lapsed in [known for known, sent in last.items() if now - sent >= interval]:
- del last[lapsed]
- if len(last) > 256:
- return False
- last[host] = now
- return True
-
- def _run(self) -> None:
- try:
- sock = _udp_socket(self.bind_port)
- except OSError as exc:
- self.error = str(exc)
- self.logger.error("pairing beacon could not bind UDP %s: %s", self.bind_port, exc)
- return
- self.error = None
- next_beacon = 0.0
- answered = {}
- refused = {}
- try:
- while not self._stop.is_set():
- now = time.monotonic()
- if now >= next_beacon:
- next_beacon = now + BEACON_INTERVAL_SECONDS
- 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
- # the real network.
- if self.announce_to[0] == "255.255.255.255":
- targets = broadcast_targets(self.announce_to[1])
- else:
- targets = [self.announce_to]
- for target in targets:
- try:
- sock.sendto(beacon, target)
- delivered += 1
- except OSError:
- continue
- if not delivered:
- self.logger.warning("beacon reached no interface")
- try:
- data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)
- except socket.timeout:
- continue
- except ConnectionResetError:
- # Windows reports an ICMP port-unreachable for a datagram this
- # socket sent as a reset on the next receive. The socket is
- # fine; the peer that was not listening is the Mac's problem.
- continue
- except OSError as exc:
- if self._stop.is_set():
- break
- self.error = str(exc)
- self.logger.error("pairing beacon stopped: %s", exc)
- break
- arrived = time.monotonic()
- 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 self._due(answered, address[0], arrived):
- 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:
- try:
- reply = self.host.handle(message)
- except Exception:
- # Whatever one datagram does, the next beacon still goes out.
- self.logger.exception("pairing datagram dropped")
- reply = None
- paired, self.host.paired = self.host.paired, None
- fresh, self.host.fresh_answer = self.host.fresh_answer, False
- # A refusal is larger than the smallest datagram that draws one, so it is rationed
- # the same way. A requester that misses one asks again after its own timeout.
- if reply is not None and (reply.get("ok") is True or self._due(refused, address[0], arrived)):
- if fresh:
- # Only the answer just worked out from the code is held back. A
- # retransmit's comes from memory, and holding each of those would let a
- # stream of replays stall this loop.
- self._stop.wait(max(0.0, arrived + PAIR_ANSWER_SECONDS - time.monotonic()))
- try:
- sock.sendto(encode(reply), address)
- except OSError as exc:
- self.logger.warning("pairing reply not sent: %s", exc)
- if paired is not None:
- self.logger.info("paired with %s at %s", paired[1] or "a Mac", address[0])
- try:
- self.on_paired(paired[0], paired[1], address[0])
- except Exception:
- self.logger.exception("on_paired failed")
- except Exception as exc:
- self.error = str(exc)
- self.logger.exception("pairing beacon stopped")
- finally:
- sock.close()
-
-
-class Discovery:
- """The Mac's socket loop: listens for beacons and carries pairing attempts on the same
- socket, so a reply comes back to the port the PC heard from."""
-
- def __init__(self, logger=None, bind_port=PAIRING_PORT, clock=time.monotonic):
- self.logger = logger or logging.getLogger("Beamer")
- self.bind_port = bind_port
- self.clock = clock
- self._lock = threading.Lock()
- self._seen = {}
- self._replies = queue.Queue(maxsize=64)
- self._awaiting = None
- self._pairing = threading.Lock()
- # Codes an answer has failed under, each with the time it may be tried again.
- self._failed = {}
- 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
- self._stop.clear()
- self._thread = threading.Thread(target=self._run, name="Beamer-discovery", daemon=True)
- self._thread.start()
-
- def stop(self) -> None:
- self._stop.set()
- thread = self._thread
- if thread is not None and thread is not threading.current_thread():
- thread.join(timeout=2.0)
- self._thread = None
-
- def pcs(self) -> list:
- """Every PC heard from recently: dicts of name, address, port, reply_port, pair_id and
- pairing, the version of the exchange it speaks."""
- cutoff = self.clock() - BEACON_STALE_SECONDS
- with self._lock:
- stale = [key for key, entry in self._seen.items() if entry["seen_at"] < cutoff]
- for key in stale:
- del self._seen[key]
- return sorted(
- ({k: v for k, v in entry.items() if k != "seen_at"} for entry in self._seen.values()),
- key=lambda entry: (entry["name"].lower(), entry["address"]),
- )
-
- def pair(self, pc: dict, code: str, name: str = None) -> tuple:
- """Runs the exchange with `pc` (an entry from pcs()) and returns (token, host_name),
- the name being the one the exchange proved. Blocks for up to PAIR_ATTEMPTS replies'
- worth, once for the answer and once for the receipt; call it off the main thread."""
- sock = self._sock
- if sock is None:
- raise PairingError("discovery is not running")
- if pc.get("pairing") != PAIRING_VERSION:
- # Said here, before anything is sent: there is no older exchange to fall back to.
- raise PairingError(ERROR_VERSION)
- if not isinstance(pc.get("pair_id"), str):
- raise PairingError(ERROR_NOT_PAIRING)
- target = (pc["address"], pc["reply_port"])
- if not self._pairing.acquire(blocking=False):
- # One attempt at a time: a second would take the first one's replies, and could
- # slip past the record of failed codes below.
- raise PairingError("busy")
- try:
- now = self.clock()
- self._failed = {failed: until for failed, until in self._failed.items() if until > now}
- if code in self._failed:
- # An answer to this code was judged and failed, so whoever answered has had a
- # guess at it. The real host has bound the code to that attempt or dropped it;
- # sending another share would pair with nobody and only buy the answerer a
- # second guess. It is the code that is remembered, not the pairing id, which a
- # beacon can forge.
- raise PairingError(ERROR_REFUSED)
- client = PairingClient(pc["pair_id"], code, name or machine_name())
- while True:
- try:
- self._replies.get_nowait()
- except queue.Empty:
- break
- self._awaiting = (target[0], client.pair_id)
- answer = self._ask(sock, target, client.pair_id, client.start(), MSG_PAIR_ANSWER)
- try:
- confirm = client.accept(answer)
- except PairingError:
- # Only an answer that claimed to be good can have tested a guess. A refusal
- # tests nothing, and a stale pairing id draws one from an honest PC.
- if answer.get("ok") is True:
- self._failed[code] = self.clock() + FAILED_CODE_SECONDS
- try:
- sock.sendto(encode(client.abort()), target)
- except OSError:
- pass
- raise
- token = client.finish(self._ask(sock, target, client.pair_id, confirm, MSG_PAIR_DONE))
- return token, client.host_name
- finally:
- self._awaiting = None
- self._pairing.release()
-
- def _ask(self, sock, target, pair_id: str, message: dict, reply_type: str) -> dict:
- """Sends one datagram until the first reply of `reply_type` from `target` comes back.
- The first one decides: the caller judges it and never waits for a better one."""
- datagram = encode(message)
- for _attempt in range(PAIR_ATTEMPTS):
- try:
- sock.sendto(datagram, target)
- except OSError as exc:
- raise PairingError("no_answer") from exc
- deadline = self.clock() + PAIR_REPLY_TIMEOUT_SECONDS
- while True:
- remaining = deadline - self.clock()
- if remaining <= 0:
- break
- try:
- reply, address = self._replies.get(timeout=remaining)
- except queue.Empty:
- break
- if address[0] != target[0] or reply.get("pair") != pair_id or reply.get("type") != reply_type:
- continue
- return reply
- raise PairingError("no_answer")
-
- def _run(self) -> None:
- try:
- sock = _udp_socket(self.bind_port)
- except OSError as exc:
- self.error = str(exc)
- self.logger.error("discovery could not bind UDP %s: %s", self.bind_port, exc)
- return
- self.error = None
- self._sock = sock
- try:
- while not self._stop.is_set():
- self._send_find(sock)
- try:
- data, address = sock.recvfrom(MAX_DATAGRAM_BYTES + 1)
- except socket.timeout:
- continue
- except ConnectionResetError:
- continue
- except OSError as exc:
- if self._stop.is_set():
- break
- self.error = str(exc)
- self.logger.error("discovery stopped: %s", exc)
- break
- message = decode(data)
- if message is None:
- continue
- kind = message.get("type")
- if kind == MSG_BEACON:
- try:
- self._note_beacon(message, address)
- except Exception:
- self.logger.exception("beacon dropped")
- elif kind in (MSG_PAIR_ANSWER, MSG_PAIR_DONE) and self._awaiting == (address[0], message.get("pair")):
- # Only what the attempt under way is waiting for is kept, and only so much
- # of it, so nothing a stranger sends piles up in memory.
- try:
- self._replies.put_nowait((message, address))
- except queue.Full:
- pass
- except Exception as exc:
- self.error = str(exc)
- self.logger.exception("discovery stopped")
- finally:
- 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")
- pair_id = message.get("pair")
- version = message.get("pairing")
- if not isinstance(name, str) or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
- return
- try:
- name.encode("utf-8")
- except UnicodeError:
- # Half a surrogate pair is JSON a parser accepts and text no window can show.
- return
- entry = {
- "name": name[:64] or address[0],
- "address": address[0],
- "port": port,
- "reply_port": address[1],
- "pair_id": pair_id if isinstance(pair_id, str) and pair_id.isascii() and 0 < len(pair_id) <= MAX_PAIR_ID_CHARS else None,
- # A beacon from 1.4.2 or earlier carries no number: that is version 1.
- "pairing": version if isinstance(version, int) and not isinstance(version, bool) else 1,
- "seen_at": self.clock(),
- }
- with self._lock:
- if address[0] not in self._seen and len(self._seen) >= MAX_SEEN_HOSTS:
- # The list is only read while the window is open, so what has gone quiet is
- # cleared here too. Beacons from made-up addresses then cost a fixed amount of
- # memory and no more.
- cutoff = self.clock() - BEACON_STALE_SECONDS
- for stale in [key for key, known in self._seen.items() if known["seen_at"] < cutoff]:
- del self._seen[stale]
- if len(self._seen) >= MAX_SEEN_HOSTS:
- # Still full: whoever has been quiet longest gives way. A flood of forgeries
- # can crowd real PCs off the list that way, which is a denial like any
- # other here, so the one address the user typed is never the one to go.
- wanted = self._finding[0] if self._finding else None
- del self._seen[min((key for key in self._seen if key != wanted), key=lambda key: self._seen[key]["seen_at"])]
- self._seen[address[0]] = entry
diff --git a/mac_app/previews.py b/mac_app/previews.py
index 25cb959..013cb06 100644
--- a/mac_app/previews.py
+++ b/mac_app/previews.py
@@ -20,7 +20,7 @@ import Quartz
import objc
import crossing
-import effects
+from core import effects
import effects_overlay
import motion
import notch_beam
diff --git a/mac_app/protocol.py b/mac_app/protocol.py
deleted file mode 100644
index 3168324..0000000
--- a/mac_app/protocol.py
+++ /dev/null
@@ -1,463 +0,0 @@
-"""Wire protocol shared by mac_app/bridge.py and win_app/receiver.py.
-
-The link is encrypted and authenticated with ChaCha20-Poly1305; the shared
-token never crosses the wire, and a peer that cannot produce a valid tag does
-not hold it.
-
-A connection opens with one cleartext preamble each way -- WIRE_MAGIC, one
-version byte, and that side's 8-byte nonce prefix, drawn fresh per connection
--- so a version mismatch produces a readable status instead of undecryptable
-garbage. Each direction then has its own key, HKDF-SHA256 over the token with
-the sender's prefix and the receiver's prefix in `info`, so nothing is sealed
-until the peer's preamble is in. Every frame after that is a 4-byte big-endian
-length, then a 4-byte big-endian counter, then the ciphertext with its tag; the
-length covers the counter and ciphertext. The nonce is prefix + counter, each
-side counting its own frames from 1, and the receiver rejects any counter that
-is not the next one.
-
-What that stops: a frame played again, dropped or reordered inside a
-connection fails the counter; a whole recorded connection played into a new
-one fails the tag, because the receiver's fresh prefix is part of the key its
-peer had to seal under; a side's own frames reflected back fail the tag,
-because the two directions' keys differ. What it does not give is forward
-secrecy: anyone who later learns the token can read a recording made before.
-"""
-
-import base64
-import binascii
-import json
-import os
-import socket
-import struct
-import threading
-import time
-
-from cryptography.exceptions import InvalidTag
-from cryptography.hazmat.primitives import hashes
-from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
-from cryptography.hazmat.primitives.kdf.hkdf import HKDF
-
-HEADER_SIZE = 4
-COUNTER_SIZE = 4
-NONCE_PREFIX_SIZE = 8
-MAX_COUNTER = 0xFFFFFFFF
-# Wire constant, deliberately kept as the pre-rename name: changing it would break an existing
-# pairing and a mixed-version pair for no gain.
-WIRE_MAGIC = b"BEAMY"
-PREAMBLE_SIZE = len(WIRE_MAGIC) + 1 + NONCE_PREFIX_SIZE
-# 5: per-connection keys bound to both prefixes (1.4.1). 4 keyed every connection alike from the
-# token, so a recorded connection could be played into a new one whole.
-PROTOCOL_VERSION = 5
-
-# Both ports sit below 49152 on purpose. Windows and macOS both hand out 49152-65535 as
-# ephemeral ports, and Windows lets WinNAT reserve whole 100-port blocks from that range that
-# move on every reboot: one landed on the old 51820 and the receiver could not bind at all,
-# while the PC's outward link carried on working, so input went one way only. Nothing is
-# handed out below 49152, so the port a user pairs on stays theirs.
-DEFAULT_PORT = 24820
-PAIRING_PORT = 24821
-# What DEFAULT_PORT used to be. A config still carrying it was never chosen by
-# anyone, so it is migrated rather than honoured; a port a user picked is left alone.
-LEGACY_DEFAULT_PORT = 51820
-KEY_SALT = b"beamer-link-v5"
-KEY_INFO = b"beamer-frames"
-CLIPBOARD_MAX_BYTES = 256 * 1024
-# The clipboard goes out ahead of the focus message on every switch, sealed as one frame and
-# 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;
-# 8MB covers that with room for a busier desktop, and as a base64 frame (~10.7MB) it is about
-# 0.1s on wired gigabit and half a second on decent Wi-Fi. Beyond it the text still goes.
-CLIPBOARD_IMAGE_MAX_BYTES = 8 * 1024 * 1024
-CLIPBOARD_IMAGE_PNG = "png"
-# The largest sealed frame either end accepts. It must hold the biggest clipboard message -- an
-# 8MB image is ~10.7MB as base64, beside up to 256KB of text -- because the clipboard also travels
-# back on the reply stream. A 1MB cap there dropped the link on every return with a screenshot on
-# the clipboard.
-MAX_FRAME_BYTES = 16 * 1024 * 1024
-# The first frame each way is a hello or a welcome of a few dozen bytes. Anything larger before
-# authentication is not a Beamer, so it is refused before it is read.
-HELLO_MAX_BYTES = 4096
-PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
-
-MSG_HELLO = "hello"
-MSG_WELCOME = "welcome"
-MSG_PING = "ping"
-MSG_KEYDOWN = "keydown"
-MSG_KEYUP = "keyup"
-MSG_MOUSEMOVE = "mousemove"
-MSG_MOUSEDOWN = "mousedown"
-MSG_MOUSEUP = "mouseup"
-MSG_SCROLL = "scroll"
-MSG_ACK = "ack"
-MSG_CLIPBOARD = "clipboard"
-MSG_FOCUS = "focus"
-MSG_GESTURE = "gesture"
-MSG_SWITCH = "switch"
-MSG_ARRANGEMENT = "arrangement"
-
-# System trackpad gestures. The Mac classifies one at the end of the movement and sends a
-# single message; the name is the finger motion, not its meaning, so the receiver decides
-# what a swipe does and Windows' own touchpad settings apply when it can inject a real one.
-GESTURE_SWIPE_UP = "swipe_up"
-GESTURE_SWIPE_DOWN = "swipe_down"
-GESTURE_SWIPE_LEFT = "swipe_left"
-GESTURE_SWIPE_RIGHT = "swipe_right"
-GESTURE_SPREAD = "spread"
-GESTURE_PINCH = "pinch"
-GESTURE_NAMES = frozenset(
- {
- GESTURE_SWIPE_UP,
- GESTURE_SWIPE_DOWN,
- GESTURE_SWIPE_LEFT,
- GESTURE_SWIPE_RIGHT,
- GESTURE_SPREAD,
- GESTURE_PINCH,
- }
-)
-
-class ProtocolError(Exception):
- pass
-
-
-class ConnectionClosed(Exception):
- pass
-
-
-class AuthenticationError(ProtocolError):
- """A frame failed authentication: the peer does not hold the shared token,
- or the stream was tampered with. Deliberately carries nothing else."""
-
- def __init__(self):
- super().__init__("frame failed authentication")
-
-
-class VersionMismatch(ProtocolError):
- """The peer's preamble named another wire version. `peer_version` is None
- when the peer sent no preamble at all -- an older Beamer that opened with a
- length-prefixed cleartext frame instead."""
-
- def __init__(self, peer_version):
- super().__init__(f"peer speaks wire version {peer_version!r}, expected {PROTOCOL_VERSION}")
- self.peer_version = peer_version
-
-
-def derive_key(token: str, sender_prefix: bytes, receiver_prefix: bytes) -> bytes:
- """The key for the frames one side seals and the other opens, on one
- connection only: both prefixes are drawn fresh per connection, and their
- order is the direction."""
- return HKDF(
- algorithm=hashes.SHA256(), length=32, salt=KEY_SALT, info=KEY_INFO + sender_prefix + receiver_prefix
- ).derive(token.encode("utf-8"))
-
-
-class SecureSession:
- """One connection's cipher state for both directions. Build a new one per
- connection: it draws a fresh nonce prefix and starts both counters at zero.
- Neither key exists until accept_preamble, so nothing can be sealed or
- opened before the peer's prefix is known.
- `send_lock` serialises sealing, and send_msg holds it across the write too,
- so counters are never reused and frames reach the wire in counter order;
- `open` is expected to run on a single reader thread per connection."""
-
- def __init__(self, token: str, prefix: bytes = None):
- self._token = token
- self.prefix = os.urandom(NONCE_PREFIX_SIZE) if prefix is None else bytes(prefix)
- if len(self.prefix) != NONCE_PREFIX_SIZE:
- raise ValueError("nonce prefix must be 8 bytes")
- self.send_lock = threading.RLock()
- self._send_counter = 0
- self._send_cipher = None
- self.peer_prefix = None
- self._recv_cipher = None
- self._recv_counter = 0
-
- def preamble(self) -> bytes:
- return WIRE_MAGIC + bytes([PROTOCOL_VERSION]) + self.prefix
-
- def accept_preamble(self, data: bytes) -> None:
- if len(data) != PREAMBLE_SIZE or not data.startswith(WIRE_MAGIC):
- raise VersionMismatch(None)
- version = data[len(WIRE_MAGIC)]
- if version != PROTOCOL_VERSION:
- raise VersionMismatch(version)
- peer_prefix = data[len(WIRE_MAGIC) + 1:]
- if self.peer_prefix is not None:
- raise ProtocolError("second preamble on one connection")
- # Equal prefixes would make both directions one key.
- if peer_prefix == self.prefix:
- raise ProtocolError("peer echoed this side's nonce prefix")
- with self.send_lock:
- self._send_cipher = ChaCha20Poly1305(derive_key(self._token, self.prefix, peer_prefix))
- self._recv_cipher = ChaCha20Poly1305(derive_key(self._token, peer_prefix, self.prefix))
- self.peer_prefix = peer_prefix
-
- def seal(self, msg: dict) -> bytes:
- body = json.dumps(msg).encode("utf-8")
- with self.send_lock:
- if self._send_cipher is None:
- raise ProtocolError("nothing is sealed before the peer's preamble")
- if self._send_counter >= MAX_COUNTER:
- raise ProtocolError("frame counter exhausted; reconnect")
- self._send_counter += 1
- counter = struct.pack(">I", self._send_counter)
- ciphertext = self._send_cipher.encrypt(self.prefix + counter, body, None)
- return struct.pack(">I", COUNTER_SIZE + len(ciphertext)) + counter + ciphertext
-
- def open(self, body: bytes) -> dict:
- if self._recv_cipher is None:
- raise ProtocolError("frame received before the peer's preamble")
- if len(body) <= COUNTER_SIZE:
- raise ProtocolError("frame too short")
- (counter,) = struct.unpack(">I", body[:COUNTER_SIZE])
- if counter != self._recv_counter + 1:
- raise ProtocolError("frame counter did not advance; replay rejected")
- try:
- plain = self._recv_cipher.decrypt(self.peer_prefix + body[:COUNTER_SIZE], body[COUNTER_SIZE:], None)
- except InvalidTag:
- raise AuthenticationError() from None
- self._recv_counter = counter
- try:
- message = json.loads(plain.decode("utf-8"))
- except (UnicodeDecodeError, json.JSONDecodeError) as exc:
- raise ProtocolError(f"malformed message body: {exc}") from exc
- if not isinstance(message, dict):
- raise ProtocolError("message body must be a JSON object")
- return message
-
-
-def send_msg(sock: socket.socket, session, msg: dict) -> None:
- with session.send_lock:
- sock.sendall(session.seal(msg))
-
-
-def legacy_frame(msg: dict) -> bytes:
- """The pre-v4 cleartext framing, kept only so an older peer can be told to
- update in words it understands rather than left waiting on silence."""
- body = json.dumps(msg).encode("utf-8")
- return struct.pack(">I", len(body)) + body
-
-
-def _recv_exact(sock: socket.socket, n: int, deadline: float = None) -> bytes:
- """`deadline` is a time.monotonic() moment the whole read must finish by.
- A socket timeout alone bounds each recv, not the read: a peer sending one
- byte every few seconds would hold a handshake open for as long as it
- liked. Past the deadline this raises socket.timeout like a quiet peer."""
- chunks = []
- remaining = n
- while remaining > 0:
- if deadline is not None:
- left = deadline - time.monotonic()
- if left <= 0:
- raise socket.timeout("deadline passed while reading")
- sock.settimeout(left)
- chunk = sock.recv(remaining)
- if not chunk:
- raise ConnectionClosed("socket closed while reading")
- chunks.append(chunk)
- remaining -= len(chunk)
- return b"".join(chunks)
-
-
-def recv_preamble(sock: socket.socket, session, deadline: float = None) -> None:
- session.accept_preamble(_recv_exact(sock, PREAMBLE_SIZE, deadline))
-
-
-def recv_msg(sock: socket.socket, session, limit: int = MAX_FRAME_BYTES, deadline: float = None) -> dict:
- """`limit` is the most a frame may claim before it is read. The receiver
- passes HELLO_MAX_BYTES for the first frame: until that frame's tag has
- been checked the peer has proved nothing, so it must not be able to make
- this side buffer a clipboard-sized frame per connection. `deadline`
- bounds the whole read the same way, for the same reason."""
- header = _recv_exact(sock, HEADER_SIZE, deadline)
- (length,) = struct.unpack(">I", header)
- if length < 1 or length > limit:
- raise ProtocolError(f"invalid message length: {length}")
- return session.open(_recv_exact(sock, length, deadline))
-
-
-def hello_msg(return_edge: str = None, resistance_px: int = None) -> dict:
- """The first encrypted frame. It carries no token: decrypting it is the
- proof the sender holds the shared secret.
-
- `return_edge` and `resistance_px` are the same pair a focus message
- carries, sent here as well so the receiver knows the way home before the
- first crossing rather than after it -- which is what lets the receiver's
- own machine push back across that same border unprompted. Both are
- omitted when None and unknown keys are ignored, so this needs no version
- bump."""
- data = {"version": PROTOCOL_VERSION}
- if return_edge is not None:
- data["return_edge"] = return_edge
- if resistance_px is not None:
- data["resistance_px"] = resistance_px
- return {"type": MSG_HELLO, "data": data}
-
-
-def welcome_msg(error: str = None) -> dict:
- """Sent by the receiver to confirm authentication and protocol version.
- `error` (e.g. "version_mismatch") is set when the sender's declared version
- is not supported."""
- data = {"version": PROTOCOL_VERSION}
- if error is not None:
- data["error"] = error
- return {"type": MSG_WELCOME, "data": data}
-
-
-def ping_msg() -> dict:
- """Sent by the sender while idle so a dead connection is detected quickly.
- Carries no `seq` and must never be recorded as a processed input event."""
- return {"type": MSG_PING, "data": {}}
-
-
-def ack_msg(seq: int, locked: bool = False) -> dict:
- """Sent by the receiver to acknowledge processed input up to `seq`.
- The sender increments `seq` once per outbound input event; the receiver
- echoes back the highest `seq` it has processed. Used as a watchdog
- heartbeat — if the sender doesn't see an ACK for ~2s while redirecting,
- it must force-revert to local input.
-
- `locked` is set only while Windows is clearing its lock screen, during
- which input is being dropped rather than injected. It is omitted when
- false, and unknown keys are ignored on both sides, so this stays
- compatible in both directions and needs no protocol version bump."""
- data = {"seq": seq}
- if locked:
- data["locked"] = True
- return {"type": MSG_ACK, "data": data}
-
-
-def scroll_msg(dy, dx=0.0, mode: str = "line") -> dict:
- """Scroll event. `mode` is "pixel" for continuous trackpad deltas (float
- px) or "line" for discrete wheel clicks. `dx` and `mode` are optional on
- receive for backward tolerance: a missing `dx` means 0, a missing `mode`
- means "line"."""
- return {"type": MSG_SCROLL, "data": {"dy": dy, "dx": dx, "mode": mode}}
-
-
-def clipboard_msg(text: str = None, image: bytes = None) -> dict:
- """Whatever was on the clipboard at the switch: `text` as before, and an
- optional PNG under `image` (base64) with `image_format` naming it. Each
- key is omitted when absent. A pre-image receiver ignores the two new keys
- and an image-only message (no `text`) the same way it ignores any other
- unknown data, so this needs no protocol version bump: SecureSession.open
- only requires a JSON object, and neither app validates keys it does not
- read."""
- data = {}
- if text is not None:
- data["text"] = text
- if image is not None:
- data["image"] = base64.b64encode(image).decode("ascii")
- data["image_format"] = CLIPBOARD_IMAGE_PNG
- return {"type": MSG_CLIPBOARD, "data": data}
-
-
-def clipboard_image(data) -> bytes:
- """The PNG bytes carried by a clipboard message's `data`, or None when
- there is no image or it is not usable: an unknown format, base64 that
- does not decode, bytes that do not start as a PNG, or more than
- CLIPBOARD_IMAGE_MAX_BYTES. Never raises; the clipboard must never break
- a switch, so junk is dropped here rather than surfaced."""
- if not isinstance(data, dict) or data.get("image_format") != CLIPBOARD_IMAGE_PNG:
- return None
- encoded = data.get("image")
- # Length check before decoding, so an oversized payload costs no decode.
- if not isinstance(encoded, str) or len(encoded) > CLIPBOARD_IMAGE_MAX_BYTES * 4 // 3 + 4:
- return None
- try:
- image = base64.b64decode(encoded, validate=True)
- except (binascii.Error, ValueError):
- return None
- if len(image) > CLIPBOARD_IMAGE_MAX_BYTES or not image.startswith(PNG_SIGNATURE):
- return None
- return image
-
-
-def focus_msg(
- target: str,
- edge: str = None,
- offset: float = None,
- return_edge: str = None,
- resistance_px: int = None,
-) -> dict:
- """Sent by the sender to move input. `edge` is the receiver edge being
- arrived at and `offset` the fraction along it, both absent when the switch
- came from the shortcut rather than a crossing. `return_edge` and
- `resistance_px` are sent on every switch to the receiver: they are how it
- knows the way home, so nothing about crossing is configured on its side.
- `target` names the machine input is moving to, which is the receiver's own
- name on the way out and the sender's on the way back. All four are omitted when None, and unknown keys are ignored,
- so this needs no protocol version bump."""
- data = {"target": target}
- if edge is not None:
- data["edge"] = edge
- if offset is not None:
- data["offset"] = offset
- if return_edge is not None:
- data["return_edge"] = return_edge
- if resistance_px is not None:
- data["resistance_px"] = resistance_px
- return {"type": MSG_FOCUS, "data": data}
-
-
-def switch_msg(target: str, edge: str = None, offset: float = None) -> dict:
- """Sent by the receiver to ask the sender to move input, when the pointer
- has been pushed through the receiver's return edge. `target` is the
- sender's machine -- "mac" on the Mac-to-Windows link, "windows" on the
- Windows-to-Mac one. `edge` is the edge to arrive at there and `offset`
- the fraction along it; both are absent for a plain return with no
- position to carry."""
- data = {"target": target}
- if edge is not None:
- data["edge"] = edge
- if offset is not None:
- data["offset"] = offset
- return {"type": MSG_SWITCH, "data": data}
-
-
-def arrangement_msg(mac_edge: str, set_at: int) -> dict:
- """Where the two machines are in relation to each other, as one value:
- the edge of the MAC that leads to the PC. Everything else follows from it
- -- the Mac crosses out by that edge, arrives at the opposite edge of the
- PC, and comes home the same way -- so the two ends cannot describe a
- border that does not exist.
-
- Either machine may change it, and tells the other with this message.
- `set_at` is unix seconds at the machine that made the change: when two
- ends meet holding different arrangements, because one was changed while
- the other was asleep, the newer one wins rather than whichever spoke
- first. Unknown message types are ignored, so an older Beamer keeps
- working with the arrangement it already has."""
- return {"type": MSG_ARRANGEMENT, "data": {"mac_edge": mac_edge, "set_at": int(set_at)}}
-
-
-def read_arrangement(data):
- """(mac_edge, set_at) from an arrangement message's data, or None when it
- carries no edge worth acting on. Never raises: a malformed arrangement
- must not take a working link down."""
- if not isinstance(data, dict):
- return None
- edge = data.get("mac_edge")
- if edge not in ("left", "right", "top", "bottom"):
- return None
- set_at = data.get("set_at")
- if isinstance(set_at, bool) or not isinstance(set_at, (int, float)):
- set_at = 0
- return edge, int(set_at)
-
-
-def arrangement_wins(theirs: int, mine: int) -> bool:
- """Whether an arrangement the peer sent should replace the one held here.
-
- Both ends stamp their own change, so the newer stamp stands: without that,
- an arrangement changed at one machine while the other was asleep would be
- silently undone by the sleeper's hello on the next connection. A peer that
- sends no stamp at all (an older Beamer, or a first connection) loses to any
- stamp of ours, and two ends that have never changed it both hold zero and
- agree anyway."""
- return int(theirs or 0) > int(mine or 0)
-
-
-def gesture_msg(name: str) -> dict:
- """One completed system gesture (a GESTURE_* name). Unknown message types are
- ignored by the receiver, so this needs no protocol version bump."""
- return {"type": MSG_GESTURE, "data": {"name": name}}
diff --git a/mac_app/receiver.py b/mac_app/receiver.py
deleted file mode 100644
index ea1a8af..0000000
--- a/mac_app/receiver.py
+++ /dev/null
@@ -1,1156 +0,0 @@
-"""Threaded TCP receiver and ACK watchdog for the Windows tray app."""
-
-import logging
-import math
-import socket
-import sys
-import threading
-import time
-from enum import Enum
-from typing import Callable, Optional, Tuple
-
-import return_edge as crossing
-import protocol
-
-
-LOGGER = logging.getLogger(__name__)
-# `config` throughout is whichever settings object the app on this side keeps.
-# Only `port` and `auth_token` are ever read from it, and the two apps' classes
-# are unrelated types, so it is not annotated or imported here -- importing one
-# app's config module would stop this file being the other app's as well.
-# The longest an idle link goes without an ACK, so the Mac's watchdog keeps
-# seeing a heartbeat when nothing is being typed.
-ACK_IDLE_SECONDS = 0.4
-# How long an ACK waits after input arrives, batching a burst into one reply.
-# A per-event ACK at ~100Hz mouse rates would roughly double the packet count;
-# 15ms caps it near 66/s while keeping the round trip the Mac reports honest,
-# which a 400ms timer did not -- every reading carried up to 400ms of waiting
-# that was never network latency.
-ACK_COALESCE_SECONDS = 0.015
-HELLO_TIMEOUT_SECONDS = 5.0
-SESSION_READ_TIMEOUT_SECONDS = 2.5
-LOCK_CHECK_SECONDS = 0.5
-INJECTION_ERROR_STATUS_INTERVAL_SECONDS = 5.0
-# Windows hands the port back only when whatever holds it lets go — WinNAT's
-# dynamic reservations move on every reboot and can land on ours — so a bind
-# that fails is waited out rather than ending the listener.
-BIND_RETRY_SECONDS = 5.0
-# Connections still inside the handshake. Each is bounded to HELLO_TIMEOUT_SECONDS as a whole,
-# so a stranger holding these slots loses them within seconds, while the real peer's handshake
-# takes milliseconds and always finds one free.
-MAX_PENDING_CONNECTIONS = 4
-
-
-class ServerState(Enum):
- STOPPED = "Stopped"
- WAITING = "Waiting"
- CONNECTED = "Connected"
- ERROR = "Error"
-
-
-class ProcessedSequence:
- def __init__(self) -> None:
- self._lock = threading.Lock()
- self._latest = 0
- self._fallback = 0
-
- def record(self, message: dict) -> int:
- data = message.get("data", {})
- raw_sequence = message.get("seq")
- if raw_sequence is None and isinstance(data, dict):
- raw_sequence = data.get("seq")
- with self._lock:
- if isinstance(raw_sequence, int) and not isinstance(raw_sequence, bool) and raw_sequence >= 0:
- self._latest = max(self._latest, raw_sequence)
- self._fallback = max(self._fallback, self._latest)
- else:
- self._fallback = max(self._fallback, self._latest) + 1
- self._latest = self._fallback
- return self._latest
-
- def latest(self) -> int:
- with self._lock:
- return self._latest
-
-
-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
- ctypes.windll. The Mac copy of this file is handed its own injector at
- construction and never reaches that import. Tests can pass a fake
- injector directly."""
- if injector is None:
- import input_injector as injector
- if not isinstance(message, dict):
- raise protocol.ProtocolError("message body must be a JSON object")
- message_type = message.get("type")
- data = message.get("data", {})
- if not isinstance(data, dict):
- raise protocol.ProtocolError("message data must be a JSON object")
- if message_type == protocol.MSG_KEYDOWN:
- injector.inject_key(data["key"], down=True, us=data.get("us"))
- elif message_type == protocol.MSG_KEYUP:
- injector.inject_key(data["key"], down=False, us=data.get("us"))
- elif message_type == protocol.MSG_MOUSEMOVE:
- dx, dy = int(data["dx"]), int(data["dy"])
- if scale is not None and (dx or dy):
- dx, dy = scale.move(dx, dy)
- if not (dx or dy):
- return True
- injector.inject_mouse_move(dx, dy)
- elif message_type == protocol.MSG_MOUSEDOWN:
- injector.inject_mouse_button(data["button"], down=True)
- elif message_type == protocol.MSG_MOUSEUP:
- injector.inject_mouse_button(data["button"], down=False)
- elif message_type == protocol.MSG_SCROLL:
- dy, dx = data["dy"], data.get("dx", 0)
- if scale is not None:
- dy, dx = scale.wheel(dy, dx)
- injector.inject_scroll(dy, dx, data.get("mode", "line"))
- elif message_type == protocol.MSG_GESTURE:
- injector.inject_gesture(data["name"])
- else:
- LOGGER.warning("Unknown message type ignored: %r", message_type)
- return False
- return True
-
-
-class ReceiverServer:
- def __init__(
- self,
- status_callback: Callable[[ServerState, str], None],
- clipboard=None,
- unlock=None,
- desktop=None,
- pressure_callback: Optional[Callable[[str, float, bool, Optional[str]], None]] = None,
- injector=None,
- focus_callback: Optional[Callable[[str], None]] = None,
- peer_callback: Optional[Callable[[str, Optional[str], Optional[int]], None]] = None,
- arrangement_callback: Optional[Callable[[str, int], None]] = None,
- arrival_callback: Optional[Callable[[str, int, int], None]] = None,
- self_name: str = "PC",
- peer_name: str = "Mac",
- self_target: str = "windows",
- peer_target: str = "mac",
- ) -> None:
- # One module serves both machines: this file is byte-identical in
- # win_app and mac_app, which test_receiver_parity enforces. Everything
- # platform-shaped is handed in -- the injector, clipboard, desktop
- # geometry and unlock modules, the two names that appear in status
- # text, and the two wire target words -- so nothing below knows which
- # side it is running on. `focus_callback(target)` fires on every focus
- # message, which is how the app that owns this receiver knows input
- # has arrived or gone home -- and once more with the peer's own target
- # when the link that brought input here ends before the peer has
- # taken it back, because the peer fails open on its side and the
- # message saying so never reaches a dead socket.
- self._injector = injector
- # This machine's speed for the peer's pointer and scroll; the owner replaces it when its
- # settings change. Read once per message on the session thread.
- self.input_scale: Optional[InputScale] = None
- # Whether this machine's edges are held (Pause crossing, a full-screen app). A hold is
- # about this screen, so it stops the peer's pointer going home through it as well as this
- # machine's own; the peer's shortcut still switches. Read on the session thread.
- self.edges_held: Callable[[], bool] = lambda: False
- # `return_model(edge, resistance)` builds the way home the peer named from this machine's
- # own ways in: the whole edge, only its chosen thirds, its corner, or None for no way home
- # by the pointer. The edges on a screen follow that machine's settings, whoever's pointer
- # pushes; without an owner's answer the whole edge is armed.
- self.return_model: Optional[Callable[[str, int], Optional[crossing.ReturnEdge]]] = None
- self._focus_callback = focus_callback
- self._peer_driving = False
- # `peer_callback(host, return_edge, resistance_px)` fires once per
- # authenticated connection, with the peer's address and the way home
- # its hello carried. It is how the machine on this side learns which
- # border to push out across without anyone configuring it twice --
- # the way home from there is the way out from here.
- self._peer_callback = peer_callback
- # `arrangement_callback(mac_edge, set_at)` fires when the peer says
- # where the two machines are in relation to each other. Either end may
- # change it, so this is how the change arrives at the end that did not
- # make it.
- self._arrangement_callback = arrangement_callback
- # `arrival_callback(edge, x, y)` fires on the session thread each time
- # a crossing lands the pointer here, with the edge it came in by and
- # where it was placed, in the desktop module's coordinates, and with
- # edge None and wherever the pointer is when input comes here by a
- # switch instead. It is how the owner plays its arrival effect; the
- # owner marshals it.
- self._arrival_callback = arrival_callback
- self._self_name = self_name
- self._peer_name = peer_name
- self._self_target = self_target
- self._peer_target = peer_target
- self._status_callback = status_callback
- # `desktop` defaults to the real desktop_win module, imported lazily for
- # the same reason as `clipboard` below. `pressure_callback(edge,
- # pressure, crossed, part)` is called on the session thread as the
- # pointer is pushed against the return edge, `part` the third or corner
- # pushed when the way home is only those; the GUI marshals it to the glow.
- self._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
- # Set while a lock-screen unlock is in flight. Input that arrives in
- # that window is dropped rather than queued: an unlock takes several
- # seconds, and replaying seconds of stale mouse moves and keystrokes
- # onto the desktop the moment it appears is worse than losing them.
- self._unlocking = threading.Event()
- # When the console was last tested for the lock screen and first seen on it while the peer
- # drives this PC, and whether its input has been sent home for that lock. See
- # _home_if_locked.
- self._lock_checked_at = float("-inf")
- self._locked_since = None
- self._sent_home_for_lock = False
- # Set from the moment a focus brings the peer's input here until the unlock it may need
- # has been asked for, so the lock check cannot act in between. See _handle_focus.
- self._arriving = threading.Event()
- # `clipboard` defaults to the real clipboard_win module, imported
- # lazily (not at module load) so receiver.py stays importable -- and
- # its non-clipboard logic testable -- on a machine without
- # ctypes.windll, e.g. this Mac. Tests can pass a fake directly, the
- # same way handle_message's `injector` argument works.
- self._clipboard = clipboard
- self._lock = threading.RLock()
- self._thread: Optional[threading.Thread] = None
- self._stop_event: Optional[threading.Event] = None
- self._listener: Optional[socket.socket] = None
- self._client: Optional[socket.socket] = None
- # The live session per connection, so a message can be sent to the
- # client from outside its own thread -- which is what an arrangement
- # changed in the window needs.
- self._sessions: dict = {}
- self._connections: set = set()
- self._pending = 0
- self._session_generation = 0
- self._requested_running = False
-
- @property
- def listening(self) -> bool:
- with self._lock:
- return self._requested_running and self._thread is not None and self._thread.is_alive()
-
- @property
- def return_edge(self) -> Optional[str]:
- """The Windows edge the Mac last named as the way home, or None."""
- model = self._return_edge
- return model.edge if model is not None else None
-
- @property
- def return_resistance(self) -> Optional[int]:
- """How many pixels of push the Mac last asked for at the return edge, or None."""
- model = self._return_edge
- return model.resistance_px if model is not None else None
-
- def start(self, config) -> None:
- with self._lock:
- if self._thread is not None and self._thread.is_alive():
- return
- stop_event = threading.Event()
- thread = threading.Thread(
- target=self._server_thread,
- args=(config, stop_event),
- name="Beamer-server",
- daemon=True,
- )
- self._stop_event = stop_event
- self._thread = thread
- self._requested_running = True
- self._set_status(ServerState.WAITING, f"Starting on port {config.port}")
- try:
- thread.start()
- except Exception:
- with self._lock:
- if self._thread is thread:
- self._thread = None
- self._stop_event = None
- self._requested_running = False
- raise
-
- def stop(self) -> None:
- with self._lock:
- self._requested_running = False
- stop_event = self._stop_event
- listener = self._listener
- connections = set(self._connections)
- thread = self._thread
- if stop_event is not None:
- stop_event.set()
- for connection in connections:
- self._close_socket(connection)
- self._close_socket(listener)
- # start() publishes the thread under the lock and starts it outside, so a
- # stop() landing in that window would join a thread that never started,
- # which raises rather than returning.
- if thread is not None and thread is not threading.current_thread() and thread.ident is not None:
- thread.join(timeout=2.0)
- if thread is not None and thread.is_alive():
- LOGGER.error("Server thread did not stop within two seconds")
- self._set_status(ServerState.ERROR, "Listener did not stop; see log")
- return
- with self._lock:
- if self._thread is thread:
- self._thread = None
- self._stop_event = None
- self._listener = None
- self._client = None
- self._hand_back("Listening stopped")
- self._set_status(ServerState.STOPPED, "Listening stopped")
-
- def _server_thread(self, config, stop_event: threading.Event) -> None:
- failed = False
- try:
- self._serve(config, stop_event)
- except Exception as exc:
- if not stop_event.is_set():
- failed = True
- LOGGER.exception("Server thread failed")
- self._set_status(ServerState.ERROR, f"Listener failed: {exc}")
- finally:
- with self._lock:
- listener = self._listener
- connections = set(self._connections)
- self._listener = None
- self._client = None
- if self._thread is threading.current_thread():
- self._thread = None
- self._stop_event = None
- if failed:
- self._requested_running = False
- for connection in connections:
- self._close_socket(connection)
- self._close_socket(listener)
- if stop_event.is_set():
- self._set_status(ServerState.STOPPED, "Listening stopped")
-
- def _bind(self, config, stop_event: threading.Event):
- """Bind the listening socket, waiting for the port if something holds it."""
- reported = ""
- while not stop_event.is_set():
- listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- # On the Mac this is what lets the port be taken back straight
- # after a restart, while the last session's connections sit in
- # TIME_WAIT. On Windows the same option means something else: a
- # second bind on a port another listener holds succeeds, and the
- # two split the Mac's connections between them, so the held-port
- # wait below never fired for a zombie Beamer. Windows does not
- # need it for TIME_WAIT, so it does without.
- if sys.platform != "win32":
- listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- try:
- listener.bind(("0.0.0.0", config.port))
- except OSError as exc:
- self._close_socket(listener)
- # Said the way a user can act on it: the log carries the error, the
- # status carries the one thing they can change.
- detail = f"Another program is using port {config.port} — change the port on the Connection page"
- # Only on a change: a retry every few seconds otherwise repeats
- # the same line and the same status for as long as the port is held.
- if detail != reported:
- LOGGER.error("Cannot listen on port %s: %s", config.port, exc)
- reported = detail
- self._set_status(ServerState.ERROR, detail)
- stop_event.wait(BIND_RETRY_SECONDS)
- continue
- return listener
- return None
-
- def _serve(self, config, stop_event: threading.Event) -> None:
- listener = self._bind(config, stop_event)
- if listener is None:
- return
- # A stale, not-yet-torn-down session must never block a reconnect: a
- # backlog of 2 lets a fresh Mac connection queue up while the previous
- # session's thread is still winding down, instead of the OS refusing
- # it outright.
- listener.listen(2)
- listener.settimeout(0.5)
- with self._lock:
- self._listener = listener
- LOGGER.info("Listening on 0.0.0.0:%s", config.port)
- self._set_status(ServerState.WAITING, f"Waiting on port {config.port}")
- while not stop_event.is_set():
- try:
- connection, address = listener.accept()
- except socket.timeout:
- continue
- except OSError:
- if stop_event.is_set():
- break
- raise
- # Hand the connection to its own thread immediately and go back
- # to accept(): a slow or stuck peer must never stall the listener,
- # which is what used to make a stale session block a reconnect.
- # Bounded, because accept() happens before any proof of the token.
- # Only handshakes count: an authenticated peer never blocks the
- # next one, and a stranger's slot frees itself within seconds.
- with self._lock:
- crowded = self._pending >= MAX_PENDING_CONNECTIONS
- if not crowded:
- self._pending += 1
- if crowded:
- LOGGER.warning("Refusing %s:%s: %d handshakes already in progress", address[0], address[1], MAX_PENDING_CONNECTIONS)
- self._close_socket(connection)
- continue
- thread = threading.Thread(
- target=self._session_thread,
- args=(connection, address, config, stop_event),
- name="Beamer-session",
- daemon=True,
- )
- thread.start()
-
- def _session_thread(
- self,
- connection: socket.socket,
- address,
- config,
- server_stop: threading.Event,
- ) -> None:
- with self._lock:
- self._connections.add(connection)
- try:
- self._handle_client(connection, address, config, server_stop)
- finally:
- with self._lock:
- self._connections.discard(connection)
- self._close_socket(connection)
-
- def _handle_client(
- self,
- connection: socket.socket,
- address,
- config,
- server_stop: threading.Event,
- ) -> None:
- peer = f"{address[0]}:{address[1]}"
- LOGGER.info("Connection from %s", peer)
- try:
- handshake = self._handshake(connection, peer, config, server_stop)
- finally:
- with self._lock:
- self._pending -= 1
- if handshake is None:
- return
- session, version, hello = handshake
- self._clipboard_module().forget_sync()
-
- if version != protocol.PROTOCOL_VERSION:
- LOGGER.warning(
- "Rejecting %s: unsupported protocol version %r (expected %s)",
- peer,
- version,
- protocol.PROTOCOL_VERSION,
- )
- self._send_message(connection, session, protocol.welcome_msg(error="version_mismatch"))
- self._note_version_mismatch(f"{self._peer_name} app is an older Beamer version — update both apps")
- return
-
- # The Mac now pings at least once a second while idle, so a read
- # timeout here means the peer is gone, not merely quiet.
- connection.settimeout(SESSION_READ_TIMEOUT_SECONDS)
- connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
- sequence = ProcessedSequence()
- if not self._send_message(connection, session, protocol.welcome_msg()):
- return
-
- with self._lock:
- previous_client = self._client
- self._client = connection
- self._sessions[connection] = session
- self._session_generation += 1
- my_generation = self._session_generation
- if previous_client is not None and previous_client is not connection:
- # Preempt: a reconnecting Mac instantly replaces a stale session
- # instead of queueing behind it. Closing it here unblocks that
- # thread's blocked recv so it can exit.
- LOGGER.info("Superseding the previous session for %s", peer)
- self._close_socket(previous_client)
-
- LOGGER.info("Authenticated %s (protocol v%s)", peer, version)
- # A peer that has just connected has its input at home, whatever the
- # session it replaced was in the middle of.
- self._hand_back(f"{self._peer_name} reconnected")
- self._notify_peer(address[0], hello)
- self._set_status(ServerState.CONNECTED, f"Connected to {address[0]}")
-
- client_stop = threading.Event()
- ack_due = threading.Event()
- ack_thread = threading.Thread(
- target=self._ack_thread,
- args=(connection, session, sequence, client_stop, server_stop, ack_due),
- name="Beamer-ack",
- daemon=True,
- )
- ack_thread.start()
-
- last_injection_status_at = 0.0
- try:
- while not server_stop.is_set() and not client_stop.is_set():
- try:
- message = protocol.recv_msg(connection, session)
- except socket.timeout:
- if self._is_current_session(my_generation):
- LOGGER.warning("%s went quiet; treating the connection as dead", peer)
- break
- except protocol.ConnectionClosed:
- if self._is_current_session(my_generation):
- LOGGER.info("%s disconnected", peer)
- break
- except protocol.ProtocolError as exc:
- if self._is_current_session(my_generation):
- LOGGER.warning("Protocol error from %s: %s", peer, exc)
- break
- except OSError as exc:
- if (
- not server_stop.is_set()
- and not client_stop.is_set()
- and self._is_current_session(my_generation)
- ):
- LOGGER.warning("Receive failed for %s: %s", peer, exc)
- break
- message_type = message.get("type") if isinstance(message, dict) else None
- if message_type == protocol.MSG_PING:
- # Liveness only; never recorded or acked as an input event.
- continue
- if message_type == protocol.MSG_FOCUS:
- # Never recorded or acked as an input event, like ping.
- self._handle_focus(message, connection, session, peer, address[0])
- continue
- if message_type == protocol.MSG_CLIPBOARD:
- # Never recorded or acked as an input event, like ping.
- self._handle_inbound_clipboard(message, peer)
- continue
- if message_type == protocol.MSG_ARRANGEMENT:
- # Never recorded or acked as an input event, like ping.
- self._handle_arrangement(message)
- continue
- if self._unlocking.is_set():
- # Dropped, not queued: see _begin_unlock. Still recorded so
- # the ACK sequence stays continuous and the Mac's watchdog
- # does not read the unlock as a dead link.
- sequence.record(message)
- continue
- if message_type == protocol.MSG_MOUSEMOVE and self._return_trip(message, connection, session):
- # Held at the edge or crossed: not injected, but still an
- # input event for the ACK sequence.
- sequence.record(message)
- continue
- try:
- processed = handle_message(message, self._injector, self.input_scale)
- except Exception:
- LOGGER.exception("Input event from %s could not be injected", peer)
- now = time.monotonic()
- if now - last_injection_status_at >= INJECTION_ERROR_STATUS_INTERVAL_SECONDS:
- last_injection_status_at = now
- self._set_status(ServerState.CONNECTED, f"Input error from {address[0]}; see log")
- continue
- if not processed:
- continue
- sequence.record(message)
- ack_due.set()
- finally:
- client_stop.set()
- ack_thread.join(timeout=1.0)
- if ack_thread.is_alive():
- LOGGER.error("ACK thread did not stop within one second")
- self._set_status(ServerState.ERROR, "ACK worker did not stop; see log")
- with self._lock:
- self._sessions.pop(connection, None)
- is_current = self._session_generation == my_generation
- if is_current:
- self._client = None
- if is_current:
- self._hand_back(f"{self._peer_name} went away")
- # A preempted (superseded) session must exit silently: only the
- # current-generation session may flip status to WAITING.
- if is_current and not server_stop.is_set():
- self._set_status(ServerState.WAITING, f"Waiting on port {config.port}")
-
- def _is_current_session(self, generation: int) -> bool:
- with self._lock:
- return self._session_generation == generation
-
- def _handshake(self, connection: socket.socket, peer: str, config, server_stop: threading.Event):
- """Read the Mac's preamble, answer with ours, then open its hello.
- Returns (session, declared version) or None once the failure has been
- logged. The preamble is read before ours is sent so an older Mac, which
- opens with a cleartext frame instead, gets a cleartext version_mismatch
- it can display rather than bytes it reads as a bogus length."""
- connection.settimeout(HELLO_TIMEOUT_SECONDS)
- # One deadline for the whole handshake, not a timeout per read: a peer
- # trickling a byte at a time would otherwise hold its slot for ever.
- deadline = time.monotonic() + HELLO_TIMEOUT_SECONDS
- session = protocol.SecureSession(config.auth_token)
- try:
- try:
- protocol.recv_preamble(connection, session, deadline=deadline)
- except protocol.VersionMismatch as exc:
- if exc.peer_version is None:
- LOGGER.warning("%s opened with the pre-v4 cleartext protocol", peer)
- connection.sendall(protocol.legacy_frame(protocol.welcome_msg(error="version_mismatch")))
- self._note_version_mismatch(f"{self._peer_name} app is an older Beamer version — update both apps")
- else:
- LOGGER.warning("%s speaks wire version %r, expected %s", peer, exc.peer_version, protocol.PROTOCOL_VERSION)
- connection.sendall(session.preamble())
- self._note_version_mismatch(
- f"{self._peer_name} app is Beamer protocol v{exc.peer_version}, this {self._self_name} is v{protocol.PROTOCOL_VERSION} — update both apps"
- )
- return None
- connection.sendall(session.preamble())
- first = protocol.recv_msg(connection, session, limit=protocol.HELLO_MAX_BYTES, deadline=deadline)
- except socket.timeout:
- LOGGER.warning("Authentication timed out for %s", peer)
- return None
- except protocol.ConnectionClosed:
- LOGGER.info("%s disconnected before authentication", peer)
- return None
- except protocol.AuthenticationError:
- # The one signal that the Mac does not hold the shared token. Nothing is sent back:
- # a reply would tell a guesser it had reached a Beamer.
- LOGGER.warning("Authentication failed for %s: frame failed authentication", peer)
- return None
- except protocol.ProtocolError as exc:
- LOGGER.warning("Protocol error during authentication from %s: %s", peer, exc)
- return None
- except OSError as exc:
- if not server_stop.is_set():
- LOGGER.warning("Authentication receive failed for %s: %s", peer, exc)
- return None
- if first.get("type") != protocol.MSG_HELLO:
- LOGGER.warning("%s authenticated but did not say hello first", peer)
- return None
- data = first.get("data")
- return session, self._hello_version(first), data if isinstance(data, dict) else {}
-
- def _note_version_mismatch(self, detail: str) -> None:
- with self._lock:
- has_active_client = self._client is not None
- if not has_active_client:
- self._set_status(ServerState.ERROR, detail)
-
- def _ack_thread(
- self,
- connection: socket.socket,
- session: protocol.SecureSession,
- sequence: ProcessedSequence,
- client_stop: threading.Event,
- server_stop: threading.Event,
- ack_due: threading.Event,
- ) -> None:
- try:
- while not server_stop.is_set():
- woken = ack_due.wait(ACK_IDLE_SECONDS)
- if client_stop.is_set():
- return
- if woken:
- ack_due.clear()
- # Coalesce on client_stop, not sleep, so a disconnect during
- # the batching window still exits promptly.
- if client_stop.wait(ACK_COALESCE_SECONDS):
- return
- ack = protocol.ack_msg(sequence.latest(), locked=self._unlocking.is_set())
- if not self._send_message(connection, session, ack):
- client_stop.set()
- self._close_socket(connection)
- return
- self._home_if_locked()
- except Exception as exc:
- LOGGER.exception("ACK thread failed")
- self._set_status(ServerState.ERROR, f"ACK worker failed: {exc}")
- client_stop.set()
- self._close_socket(connection)
-
- def _home_if_locked(self) -> None:
- """Send the peer's input home when this PC is on its lock screen. Beamer can neither inject
- into the secure desktop nor watch the return edge there, so a Mac left driving a locked PC
- had no way back until someone unlocked it by hand (issue #5).
-
- Timed, not per tick: the ACK thread wakes on every injected event, and is_locked walks the
- process list. Locked on two checks LOCK_CHECK_SECONDS apart, and never while an unlock is
- in flight: a switch to a locked PC reaches _begin_unlock a moment after focus, and an
- unlock provider that can clear the lock screen must be given the chance."""
- if not self._peer_driving or self._unlocking.is_set() or self._arriving.is_set():
- self._locked_since = None
- return
- now = time.monotonic()
- if now - self._lock_checked_at < LOCK_CHECK_SECONDS:
- return
- self._lock_checked_at = now
- try:
- locked = self._unlock_module().is_locked() is True
- except Exception:
- locked = False
- if not locked:
- self._locked_since = None
- return
- if self._locked_since is None:
- self._locked_since = now
- return
- if self._sent_home_for_lock:
- return
- LOGGER.info("Windows is locked while the %s drives it; sending its input home", self._peer_name)
- self._sent_home_for_lock = self.send_home()
-
- def _clipboard_module(self):
- if self._clipboard is not None:
- return self._clipboard
- import clipboard_win
- return clipboard_win
-
- def _unlock_module(self):
- if self._unlock is not None:
- return self._unlock
- import unlock_win
- return unlock_win
-
- def _desktop_module(self):
- if self._desktop is not None:
- return self._desktop
- import desktop_win
- return desktop_win
-
- def _return_trip(self, message: dict, connection: socket.socket, session: protocol.SecureSession) -> bool:
- """The return path. Feeds every mouse move to the pressure model while
- a return edge is armed; True means the move was consumed — the pointer
- was held at the edge, or it broke through and the Mac has been asked
- to take input back — and must not be injected."""
- data = message.get("data")
- if not isinstance(data, dict):
- return False
- try:
- 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:
- LOGGER.info("Pointer pushed through the %s edge; returning input to the %s", model.edge, self._peer_name)
- self._send_message(connection, session, protocol.switch_msg(self._peer_target, outcome.edge, outcome.offset))
- except Exception:
- # Logged once, not at 100Hz: the return edge is dropped until the
- # Mac's next switch re-arms it, and input keeps flowing normally.
- LOGGER.exception("Return edge failed; crossing back is off until the next switch")
- self._drop_return()
- return False
- if outcome.action == crossing.PASS:
- return False
- self._notify_pressure(model.edge, outcome.pressure, outcome.action == crossing.CROSS, part)
- return True
-
- def send_arrangement(self, mac_edge: str, set_at: int) -> bool:
- """Tell the peer where the machines are, over the connection it opened
- to this one. Used when the change was made at this end: the outward
- link may be down, or may not exist on this machine at all, and this
- one is up by definition whenever there is anyone to tell."""
- with self._lock:
- connection = self._client
- session = self._session_for(connection)
- if connection is None or session is None:
- return False
- return self._send_message(connection, session, protocol.arrangement_msg(mac_edge, set_at))
-
- def send_home(self) -> bool:
- """Send the peer's input back to it from this end, as its own return
- edge would. The escape that does not depend on that edge: the owner
- calls it when someone here asks to switch while the peer is driving.
- Earlier versions refused this outright, and a push through the edge
- that failed to fire could then leave the peer's pointer stuck here
- with no way back. The send runs on its own thread, because the
- callers are a hook and an event tap that must never block on a
- socket."""
- with self._lock:
- connection = self._client
- session = self._session_for(connection)
- if not self._peer_driving or connection is None or session is None:
- return False
- self._drop_return()
- LOGGER.info("Switch asked for here; sending input home to the %s", self._peer_name)
- threading.Thread(
- target=self._send_message,
- args=(connection, session, protocol.switch_msg(self._peer_target)),
- name="Beamer-send-home",
- daemon=True,
- ).start()
- return True
-
- def _session_for(self, connection):
- return self._sessions.get(connection) if connection is not None else None
-
- def _handle_arrangement(self, message: dict) -> None:
- read = protocol.read_arrangement(message.get("data"))
- if read is None or self._arrangement_callback is None:
- return
- try:
- self._arrangement_callback(*read)
- except Exception:
- LOGGER.exception("Arrangement callback failed")
-
- def _notify_peer(self, host: str, hello: dict) -> None:
- if self._peer_callback is None:
- return
- edge = hello.get("return_edge")
- if edge not in crossing.EDGES:
- edge = None
- resistance = hello.get("resistance_px")
- if isinstance(resistance, bool) or not isinstance(resistance, (int, float)):
- resistance = None
- try:
- self._peer_callback(host, edge, None if resistance is None else int(resistance))
- except Exception:
- LOGGER.exception("Peer callback failed")
-
- def _notify_focus(self, target) -> None:
- if self._focus_callback is None or not isinstance(target, str):
- return
- if target == self._self_target:
- self._peer_driving = True
- self._sent_home_for_lock = False
- # A lock seen on the last visit says nothing about this one.
- self._locked_since = None
- elif target == self._peer_target:
- self._peer_driving = False
- try:
- self._focus_callback(target)
- except Exception:
- LOGGER.exception("Focus callback failed")
-
- def _hand_back(self, why: str) -> None:
- """The peer's input was on this machine and the link that carried it
- is over. The peer has already failed open on its own side; the focus
- that would have said so died with the socket, so it is raised here.
- Otherwise the owner of this receiver keeps treating the peer as
- driving, and its own edge and shortcut stay dead until the peer next
- crosses in and back."""
- if not self._peer_driving:
- return
- self._drop_return()
- LOGGER.info("%s while its input was here; input returned to this %s", why, self._self_name)
- self._release_peer_keys()
- self._notify_focus(self._peer_target)
-
- def _release_peer_keys(self) -> None:
- """Let go of whatever the peer was holding here. A modifier or button
- injected for the peer and never released -- a chord in flight when
- input went home or the link died -- would otherwise stay down on this
- machine, turning every later local keystroke into a shortcut."""
- injector = self._injector
- if injector is None:
- try:
- import input_injector as injector
- except Exception:
- LOGGER.exception("Injector unavailable; keys the peer held may still be down")
- return
- release = getattr(injector, "release_all", None)
- if release is None:
- return
- try:
- release()
- except Exception:
- LOGGER.exception("Could not release the keys the %s was holding", self._peer_name)
-
- def _notify_pressure(self, edge: str, pressure: float, crossed: bool, part: Optional[str] = None) -> None:
- if self._pressure_callback is None:
- return
- try:
- 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._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()
- 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
- about to arrive has somewhere to land. Beamer cannot type on the secure
- desktop at all -- see unlock_win -- so without this, switching to a
- locked PC silently injects into nothing.
-
- The lock test is a cheap in-process snapshot, so the common case (an
- unlocked PC) stays inline and costs nothing. Only a real unlock goes to
- a thread, because it takes seconds and this runs on the message loop
- that has to keep draining pings."""
- try:
- unlock = self._unlock_module()
- except Exception:
- LOGGER.exception("Unlock support unavailable")
- return
- if unlock.is_locked() is not True:
- return
- if self._unlocking.is_set():
- return
- self._unlocking.set()
- LOGGER.info("%s switched to a locked PC; asking the provider to unlock", peer)
- self._set_status(ServerState.CONNECTED, "Unlocking Windows…")
- with self._lock:
- generation = self._session_generation
- threading.Thread(
- target=self._unlock_worker,
- args=(unlock, peer, host, generation),
- name="Beamer-unlock",
- daemon=True,
- ).start()
-
- def _unlock_worker(self, unlock, peer: str, host: str, generation: int) -> None:
- try:
- unlocked = unlock.ensure_unlocked()
- except Exception:
- LOGGER.exception("Unlock failed for %s", peer)
- unlocked = False
- finally:
- self._unlocking.clear()
- # An unlock takes seconds, so the Mac may have gone in the meantime and
- # the session's own exit already have set WAITING. Only the session
- # that asked for this unlock may report its outcome.
- if not self._is_current_session(generation):
- return
- if unlocked:
- self._set_status(ServerState.CONNECTED, f"Connected to {host}")
- else:
- self._set_status(
- ServerState.CONNECTED, "Windows is locked — unlock it at the PC"
- )
-
- def _handle_focus(
- self,
- message: dict,
- connection: socket.socket,
- session: protocol.SecureSession,
- peer: str,
- host: str,
- ) -> None:
- """`focus{target:"mac"}` means the Mac just switched input back to
- itself: reply with this Windows clipboard's text so the Mac's
- pasteboard picks up whatever was last copied here.
- `target:"windows"` means input is coming here: learn the way home
- from it, land the pointer where a crossing says, and clear the lock
- screen out of its way."""
- data = message.get("data")
- target = data.get("target") if isinstance(data, dict) else None
- if target == self._peer_target:
- # Released before the owner hears input is home: the Mac's tap
- # comes back on at that notice, and a modifier still down would
- # chord with the first local keystroke.
- self._drop_return()
- self._release_peer_keys()
- if target == self._self_target:
- # Raised before anyone hears the peer is driving, and held until the unlock has been
- # asked for. Placing the pointer or an owner's callback can take a second, and in
- # that second the lock check saw a locked PC with the peer driving and sent its
- # input home before the provider that could have unlocked it was tried.
- self._arriving.set()
- try:
- self._notify_focus(target)
- self._arm_return(data)
- self._place_pointer(data)
- self._begin_unlock(peer, host)
- finally:
- self._arriving.clear()
- return
- self._notify_focus(target)
- if target != self._peer_target:
- return
- clipboard = self._clipboard_module()
- try:
- text, image = clipboard.changed_contents()
- except Exception:
- LOGGER.exception("Failed to read the local clipboard for %s", peer)
- return
- if text and len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:
- LOGGER.warning("Local clipboard text too large; skipping the text for %s", peer)
- text = None
- if image is not None and len(image) > protocol.CLIPBOARD_IMAGE_MAX_BYTES:
- LOGGER.warning(
- "Local clipboard image is %d bytes, over the %d cap; skipping the image for %s",
- len(image),
- protocol.CLIPBOARD_IMAGE_MAX_BYTES,
- peer,
- )
- image = None
- if not text and image is None:
- return
- self._send_message(connection, session, protocol.clipboard_msg(text or None, image))
-
- def _handle_inbound_clipboard(self, message: dict, peer: str) -> None:
- data = message.get("data")
- text = data.get("text") if isinstance(data, dict) else None
- if not isinstance(text, str) or not text:
- text = None
- elif len(text.encode("utf-8")) > protocol.CLIPBOARD_MAX_BYTES:
- LOGGER.warning("Ignoring oversized inbound clipboard text from %s", peer)
- text = None
- image = protocol.clipboard_image(data)
- if text is None and image is None:
- return
- clipboard = self._clipboard_module()
- try:
- if not clipboard.set_contents(text, image):
- LOGGER.warning("Failed to set the local clipboard for %s", peer)
- except Exception:
- LOGGER.exception("Failed to set the local clipboard for %s", peer)
-
- @staticmethod
- def _hello_version(message: dict):
- data = message.get("data", {})
- if not isinstance(data, dict):
- return None
- return data.get("version")
-
- @staticmethod
- def _send_message(
- connection: socket.socket,
- session: protocol.SecureSession,
- message: dict,
- ) -> bool:
- """The session's own lock serialises the seal and the write together,
- so frames reach the wire in counter order from every thread."""
- try:
- protocol.send_msg(connection, session, message)
- return True
- except (OSError, protocol.ProtocolError) as exc:
- LOGGER.warning("Send failed: %s", exc)
- return False
-
- def _set_status(self, state: ServerState, detail: str) -> None:
- try:
- self._status_callback(state, detail)
- except Exception:
- LOGGER.exception("Status callback failed")
-
- @staticmethod
- def _close_socket(sock: Optional[socket.socket]) -> None:
- if sock is None:
- return
- try:
- sock.shutdown(socket.SHUT_RDWR)
- except OSError:
- pass
- try:
- sock.close()
- except OSError:
- pass
diff --git a/mac_app/requirements-mac.txt b/mac_app/requirements-mac.txt
index b0e3993..684fee9 100644
--- a/mac_app/requirements-mac.txt
+++ b/mac_app/requirements-mac.txt
@@ -3,6 +3,5 @@ pyobjc-framework-Quartz==12.2.2
pyobjc-framework-ApplicationServices==12.2.2
rumps==0.4.0
py2app==0.28.10
-cryptography>=42
PyNaCl>=1.6
dmgbuild==1.6.7
diff --git a/mac_app/settings_store.py b/mac_app/settings_store.py
index 1aa541c..f680faa 100644
--- a/mac_app/settings_store.py
+++ b/mac_app/settings_store.py
@@ -5,10 +5,10 @@ from dataclasses import replace
from pathlib import Path
import config as config_module
-import effects
-import ignored
-import protocol
-import return_edge
+from core import effects
+from core import ignored
+from core import protocol
+from core import return_edge
from crossing import CORNERS, EDGES, GLOW_COLOURS, GLOW_STYLES, HAPTIC_FEELS, HAPTIC_STEPS, METHODS, NOTCH_STYLES
from key_codes import KEY_NAME_TO_CODE
@@ -40,6 +40,8 @@ def editable_default_config():
allow_windows_to_drive=True,
check_updates=True,
hide_addresses=False,
+ same_on_both=False,
+ same_set_at=0,
pointer_speed=1.0,
scroll_speed=1.0,
reverse_scroll=False,
@@ -69,6 +71,8 @@ def config_to_raw(cfg):
"allow_windows_to_drive": cfg.allow_windows_to_drive,
"check_updates": cfg.check_updates,
"hide_addresses": cfg.hide_addresses,
+ "same_on_both": cfg.same_on_both,
+ "same_set_at": cfg.same_set_at,
"pointer_speed": cfg.pointer_speed,
"scroll_speed": cfg.scroll_speed,
"reverse_scroll": cfg.reverse_scroll,
@@ -194,7 +198,7 @@ class SettingsStore:
for name, allowed in choices:
if crossing[name] not in allowed:
raise SettingsError(f"crossing.{name} must be one of: {', '.join(allowed)}")
- for name in ("haptics", "glow", "block_while_dragging", "shortcut_arrival"):
+ for name in ("haptics", "glow", "block_while_dragging", "shortcut_arrival", "hold_full_screen"):
if not isinstance(crossing[name], bool):
raise SettingsError(f"crossing.{name} must be true or false")
for name in ("pointer_speed", "scroll_speed"):
diff --git a/mac_app/setup.py b/mac_app/setup.py
index bf7c82f..587a38e 100644
--- a/mac_app/setup.py
+++ b/mac_app/setup.py
@@ -9,12 +9,15 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
VERSION = (Path(__file__).resolve().parent.parent / "VERSION").read_text().strip()
+# Launch Services accepts only three integers in CFBundleShortVersionString, so a beta such as
+# 1.5.0-beta.1 carries its release number there; the bundled VERSION file says beta to the user.
+PLIST_VERSION = VERSION.split("-")[0]
BUILD = os.environ.get("BEAMER_BUILD", "1")
setup(
name="Beamer",
- version=VERSION,
+ version=PLIST_VERSION,
app=["kvm_bridge_app.py"],
py_modules=[
"bridge",
@@ -22,15 +25,8 @@ setup(
"config",
"crossing",
"desktop_mac",
- "effects",
"effects_overlay",
- "fx_ink",
- "fx_instrument",
- "fx_membrane",
- "fx_sparks",
- "fx_warp",
"gestures",
- "ignored",
"input_injector_mac",
"key_codes",
"keyboard_layout",
@@ -41,15 +37,10 @@ setup(
"pages",
"previews",
"no_unlock",
- "pairing",
- "protocol",
- "receiver",
- "return_edge",
"settings_store",
"theme",
"tokens",
"wake",
- "wol",
"widgets",
"windows_input",
],
@@ -67,22 +58,23 @@ setup(
options={
"py2app": {
"argv_emulation": False,
- # cryptography ships a compiled _rust extension plus cffi; py2app's own recipe pulls
- # both in, but naming the package keeps its data files and submodules in the bundle.
- # PyNaCl (nacl) is the same shape: a compiled _sodium extension reached through cffi.
- "packages": ["rumps", "cryptography", "cffi", "nacl"],
- # 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.
+ # PyNaCl (nacl) ships a compiled _sodium extension reached through cffi; naming both
+ # packages keeps their data files and submodules in the bundle.
+ "packages": ["rumps", "cffi", "nacl"],
+ # core/effects.py imports its fx_* modules by name at first use, which py2app's import
+ # scan cannot see, so they are named here or the bundle ships without a single effect.
+ # The rest of core/ is found by the scan, through the repo root put on sys.path above;
+ # naming the package whole would ship its tests too.
"includes": [
"objc", "AppKit", "ApplicationServices", "Quartz",
- "fx_ink", "fx_instrument", "fx_membrane", "fx_sparks", "fx_warp",
+ "core.fx_ink", "core.fx_instrument", "core.fx_membrane", "core.fx_sparks", "core.fx_warp",
],
"iconfile": "../Beamer.icns",
"plist": {
"CFBundleDisplayName": "Beamer",
"CFBundleIdentifier": "uk.co.kalkman.beamer",
"CFBundleName": "Beamer",
- "CFBundleShortVersionString": VERSION,
+ "CFBundleShortVersionString": PLIST_VERSION,
"CFBundleVersion": BUILD,
"LSMinimumSystemVersion": "13.0",
"LSUIElement": False,
diff --git a/mac_app/tests/test_appearance.py b/mac_app/tests/test_appearance.py
index 1a06b10..31ecc87 100644
--- a/mac_app/tests/test_appearance.py
+++ b/mac_app/tests/test_appearance.py
@@ -6,6 +6,7 @@ import json
import logging
import sys
import tempfile
+import time
import unittest
from pathlib import Path
from unittest import mock
@@ -13,6 +14,7 @@ from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
import AppKit # noqa: E402
+import objc # noqa: E402
import Quartz # noqa: E402
AppKit.NSApplication.sharedApplication()
@@ -117,6 +119,43 @@ class WindowAppearanceTests(unittest.TestCase):
self.window._apply_settings()
self.assertEqual(self.window.settings_store.load().appearance, "light")
+ def test_turning_animations_off_folds_the_modules_while_the_scroll_offset_slides(self):
+ window = self.window
+ window._select_page("design")
+ scroll = window.pages["design"]
+ clip = scroll.contentView()
+ window.glow_box.value = True
+ window._reflect()
+ window.window.contentView().layoutSubtreeIfNeeded()
+ clip.scrollToPoint_((0, scroll.documentView().frame().size.height))
+ scroll.reflectScrolledClipView_(clip)
+ start = clip.bounds().origin.y
+ body = scroll.documentView().subviews()[0]
+ offsets, heights = [], []
+ with mock.patch.object(motion, "live", return_value=True):
+ window.glow_box.value = False
+ window._reflect()
+ deadline = time.monotonic() + 1.0
+ while time.monotonic() < deadline:
+ AppKit.NSRunLoop.currentRunLoop().runUntilDate_(AppKit.NSDate.dateWithTimeIntervalSinceNow_(0.01))
+ offsets.append(clip.bounds().origin.y)
+ heights.append({objc.pyobjc_id(view): view.frame().size.height
+ for view in body.arrangedSubviews() if not view.isHidden()})
+ end = offsets[-1]
+ self.assertTrue(window.style_module.view.isHidden())
+ self.assertTrue(window.colour_module.view.isHidden())
+ self.assertLess(end, start)
+ # Clamped at once, the offset would jump straight from where it was to where it ends.
+ self.assertGreater(len({offset for offset in offsets if end < offset < start}), 3)
+ self.assertEqual(scroll.documentView().floor.constant(), 0.0)
+ # The held space is left empty at the foot of the page, never taken up by a module.
+ for sample in heights:
+ for view, height in sample.items():
+ bound = max(heights[0].get(view, height), heights[-1].get(view, height))
+ self.assertLessEqual(height, bound + 1)
+ window.glow_box.value = True
+ window._reflect()
+
if __name__ == "__main__":
unittest.main()
diff --git a/mac_app/tests/test_arm_return_resistance.py b/mac_app/tests/test_arm_return_resistance.py
index 1affa54..f3b173e 100644
--- a/mac_app/tests/test_arm_return_resistance.py
+++ b/mac_app/tests/test_arm_return_resistance.py
@@ -1,8 +1,12 @@
import json
import unittest
+import os
+import sys
-import return_edge
-from receiver import ReceiverServer
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import return_edge
+from core.receiver import ReceiverServer
class ArmReturnResistanceTest(unittest.TestCase):
diff --git a/mac_app/tests/test_bridge.py b/mac_app/tests/test_bridge.py
index d77cfad..1b18796 100644
--- a/mac_app/tests/test_bridge.py
+++ b/mac_app/tests/test_bridge.py
@@ -8,10 +8,13 @@ import struct
import threading
import types
import unittest
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import config
import media_keys
-import protocol
+from core import protocol
from bridge import (
ACK_TIMEOUT_SECONDS,
AUTH_FAILED_STATUS,
@@ -2091,6 +2094,19 @@ class CrossingWiringTests(unittest.TestCase):
self._push(10)
self.assertTrue(self.controller.redirecting)
+ def test_with_the_hold_off_a_full_screen_app_does_not_hold_the_edges(self):
+ self.controller.cfg.crossing["hold_full_screen"] = False
+ self.controller.full_screen_app = "Steam"
+ self.assertIsNone(self.controller.full_screen_app)
+ self._push(10)
+ self.assertTrue(self.controller.redirecting)
+
+ def test_turning_the_hold_back_on_holds_for_the_app_still_in_front(self):
+ self.controller.cfg.crossing["hold_full_screen"] = False
+ self.controller.full_screen_app = "Steam"
+ self.controller.cfg.crossing["hold_full_screen"] = True
+ self.assertEqual(self.controller.full_screen_app, "Steam")
+
def _double_tap(self):
down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": FakeQuartz.kCGEventFlagMaskAlternate}
up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}
diff --git a/mac_app/tests/test_clipboard_mac.py b/mac_app/tests/test_clipboard_mac.py
index 958ac9f..791e28e 100644
--- a/mac_app/tests/test_clipboard_mac.py
+++ b/mac_app/tests/test_clipboard_mac.py
@@ -5,9 +5,13 @@ general pasteboard, so the suite leaves the machine's clipboard alone."""
import struct
import unittest
import zlib
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import clipboard_mac
-import protocol
+from core import protocol
def tiny_png(width=2, height=2):
diff --git a/mac_app/tests/test_config_key_map_override.py b/mac_app/tests/test_config_key_map_override.py
index bd80ad1..a9fba22 100644
--- a/mac_app/tests/test_config_key_map_override.py
+++ b/mac_app/tests/test_config_key_map_override.py
@@ -2,6 +2,9 @@ import json
import os
import tempfile
import unittest
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import config
diff --git a/mac_app/tests/test_core.py b/mac_app/tests/test_core.py
new file mode 100644
index 0000000..034b8ab
--- /dev/null
+++ b/mac_app/tests/test_core.py
@@ -0,0 +1,18 @@
+"""core/'s own tests, run as part of this app's suite so one command still covers everything this
+app ships, under this app's interpreter and packages."""
+
+import os
+import sys
+import unittest
+
+_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+
+def load_tests(loader, tests, pattern):
+ tests.addTests(loader.discover(os.path.join(_REPO_ROOT, "core", "tests"), pattern="test*.py", top_level_dir=_REPO_ROOT))
+ # discover leaves the root first on sys.path. It goes behind the app's own folder instead: the
+ # root also holds the Mac's theme.py, which must not stand in for win_app's.
+ while _REPO_ROOT in sys.path:
+ sys.path.remove(_REPO_ROOT)
+ sys.path.append(_REPO_ROOT)
+ return tests
diff --git a/mac_app/tests/test_crossing.py b/mac_app/tests/test_crossing.py
index 21aa973..a729344 100644
--- a/mac_app/tests/test_crossing.py
+++ b/mac_app/tests/test_crossing.py
@@ -1,4 +1,8 @@
import unittest
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from crossing import DECAY_S, CrossingEngine
diff --git a/mac_app/tests/test_crossing_matrix.py b/mac_app/tests/test_crossing_matrix.py
index 2d636ce..44136d9 100644
--- a/mac_app/tests/test_crossing_matrix.py
+++ b/mac_app/tests/test_crossing_matrix.py
@@ -6,6 +6,9 @@ import itertools
import os
import types
import unittest
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from crossing import CORNERS, EDGES, OPPOSITE, CrossingEngine
from settings_store import config_to_raw
diff --git a/mac_app/tests/test_effect_fires.py b/mac_app/tests/test_effect_fires.py
index 02750ab..a5cab41 100644
--- a/mac_app/tests/test_effect_fires.py
+++ b/mac_app/tests/test_effect_fires.py
@@ -13,6 +13,10 @@ import logging
import unittest
from types import SimpleNamespace
from unittest import mock
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from PyObjCTools import AppHelper
diff --git a/mac_app/tests/test_effect_layouts.py b/mac_app/tests/test_effect_layouts.py
index db83623..b6c3bd3 100644
--- a/mac_app/tests/test_effect_layouts.py
+++ b/mac_app/tests/test_effect_layouts.py
@@ -6,8 +6,12 @@ Byte-identical in mac_app and win_app."""
import colorsys
import unittest
from types import SimpleNamespace
+import os
+import sys
-import effects
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import effects
PALETTE = ["#ff7828", "#ff3264", "#ffb43c"]
NOTCH = {"x": 771.5, "y": 0.0, "w": 185.0, "h": 32.0, "r": 10.0}
diff --git a/mac_app/tests/test_effects_overlay.py b/mac_app/tests/test_effects_overlay.py
index 75bd8be..52744af 100644
--- a/mac_app/tests/test_effects_overlay.py
+++ b/mac_app/tests/test_effects_overlay.py
@@ -9,9 +9,9 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
import crossing
-import effects
+from core import effects
import effects_overlay
-from return_edge import Rect
+from core.return_edge import Rect
class FakeCG:
@@ -606,7 +606,7 @@ class RealEffectIntegrationTest(unittest.TestCase):
module_name = _MODULE_FOR_EFFECT[effect_id]
with self.subTest(effect=effect_id, module=module_name):
try:
- importlib.import_module(module_name)
+ importlib.import_module(f"core.{module_name}")
except ImportError:
continue
fx = effects.effect(effect_id)
diff --git a/mac_app/tests/test_gestures.py b/mac_app/tests/test_gestures.py
index 7d2be86..e880e2f 100644
--- a/mac_app/tests/test_gestures.py
+++ b/mac_app/tests/test_gestures.py
@@ -1,6 +1,10 @@
import unittest
+import os
+import sys
-import protocol
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import protocol
from gestures import (
DOCK_PHASE_ENDED,
DOCK_SWIPE_HID_TYPE,
diff --git a/mac_app/tests/test_handshake_deadline.py b/mac_app/tests/test_handshake_deadline.py
index 8193a6e..7bda966 100644
--- a/mac_app/tests/test_handshake_deadline.py
+++ b/mac_app/tests/test_handshake_deadline.py
@@ -3,10 +3,14 @@ import struct
import threading
import time
import unittest
+import os
+import sys
-import protocol
-import receiver
-from receiver import ReceiverServer, ServerState
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import protocol
+from core import receiver
+from core.receiver import ReceiverServer, ServerState
class HandshakeDeadlineTests(unittest.TestCase):
diff --git a/mac_app/tests/test_hello_limit.py b/mac_app/tests/test_hello_limit.py
index b330a57..5e6efca 100644
--- a/mac_app/tests/test_hello_limit.py
+++ b/mac_app/tests/test_hello_limit.py
@@ -2,8 +2,12 @@ import socket
import struct
import threading
import unittest
+import os
+import sys
-import protocol
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import protocol
class HelloFrameLimitTests(unittest.TestCase):
diff --git a/mac_app/tests/test_ignored.py b/mac_app/tests/test_ignored.py
deleted file mode 100644
index 244af59..0000000
--- a/mac_app/tests/test_ignored.py
+++ /dev/null
@@ -1,56 +0,0 @@
-"""The ignored-inputs gate both apps share. Byte-identical in mac_app and win_app."""
-
-import unittest
-
-import ignored
-
-
-class GateTests(unittest.TestCase):
- def test_a_listed_press_and_its_release_stay_here(self):
- gate = ignored.Gate([ignored.button("back")])
- self.assertTrue(gate.keeps("button:back", True))
- self.assertTrue(gate.keeps("button:back", False))
-
- def test_anything_else_goes_across(self):
- gate = ignored.Gate([ignored.button("back")])
- self.assertFalse(gate.keeps("key:12", True))
- self.assertFalse(gate.keeps("key:12", False))
-
- def test_a_release_follows_its_press_across_when_the_list_changes_mid_hold(self):
- gate = ignored.Gate()
- self.assertFalse(gate.keeps("key:122", True))
- gate.configure([ignored.key(122)])
- self.assertFalse(gate.keeps("key:122", True), "an autorepeat of a key already across stays across")
- self.assertFalse(gate.keeps("key:122", False), "its release must reach the far side")
- self.assertTrue(gate.keeps("key:122", True), "the next press is kept here")
-
- def test_a_press_kept_here_keeps_its_release_here_when_taken_off_the_list(self):
- gate = ignored.Gate([ignored.key(122)])
- self.assertTrue(gate.keeps("key:122", True))
- gate.configure([])
- self.assertTrue(gate.keeps("key:122", False), "the release must reach this machine, which has the press")
- self.assertFalse(gate.keeps("key:122", True), "the next press goes across")
-
- def test_a_release_outside_the_list_with_no_press_seen_goes_across(self):
- gate = ignored.Gate()
- self.assertFalse(gate.keeps("key:5", False))
-
- def test_reset_forgets_what_went_across(self):
- gate = ignored.Gate()
- gate.keeps("key:5", True)
- gate.configure(["key:5"])
- gate.reset()
- self.assertTrue(gate.keeps("key:5", False))
-
- def test_validate_takes_every_kind_of_entry(self):
- entries = [ignored.key(0), ignored.key(0xA3), ignored.button("forward"), ignored.button("6"), ignored.media("volume_up")]
- self.assertEqual(ignored.validate(entries), entries)
-
- def test_validate_refuses_what_it_cannot_read(self):
- for bad in ("f13", ["key:"], ["key:abc"], ["mouse:back"], [12], ["key:1"] * (ignored.MAX_ENTRIES + 1)):
- with self.subTest(bad=bad), self.assertRaises(ValueError):
- ignored.validate(bad)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/mac_app/tests/test_ignored_inputs.py b/mac_app/tests/test_ignored_inputs.py
index 673301a..d51e621 100644
--- a/mac_app/tests/test_ignored_inputs.py
+++ b/mac_app/tests/test_ignored_inputs.py
@@ -6,9 +6,13 @@ import tempfile
import unittest
from dataclasses import replace
from pathlib import Path
+import os
+import sys
-import ignored
-import protocol
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import ignored
+from core import protocol
import settings_store
from bridge import KVMController
from tests.test_bridge import FakeClock, FakeQuartz, make_config, quiet_logger
diff --git a/mac_app/tests/test_ignored_titles.py b/mac_app/tests/test_ignored_titles.py
index 6349d6f..6b29f08 100644
--- a/mac_app/tests/test_ignored_titles.py
+++ b/mac_app/tests/test_ignored_titles.py
@@ -1,8 +1,12 @@
"""Display names for ignored_inputs entries, and the recorder's pure decision behind one."""
import unittest
+import os
+import sys
-import ignored
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import ignored
import ignored_titles
import media_keys
diff --git a/mac_app/tests/test_input_injector_mac.py b/mac_app/tests/test_input_injector_mac.py
index c596246..513d5ad 100644
--- a/mac_app/tests/test_input_injector_mac.py
+++ b/mac_app/tests/test_input_injector_mac.py
@@ -4,9 +4,13 @@ when a click counts as a double. No Quartz — everything here is arithmetic and
table lookup, which is exactly the part that can be wrong without crashing."""
import unittest
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import input_injector_mac as injector
-from return_edge import Rect
+from core.return_edge import Rect
class KeyPlanTests(unittest.TestCase):
diff --git a/mac_app/tests/test_keyboard_layout.py b/mac_app/tests/test_keyboard_layout.py
index efd0b08..aa08497 100644
--- a/mac_app/tests/test_keyboard_layout.py
+++ b/mac_app/tests/test_keyboard_layout.py
@@ -6,11 +6,14 @@ layouts; the last class reads them from the system to prove that."""
import ctypes
import sys
import unittest
+import os
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import config
import keyboard_layout
import input_injector_mac as injector
-import protocol
+from core import protocol
from bridge import QuartzEventTranslator
from tests.test_bridge import FakeQuartz
diff --git a/mac_app/tests/test_pages.py b/mac_app/tests/test_pages.py
index 21d3422..e496382 100644
--- a/mac_app/tests/test_pages.py
+++ b/mac_app/tests/test_pages.py
@@ -1,10 +1,13 @@
import sys
import unittest
from pathlib import Path
+import os
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-import effects
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import effects
import pages
@@ -76,7 +79,7 @@ class DiagramTest(unittest.TestCase):
class DesignChoicesTest(unittest.TestCase):
def test_styles_are_today_then_each_direction_quiet_medium_showpiece(self):
- import effects
+ from core import effects
groups = pages.style_groups()
self.assertEqual([group for group, _ in groups], ["Classic", "Membrane", "Sparks", "Instrument"])
@@ -90,7 +93,7 @@ class DesignChoicesTest(unittest.TestCase):
def test_colours_are_today_then_each_direction_three_packs(self):
import crossing
- import effects
+ from core import effects
groups = pages.colour_groups(crossing.GLOW_COLOURS)
self.assertEqual(groups[0], ("Classic", [(name, name.capitalize()) for name in crossing.GLOW_COLOURS]))
@@ -105,7 +108,7 @@ class DesignChoicesTest(unittest.TestCase):
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
+ from core import effects
with mock.patch.object(effects, "_load", side_effect=ModuleNotFoundError("fx_ink")):
self.assertIsInstance(pages.effects_load_error(), ModuleNotFoundError)
diff --git a/mac_app/tests/test_pairing.py b/mac_app/tests/test_pairing.py
index 4966479..c0afd6d 100644
--- a/mac_app/tests/test_pairing.py
+++ b/mac_app/tests/test_pairing.py
@@ -1,18 +1,18 @@
-import filecmp
import logging
-import os
import socket
import threading
import time
import unittest
from unittest import mock
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
-import pairing
-from pairing import Announcer, Discovery, PairingHost
+from core import pairing
+from core.pairing import Announcer, Discovery, PairingHost
-_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
-_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))
def quiet_logger():
@@ -39,13 +39,6 @@ def wait_until(predicate, timeout=5.0):
return False
-class ParityTests(unittest.TestCase):
- def test_both_copies_are_identical(self):
- mac = os.path.join(_REPO_ROOT, "mac_app", "pairing.py")
- win = os.path.join(_REPO_ROOT, "win_app", "pairing.py")
- self.assertTrue(filecmp.cmp(mac, win, shallow=False), "mac_app/pairing.py and win_app/pairing.py differ")
-
-
class LoopbackTests(unittest.TestCase):
"""The two socket loops against each other on 127.0.0.1, with the broadcast address
replaced so nothing leaves this machine."""
diff --git a/mac_app/tests/test_pairing_announcer_error.py b/mac_app/tests/test_pairing_announcer_error.py
index 7916a36..4ba3795 100644
--- a/mac_app/tests/test_pairing_announcer_error.py
+++ b/mac_app/tests/test_pairing_announcer_error.py
@@ -1,8 +1,12 @@
import logging
import socket
import unittest
+import os
+import sys
-from pairing import Announcer, Discovery
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core.pairing import Announcer, Discovery
def quiet_logger():
diff --git a/mac_app/tests/test_pairing_cpace.py b/mac_app/tests/test_pairing_cpace.py
deleted file mode 100644
index 078bbd6..0000000
--- a/mac_app/tests/test_pairing_cpace.py
+++ /dev/null
@@ -1,640 +0,0 @@
-"""The pairing exchange itself: CPace against the published vectors, the committed vectors
-replayed value by value, and the rules that hold an attacker to one guess at the code.
-
-Pure: no sockets and no clock but the fake one, so it runs the same in both apps' suites.
-"""
-
-import json
-import os
-import unittest
-
-import pairing
-from pairing import PairingClient, PairingError, PairingHost, encode
-
-_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
-
-with open(os.path.join(_TESTS_DIR, "pairing_vectors.json"), encoding="utf-8") as _handle:
- VECTORS = json.load(_handle)
-
-
-class FakeClock:
- def __init__(self, value=1000.0):
- self.value = value
-
- def __call__(self):
- return self.value
-
- def advance(self, seconds):
- self.value += seconds
-
-
-def scripted(*values):
- queue = list(values)
- return lambda length: queue.pop(0)
-
-
-def other_code(code):
- return str((int(code) + 1) % 10**6).zfill(6)
-
-
-def paired(host, code, name="Test Mac"):
- """One honest exchange, as (client, start, answer, confirm, done, token)."""
- client = PairingClient(host.pair_id, code, name)
- start = client.start()
- answer = host.handle(start)
- confirm = client.accept(answer)
- done = host.handle(confirm)
- return client, start, answer, confirm, done, client.finish(done)
-
-
-class PublishedVectorTests(unittest.TestCase):
- """The numbers other people published, so the core is right before Beamer adds to it."""
-
- def test_length_prefixes_match_the_draft(self):
- self.assertEqual(pairing._prepend_len(b"").hex(), "00")
- self.assertEqual(pairing._prepend_len(b"1234").hex(), "0431323334")
- self.assertEqual(pairing._prepend_len(bytes(128))[:2].hex(), "8001")
- self.assertEqual(pairing._prepend_len(bytes(300))[:2].hex(), "ac02")
- self.assertEqual(pairing._lv_cat(b"1234", b"5", b"", b"678").hex(), "043132333401350003363738")
-
- def test_the_draft_exchange_is_reproduced_step_by_step(self):
- draft = VECTORS["cpace_draft"]
- sid = bytes.fromhex(draft["sid_hex"])
- generator = pairing._generator(draft["prs_ascii"].encode(), bytes.fromhex(draft["ci_hex"]), sid)
- self.assertEqual(generator.hex(), draft["generator_hex"])
- ya_scalar = bytes.fromhex(draft["ya_scalar_hex"])
- yb_scalar = bytes.fromhex(draft["yb_scalar_hex"])
- ya = pairing._x25519(ya_scalar, generator)
- yb = pairing._x25519(yb_scalar, generator)
- self.assertEqual((ya.hex(), yb.hex()), (draft["ya_hex"], draft["yb_hex"]))
- self.assertEqual(pairing._x25519(ya_scalar, yb).hex(), draft["k_hex"])
- self.assertEqual(pairing._x25519(yb_scalar, ya).hex(), draft["k_hex"])
-
- def test_elligator_matches_rfc_9380(self):
- for vector in VECTORS["elligator2"]:
- with self.subTest(element=vector["field_element_hex_be"]):
- self.assertEqual(pairing._elligator2(int(vector["field_element_hex_be"], 16)), int(vector["u_hex_be"], 16))
-
- def test_low_order_shares_are_refused(self):
- low = VECTORS["low_order_shares"]
- scalar = bytes.fromhex(low["scalar_hex"])
- for share in low["must_refuse"]:
- with self.subTest(share=share):
- with self.assertRaises(PairingError):
- pairing._x25519(scalar, bytes.fromhex(share))
- for vector in low["must_give"]:
- with self.subTest(share=vector["share_hex"]):
- self.assertEqual(pairing._x25519(scalar, bytes.fromhex(vector["share_hex"])).hex(), vector["product_hex"])
-
- def test_base64_has_one_spelling(self):
- for length in range(40):
- data = bytes(range(length))
- self.assertEqual(pairing._unb64(pairing._b64(data)), data)
- for text in ("AA==", "AA=", "A", "AAB", "AB+/", " AAAA", "AAAA\n", "!!!!", "====", "AA!A", None, 7, b"AAAA"):
- with self.subTest(text=text):
- with self.assertRaises(PairingError):
- pairing._unb64(text)
-
- def test_hkdf_matches_rfc_5869(self):
- # Test case 1, whose first 32 bytes are the single block this HKDF produces.
- block = pairing._hkdf(bytes([0x0B]) * 22, bytes(range(13)), bytes(range(0xF0, 0xFA)))
- self.assertEqual(block.hex(), "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf")
-
-
-class PhoneVectorTests(unittest.TestCase):
- """pairing_vectors.json is what a second implementation is built against; these replay
- it through this module, so a change to the exchange cannot leave the file behind."""
-
- def test_constants_are_the_ones_in_the_file(self):
- constants = VECTORS["constants"]
- self.assertEqual(VECTORS["pairing_version"], pairing.PAIRING_VERSION)
- self.assertEqual(constants["channel_ascii"].encode(), pairing.CHANNEL)
- self.assertEqual(constants["role_requester_ascii"].encode(), pairing.ROLE_REQUESTER)
- self.assertEqual(constants["role_host_ascii"].encode(), pairing.ROLE_HOST)
- self.assertEqual(constants["token_info_ascii"].encode(), pairing.TOKEN_INFO)
- self.assertEqual(constants["done_label_ascii"].encode(), pairing.DONE_LABEL)
- self.assertEqual(constants["max_name_chars"], pairing.MAX_NAME_CHARS)
-
- def test_each_exchange_replays_to_the_same_messages_and_token(self):
- for vector in VECTORS["exchanges"]:
- with self.subTest(exchange=vector["comment"]):
- requester, host_side = vector["requester"], vector["host"]
- host = PairingHost(
- name=host_side["name"],
- identity=bytes.fromhex(host_side["id_hex"]),
- entropy=scripted(bytes.fromhex(vector["pair_id"]), bytes.fromhex(host_side["scalar_hex"])),
- )
- host.begin()
- host.code = vector["code"]
- self.assertEqual(host.pair_id, vector["pair_id"])
- client = PairingClient(
- host.pair_id,
- vector["code"],
- requester["name"],
- identity=bytes.fromhex(requester["id_hex"]),
- entropy=scripted(bytes.fromhex(requester["nonce_hex"]), bytes.fromhex(requester["scalar_hex"])),
- )
- messages = vector["messages"]
- self.assertEqual(client.start(), messages["pair_start"])
- answer = host.handle(messages["pair_start"])
- self.assertEqual(answer, messages["pair_answer"])
- confirm = client.accept(answer)
- self.assertEqual(confirm, messages["pair_confirm"])
- done = host.handle(confirm)
- self.assertEqual(done, messages["pair_done"])
- self.assertEqual(client.finish(done), vector["token"])
- self.assertEqual(host.paired, (vector["token"], requester["name"]))
-
- def test_each_exchange_s_intermediate_values_follow_the_specification(self):
- for vector in VECTORS["exchanges"]:
- with self.subTest(exchange=vector["comment"]):
- requester, host_side = vector["requester"], vector["host"]
- sid = pairing._session_id(vector["pair_id"], bytes.fromhex(requester["nonce_hex"]))
- self.assertEqual(sid.hex(), vector["sid_hex"])
- ada = pairing._party(pairing.ROLE_REQUESTER, bytes.fromhex(requester["id_hex"]), requester["name"])
- adb = pairing._party(pairing.ROLE_HOST, bytes.fromhex(host_side["id_hex"]), host_side["name"])
- self.assertEqual((ada.hex(), adb.hex()), (vector["ada_hex"], vector["adb_hex"]))
- self.assertEqual(pairing._generator(vector["code"].encode(), pairing.CHANNEL, sid).hex(), vector["generator_hex"])
- ya = pairing._share(vector["code"], sid, bytes.fromhex(requester["scalar_hex"]))
- yb = pairing._share(vector["code"], sid, bytes.fromhex(host_side["scalar_hex"]))
- self.assertEqual((ya.hex(), yb.hex()), (vector["ya_hex"], vector["yb_hex"]))
- for scalar, peer in ((requester["scalar_hex"], yb), (host_side["scalar_hex"], ya)):
- shared = pairing._x25519(bytes.fromhex(scalar), peer)
- token, ta, tb, td = pairing._keys(sid, shared, ya, ada, yb, adb)
- self.assertEqual(token, vector["token"])
- self.assertEqual((ta.hex(), tb.hex(), td.hex()), (vector["ta_hex"], vector["tb_hex"], vector["td_hex"]))
-
- def test_the_wrong_code_vector_is_refused_and_aborted(self):
- vector = VECTORS["wrong_code"]
- requester = vector["requester"]
- client = PairingClient(
- vector["pair_id"],
- vector["requester_code"],
- requester["name"],
- entropy=scripted(bytes.fromhex(requester["nonce_hex"]), bytes.fromhex(requester["scalar_hex"])),
- )
- self.assertEqual(client.start(), vector["pair_start"])
- with self.assertRaises(PairingError) as caught:
- client.accept(vector["pair_answer"])
- self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)
- self.assertEqual(client.abort(), vector["pair_confirm_abort"])
- self.assertEqual(vector["requester_must"], pairing.ERROR_REFUSED)
-
- def test_a_name_is_cut_by_code_points(self):
- vector = VECTORS["name_cut"]
- client = PairingClient("00" * 16, "482913", vector["name"])
- self.assertEqual(client.start()["name"], vector["sent"])
- self.assertEqual((len(vector["name"]), len(vector["sent"])), (vector["code_points"], pairing.MAX_NAME_CHARS))
-
-
-class ExchangeTests(unittest.TestCase):
- def setUp(self):
- self.clock = FakeClock()
- self.host = PairingHost(self.clock, name="TEST-PC")
- self.code = self.host.begin()
-
- def test_right_code_agrees_one_token_without_sending_it_or_the_code(self):
- _client, start, answer, confirm, done, token = paired(self.host, self.code)
- self.assertEqual(self.host.paired, (token, "Test Mac"))
- self.assertGreaterEqual(len(token), 40)
- self.assertEqual(self.host.outcome, "paired")
- self.assertFalse(self.host.active)
- wire = b"".join(encode(message) for message in (start, answer, confirm, done))
- self.assertNotIn(token.encode(), wire)
- self.assertNotIn(self.code.encode(), wire)
-
- def test_the_host_stores_nothing_until_the_requester_confirms(self):
- client = PairingClient(self.host.pair_id, self.code, "Test Mac")
- answer = self.host.handle(client.start())
- self.assertTrue(answer["ok"])
- self.assertIsNone(self.host.paired)
- self.assertTrue(self.host.active)
-
- def test_two_exchanges_never_share_a_token_or_a_share(self):
- _client, first_start, _answer, _confirm, _done, first = paired(self.host, self.code)
- code = self.host.begin()
- _client, second_start, _answer, _confirm, _done, second = paired(self.host, code)
- self.assertNotEqual(first, second)
- self.assertNotEqual(first_start["share"], second_start["share"])
-
- def test_a_requester_with_the_wrong_code_refuses_the_answer_and_never_confirms(self):
- client = PairingClient(self.host.pair_id, other_code(self.code), "Test Mac")
- answer = self.host.handle(client.start())
- self.assertTrue(answer["ok"], "the host cannot tell a wrong code from its answer alone")
- with self.assertRaises(PairingError) as caught:
- client.accept(answer)
- self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)
- self.assertIsNone(self.host.paired)
-
- def test_the_abort_ends_the_code_and_says_a_wrong_one_was_entered(self):
- client = PairingClient(self.host.pair_id, other_code(self.code), "Test Mac")
- self.host.handle(client.start())
- done = self.host.handle(client.abort())
- self.assertEqual(done, {"type": "pair_done", "pair": client.pair_id, "ok": False, "error": "refused"})
- self.assertFalse(self.host.active)
- self.assertEqual(self.host.outcome, "refused")
- self.assertIsNone(self.host.paired)
-
- def test_a_host_with_another_code_is_refused(self):
- impostor = PairingHost(FakeClock(), name="TEST-PC")
- impostor.begin()
- impostor.code = other_code(self.code)
- impostor.pair_id = self.host.pair_id
- client = PairingClient(self.host.pair_id, self.code, "Test Mac")
- with self.assertRaises(PairingError):
- client.accept(impostor.handle(client.start()))
- with self.assertRaises(PairingError):
- client.finish({"type": "pair_done", "pair": client.pair_id, "ok": True, "tag": ""})
-
-
-class OneGuessTests(unittest.TestCase):
- """Each rule here is what stops a second guess at the code; loosening one is a hole."""
-
- def setUp(self):
- self.clock = FakeClock()
- self.host = PairingHost(self.clock, name="TEST-PC")
- self.code = self.host.begin()
-
- def test_a_code_answers_one_share_even_for_the_right_code(self):
- attacker = PairingClient(self.host.pair_id, other_code(self.code), "Attacker")
- self.assertTrue(self.host.handle(attacker.start())["ok"])
- honest = PairingClient(self.host.pair_id, self.code, "Test Mac")
- reply = self.host.handle(honest.start())
- self.assertEqual(reply, {"type": "pair_answer", "pair": honest.pair_id, "ok": False, "error": "refused"})
- second = PairingClient(self.host.pair_id, other_code(other_code(self.code)), "Attacker")
- self.assertFalse(self.host.handle(second.start())["ok"])
-
- def test_a_second_share_does_not_disturb_the_exchange_under_way(self):
- honest = PairingClient(self.host.pair_id, self.code, "Test Mac")
- answer = self.host.handle(honest.start())
- stranger = PairingClient(self.host.pair_id, other_code(self.code), "Attacker")
- self.assertFalse(self.host.handle(stranger.start())["ok"])
- done = self.host.handle(honest.accept(answer))
- self.assertEqual(self.host.paired[0], honest.finish(done))
-
- def test_a_requester_judges_one_answer_and_no_more(self):
- client = PairingClient(self.host.pair_id, self.code, "Test Mac")
- good = self.host.handle(client.start())
- forged = dict(good, tag=pairing._b64(bytes(pairing.TAG_BYTES)))
- with self.assertRaises(PairingError):
- client.accept(forged)
- with self.assertRaises(PairingError) as caught:
- client.accept(good)
- self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)
-
- def test_an_error_answer_also_spends_the_attempt(self):
- client = PairingClient(self.host.pair_id, self.code, "Test Mac")
- good = self.host.handle(client.start())
- with self.assertRaises(PairingError):
- client.accept({"type": "pair_answer", "pair": client.pair_id, "ok": False, "error": "not_pairing"})
- with self.assertRaises(PairingError):
- client.accept(good)
-
- def test_a_wrong_confirmation_ends_the_code_and_stores_nothing(self):
- client = PairingClient(self.host.pair_id, self.code, "Test Mac")
- answer = self.host.handle(client.start())
- confirm = client.accept(answer)
- forged = dict(confirm, tag=pairing._b64(bytes(pairing.TAG_BYTES)))
- self.assertEqual(self.host.handle(forged)["error"], "refused")
- self.assertIsNone(self.host.paired)
- self.assertEqual(self.host.handle(confirm)["error"], "not_pairing")
- self.assertIsNone(self.host.paired)
-
- def test_the_host_s_own_tag_reflected_back_is_not_a_confirmation(self):
- client = PairingClient(self.host.pair_id, self.code, "Test Mac")
- answer = self.host.handle(client.start())
- done = self.host.handle({"type": "pair_confirm", "pair": client.pair_id, "tag": answer["tag"]})
- self.assertEqual(done["error"], "refused")
- self.assertIsNone(self.host.paired)
-
- def test_a_confirmation_with_no_exchange_under_way_does_nothing(self):
- done = self.host.handle({"type": "pair_confirm", "pair": self.host.pair_id, "tag": ""})
- self.assertEqual(done["error"], "not_pairing")
- self.assertTrue(self.host.active)
-
- def test_an_unknown_pairing_id_does_not_touch_the_code(self):
- stranger = PairingClient("deadbeef", self.code, "Test Mac")
- self.assertEqual(self.host.handle(stranger.start())["error"], "not_pairing")
- self.assertTrue(self.host.active)
- paired(self.host, self.code)
-
- def test_a_tampered_share_or_name_is_refused(self):
- for field, value in (("share", pairing._b64(bytes(range(1, 33)))), ("name", "EVIL-PC"), ("id", pairing._b64(b"x"))):
- with self.subTest(field=field):
- host = PairingHost(FakeClock(), name="TEST-PC")
- code = host.begin()
- client = PairingClient(host.pair_id, code, "Test Mac")
- answer = dict(host.handle(client.start()), **{field: value})
- with self.assertRaises(PairingError):
- client.accept(answer)
-
- def test_a_name_changed_on_the_way_to_the_host_fails_the_exchange(self):
- client = PairingClient(self.host.pair_id, self.code, "Test Mac")
- answer = self.host.handle(dict(client.start(), name="Someone Else"))
- with self.assertRaises(PairingError):
- client.accept(answer)
-
- def test_identities_are_bound_into_the_token(self):
- host = PairingHost(FakeClock(), name="TEST-PC", identity=b"h" * 16)
- code = host.begin()
- client = PairingClient(host.pair_id, code, "Test Mac", identity=b"r" * 16)
- start = client.start()
- answer = host.handle(start)
- self.assertEqual((start["id"], answer["id"]), (pairing._b64(b"r" * 16), pairing._b64(b"h" * 16)))
- self.assertEqual(client.finish(host.handle(client.accept(answer))), host.paired[0])
- host = PairingHost(FakeClock(), name="TEST-PC", identity=b"h" * 16)
- code = host.begin()
- client = PairingClient(host.pair_id, code, "Test Mac", identity=b"r" * 16)
- answer = host.handle(dict(client.start(), id=pairing._b64(b"q" * 16)))
- with self.assertRaises(PairingError):
- client.accept(answer)
-
-
-class HostStateTests(unittest.TestCase):
- def setUp(self):
- self.clock = FakeClock()
- self.host = PairingHost(self.clock, name="TEST-PC")
- self.code = self.host.begin()
-
- def test_retransmitted_datagrams_get_the_same_replies(self):
- client = PairingClient(self.host.pair_id, self.code, "Test Mac")
- start = client.start()
- answer = self.host.handle(start)
- self.assertEqual(self.host.handle(start), answer)
- confirm = client.accept(answer)
- done = self.host.handle(confirm)
- self.assertEqual(self.host.handle(confirm), done)
- self.assertTrue(done["ok"])
-
- def test_a_refused_start_is_answered_the_same_way_again(self):
- start = dict(PairingClient(self.host.pair_id, self.code, "Test Mac").start(), share="!!")
- reply = self.host.handle(start)
- self.assertEqual(reply["error"], "refused")
- self.assertEqual(self.host.handle(start), reply)
-
- def test_an_expired_code_is_not_answered(self):
- pair_id = self.host.pair_id
- self.clock.advance(pairing.CODE_LIFETIME_SECONDS)
- client = PairingClient(pair_id, self.code, "Test Mac")
- self.assertEqual(self.host.handle(client.start())["error"], "not_pairing")
- self.assertEqual(self.host.outcome, "expired")
-
- def test_an_exchange_the_code_outlives_is_not_completed(self):
- client = PairingClient(self.host.pair_id, self.code, "Test Mac")
- confirm = client.accept(self.host.handle(client.start()))
- self.clock.advance(pairing.CODE_LIFETIME_SECONDS)
- self.assertEqual(self.host.handle(confirm)["error"], "not_pairing")
- self.assertIsNone(self.host.paired)
-
- def test_a_new_code_forgets_the_last_exchange(self):
- client, start, _answer, confirm, _done, _token = paired(self.host, self.code)
- self.host.paired = None
- self.host.begin()
- self.assertEqual(self.host.handle(start)["error"], "not_pairing")
- self.assertEqual(self.host.handle(confirm)["error"], "not_pairing")
- self.assertIsNone(self.host.paired)
-
- def test_malformed_starts_are_refused_without_an_exception(self):
- good = PairingClient(self.host.pair_id, self.code, "Test Mac").start()
- bad_fields = [
- ("nonce", "!!"), ("nonce", pairing._b64(b"short")), ("nonce", None), ("nonce", ["a"]),
- ("share", "??"), ("share", pairing._b64(bytes(31))), ("share", 7), ("share", {"a": 1}),
- ("share", pairing._b64(bytes(32))), ("share", pairing._b64(b"\x01" + bytes(31))),
- ("name", None), ("name", 12), ("name", "x" * (pairing.MAX_NAME_CHARS + 1)), ("name", "\ud800"),
- ("id", None), ("id", pairing._b64(bytes(pairing.MAX_IDENTITY_BYTES + 1))), ("id", "é"),
- ]
- for field, value in bad_fields:
- with self.subTest(field=field, value=value):
- host = PairingHost(FakeClock(), name="TEST-PC")
- host.begin()
- host.code = self.code
- host.pair_id = self.host.pair_id
- reply = host.handle(dict(good, **{field: value}))
- self.assertEqual(reply, {"type": "pair_answer", "pair": host.pair_id or good["pair"], "ok": False, "error": "refused"})
- self.assertFalse(host.active)
- self.assertIsNone(host.paired)
-
- def test_a_refusal_never_touches_the_code(self):
- # A refusal goes back at once, so nothing worked out from the code may come before it:
- # how long that took would be in the reply's timing.
- good = PairingClient(self.host.pair_id, self.code, "Test Mac").start()
- calls = []
- real = pairing._generator
- pairing._generator = lambda *args: calls.append(args) or real(*args)
- try:
- for field, value in (("share", pairing._b64(bytes(32))), ("share", pairing._b64(b"\x01" + bytes(31))),
- ("name", "\ud800"), ("nonce", "!!"), ("id", "=")):
- host = PairingHost(FakeClock(), name="TEST-PC")
- host.begin()
- host.code = self.code
- reply = host.handle(dict(good, pair=host.pair_id, **{field: value}))
- self.assertEqual(reply["error"], "refused")
- self.assertFalse(host.fresh_answer)
- self.assertEqual(calls, [])
- self.assertTrue(self.host.handle(good)["ok"])
- self.assertEqual(len(calls), 1)
- finally:
- pairing._generator = real
-
- def test_only_a_newly_made_answer_is_marked_fresh(self):
- start = PairingClient(self.host.pair_id, self.code, "Test Mac").start()
- self.assertFalse(self.host.fresh_answer)
- self.host.handle(start)
- self.assertTrue(self.host.fresh_answer)
- self.host.fresh_answer = False
- self.assertTrue(self.host.handle(start)["ok"])
- self.assertFalse(self.host.fresh_answer)
-
- def test_datagrams_that_are_not_for_the_host_get_no_answer(self):
- self.assertIsNone(self.host.handle({"type": "beacon", "name": "x", "port": 1}))
- self.assertIsNone(self.host.handle({"type": "pair_start", "pair": 7}))
- for pair_id in ("", "x" * 65, "\u00e9" * 8, "\ud83d"):
- self.assertIsNone(self.host.handle({"type": "pair_start", "pair": pair_id}))
- self.assertIsNone(self.host.handle({"type": "pair_request", "pair": pair_id}))
- self.assertIsNone(self.host.handle({"type": "pair_answer", "pair": self.host.pair_id}))
- self.assertTrue(self.host.active)
-
- def test_another_pairing_version_is_told_so(self):
- start = dict(PairingClient(self.host.pair_id, self.code, "Test Mac").start(), v=3)
- self.assertEqual(self.host.handle(start)["error"], "version")
- self.assertEqual(self.host.outcome, "version")
- self.assertFalse(self.host.active)
-
- def test_a_1_4_2_request_is_refused_in_the_reply_that_mac_reads(self):
- request = {"type": "pair_request", "pair": self.host.pair_id, "pub": "AAAA", "proof": "BBBB", "name": "Old Mac"}
- reply = self.host.handle(request)
- self.assertEqual(reply, {"type": "pair_reply", "pair": request["pair"], "ok": False, "error": "refused"})
- self.assertEqual(self.host.outcome, "version")
- self.assertIsNone(self.host.paired)
- self.assertEqual(self.host.handle(request)["error"], "not_pairing")
-
- def test_a_1_4_2_request_does_not_disturb_an_exchange_under_way(self):
- client = PairingClient(self.host.pair_id, self.code, "Test Mac")
- answer = self.host.handle(client.start())
- self.host.handle({"type": "pair_request", "pair": self.host.pair_id, "pub": "AAAA", "proof": "BBBB"})
- done = self.host.handle(client.accept(answer))
- self.assertEqual(self.host.paired[0], client.finish(done))
-
-
-class ClientStateTests(unittest.TestCase):
- def setUp(self):
- self.host = PairingHost(FakeClock(), name="TEST-PC")
- self.code = self.host.begin()
- self.client = PairingClient(self.host.pair_id, self.code, "Test Mac")
-
- def test_malformed_answers_are_refused_without_an_exception(self):
- good = self.host.handle(self.client.start())
- bad_fields = [
- ("share", None), ("share", pairing._b64(bytes(32))), ("share", pairing._b64(bytes(33))), ("share", [1]),
- ("tag", None), ("tag", "!!"), ("tag", ""), ("name", 5), ("name", "\udfff"),
- ("name", "x" * (pairing.MAX_NAME_CHARS + 1)), ("id", 1.5), ("ok", 1), ("ok", "true"),
- ]
- for field, value in bad_fields:
- with self.subTest(field=field, value=value):
- client = PairingClient(self.host.pair_id, self.code, "Test Mac")
- with self.assertRaises(PairingError):
- client.accept(dict(good, **{field: value}))
-
- def test_a_reply_to_another_attempt_is_not_judged(self):
- good = self.host.handle(self.client.start())
- for stray in (dict(good, pair="someone-else"), dict(good, type="pair_done"), {"type": "pair_reply", "pair": self.client.pair_id}):
- with self.assertRaises(PairingError) as caught:
- self.client.accept(stray)
- self.assertEqual(str(caught.exception), "not a reply to this attempt")
- self.client.accept(good)
-
- def test_the_token_is_only_handed_over_for_the_host_s_own_receipt(self):
- confirm = self.client.accept(self.host.handle(self.client.start()))
- done = self.host.handle(confirm)
- for forged in (dict(done, tag=confirm["tag"]), dict(done, tag=""), dict(done, tag=None)):
- with self.assertRaises(PairingError) as caught:
- self.client.finish(forged)
- self.assertEqual(str(caught.exception), pairing.ERROR_REFUSED)
- with self.assertRaises(PairingError) as caught:
- self.client.finish({"type": "pair_done", "pair": self.client.pair_id, "ok": False, "error": "not_pairing"})
- self.assertEqual(str(caught.exception), pairing.ERROR_NOT_PAIRING)
- self.assertEqual(self.client.finish(done), self.host.paired[0])
-
- def test_the_host_s_name_is_known_only_once_its_tag_checks_out(self):
- answer = self.host.handle(self.client.start())
- self.assertIsNone(self.client.host_name)
- self.client.accept(answer)
- self.assertEqual((self.client.host_name, self.client.host_identity), ("TEST-PC", b""))
-
- def test_no_token_before_the_answer_was_accepted(self):
- with self.assertRaises(PairingError):
- self.client.finish({"type": "pair_done", "pair": self.client.pair_id, "ok": True, "tag": ""})
-
- def test_names_are_cut_before_they_are_sent_and_bound_as_sent(self):
- long_name = "M" * 200
- host = PairingHost(FakeClock(), name="P" * 200)
- code = host.begin()
- _client, start, answer, _confirm, _done, token = paired(host, code, name=long_name)
- self.assertEqual(start["name"], long_name[: pairing.MAX_NAME_CHARS])
- self.assertEqual(answer["name"], "P" * pairing.MAX_NAME_CHARS)
- self.assertEqual(host.paired, (token, long_name[: pairing.MAX_NAME_CHARS]))
-
- def test_the_largest_datagrams_fit(self):
- name = "\U0001d539" * pairing.MAX_NAME_CHARS
- host = PairingHost(FakeClock(), name=name, identity=bytes(pairing.MAX_IDENTITY_BYTES))
- code = host.begin()
- client = PairingClient(host.pair_id, code, name, identity=bytes(pairing.MAX_IDENTITY_BYTES))
- start = client.start()
- answer = host.handle(start)
- confirm = client.accept(answer)
- done = host.handle(confirm)
- for message in (start, answer, confirm, done, pairing.beacon_msg(name, 65535, host.pair_id or start["pair"])):
- self.assertLessEqual(len(encode(message)), pairing.MAX_DATAGRAM_BYTES)
- self.assertEqual(pairing.decode(encode(message))["type"], message["type"])
- self.assertEqual(client.finish(done), host.paired[0])
-
-
-class VersionTests(unittest.TestCase):
- def test_every_beacon_says_which_exchange_the_host_speaks(self):
- self.assertEqual(pairing.beacon_msg("TEST-PC", 51820)["pairing"], pairing.PAIRING_VERSION)
- self.assertEqual(pairing.beacon_msg("TEST-PC", 51820, "abcd")["pairing"], pairing.PAIRING_VERSION)
-
- def test_a_host_on_another_version_is_never_sent_anything(self):
- class Recorder:
- sent = []
-
- def sendto(self, data, address):
- self.sent.append((data, address))
-
- discovery = pairing.Discovery(bind_port=0)
- discovery._sock = Recorder()
- for version in (1, 3, None):
- pc = {"name": "OLD-PC", "address": "127.0.0.1", "port": 1, "reply_port": 1, "pair_id": "abcd", "pairing": version}
- with self.assertRaises(PairingError) as caught:
- discovery.pair(pc, "123456")
- self.assertEqual(str(caught.exception), pairing.ERROR_VERSION)
- self.assertEqual(Recorder.sent, [])
-
- def test_a_pairing_id_that_could_not_be_hashed_is_not_offered(self):
- discovery = pairing.Discovery(bind_port=0)
- for number, pair_id in enumerate(("\ud800", "é" * 8, "a" * 65, "", 7)):
- beacon = dict(pairing.beacon_msg("PC", 24820), pair=pair_id)
- discovery._note_beacon(beacon, (f"127.0.0.{number + 1}", 24821))
- self.assertEqual([pc["pair_id"] for pc in discovery.pcs()], [None] * 5)
-
- def test_a_beacon_whose_name_cannot_be_shown_is_dropped(self):
- discovery = pairing.Discovery(bind_port=0)
- discovery._note_beacon(pairing.beacon_msg("\ud800", 24820), ("127.0.0.1", 24821))
- self.assertEqual(discovery.pcs(), [])
-
- def test_only_one_attempt_runs_at_a_time(self):
- discovery = pairing.Discovery(bind_port=0)
- discovery._sock = object()
- discovery._pairing.acquire()
- pc = {"name": "PC", "address": "127.0.0.1", "port": 1, "reply_port": 1, "pair_id": "ab" * 16, "pairing": pairing.PAIRING_VERSION}
- with self.assertRaises(PairingError) as caught:
- discovery.pair(pc, "123456")
- self.assertEqual(str(caught.exception), "busy")
-
- def test_the_ration_is_not_wiped_by_a_burst_of_made_up_addresses(self):
- last = {}
- self.assertTrue(pairing.Announcer._due(last, "target", 100.0))
- for number in range(400):
- pairing.Announcer._due(last, f"spoofed-{number}", 100.1)
- self.assertFalse(pairing.Announcer._due(last, "target", 100.2))
- self.assertTrue(pairing.Announcer._due(last, "target", 101.0))
- self.assertLessEqual(len(last), 258)
-
- def test_forged_beacons_cannot_make_the_list_grow_without_end(self):
- clock = FakeClock()
- discovery = pairing.Discovery(bind_port=0, clock=clock)
- for number in range(500):
- discovery._note_beacon(pairing.beacon_msg(f"PC-{number}", 24820), (f"10.1.{number // 250}.{number % 250 + 1}", 24821))
- self.assertEqual(len(discovery._seen), pairing.MAX_SEEN_HOSTS)
- # A full list lets a newcomer in, the longest quiet making way for it.
- discovery._note_beacon(pairing.beacon_msg("REAL-PC", 24820), ("10.9.9.9", 24821))
- self.assertIn("REAL-PC", [pc["name"] for pc in discovery.pcs()])
- # A flood can still crowd it off again. The way through is the PC's address, typed:
- # that one is never the one to go.
- discovery._finding = ("10.9.9.9", 24821)
- for second in range(6):
- clock.advance(1.0)
- if second % 2 == 0:
- discovery._note_beacon(pairing.beacon_msg("REAL-PC", 24820), ("10.9.9.9", 24821))
- for number in range(200):
- discovery._note_beacon(pairing.beacon_msg("FORGED", 24820), (f"10.3.{second}.{number + 1}", 24821))
- self.assertIn("REAL-PC", [pc["name"] for pc in discovery.pcs()])
- self.assertEqual(len(discovery._seen), pairing.MAX_SEEN_HOSTS)
- discovery._finding = None
- clock.advance(pairing.BEACON_STALE_SECONDS + 1)
- discovery._note_beacon(pairing.beacon_msg("LATE-PC", 24820), ("10.2.0.1", 24821))
- self.assertEqual([pc["name"] for pc in discovery.pcs()], ["LATE-PC"])
-
- def test_a_datagram_of_nothing_but_brackets_is_just_ignored(self):
- self.assertIsNone(pairing.decode(b"[" * pairing.MAX_DATAGRAM_BYTES))
- self.assertIsNone(pairing.decode(b'{"a":' * 170))
-
- def test_a_beacon_without_a_version_is_the_old_exchange(self):
- discovery = pairing.Discovery(bind_port=0)
- discovery._note_beacon({"type": "beacon", "name": "OLD-PC", "port": 24820, "pair": "abcd"}, ("127.0.0.1", 24821))
- discovery._note_beacon(pairing.beacon_msg("NEW-PC", 24820, "abcd"), ("127.0.0.2", 24821))
- self.assertEqual({pc["name"]: pc["pairing"] for pc in discovery.pcs()}, {"OLD-PC": 1, "NEW-PC": pairing.PAIRING_VERSION})
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/mac_app/tests/test_pairing_selection.py b/mac_app/tests/test_pairing_selection.py
new file mode 100644
index 0000000..a5d719a
--- /dev/null
+++ b/mac_app/tests/test_pairing_selection.py
@@ -0,0 +1,134 @@
+"""Pairing selection follows current discovery without opening a window or a socket."""
+
+import unittest
+from types import MethodType, SimpleNamespace
+from unittest import mock
+
+import kvm_bridge_app
+
+
+class PairingSelectionTests(unittest.TestCase):
+ def setUp(self):
+ self.window = SimpleNamespace(
+ discovery=mock.Mock(error=None, pcs=mock.Mock(return_value=[])),
+ chosen_pc=None, _pcs=[], _pcs_key=None, _pairing=False,
+ pc_list=mock.Mock(arrangedSubviews=mock.Mock(return_value=[])),
+ pc_frame=mock.Mock(), pc_empty=mock.Mock(), pair_status=mock.Mock(),
+ confirm_button=mock.Mock(), code_boxes=mock.Mock(value=""),
+ window=mock.Mock(), _find_answered=mock.Mock(), _pairing_finished=mock.Mock(),
+ _shown=lambda text: text,
+ )
+ self.window.code_boxes.clear.side_effect = lambda: setattr(self.window.code_boxes, "value", "")
+ self.window.pair_status.set.side_effect = lambda text, **kwargs: setattr(self, "status_text", text)
+ self.status_text = ""
+ for name in ("_refresh_pcs", "_choose_pc", "_say_choice", "_say_pairing", "confirmPair_"):
+ method = getattr(kvm_bridge_app.ControlWindow, name)
+ setattr(self.window, name, MethodType(getattr(method, "callable", method), self.window))
+ for name in ("pressable", "stack", "LED", "Label", "hug", "squeeze", "pin", "add"):
+ patcher = mock.patch.object(kvm_bridge_app.widgets, name)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def beacon(self, pair_id=None, reply_port=24821):
+ return dict(name="TEST-PC", address="192.0.2.20", port=24820,
+ reply_port=reply_port, pair_id=pair_id)
+
+ def refresh(self, pc):
+ self.window.discovery.pcs.return_value = [pc] if pc is not None else []
+ self.window._refresh_pcs()
+
+ def choose(self, pc):
+ self.refresh(pc)
+ self.window._choose_pc(0)
+
+ def enter(self, code):
+ self.window.code_boxes.value = code
+
+ def status(self):
+ return self.status_text
+
+ def test_selected_pc_starting_pairing_updates_hint_and_keeps_partial_code(self):
+ self.choose(self.beacon())
+ self.assertIn("not showing a code", self.status())
+ self.enter("123")
+ active = self.beacon("first-code")
+ self.refresh(active)
+ self.assertEqual(self.window.chosen_pc, active)
+ self.assertEqual(self.status(), "Six digits, as shown on the PC.")
+ self.assertEqual(self.window.code_boxes.value, "123")
+
+ def test_selected_pc_stopping_pairing_updates_hint(self):
+ self.choose(self.beacon("first-code"))
+ self.refresh(self.beacon())
+ self.assertIsNone(self.window.chosen_pc["pair_id"])
+ self.assertIn("not showing a code", self.status())
+
+ def test_active_code_rotation_updates_selected_and_submission_state(self):
+ self.choose(self.beacon("first-code"))
+ current = self.beacon("second-code")
+ self.refresh(current)
+ self.assertEqual(self.window.chosen_pc, current)
+ self.assertEqual(self.window._pcs, [current])
+
+ def test_reply_port_change_updates_selected_and_submission_state(self):
+ self.choose(self.beacon("first-code"))
+ current = self.beacon("first-code", reply_port=24822)
+ self.refresh(current)
+ self.assertEqual(self.window.chosen_pc, current)
+ self.assertEqual(self.window._pcs, [current])
+
+ def test_submit_uses_latest_pairing_id_and_reply_port(self):
+ self.choose(self.beacon("first-code"))
+ current = self.beacon("second-code", reply_port=24822)
+ self.refresh(current)
+ self.enter("123456")
+ with mock.patch.object(kvm_bridge_app.threading, "Thread") as thread, \
+ mock.patch.object(kvm_bridge_app.AppHelper, "callAfter"):
+ self.window.confirmPair_(None)
+ thread.assert_called_once()
+ thread.call_args.kwargs["target"]()
+ self.window.discovery.pair.assert_called_once_with(current, "123456")
+
+ def test_pairing_progress_survives_beacon_changes(self):
+ self.choose(self.beacon("first-code"))
+ self.window._pairing = True
+ self.window._say_pairing("Pairing with TEST-PC…")
+ self.refresh(self.beacon())
+ self.assertEqual(self.status(), "Pairing with TEST-PC…")
+
+ def test_unchanged_beacon_preserves_error_message(self):
+ pc = self.beacon("first-code")
+ self.choose(pc)
+ self.window._say_pairing("That code was not accepted.", "fault")
+ self.refresh(dict(pc))
+ self.assertEqual(self.status(), "That code was not accepted.")
+
+ def test_refusal_stays_up_when_the_pc_drops_its_code(self):
+ self.choose(self.beacon("first-code"))
+ self.window._say_pairing("That code was not accepted.", "fault")
+ self.refresh(self.beacon())
+ self.assertEqual(self.status(), "That code was not accepted.")
+ self.refresh(self.beacon("fresh-code"))
+ self.assertEqual(self.status(), "Six digits, as shown on the PC.")
+
+ def test_disappeared_pc_clears_selection_and_disables_submission(self):
+ self.choose(self.beacon("first-code"))
+ self.refresh(None)
+ self.assertIsNone(self.window.chosen_pc)
+ self.assertEqual(self.window._pcs, [])
+ self.window.confirm_button.set_enabled.assert_called_with(False)
+
+ def test_a_pc_on_another_version_of_the_exchange_is_said_plainly(self):
+ pc = self.beacon("first-code")
+ self.choose(pc)
+ finished = kvm_bridge_app.ControlWindow._pairing_finished
+ finished = MethodType(getattr(finished, "callable", finished), self.window)
+ finished(pc, kvm_bridge_app.pairing.PairingError(kvm_bridge_app.pairing.ERROR_VERSION))
+ self.assertEqual(
+ self.status(),
+ "The PC runs a different version of Beamer. Update Beamer on both machines, then pair again.",
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_protocol_parity.py b/mac_app/tests/test_protocol_parity.py
deleted file mode 100644
index 18e74fe..0000000
--- a/mac_app/tests/test_protocol_parity.py
+++ /dev/null
@@ -1,118 +0,0 @@
-"""Protocol parity test: mac_app/protocol.py and win_app/protocol.py are two
-independent copies of the same wire protocol (see the module docstring in
-either file) and must never be allowed to silently drift apart -- a v2
-sender talking to a stale v1-ish receiver (or vice versa) is exactly the
-failure mode protocol.py's own version handshake exists to catch, and this
-test exists to catch the same class of problem one step earlier, at review
-time, before either app ships.
-
-Both files are loaded via importlib file-path loading rather than a normal
-`import protocol`, so this test has no dependency on sys.path/PYTHONPATH
-ordering -- it always compares these two specific files on disk, not
-whichever `protocol` module happens to be importable first. Dependency-free:
-only the standard library (importlib, inspect, unittest).
-"""
-
-import importlib.util
-import inspect
-import os
-import types
-import unittest
-
-
-_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
-_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))
-MAC_PROTOCOL_PATH = os.path.join(_REPO_ROOT, "mac_app", "protocol.py")
-WIN_PROTOCOL_PATH = os.path.join(_REPO_ROOT, "win_app", "protocol.py")
-
-
-def _load_module_from_path(module_name, path):
- spec = importlib.util.spec_from_file_location(module_name, path)
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
-
-
-def _public_attribute_names(module):
- """Names protocol.py itself defines and exposes: everything not starting
- with "_", excluding re-exported stdlib modules (json, socket, struct)
- that show up in dir() purely because they were imported at module level
- -- those aren't part of the protocol surface being compared here."""
- return {
- name
- for name in dir(module)
- if not name.startswith("_") and not isinstance(getattr(module, name), types.ModuleType)
- }
-
-
-class ProtocolParityTests(unittest.TestCase):
- @classmethod
- def setUpClass(cls):
- if not os.path.isfile(MAC_PROTOCOL_PATH):
- raise unittest.SkipTest(f"mac_app/protocol.py not found at {MAC_PROTOCOL_PATH}")
- if not os.path.isfile(WIN_PROTOCOL_PATH):
- raise unittest.SkipTest(f"win_app/protocol.py not found at {WIN_PROTOCOL_PATH}")
- # Distinct module names, so this never collides with (or is
- # satisfied by) an already-imported `protocol` module from either
- # app's own test suite / sys.path setup.
- cls.mac = _load_module_from_path("_protocol_parity_mac", MAC_PROTOCOL_PATH)
- cls.win = _load_module_from_path("_protocol_parity_win", WIN_PROTOCOL_PATH)
-
- def test_public_names_match(self):
- self.assertEqual(
- _public_attribute_names(self.mac),
- _public_attribute_names(self.win),
- "mac_app/protocol.py and win_app/protocol.py expose different public names",
- )
-
- def test_constants_have_identical_values(self):
- for name in sorted(_public_attribute_names(self.mac)):
- mac_value = getattr(self.mac, name)
- if not isinstance(mac_value, (int, float, str, bytes, bool)):
- continue
- win_value = getattr(self.win, name)
- with self.subTest(name=name):
- self.assertEqual(
- mac_value,
- win_value,
- f"constant {name!r} differs between mac_app and win_app protocol.py",
- )
-
- def test_function_signatures_match(self):
- for name in sorted(_public_attribute_names(self.mac)):
- mac_value = getattr(self.mac, name)
- if not inspect.isfunction(mac_value):
- continue
- win_value = getattr(self.win, name)
- with self.subTest(name=name):
- self.assertTrue(
- inspect.isfunction(win_value),
- f"{name!r} is a function in mac_app/protocol.py but not in win_app/protocol.py",
- )
- self.assertEqual(
- inspect.signature(mac_value),
- inspect.signature(win_value),
- f"signature of {name!r} differs between mac_app and win_app protocol.py",
- )
-
- def test_classes_match(self):
- for name in sorted(_public_attribute_names(self.mac)):
- mac_value = getattr(self.mac, name)
- if not inspect.isclass(mac_value):
- continue
- win_value = getattr(self.win, name)
- with self.subTest(name=name):
- self.assertTrue(
- inspect.isclass(win_value),
- f"{name!r} is a class in mac_app/protocol.py but not in win_app/protocol.py",
- )
- self.assertEqual(mac_value.__name__, win_value.__name__)
- self.assertEqual(
- [base.__name__ for base in mac_value.__mro__],
- [base.__name__ for base in win_value.__mro__],
- f"MRO of {name!r} differs between mac_app and win_app protocol.py",
- )
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/mac_app/tests/test_replay.py b/mac_app/tests/test_replay.py
index fea24b7..94e4d52 100644
--- a/mac_app/tests/test_replay.py
+++ b/mac_app/tests/test_replay.py
@@ -8,8 +8,12 @@ responder, and it must fail the tag rather than inject what was recorded."""
import socket
import time
import unittest
+import os
+import sys
-import protocol
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import protocol
from two_machines import Duo, wait_for
diff --git a/mac_app/tests/test_same_on_both.py b/mac_app/tests/test_same_on_both.py
new file mode 100644
index 0000000..de70053
--- /dev/null
+++ b/mac_app/tests/test_same_on_both.py
@@ -0,0 +1,135 @@
+"""Same on both machines in the real window: the Overview switch, a PC's settings arriving, and a
+change here going out. Built as test_appearance builds it, never put on screen; the two links'
+sends are recorded instead."""
+
+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 pages # noqa: E402
+import settings_store # noqa: E402
+from core import settings_sync # noqa: E402
+from wake import WakingController # noqa: E402
+
+
+def pc_message(on, set_at, **values):
+ base = dict(methods=["corner"], edge_parts=["start"], corner="bottom_left", resistance_px=60,
+ block_while_dragging=False, trigger_key="cmd_r", trigger_style="hold", double_tap_ms=400,
+ glow_style="beam", glow_colour="ocean", effect_length="long", shortcut_arrival=False,
+ shortcut_arrival_style="locator")
+ base.update(values)
+ return settings_sync.message_data(on, set_at, base)
+
+
+class SameOnBothTests(unittest.TestCase):
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.addCleanup(self.directory.cleanup)
+ path = Path(self.directory.name) / "config.json"
+ raw = settings_store.config_to_raw(settings_store.editable_default_config())
+ raw.update(host="192.0.2.20", auth_token="synthetic")
+ raw["crossing"]["methods"] = ["shortcut", "edge", "notch"]
+ path.write_text(json.dumps(raw))
+ self.store = settings_store.SettingsStore(path)
+ logger = logging.getLogger("test-same-on-both")
+ with mock.patch.object(kvm_bridge_app, "accessibility_granted", return_value=True), \
+ mock.patch.object(kvm_bridge_app, "input_monitoring_granted", return_value=True):
+ self.window = kvm_bridge_app.ControlWindow.alloc().initWithController_settingsStore_logger_(
+ WakingController(self.store.load(), logger=logger), self.store, logger
+ )
+ self.addCleanup(self.window.appearance_watch.stop)
+ self.sent = []
+ self.window.controller.send_settings = lambda data: self.sent.append(data) or True
+ self.window._show_same()
+
+ def test_off_by_default_with_each_page_its_own(self):
+ self.assertFalse(self.window.same_switch.value)
+ self.assertEqual(self.window.scope_labels["design"].text, pages.SCOPE["design"])
+ self.assertTrue(all(note.view.isHidden() for note in self.window.own_notes))
+
+ def test_the_pcs_settings_arrive_and_this_macs_own_stay(self):
+ self.window.apply_same(pc_message(True, 100))
+ cfg = self.window.controller.cfg
+ self.assertTrue(cfg.same_on_both)
+ self.assertEqual(cfg.crossing["methods"], ["corner", "notch"])
+ self.assertEqual((cfg.crossing["glow_style"], cfg.crossing["effect_length"]), ("beam", "long"))
+ self.assertEqual((cfg.trigger_key, cfg.trigger_style, cfg.double_tap_ms), ("cmd_r", "hold", 400))
+ self.assertEqual(self.store.load().crossing["glow_colour"], "ocean")
+ self.assertEqual(self.window.glow_style_select.value, "beam")
+ self.assertEqual(self.window.resistance_ruler.value, 60)
+ self.assertTrue(self.window.same_switch.value)
+ self.assertEqual(self.window.scope_labels["crossing"].text,
+ "Kept the same as your PC. Change it on either machine.")
+ self.assertEqual(self.sent, [])
+
+ def test_arriving_settings_leave_a_half_typed_address_and_the_pairing_card(self):
+ self.window.host_field.setStringValue_("192.0.2.99")
+ self.window._say_pairing("That code was not accepted.", "fault")
+ self.window.apply_same(pc_message(True, 100))
+ self.assertEqual(self.window.host_field.stringValue(), "192.0.2.99")
+ self.assertEqual(self.window.pair_status.text, "That code was not accepted.")
+
+ def test_the_hold_switch_reaches_the_controller_before_the_debounce(self):
+ self.window.controller.full_screen_app = "Game"
+ self.window.hold_box._toggle()
+ self.assertIs(self.window.controller.cfg.crossing["hold_full_screen"], False)
+ self.assertIsNone(self.window.controller.full_screen_app)
+ self.window.hold_box._toggle()
+ self.assertEqual(self.window.controller.full_screen_app, "Game")
+
+ def test_settings_arriving_from_the_pc_leave_the_hold_switch_as_chosen(self):
+ self.window.hold_box._toggle()
+ self.window.apply_same(pc_message(True, 100))
+ self.assertFalse(self.window.hold_box.value)
+ self.window._apply_settings()
+ self.assertFalse(self.store.load().crossing["hold_full_screen"])
+
+ def test_an_older_message_changes_nothing(self):
+ self.window.apply_same(pc_message(True, 100))
+ self.window.apply_same(pc_message(True, 90, glow_style="glow"))
+ self.assertEqual(self.window.controller.cfg.crossing["glow_style"], "beam")
+
+ def test_turning_it_on_here_sends_this_macs_values(self):
+ self.window._set_same(True)
+ self.assertEqual(len(self.sent), 1)
+ self.assertTrue(self.sent[0]["on"])
+ self.assertEqual(self.sent[0]["crossing"]["methods"], ["shortcut", "edge"])
+
+ def test_a_change_here_while_on_is_sent_and_one_to_this_macs_own_is_not(self):
+ self.window._set_same(True)
+ self.sent.clear()
+ self.window.notch_after_select.value = 3000
+ self.window._apply_settings()
+ self.assertEqual(self.sent, [])
+ self.window.length_select.value = "short"
+ self.window._apply_settings()
+ self.assertEqual(len(self.sent), 1)
+ self.assertEqual(self.sent[0]["design"]["effect_length"], "short")
+
+ def test_a_change_here_while_off_goes_nowhere(self):
+ self.window.length_select.value = "short"
+ self.window._apply_settings()
+ self.assertEqual(self.sent, [])
+
+ def test_an_old_pc_turns_the_switch_off_and_says_why(self):
+ self.window._set_same(True)
+ self.window.controller.peer_settings = False
+ with mock.patch.object(type(self.window.controller), "connected", new_callable=mock.PropertyMock, return_value=True):
+ self.window._show_same()
+ self.assertFalse(self.window.same_switch.value)
+ self.assertIn("too old", self.window.same_note.text)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_settings_store.py b/mac_app/tests/test_settings_store.py
index 0dd544e..60a1488 100644
--- a/mac_app/tests/test_settings_store.py
+++ b/mac_app/tests/test_settings_store.py
@@ -4,9 +4,12 @@ import tempfile
import unittest
from pathlib import Path
from unittest import mock
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import config as config_module
-import protocol
+from core import protocol
import settings_store
from settings_store import SettingsError, SettingsStore, config_to_raw
@@ -47,6 +50,19 @@ class SettingsStoreTests(unittest.TestCase):
self.assertTrue(loaded.allow_windows_to_drive)
self.assertFalse(store.load().send_to_windows)
+ def test_the_full_screen_hold_defaults_on_and_round_trips(self):
+ with tempfile.TemporaryDirectory() as directory:
+ store = SettingsStore(Path(directory) / "config.json")
+ loaded = store.save(self.valid_raw())
+ self.assertTrue(loaded.crossing["hold_full_screen"])
+ raw = config_to_raw(loaded)
+ raw["crossing"]["hold_full_screen"] = False
+ store.save(raw)
+ self.assertFalse(store.load().crossing["hold_full_screen"])
+ raw["crossing"]["hold_full_screen"] = "no"
+ with self.assertRaises(SettingsError):
+ store.save(raw)
+
def test_appearance_defaults_to_system_and_each_choice_round_trips(self):
with tempfile.TemporaryDirectory() as directory:
store = SettingsStore(Path(directory) / "config.json")
@@ -208,7 +224,7 @@ class SettingsStoreTests(unittest.TestCase):
self.assertIn(field, str(caught.exception))
def test_every_crossing_effect_and_colour_pack_round_trips(self):
- import effects
+ from core 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]
diff --git a/mac_app/tests/test_settings_sync_link.py b/mac_app/tests/test_settings_sync_link.py
new file mode 100644
index 0000000..e3cea4b
--- /dev/null
+++ b/mac_app/tests/test_settings_sync_link.py
@@ -0,0 +1,168 @@
+"""Same on both machines over loopback: the real links of both apps, announcing on connect and
+carrying each change, with two small ends holding each machine's state through settings_sync as
+the apps' windows do (apply_same on the Mac, _on_settings on the PC)."""
+
+import unittest
+from unittest import mock
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from two_machines import Duo, wait_for # first: it puts the PC's own modules on the path
+
+import app_config # noqa: E402
+from core import protocol # noqa: E402
+from core import settings_sync # noqa: E402
+from key_codes import KEY_NAME_TO_CODE # noqa: E402
+from settings_store import config_to_raw # noqa: E402
+
+
+class MacEnd:
+ def __init__(self, duo):
+ self.duo = duo
+ self.raw = config_to_raw(duo.mac.cfg)
+ self.raw["same_on_both"], self.raw["same_set_at"] = False, 0
+
+ def state(self):
+ return settings_sync.message_data(self.raw["same_on_both"], self.raw["same_set_at"],
+ settings_sync.mac_values(self.raw))
+
+ def take(self, data):
+ taken = settings_sync.arrived(data, self.raw["same_set_at"], KEY_NAME_TO_CODE)
+ if taken is None:
+ return
+ on, set_at, values = taken
+ raw = settings_sync.apply_mac(self.raw, values) if on else dict(self.raw)
+ raw["same_on_both"], raw["same_set_at"] = on, set_at
+ self.raw = raw
+
+ def set(self, on=None, at=0, **crossing):
+ if on is not None:
+ self.raw["same_on_both"] = on
+ self.raw["crossing"] = {**self.raw["crossing"], **crossing}
+ self.raw["same_set_at"] = at
+ data = self.state()
+ self.duo.mac.send_settings(data)
+ self.duo.mac_server.send_settings(data)
+
+
+class PCEnd:
+ def __init__(self, duo):
+ self.duo = duo
+ self.config = duo.pc_config
+
+ def state(self):
+ return settings_sync.message_data(self.config.same_on_both, self.config.same_set_at,
+ settings_sync.pc_values(self.config))
+
+ def take(self, data):
+ taken = settings_sync.arrived(data, self.config.same_set_at, app_config.TRIGGER_KEYS)
+ if taken is None:
+ return
+ on, set_at, values = taken
+ if on:
+ settings_sync.apply_pc(self.config, values)
+ self.config.same_on_both, self.config.same_set_at = on, set_at
+
+ def set(self, on=None, at=0, **fields):
+ if on is not None:
+ self.config.same_on_both = on
+ for name, value in fields.items():
+ setattr(self.config, name, value)
+ self.config.same_set_at = at
+ data = self.state()
+ self.duo.pc.send_settings(data)
+ self.duo.pc_server.send_settings(data)
+
+
+class SettingsOverLoopbackTests(unittest.TestCase):
+ def setUp(self):
+ self.duo = Duo(pc=dict(mac_return_edge="left"))
+ self.addCleanup(self.duo.close)
+ self.mac, self.pc = MacEnd(self.duo), PCEnd(self.duo)
+ for link in (self.duo.mac, self.duo.mac_server):
+ link.announce = lambda: [protocol.settings_msg(self.mac.state())]
+ self.duo.mac.on_settings = self.mac.take
+ self.duo.mac_server.settings_callback = self.mac.take
+ for link in (self.duo.pc, self.duo.pc_server):
+ link.announce = lambda: [protocol.settings_msg(self.pc.state())]
+ link.settings_callback = self.pc.take
+
+ def both_links(self):
+ self.duo.listen().link_mac_to_pc().link_pc_to_mac()
+
+ def test_turning_it_on_carries_this_machines_values_across(self):
+ self.both_links()
+ self.mac.set(on=True, at=100, glow_style="beam", corner="bottom_right", resistance_px=60)
+ self.assertTrue(wait_for(lambda: self.pc.config.same_on_both))
+ self.assertEqual((self.pc.config.glow_style, self.pc.config.crossing_resistance_px), ("beam", 60))
+ # The PC's Mac is on its left, so the Mac's bottom right is the PC's bottom left.
+ self.assertEqual(self.pc.config.crossing_corner, "bottom_left")
+ self.assertEqual(self.pc.config.same_set_at, 100)
+
+ def test_a_change_on_either_machine_reaches_the_other_while_on(self):
+ self.both_links()
+ self.mac.set(on=True, at=100)
+ self.assertTrue(wait_for(lambda: self.pc.config.same_on_both))
+ self.pc.set(at=101, effect_length="long", crossing_methods=["corner"])
+ self.assertTrue(wait_for(lambda: self.mac.raw["crossing"]["effect_length"] == "long"))
+ # The notch is the Mac's own way in and stays.
+ self.assertEqual(self.mac.raw["crossing"]["methods"], ["corner", "notch"]
+ if "notch" in self.duo.mac.cfg.crossing["methods"] else ["corner"])
+ self.mac.set(at=102, glow_colour="ocean")
+ self.assertTrue(wait_for(lambda: self.pc.config.glow_colour == "ocean"))
+
+ def test_the_newer_end_wins_when_a_link_comes_up(self):
+ # Changed on the PC while the Mac was away: the PC's is newer, and the Mac takes it the
+ # moment its own link connects, from the PC receiver's announcement.
+ self.pc.config.same_on_both, self.pc.config.same_set_at = True, 500
+ self.pc.config.glow_style = "beam"
+ self.mac.raw["same_on_both"], self.mac.raw["same_set_at"] = True, 400
+ self.duo.listen().link_mac_to_pc()
+ self.assertTrue(wait_for(lambda: self.mac.raw["same_set_at"] == 500))
+ self.assertEqual(self.mac.raw["crossing"]["glow_style"], "beam")
+ # And the older end's own announcement changed nothing at the newer.
+ self.assertEqual(self.pc.config.same_set_at, 500)
+
+ def test_turning_it_off_turns_it_off_at_both_and_leaves_the_values(self):
+ self.both_links()
+ self.mac.set(on=True, at=100, glow_style="beam")
+ self.assertTrue(wait_for(lambda: self.pc.config.glow_style == "beam"))
+ self.pc.set(on=False, at=200)
+ self.assertTrue(wait_for(lambda: self.mac.raw["same_on_both"] is False))
+ self.assertEqual(self.mac.raw["crossing"]["glow_style"], "beam")
+ self.mac.raw["crossing"]["glow_style"] = "glow"
+ self.assertEqual(self.pc.config.glow_style, "beam")
+
+ def test_both_ends_know_a_peer_that_keeps_settings_in_step(self):
+ self.both_links()
+ self.assertTrue(wait_for(lambda: self.duo.mac_server.peer_settings is True))
+ self.assertTrue(self.duo.mac.peer_settings)
+ self.assertTrue(self.duo.pc.peer_settings)
+ self.assertTrue(wait_for(lambda: self.duo.pc_server.peer_settings is True))
+
+ def test_an_older_peer_is_known_as_one_on_either_link(self):
+ # A Beamer before 1.5.0 sends a hello and a welcome with no settings flag.
+ older_hello, older_welcome = protocol.hello_msg, protocol.welcome_msg
+
+ def strip(message):
+ message["data"].pop("settings", None)
+ return message
+
+ with mock.patch.object(protocol, "hello_msg", lambda *a, **k: strip(older_hello(*a, **k))), \
+ mock.patch.object(protocol, "welcome_msg", lambda *a, **k: strip(older_welcome(*a, **k))):
+ self.both_links()
+ self.assertTrue(wait_for(lambda: self.duo.mac_server.peer_settings is False))
+ self.assertIs(self.duo.mac.peer_settings, False)
+ self.assertIs(self.duo.pc.peer_settings, False)
+
+ def test_the_arrangement_is_announced_when_a_link_comes_up(self):
+ # G1: a change made while nobody was connected reaches the other end on the next link.
+ self.duo.mac.announce = lambda: [protocol.arrangement_msg("top", 300), protocol.settings_msg(self.mac.state())]
+ self.duo.listen().link_mac_to_pc()
+ self.assertTrue(wait_for(lambda: ("top", 300) in self.duo.pc_arrangements))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/mac_app/tests/test_shared_copies.py b/mac_app/tests/test_shared_copies.py
deleted file mode 100644
index 6e7cd04..0000000
--- a/mac_app/tests/test_shared_copies.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""The files both apps share are kept byte-identical, not merely similar.
-
-`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
-legitimate reason for the two copies to differ by a byte, and a diff is
-always drift. This test is byte-for-byte on purpose: a structural comparison
-would pass while the two sides' return-edge arithmetic or status wording
-quietly diverged.
-
-This file is itself one of those copies, and checks itself.
-"""
-
-import hashlib
-import os
-import unittest
-
-_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
-_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))
-
-SHARED_MODULES = (
- "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 = (
- "pairing_vectors.json", "test_ignored.py", "test_pairing_cpace.py", "test_shared_copies.py", "test_switch_arrival.py",
- "test_updates.py",
-)
-
-
-def _digest(path):
- with open(path, "rb") as handle:
- return hashlib.sha256(handle.read()).hexdigest()
-
-
-class SharedCopyTests(unittest.TestCase):
- def _assert_identical(self, mac_path, win_path, name):
- for path in (mac_path, win_path):
- self.assertTrue(os.path.isfile(path), f"{name} is missing from {os.path.dirname(path)}")
- self.assertEqual(
- _digest(mac_path),
- _digest(win_path),
- f"mac_app and win_app copies of {name} have drifted apart",
- )
-
- def test_shared_modules_are_identical(self):
- for name in SHARED_MODULES:
- with self.subTest(module=name):
- self._assert_identical(
- os.path.join(_REPO_ROOT, "mac_app", name),
- os.path.join(_REPO_ROOT, "win_app", name),
- name,
- )
-
- def test_shared_tests_are_identical(self):
- for name in SHARED_TESTS:
- with self.subTest(module=name):
- self._assert_identical(
- os.path.join(_REPO_ROOT, "mac_app", "tests", name),
- os.path.join(_REPO_ROOT, "win_app", "tests", name),
- name,
- )
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/mac_app/tests/test_switch_arrival.py b/mac_app/tests/test_switch_arrival.py
deleted file mode 100644
index 532b99c..0000000
--- a/mac_app/tests/test_switch_arrival.py
+++ /dev/null
@@ -1,189 +0,0 @@
-"""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 4be45cd..1d0d3bf 100644
--- a/mac_app/tests/test_update_config_redirecting.py
+++ b/mac_app/tests/test_update_config_redirecting.py
@@ -1,4 +1,8 @@
import unittest
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from bridge import KVMController
from test_bridge import FakeClock, FakeQuartz, FakeSocket, crossing_config, link, quiet_logger
diff --git a/mac_app/tests/test_wake.py b/mac_app/tests/test_wake.py
index cc1b2c3..d7fe204 100644
--- a/mac_app/tests/test_wake.py
+++ b/mac_app/tests/test_wake.py
@@ -2,6 +2,10 @@ import logging
import threading
import types
import unittest
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import config
import wake
@@ -159,7 +163,7 @@ class WakingControllerTests(unittest.TestCase):
def test_successful_connection_learns_and_reports_a_new_address(self):
from test_bridge import FakeSocket, seed_receiver_reply
- import protocol
+ from core import protocol
sock = FakeSocket()
seed_receiver_reply(sock, protocol.welcome_msg())
@@ -197,7 +201,7 @@ class ComingHomeThroughTheAppsControllerTests(unittest.TestCase):
class FollowingAMovedPcThroughTheAppsControllerTests(unittest.TestCase):
def test_the_app_controller_takes_the_new_address(self):
from test_bridge import FakeSocket, seed_receiver_reply
- import protocol
+ from core import protocol
sock = FakeSocket()
seed_receiver_reply(sock, protocol.welcome_msg())
diff --git a/mac_app/tests/test_way_home.py b/mac_app/tests/test_way_home.py
index 2606743..f027f83 100644
--- a/mac_app/tests/test_way_home.py
+++ b/mac_app/tests/test_way_home.py
@@ -7,7 +7,9 @@ from unittest import mock
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-import return_edge
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import return_edge
from windows_input import WindowsInput
diff --git a/mac_app/tests/two_machines.py b/mac_app/tests/two_machines.py
index 82cd4e8..74d2e29 100644
--- a/mac_app/tests/two_machines.py
+++ b/mac_app/tests/two_machines.py
@@ -5,8 +5,8 @@ real MacSender, driven through its hook entry points. Each machine also runs the
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.
+win_app's modules are put on the path after this app's, so the PC's own (`sender`, `app_config`)
+resolve to the PC's; what both share comes from core.
"""
import os
@@ -20,9 +20,11 @@ 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
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import protocol
+from core import receiver
+from core.return_edge import Rect
import app_config
import sender as pc_sender_module
diff --git a/mac_app/wake.py b/mac_app/wake.py
index 770d693..e0e5a18 100644
--- a/mac_app/wake.py
+++ b/mac_app/wake.py
@@ -7,7 +7,7 @@ from __future__ import annotations
import threading
from bridge import AUTH_FAILED_STATUS, KVMController
-from wol import WAKE_WINDOW_SECONDS, lookup_mac, mac_from_arp_output, magic_packet, parse_mac, send_magic_packet
+from core.wol import WAKE_WINDOW_SECONDS, lookup_mac, mac_from_arp_output, magic_packet, parse_mac, send_magic_packet
__all__ = [
"NOT_WOKEN_STATUS", "WAKE_WINDOW_SECONDS", "WAKING_STATUS", "WakingController",
diff --git a/mac_app/windows_input.py b/mac_app/windows_input.py
index 4e0f65e..7d610df 100644
--- a/mac_app/windows_input.py
+++ b/mac_app/windows_input.py
@@ -19,9 +19,9 @@ import clipboard_mac
import desktop_mac
import input_injector_mac
import no_unlock
-import receiver
-import return_edge
-from receiver import ReceiverServer, ServerState
+from core import receiver
+from core import return_edge
+from core.receiver import ReceiverServer, ServerState
LOGGER = logging.getLogger("Beamer")
diff --git a/win_app/Beamer-Setup.iss b/win_app/Beamer-Setup.iss
index 3e5ca8a..b4738da 100644
--- a/win_app/Beamer-Setup.iss
+++ b/win_app/Beamer-Setup.iss
@@ -5,11 +5,16 @@
#define VersionFile FileOpen(AddBackslash(SourcePath) + "..\VERSION")
#define AppVersion Trim(FileRead(VersionFile))
#expr FileClose(VersionFile)
+; A beta such as 1.5.0-beta.1 names itself in the shown version, but the file version resource
+; takes four integers, so it carries the release number.
+#define NumericVersion Copy(AppVersion, 1, Pos("-", AppVersion + "-") - 1)
[Setup]
AppId={{9A4E2B1F-4309-4E65-B86D-C7B9F4F64D01}
AppName=Beamer
AppVersion={#AppVersion}
+VersionInfoVersion={#NumericVersion}.0
+VersionInfoProductTextVersion={#AppVersion}
AppPublisher=Kalkman Code
DefaultDirName={localappdata}\Beamer
DisableProgramGroupPage=yes
diff --git a/win_app/app_config.py b/win_app/app_config.py
index fccda56..c08a29c 100644
--- a/win_app/app_config.py
+++ b/win_app/app_config.py
@@ -7,10 +7,10 @@ from dataclasses import dataclass, field
from pathlib import Path
import capture_win
-import effects
-import ignored
-import protocol
-import return_edge
+from core import effects
+from core import ignored
+from core import protocol
+from core import return_edge
import tokens
@@ -78,6 +78,10 @@ class Config:
check_updates: bool = True
# Every address the window shows is hidden.
hide_addresses: bool = False
+ # Same on both machines: the Crossing and Design pages kept in step with the Mac's, and the unix
+ # seconds of the last change to that or to a shared value; see settings_sync.
+ same_on_both: bool = False
+ same_set_at: int = 0
# How the Mac's pointer and scroll feel on this PC; see receiver.InputScale.
pointer_speed: float = 1.0
scroll_speed: float = 1.0
@@ -98,6 +102,8 @@ class Config:
modifier_style: str = "semantic"
# A push against the edge with a button held is a drag, not a crossing, as on the Mac.
block_while_dragging: bool = True
+ # A full-screen app in front holds this PC's edges. This PC's own choice, never shared.
+ hold_full_screen: bool = True
# The Mac's address is learned, never typed: it is the peer address the
# Mac's own link arrives from.
mac_host: str = ""
@@ -122,6 +128,11 @@ class Config:
appearance: str = "system"
+def _stamp(value) -> int:
+ """A saved unix-seconds stamp, or 0 for anything that is not one."""
+ return int(value) if not isinstance(value, bool) and isinstance(value, (int, float)) and value > 0 else 0
+
+
def migrated_port(value) -> int:
"""The port to use for a config that still carries the old default.
@@ -173,6 +184,8 @@ def validate_config(config: Config) -> None:
raise ConfigError(f"modifier_style must be one of: {', '.join(MODIFIER_STYLES)}")
if not isinstance(config.block_while_dragging, bool):
raise ConfigError("block_while_dragging must be true or false")
+ if not isinstance(config.hold_full_screen, bool):
+ raise ConfigError("hold_full_screen must be true or false")
if not isinstance(config.mac_hardware_address, str):
raise ConfigError("mac_hardware_address must be text")
if not isinstance(config.crossing_methods, list) or any(
@@ -198,6 +211,8 @@ def validate_config(config: Config) -> None:
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")
+ if not isinstance(config.same_on_both, bool):
+ raise ConfigError("same_on_both 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:
@@ -264,6 +279,8 @@ def config_from_dict(raw: dict) -> Config:
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),
+ same_on_both=raw.get("same_on_both", False),
+ same_set_at=_stamp(raw.get("same_set_at", 0)),
pointer_speed=raw.get("pointer_speed", 1.0),
scroll_speed=raw.get("scroll_speed", 1.0),
reverse_scroll=raw.get("reverse_scroll", False),
@@ -277,6 +294,7 @@ def config_from_dict(raw: dict) -> Config:
double_tap_ms=int(raw.get("double_tap_ms", 300)),
modifier_style=raw.get("modifier_style", "semantic"),
block_while_dragging=raw.get("block_while_dragging", True),
+ hold_full_screen=raw.get("hold_full_screen", True),
mac_hardware_address=raw.get("mac_hardware_address", "") or "",
mac_host=raw.get("mac_host", "") or "",
mac_return_edge=raw.get("mac_return_edge", "") or "",
@@ -329,6 +347,8 @@ def config_to_dict(config: Config) -> dict:
"allow_mac_to_drive": config.allow_mac_to_drive,
"check_updates": config.check_updates,
"hide_addresses": config.hide_addresses,
+ "same_on_both": config.same_on_both,
+ "same_set_at": int(config.same_set_at),
"pointer_speed": config.pointer_speed,
"scroll_speed": config.scroll_speed,
"reverse_scroll": config.reverse_scroll,
@@ -342,6 +362,7 @@ def config_to_dict(config: Config) -> dict:
"double_tap_ms": int(config.double_tap_ms),
"modifier_style": config.modifier_style,
"block_while_dragging": config.block_while_dragging,
+ "hold_full_screen": config.hold_full_screen,
"mac_hardware_address": config.mac_hardware_address,
"mac_host": config.mac_host,
"mac_return_edge": config.mac_return_edge,
diff --git a/win_app/build.spec b/win_app/build.spec
index 5e28fa4..4ad0e9f 100644
--- a/win_app/build.spec
+++ b/win_app/build.spec
@@ -5,11 +5,12 @@ source_dir = Path(SPECPATH)
analysis = Analysis(
[str(source_dir / "kvm_bridge_win.py")],
- pathex=[str(source_dir)],
+ # The repo root, for core/, which both apps share.
+ pathex=[str(source_dir), str(source_dir.parent)],
binaries=[],
datas=[(str(source_dir / "Beamer.ico"), "."), (str(source_dir / "assets"), "assets"), (str(source_dir.parent / "VERSION"), ".")],
- # effects.py imports its fx_* modules by name, which PyInstaller's analysis cannot see.
- hiddenimports=["cryptography", "nacl", "_cffi_backend"] + sorted(path.stem for path in source_dir.glob("fx_*.py")),
+ # core/effects.py imports its fx_* modules by name, which PyInstaller's analysis cannot see.
+ hiddenimports=["nacl", "_cffi_backend"] + sorted(f"core.{path.stem}" for path in (source_dir.parent / "core").glob("fx_*.py")),
hookspath=[],
hooksconfig={},
runtime_hooks=[],
diff --git a/win_app/desktop_win.py b/win_app/desktop_win.py
index 532f4f1..8130653 100644
--- a/win_app/desktop_win.py
+++ b/win_app/desktop_win.py
@@ -9,7 +9,7 @@ import logging
import sys
from typing import List, Tuple
-from return_edge import Rect
+from core.return_edge import Rect
_IS_WINDOWS = sys.platform == "win32"
user32 = ctypes.WinDLL("user32", use_last_error=True) if _IS_WINDOWS else None
diff --git a/win_app/edge_glow.py b/win_app/edge_glow.py
index 880613f..3e72e55 100644
--- a/win_app/edge_glow.py
+++ b/win_app/edge_glow.py
@@ -21,8 +21,8 @@ from PySide6.QtGui import QColor, QCursor, QImage, QLinearGradient, QPainter, QP
from PySide6.QtWidgets import QApplication, QSizePolicy, QWidget
import app_config
-import effects
-import return_edge as crossing
+from core import effects
+from core import return_edge as crossing
import theme
import tokens
diff --git a/win_app/effect_overlay.py b/win_app/effect_overlay.py
index 3baec68..2d56585 100644
--- a/win_app/effect_overlay.py
+++ b/win_app/effect_overlay.py
@@ -34,8 +34,8 @@ from PySide6.QtWidgets import QWidget
import app_config
import edge_glow
-import effects
-import return_edge as crossing
+from core import effects
+from core import return_edge as crossing
LOGGER = logging.getLogger(__name__)
diff --git a/win_app/effect_previews.py b/win_app/effect_previews.py
index 3fedddd..98fd5e5 100644
--- a/win_app/effect_previews.py
+++ b/win_app/effect_previews.py
@@ -12,7 +12,7 @@ from PySide6.QtGui import QColor, QImage, QPainter, QPainterPath, QPen
from PySide6.QtWidgets import QSizePolicy, QWidget
import edge_glow
-import effects
+from core import effects
import motion
import theme
import tokens
diff --git a/win_app/effects.py b/win_app/effects.py
deleted file mode 100644
index ab4ac74..0000000
--- a/win_app/effects.py
+++ /dev/null
@@ -1,959 +0,0 @@
-"""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 67d4c0a..25cfc49 100644
--- a/win_app/firewall_win.py
+++ b/win_app/firewall_win.py
@@ -15,7 +15,7 @@ import subprocess
import sys
from typing import Iterable, Optional, Sequence
-import protocol
+from core import protocol
LOGGER = logging.getLogger(__name__)
diff --git a/win_app/fx_ink.py b/win_app/fx_ink.py
deleted file mode 100644
index d0e587f..0000000
--- a/win_app/fx_ink.py
+++ /dev/null
@@ -1,958 +0,0 @@
-"""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
deleted file mode 100644
index 84bbc5a..0000000
--- a/win_app/fx_instrument.py
+++ /dev/null
@@ -1,733 +0,0 @@
-"""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_sparks.py b/win_app/fx_sparks.py
deleted file mode 100644
index b60128f..0000000
--- a/win_app/fx_sparks.py
+++ /dev/null
@@ -1,484 +0,0 @@
-"""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
deleted file mode 100644
index 2adb36c..0000000
--- a/win_app/fx_warp.py
+++ /dev/null
@@ -1,291 +0,0 @@
-"""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/ignored.py b/win_app/ignored.py
deleted file mode 100644
index 5bc01a5..0000000
--- a/win_app/ignored.py
+++ /dev/null
@@ -1,85 +0,0 @@
-"""Keys and buttons that stay on the machine they were pressed on while its input is on the other
-one: a mouse's back and forward buttons kept for this machine's browser, a volume key kept for its
-speakers. A per-machine setting, so each app records its own keyboard's codes -- a Mac keycode and
-a Windows virtual key are different numbers for the same key, and neither end ever reads the
-other's list.
-
-Each entry is a string: `key:<code>` for a key in the platform's own numbering, `button:<name>`
-for a mouse button, and `media:<name>` for a Mac media key, which arrives as a system event rather
-than a key. Byte-identical in both apps.
-"""
-
-import re
-import threading
-
-MAX_ENTRIES = 64
-_ENTRY = re.compile(r"^(key:[0-9]{1,5}|button:[a-z0-9_]{1,24}|media:[a-z_]{1,24})$")
-
-
-def key(code):
- return f"key:{int(code)}"
-
-
-def button(name):
- return f"button:{name}"
-
-
-def media(name):
- return f"media:{name}"
-
-
-def validate(entries):
- """The list as saved, or ValueError naming what is wrong with it."""
- if not isinstance(entries, list):
- raise ValueError("ignored_inputs must be a list")
- if len(entries) > MAX_ENTRIES:
- raise ValueError(f"ignored_inputs holds at most {MAX_ENTRIES} entries")
- for entry in entries:
- if not isinstance(entry, str) or not _ENTRY.match(entry):
- raise ValueError(f"ignored_inputs has an entry Beamer cannot read: {entry!r}")
- return list(entries)
-
-
-class Gate:
- """Decides, while input is on the other machine, which presses stay here.
-
- A press stays when it is on the list. Its release goes wherever its press went, whatever the
- list says by then: a key sent across and put on the list while still held would otherwise have
- its release kept here and stay down on the far side, and one kept here and taken off the list
- would stay down here. `keeps` runs on the one thread that reads input on each platform; `reset`
- is for when input comes home, since the far side lets go of everything it was holding then, and
- is called from other threads, hence the lock."""
-
- def __init__(self, entries=()):
- self.entries = frozenset(entries)
- self._sent = set()
- self._kept = set()
- self._lock = threading.Lock()
-
- def configure(self, entries):
- self.entries = frozenset(entries)
-
- def keeps(self, entry, down):
- with self._lock:
- if entry in self._sent:
- if not down:
- self._sent.discard(entry)
- return False
- if entry in self._kept:
- if not down:
- self._kept.discard(entry)
- return True
- if entry in self.entries:
- if down:
- self._kept.add(entry)
- return True
- if down:
- self._sent.add(entry)
- return False
-
- def reset(self):
- with self._lock:
- self._sent.clear()
- # A release that arrives once input is home is never asked about, so what was kept
- # here is forgotten too.
- self._kept.clear()
diff --git a/win_app/kvm_bridge_win.py b/win_app/kvm_bridge_win.py
index eccd33c..3d20ba6 100644
--- a/win_app/kvm_bridge_win.py
+++ b/win_app/kvm_bridge_win.py
@@ -32,6 +32,10 @@ from PySide6.QtWidgets import (
QWidget,
)
+# From source, core/ sits beside this folder; the built app bundles it. Behind this folder, not
+# before it: the root also holds the Mac's theme.py, which must not stand in for this app's.
+sys.path.append(str(Path(__file__).resolve().parent.parent))
+
import app_config
from app_config import (
Config,
@@ -47,26 +51,27 @@ from app_config import (
import autostart_win
import capture_win
import desktop_win
-import effects
+from core 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
+from core import ignored
import motion
-import pairing
-from pairing import PAIRING_PORT, Announcer, local_address_towards
+from core import pairing
+from core.pairing import PAIRING_PORT, Announcer, local_address_towards
import pages_win
-import protocol
-import receiver
-from receiver import ReceiverServer, ServerState
-import return_edge
+from core import protocol
+from core import receiver
+from core.receiver import ReceiverServer, ServerState
+from core import return_edge
import sender
+from core import settings_sync
from sender import MacSender
import theme
import tokens
-import updates
+from core import updates
import widgets
LOGGER = logging.getLogger(__name__)
@@ -202,6 +207,8 @@ class StatusBridge(QObject):
learned = Signal(str, object, object)
# Either link, telling us the two machines' arrangement changed at the other end.
arrangement = Signal(str, int)
+ # Either link, carrying the Mac's Same on both machines state.
+ settings = Signal(object)
alert = Signal(str, str)
mac_learned = Signal(str)
# (version, url) when a newer Beamer is out, else None.
@@ -232,6 +239,7 @@ 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.settings.connect(self._on_settings)
self.bridge.update.connect(self._on_update)
self.bridge.rules_ready.connect(self._listen)
self._update = None
@@ -274,6 +282,14 @@ class WindowsApplication(QWidget):
),
)
self.sender.send_peer_home = self.server.send_home
+ # Same on both machines, over either link: applied on the GUI thread, and announced with
+ # this PC's own arrangement the moment either link comes up.
+ for link in (self.server, self.sender):
+ link.settings_callback = self.bridge.settings.emit
+ link.announce = self._announce
+ self.scope_labels: dict = {}
+ self.own_notes: list = []
+ self._same_seen = None
# Pause crossing and the full-screen hold are about this screen: the Mac's pointer does
# not go home through a held edge either.
self.server.edges_held = lambda: self.sender.edges_held
@@ -290,6 +306,7 @@ class WindowsApplication(QWidget):
)
try:
self._config = load_config(config_path)
+ self._same_seen = self._same_fields()
self._apply_input_scale(self._config)
self._host = self._config.host
self._status = ServerState.WAITING
@@ -371,7 +388,7 @@ class WindowsApplication(QWidget):
}
self._page_indexes: dict = {}
for key, name, purpose in pages_win.PAGES:
- scroll, layout = self._page_shell(name, purpose, pages_win.SCOPE.get(key))
+ scroll, layout = self._page_shell(name, purpose, pages_win.SCOPE.get(key), key)
builders[key](layout, current)
layout.addStretch(1)
self._page_indexes[key] = self.stack.addWidget(scroll)
@@ -382,7 +399,7 @@ class WindowsApplication(QWidget):
self._select_page("overview")
- def _page_shell(self, title: str, purpose: str, scope: Optional[str] = None):
+ def _page_shell(self, title: str, purpose: str, scope: Optional[str] = None, key: Optional[str] = None):
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setFrameShape(QFrame.Shape.NoFrame)
@@ -400,7 +417,8 @@ class WindowsApplication(QWidget):
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))
+ self.scope_labels[key] = widgets.label(scope, "note-quiet", wrap=True)
+ layout.addWidget(self.scope_labels[key])
scroll.setWidget(page)
return scroll, layout
@@ -428,6 +446,7 @@ class WindowsApplication(QWidget):
layout.addWidget(self.link_module)
layout.addWidget(self._input_module())
layout.addWidget(self._directions_module(current))
+ layout.addWidget(self._same_module(current))
self.sign_in_module = self._sign_in_module()
layout.addWidget(self.sign_in_module)
layout.addWidget(self._updates_module(current))
@@ -532,6 +551,15 @@ class WindowsApplication(QWidget):
# 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)
+ self.hold_switch = widgets.Switch("Hold the edges while an app is full screen")
+ self.hold_switch.setFont(theme.font(theme.TYPE["body"]))
+ self.hold_switch.setChecked(self._config.hold_full_screen if self._config else True)
+ self.hold_switch.toggled.connect(self._set_hold_full_screen)
+ module.body.addWidget(self.hold_switch)
+ module.body.addWidget(self._own_note())
+ module.body.addWidget(widgets.label(
+ "Off, your pointer can leave a full-screen game or video, and the Mac's pointer can come home "
+ "through this PC's edge. Useful if your keyboard has no key for the shortcut.", "note", wrap=True))
return module
def toggle_redirect(self) -> None:
@@ -597,6 +625,120 @@ class WindowsApplication(QWidget):
self.send_switch.setEnabled(False)
return module
+ def _same_module(self, current: Config) -> QWidget:
+ module = widgets.Module("Settings")
+ self.same_switch = widgets.Switch("Same on both machines")
+ self.same_switch.setFont(theme.font(theme.TYPE["body"]))
+ self.same_switch.setChecked(current.same_on_both)
+ self.same_switch.toggled.connect(self._set_same)
+ module.body.addWidget(self.same_switch)
+ self.same_note = widgets.label("", "note", wrap=True)
+ module.body.addWidget(self.same_note)
+ if self._config is None:
+ self.same_switch.setEnabled(False)
+ return module
+
+ def _own_note(self) -> QWidget:
+ """A note on a row this PC keeps to itself, shown only while the pages are kept in step."""
+ note = widgets.label(pages_win.OWN_ROW, "note", wrap=True)
+ note.setVisible(False)
+ self.own_notes.append(note)
+ return note
+
+ def _peer_too_old(self) -> bool:
+ """Whether a link is up to a Mac whose Beamer does not keep settings in step."""
+ with self._status_lock:
+ receiving = self._status == ServerState.CONNECTED
+ links = ((receiving, self.server.peer_settings), (self.sender.connected, self.sender.peer_settings))
+ return any(up and known is False for up, known in links)
+
+ def _show_same(self) -> None:
+ if self._config is None:
+ return
+ old = self._peer_too_old()
+ on = self._config.same_on_both and not old
+ if self.same_switch.isChecked() != on:
+ self.same_switch.blockSignals(True)
+ self.same_switch.setChecked(on)
+ self.same_switch.blockSignals(False)
+ self.same_switch.setEnabled(not old)
+ self.same_note.setText(settings_sync.switch_note("Mac", self._config.same_on_both, old))
+ widgets.set_role(self.same_note, "note-amber" if old else "note")
+ for key, label in self.scope_labels.items():
+ text = settings_sync.scope(key, "Mac", on, pages_win.SCOPE.get(key))
+ if label.text() != text:
+ label.setText(text)
+ for note in self.own_notes:
+ if motion.target_shown(note) != on:
+ motion.set_shown(note, on)
+
+ def _same_fields(self) -> tuple:
+ return tuple(getattr(self._config, field) if not isinstance(getattr(self._config, field), list)
+ else tuple(getattr(self._config, field)) for field in settings_sync.PC_FIELDS.values())
+
+ def _same_state(self) -> dict:
+ config = self._config
+ return settings_sync.message_data(config.same_on_both, config.same_set_at, settings_sync.pc_values(config))
+
+ def _send_same(self) -> None:
+ data = self._same_state()
+ self.sender.send_settings(data)
+ self.server.send_settings(data)
+
+ def _announce(self) -> list:
+ """What this PC tells the Mac on every new link: its arrangement, only once chosen here
+ (one a hello filled in is the Mac's to name), and its settings state. On the link's thread."""
+ config = self._config
+ if config is None:
+ return []
+ messages = []
+ if config.mac_return_edge in return_edge.OPPOSITE and config.arrangement_set_at:
+ messages.append(protocol.arrangement_msg(return_edge.OPPOSITE[config.mac_return_edge], config.arrangement_set_at))
+ messages.append(protocol.settings_msg(self._same_state()))
+ return messages
+
+ def _set_same(self, on: bool) -> None:
+ """Turning it on carries this PC's Crossing and Design across; off, each end keeps what it
+ has. Either way the Mac follows, now if a link is up, else when one next comes up."""
+ if self._config is None:
+ return
+ self._config.same_on_both = bool(on)
+ self._config.same_set_at = settings_sync.next_stamp(self._config.same_set_at, time.time())
+ self._persist()
+ self._send_same()
+ self._show_same()
+
+ def _on_settings(self, data) -> None:
+ """The Mac's settings message, over either link. Its state stands only when it is newer
+ than this PC's; then its values replace the shared ones here."""
+ if self._config is None:
+ return
+ held = (self._config.same_on_both, settings_sync.pc_values(self._config))
+ taken = settings_sync.arrived(data, self._config.same_set_at, TRIGGER_KEYS, held)
+ if taken is None:
+ return
+ on, set_at, values = taken
+ config = replace(self._config, crossing_methods=list(self._config.crossing_methods),
+ crossing_edge_parts=list(self._config.crossing_edge_parts))
+ config.same_on_both = on
+ config.same_set_at = set_at
+ if on:
+ settings_sync.apply_pc(config, values)
+ try:
+ app_config.validate_config(config)
+ except ConfigError:
+ LOGGER.exception("Settings from the Mac could not be applied")
+ return
+ self._config = config
+ self._same_seen = self._same_fields()
+ if not self._persist():
+ return
+ LOGGER.info("Settings from the Mac applied (same on both machines %s)", "on" if on else "off")
+ self.sender.update_config(config)
+ self._configure_trigger(config)
+ self._reflect_config(config)
+ self._show_same()
+
def _sign_in_module(self) -> QWidget:
module = widgets.Module("At sign-in")
self.logon_switch = widgets.Switch("Start Beamer when you sign in")
@@ -840,6 +982,13 @@ class WindowsApplication(QWidget):
self._reflect_look()
self._reflect_ways()
+ def _set_hold_full_screen(self, enabled: bool) -> None:
+ if self._config is None:
+ return
+ self._config.hold_full_screen = bool(enabled)
+ self._persist()
+ self.sender.update_config(self._config)
+
def _set_block_while_dragging(self, enabled: bool) -> None:
if self._config is None:
return
@@ -1168,6 +1317,7 @@ class WindowsApplication(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")
+ module.body.addWidget(self._own_note())
self.appearance_choice = widgets.Choice(
(("system", "System"), ("light", "Light"), ("dark", "Dark")), 3, current.appearance,
on_change=self._appearance_chosen,
@@ -1191,6 +1341,7 @@ class WindowsApplication(QWidget):
self.glow_toggle.setChecked(current.edge_glow)
self.glow_toggle.toggled.connect(self._apply_look)
module.body.addWidget(self.glow_toggle)
+ module.body.addWidget(self._own_note())
module.body.addWidget(
widgets.label(
"Lights this PC as you push toward your Mac. Switched off, crossing still works. "
@@ -1416,11 +1567,20 @@ class WindowsApplication(QWidget):
def _persist(self) -> bool:
if self._config is None:
return False
+ # A change to a shared setting while Same on both machines is on is stamped here, where
+ # every page's changes are saved, and sent once saved.
+ fields = self._same_fields()
+ shared = self._same_seen is not None and fields != self._same_seen and self._config.same_on_both
+ self._same_seen = fields
+ if shared:
+ self._config.same_set_at = settings_sync.next_stamp(self._config.same_set_at, time.time())
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()
+ if shared:
+ self._send_same()
return True
except (ConfigError, OSError):
LOGGER.exception("Setting could not be saved")
@@ -1731,6 +1891,7 @@ class WindowsApplication(QWidget):
if self.server.listening:
self.server.stop()
self._config = config
+ self._same_seen = self._same_fields()
self._apply_input_scale(config)
if not config.edge_glow:
self._hide_crossing()
@@ -1955,18 +2116,21 @@ 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, self.landing_toggle,
+ for box in (*self.way_boxes.values(), self.dragging_switch, self.hold_switch, self.glow_toggle,
+ self.landing_toggle,
self.resistance_slider, self.double_tap_slider):
box.blockSignals(True)
try:
self.dragging_switch.setChecked(config.block_while_dragging)
+ self.hold_switch.setChecked(config.hold_full_screen)
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, self.landing_toggle,
+ for box in (*self.way_boxes.values(), self.dragging_switch, self.hold_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")
@@ -2104,6 +2268,11 @@ class WindowsApplication(QWidget):
# A different Mac: the old one's hardware address would wake the wrong machine.
self._config.mac_hardware_address = ""
changed = True
+ # The hello's way home only fills an edge this PC does not hold yet: one chosen here, or
+ # one the Mac's stamped arrangement set, stands, and the Mac announces its arrangement on
+ # every new link anyway.
+ if self._config.mac_return_edge:
+ edge = None
for name, value in (("mac_host", host), ("mac_return_edge", edge or ""), ("mac_resistance_px", resistance)):
if value in (None, "") or getattr(self._config, name) == value:
continue
@@ -2320,6 +2489,7 @@ class WindowsApplication(QWidget):
def _refresh_window(self) -> None:
if self._closing:
return
+ self._show_same()
with self._status_lock:
state = self._status
detail = self._status_detail
@@ -2456,5 +2626,26 @@ def main() -> None:
kernel32.CloseHandle(mutex)
+def import_probe(out_path: str, names: list) -> int:
+ """tools/import_probe.py's way into the built exe, which has no interpreter of its own to lend:
+ import each named module from inside the build, write each outcome to out_path (a windowed
+ exe has no console), and stop at the first that fails. Touches no config, lock or window."""
+ import importlib
+ import traceback
+
+ with open(out_path, "w", encoding="utf-8") as out:
+ for name in names:
+ try:
+ module = importlib.import_module(name)
+ except BaseException:
+ out.write(f"FAIL {name}\n{traceback.format_exc()}")
+ return 1
+ out.write(f"ok {name} {getattr(module, '__file__', None) or 'built in'}\n")
+ return 0
+
+
if __name__ == "__main__":
+ # Before the single-instance lock, so a Beamer already running does not turn the probe away.
+ if sys.argv[1:2] == ["--import-probe"]:
+ sys.exit(import_probe(sys.argv[2], sys.argv[3:]))
main()
diff --git a/win_app/pages_win.py b/win_app/pages_win.py
index 6e9398c..fc2c8c7 100644
--- a/win_app/pages_win.py
+++ b/win_app/pages_win.py
@@ -7,7 +7,7 @@ from __future__ import annotations
import re
-import effects
+from core import effects
# (key, name, what the page is for), in sidebar order, which is setup order; Ctrl+1 is the first.
PAGES = (
@@ -36,6 +36,8 @@ SCOPE = {
"design": "For this PC's screen only; your Mac keeps its own.",
"keyboard": "For this PC's keyboard only; your Mac keeps its own.",
}
+# With Same on both machines on, under each row of the shared pages that stays this PC's own.
+OWN_ROW = "This PC only."
# The window's footer; the first sentence goes on Connection, whose changes wait for its button.
FOOTER_APPLY = "Changes apply as you make them."
FOOTER_TRAY = "Closing this window keeps Beamer running in the tray."
diff --git a/win_app/requirements-win.txt b/win_app/requirements-win.txt
index 6341dae..a2f58ec 100644
--- a/win_app/requirements-win.txt
+++ b/win_app/requirements-win.txt
@@ -1,5 +1,4 @@
PySide6-Essentials>=6.11.1
pyinstaller>=6.0
pyinstaller-hooks-contrib>=2024.1
-cryptography>=42
PyNaCl>=1.6
diff --git a/win_app/return_edge.py b/win_app/return_edge.py
deleted file mode 100644
index 643b7b7..0000000
--- a/win_app/return_edge.py
+++ /dev/null
@@ -1,297 +0,0 @@
-"""Return-edge geometry and the pressure model for crossing back to the Mac.
-
-Pure: no ctypes, no Qt, no Windows. The receiver feeds it the monitor
-rectangles, the pointer position, each incoming movement delta and a clock, and it
-answers with what to do — inject the delta, hold the pointer at the edge, or
-cross. The model mirrors the Mac's so the two boundaries feel like one:
-outward travel at the edge accumulates as pressure, inward travel subtracts,
-time decays it to nothing over DECAY_SECONDS, and at `resistance_px` of net
-outward travel the edge gives.
-"""
-
-import time
-from dataclasses import dataclass
-from typing import Callable, Iterable, List, Optional, Tuple
-
-EDGES = ("left", "right", "top", "bottom")
-OPPOSITE = {"left": "right", "right": "left", "top": "bottom", "bottom": "top"}
-DEFAULT_RESISTANCE_PX = 120
-DECAY_SECONDS = 0.4
-# How near a corner counts as being in it. The Mac's own engine uses the same
-# 8 pixels, and the two boundaries are meant to feel like one.
-CORNER_PX = 8
-CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")
-# 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"
-CROSS = "cross"
-
-
-@dataclass(frozen=True)
-class Rect:
- """A monitor or the virtual desktop, in virtual-desktop pixels. `x`/`y` may
- be negative: the primary monitor is at the origin, not the bounding box."""
-
- x: int
- y: int
- width: int
- height: int
-
- @property
- def right(self) -> int:
- return self.x + self.width - 1
-
- @property
- def bottom(self) -> int:
- return self.y + self.height - 1
-
-
-def union(monitors: Iterable[Rect]) -> Rect:
- rects = list(monitors)
- x = min(r.x for r in rects)
- y = min(r.y for r in rects)
- return Rect(x, y, max(r.right for r in rects) - x + 1, max(r.bottom for r in rects) - y + 1)
-
-
-@dataclass(frozen=True)
-class Outcome:
- action: str
- pressure: float = 0.0
- position: Optional[Tuple[int, int]] = None
- edge: Optional[str] = None
- offset: Optional[float] = None
-
-
-def _clamp(value, low, high):
- return max(low, min(high, value))
-
-
-def _contains(rect: Rect, point: Tuple[int, int]) -> bool:
- return rect.x <= point[0] <= rect.right and rect.y <= point[1] <= rect.bottom
-
-
-def edge_offset(bounds: Rect, edge: str, pointer: Tuple[int, int]) -> float:
- """Fraction along `edge`, top to bottom or left to right, against the
- bounding box — the convention the Mac measures its own departures in."""
- if edge in ("left", "right"):
- return _clamp((pointer[1] - bounds.y) / max(bounds.height, 1), 0.0, 1.0)
- return _clamp((pointer[0] - bounds.x) / max(bounds.width, 1), 0.0, 1.0)
-
-
-def 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."""
- if edge == "left":
- return min(monitors, key=lambda r: r.x)
- if edge == "right":
- return max(monitors, key=lambda r: r.right)
- if edge == "top":
- return min(monitors, key=lambda r: r.y)
- return max(monitors, key=lambda r: r.bottom)
-
-
-def 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 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)
- 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(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(along, owner.x, owner.right)
- return x, y
-
-
-class ReturnEdge:
- """Pressure against one edge of the Windows virtual desktop. Armed by the
- Mac on every switch (it sends `return_edge` and `resistance_px`), and
- disarmed once a crossing has been sent, so a burst of deltas still in
- flight after breakthrough cannot send a second one."""
-
- def __init__(self, edge: str, resistance_px: int = DEFAULT_RESISTANCE_PX, clock: Callable[[], float] = time.monotonic) -> None:
- if edge not in EDGES:
- raise ValueError(f"unknown edge {edge!r}")
- self.edge = edge
- self.resistance_px = max(0, int(resistance_px))
- self._clock = clock
- self._travel = 0.0
- self._last_at = clock()
- self.armed = True
-
- @property
- def pressure(self) -> float:
- if self.resistance_px == 0:
- return 1.0 if self._travel > 0 else 0.0
- return _clamp(self._travel / self.resistance_px, 0.0, 1.0)
-
- def reset(self) -> None:
- self._travel = 0.0
- self._last_at = self._clock()
-
- def _outward(self, dx: float, dy: float) -> float:
- if self.edge == "left":
- return -dx
- if self.edge == "right":
- return dx
- if self.edge == "top":
- return -dy
- return dy
-
- def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:
- """On a monitor, with no monitor one pixel beyond it: the pointer is
- against a wall. Testing the bounding box instead made the edge of a
- shorter monitor in a staggered arrangement unreachable — 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)
- return any(_contains(m, pointer) for m in monitors) and not any(_contains(m, beyond) for m in monitors)
-
- def feed(self, monitors: List[Rect], pointer: Tuple[int, int], dx: float, dy: float) -> Outcome:
- bounds = union(monitors)
- now = self._clock()
- elapsed = max(0.0, now - self._last_at)
- self._last_at = now
- # Decay runs against the wall clock between deltas, pushing or not. A
- # brisk push outruns it; a slow lean on the edge to reach a menu never
- # accumulates, which is the whole point of the resistance.
- self._travel = max(0.0, self._travel - self.resistance_px * elapsed / DECAY_SECONDS)
- if not self.armed:
- return Outcome(PASS, self.pressure)
- outward = self._outward(dx, dy)
- if outward <= 0 or not self._at_edge(monitors, pointer):
- if outward < 0:
- self._travel = max(0.0, self._travel + outward)
- return Outcome(PASS, self.pressure)
- self._travel += outward
- if self._travel >= self.resistance_px:
- self.armed = False
- offset = edge_offset(bounds, self.edge, pointer)
- self._travel = 0.0
- return Outcome(CROSS, 1.0, edge=OPPOSITE[self.edge], offset=offset)
- x, y = pointer
- if self.edge in ("left", "right"):
- position = (x, _clamp(int(y + dy), bounds.y, bounds.bottom))
- else:
- position = (_clamp(int(x + dx), bounds.x, bounds.right), y)
- return Outcome(HOLD, self.pressure, position=position)
-
-
-class 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
- leaves by only one of the corner's two sides is not a corner push and
- counts for nothing, which is what stops a slide along an edge triggering
- the corner it ends at.
-
- `edge` is still the side that leads to the other machine, so a corner
- crossing arrives where an edge crossing would, at the end of that edge the
- corner sits at."""
-
- def __init__(self, corner: str, edge: str, resistance_px: int = DEFAULT_RESISTANCE_PX, clock=time.monotonic) -> None:
- if corner not in CORNERS:
- raise ValueError(f"unknown corner {corner!r}")
- super().__init__(edge, resistance_px, clock)
- self.corner = corner
- self.vertical, self.horizontal = corner.split("_")
-
- def _outward(self, dx: float, dy: float) -> float:
- out_x = -dx if self.horizontal == "left" else dx
- out_y = -dy if self.vertical == "top" else dy
- if out_x > 0 and out_y > 0:
- return (out_x * out_x + out_y * out_y) ** 0.5
- inward = (min(0.0, out_x) ** 2 + min(0.0, out_y) ** 2) ** 0.5
- return -inward
-
- def _at_edge(self, monitors: List[Rect], pointer: Tuple[int, int]) -> bool:
- """In the corner's own box, and against at least one of its two walls.
- The box is measured on the monitor the pointer is on, for the same
- reason the edge test is: on a staggered arrangement the bounding box
- has corners no display reaches."""
- x, y = pointer
- home = next((m for m in monitors if _contains(m, pointer)), None)
- if home is None:
- return False
- near_x = x <= home.x + CORNER_PX if self.horizontal == "left" else x >= home.right - CORNER_PX
- near_y = y <= home.y + CORNER_PX if self.vertical == "top" else y >= home.bottom - CORNER_PX
- if not (near_x and near_y):
- return False
- return any(
- not any(_contains(m, beyond) for m in monitors)
- for beyond in ((x + (-1 if self.horizontal == "left" else 1), y), (x, y + (-1 if self.vertical == "top" else 1)))
- )
diff --git a/win_app/sender.py b/win_app/sender.py
index db95afd..a3b4390 100644
--- a/win_app/sender.py
+++ b/win_app/sender.py
@@ -29,10 +29,10 @@ import threading
import time
from typing import Callable, Optional
-import ignored
-import protocol
-import return_edge
-import wol
+from core import ignored
+from core import protocol
+from core import return_edge
+from core import wol
LOGGER = logging.getLogger(__name__)
@@ -119,7 +119,7 @@ def is_this_machine(host: str, local_addresses=None, address_towards=None) -> bo
return False
if address.is_loopback or address.is_unspecified:
return True
- import pairing
+ from core import pairing
if local_addresses is None:
local_addresses = pairing._local_ipv4_addresses()
@@ -165,6 +165,12 @@ class MacSender:
self._redirect_callback = redirect_callback
self._pressure_callback = pressure_callback
self._arrangement_callback = arrangement_callback
+ # Same on both machines, as the receiver's: `settings_callback(data)` for each settings
+ # message from the Mac, `announce()` for what to send the moment the link is up,
+ # `peer_settings` whether the Mac's welcome said it keeps settings in step.
+ self.settings_callback: Optional[Callable[[dict], None]] = None
+ self.announce: Callable[[], list] = lambda: []
+ self.peer_settings: Optional[bool] = None
# `arrival_callback(edge, x, y)`, as the shared receiver's: the pointer came home through the
# Mac's return edge and was placed at desktop pixel (x, y) on `edge` of this PC, or, with
# edge None, input came home by a switch and the pointer is at (x, y) where it was left.
@@ -220,7 +226,7 @@ class MacSender:
# Both hold the edges and leave the shortcut working, as on the Mac: Pause crossing,
# which a restart forgets, and the name of a full-screen app in front, set by the app.
self.crossing_paused = False
- self.full_screen_app = None
+ self._full_screen_app = None
# The buttons of this PC's own mouse that are down, so a push with one held is a drag.
self._buttons_held = set()
# (title, message) for a notification, and the Mac's hardware address when the ARP table
@@ -268,6 +274,18 @@ class MacSender:
return None
return int(round(trips[len(trips) // 2] * 1000))
+ @property
+ def full_screen_app(self):
+ """The full-screen app holding the edges, or None: also None while this PC's own setting
+ has the hold off, read here so every reader of the hold agrees and a change applies at once."""
+ if self._setting("hold_full_screen", True):
+ return self._full_screen_app
+ return None
+
+ @full_screen_app.setter
+ def full_screen_app(self, name) -> None:
+ self._full_screen_app = name
+
@property
def edges_held(self) -> bool:
return self.crossing_paused or self.full_screen_app is not None
@@ -691,6 +709,7 @@ class MacSender:
raise protocol.ProtocolError("welcome message missing data")
if data.get("error") or data.get("version") != protocol.PROTOCOL_VERSION:
raise HandshakeError(OLD_RECEIVER_STATUS)
+ self.peer_settings = protocol.keeps_settings(data)
sock.settimeout(SOCKET_IO_TIMEOUT_SECONDS)
except HandshakeError as exc:
self._close(sock)
@@ -722,6 +741,13 @@ class MacSender:
self._set_status(f"Connected to the Mac at {host}")
LOGGER.info("connected to the Mac at %s:%s", host, port)
self._learn_mac_address(host)
+ try:
+ announcements = list(self.announce())
+ except Exception:
+ LOGGER.exception("announce failed")
+ announcements = []
+ for announcement in announcements:
+ self._send_raw(announcement)
return True
def _learn_mac_address(self, host) -> None:
@@ -831,6 +857,10 @@ class MacSender:
"""Tell the Mac where the machines are, when the change was made here."""
return self._send_raw(protocol.arrangement_msg(mac_edge, set_at))
+ def send_settings(self, data: dict) -> bool:
+ """Tell the Mac this PC's settings state."""
+ return self._send_raw(protocol.settings_msg(data))
+
def _send_local_clipboard(self) -> None:
try:
text, image = self._clipboard_module().changed_contents()
@@ -924,6 +954,14 @@ class MacSender:
except Exception:
LOGGER.exception("Arrangement callback failed")
return
+ if message_type == protocol.MSG_SETTINGS:
+ data = message.get("data")
+ if isinstance(data, dict) and self.settings_callback is not None:
+ try:
+ self.settings_callback(data)
+ except Exception:
+ LOGGER.exception("Settings callback failed")
+ return
def _record_ack(self, message) -> None:
data = message.get("data")
diff --git a/win_app/tests/fakes.py b/win_app/tests/fakes.py
index 104211f..d0a5883 100644
--- a/win_app/tests/fakes.py
+++ b/win_app/tests/fakes.py
@@ -9,8 +9,12 @@ platform, including this Mac, without touching a real desktop.
import socket
import time
from typing import List, Optional, Tuple
+import os
+import sys
-import protocol
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import protocol
class FakeInjector:
diff --git a/win_app/tests/pairing_vectors.json b/win_app/tests/pairing_vectors.json
deleted file mode 100644
index 7426de5..0000000
--- a/win_app/tests/pairing_vectors.json
+++ /dev/null
@@ -1,252 +0,0 @@
-{
- "$comment": "Hex is bytes in wire order, except the two elligator2 fields, which are integers printed big-endian as RFC 9380 prints them. Messages are shown before the \"beamy\": 1 every datagram adds.",
- "suite": "CPACE-X25519-SHA512, draft-irtf-cfrg-cpace-21, initiator-responder, key confirmation per section 10.4",
- "specification": "PAIRING.md",
- "pairing_version": 2,
- "constants": {
- "dsi_ascii": "CPace255",
- "channel_ascii": "beamer-pair-v2",
- "role_requester_ascii": "requester",
- "role_host_ascii": "host",
- "token_info_ascii": "beamer-pair-token-v2",
- "done_label_ascii": "beamer-pair-done",
- "nonce_bytes": 16,
- "max_name_chars": 48,
- "max_identity_bytes": 32
- },
- "cpace_draft": {
- "prs_ascii": "Password",
- "ci_hex": "0b415f696e69746961746f720b425f726573706f6e646572",
- "sid_hex": "7e4b4791d6a8ef019b936c79fb7f2c57",
- "generator_hex": "d04bf6d41f6a289632a2e929fa29bebd51092512a7829fdde7d314b62f05a73f",
- "ada_ascii": "ADa",
- "ya_scalar_hex": "21b4f4bd9e64ed355c3eb676a28ebedaf6d8f17bdc365995b319097153044080",
- "ya_hex": "1d13c89278cdadd826f6d8d7f887701430f8380ddc17611cdd6dc989ce0c9f32",
- "adb_ascii": "ADb",
- "yb_scalar_hex": "848b0779ff415f0af4ea14df9dd1d3c29ac41d836c7808896c4eba19c51ac40a",
- "yb_hex": "248cccf6d5cdc3646f0ad593f9e6cef4e69d4945f8372e623512ecea32185623",
- "k_hex": "5b067effbdc0b2a0e1d907b21ebb25cfedb96a852179a847c37e43ee71322c6b",
- "isk_hex": "6e19b875f7a561d6b3ca3dbb9ef42ac55de3e717881018204b8922b4d5e53bb2aa82c300bea7b65d2b671da71922ddf6472301b79bc270adfa8bf413285f2263"
- },
- "elligator2": [
- {
- "field_element_hex_be": "608d892b641f0328523802a6603427c26e55e6f27e71a91a478148d45b5093cd",
- "u_hex_be": "51125222da5e763d97f3c10fcc92ea6860b9ccbbd2eb1285728f566721c1e65b"
- },
- {
- "field_element_hex_be": "46f5b22494bfeaa7f232cc8d054be68561af50230234d7d1d63d1d9abeca8da5",
- "u_hex_be": "7d56d1e08cb0ccb92baf069c18c49bb5a0dcd927eff8dcf75ca921ef7f3e6eeb"
- },
- {
- "field_element_hex_be": "235fe40c443766ce7e18111c33862d66c3b33267efa50d50f9e8e5d252a40aaa",
- "u_hex_be": "3fbe66b9c9883d79e8407150e7c2a1c8680bee496c62fabe4619a72b3cabe90f"
- },
- {
- "field_element_hex_be": "001e92a544463bda9bd04ddbe3d6eed248f82de32f522669efc5ddce95f46f5b",
- "u_hex_be": "227e0bb89de700385d19ec40e857db6e6a3e634b1c32962f370d26f84ff19683"
- },
- {
- "field_element_hex_be": "1a68a1af9f663592291af987203393f707305c7bac9c8d63d6a729bdc553dc19",
- "u_hex_be": "3bcd651ee54d5f7b6013898aab251ee8ecc0688166fce6e9548d38472f6bd196"
- }
- ],
- "low_order_shares": {
- "scalar_hex": "af46e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449aff",
- "must_refuse": [
- "0000000000000000000000000000000000000000000000000000000000000000",
- "0100000000000000000000000000000000000000000000000000000000000000",
- "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
- "e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800",
- "5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157",
- "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
- "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"
- ],
- "must_give": [
- {
- "share_hex": "daffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- "product_hex": "d8e2c776bbacd510d09fd9278b7edcd25fc5ae9adfba3b6e040e8d3b71b21806"
- },
- {
- "share_hex": "dbffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- "product_hex": "c85c655ebe8be44ba9c0ffde69f2fe10194458d137f09bbff725ce58803cdb38"
- },
- {
- "share_hex": "d9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
- "product_hex": "db64dafa9b8fdd136914e61461935fe92aa372cb056314e1231bc4ec12417456"
- },
- {
- "share_hex": "cdeb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b880",
- "product_hex": "e062dcd5376d58297be2618c7498f55baa07d7e03184e8aada20bca28888bf7a"
- },
- {
- "share_hex": "4c9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f11d7",
- "product_hex": "993c6ad11c4c29da9a56f7691fd0ff8d732e49de6250b6c2e80003ff4629a175"
- }
- ]
- },
- "exchanges": [
- {
- "comment": "1.4.3: no machine ids yet, so both identities are empty",
- "code": "482913",
- "pair_id": "eb6cf2ee3c1c8cbd2161b67b41be3003",
- "requester": {
- "name": "Vector Mac",
- "id_hex": "",
- "nonce_hex": "edad1eba42ed11cfd8ba0daba74a4bc8",
- "scalar_hex": "842bca52bbbdc727263dfa19a0c2851f18862e0c31e7a1b706d6ce9d1934c604"
- },
- "host": {
- "name": "VECTOR-PC",
- "id_hex": "",
- "scalar_hex": "a2fa23319131feac78653467b4863a444f5da2af0158d1d5e1e239710d691580"
- },
- "sid_hex": "20656236636632656533633163386362643231363162363762343162653330303310edad1eba42ed11cfd8ba0daba74a4bc8",
- "ada_hex": "09726571756573746572000a566563746f72204d6163",
- "adb_hex": "04686f73740009564543544f522d5043",
- "generator_string_hex": "084350616365323535063438323931336f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6265616d65722d706169722d76323220656236636632656533633163386362643231363162363762343162653330303310edad1eba42ed11cfd8ba0daba74a4bc8",
- "generator_hex": "1a750835aae9d408194e8e1393132e02c2495de72b6f265184749f056130ca10",
- "ya_hex": "2649f89325b72e646000fa5dc7c4221bf869de4938a88fecedbda398cbf34150",
- "yb_hex": "2d0dc754bb17865b276c39ba6ff00c0954b4804371a46742c3a2287c04e01347",
- "k_hex": "796f912ddb354ceba9a7642244ed553149bfc23f22f374bff3ad8315df817b2b",
- "isk_hex": "7dc167e8b761b5808f8e873878556f5dd1c52bdd62f3c348ea60a60512ea4294e19f6e72a0c54dacf5656a8debd79bf9615bee6fe5a59bbc98be15cf3b0bd077",
- "mac_key_hex": "8c619a26e16124af43935ba791b7de2b733ee32f13bae3c0943d574dbbbf1a0b6cd32997bf518db4b33a513f306c85ed9ac595806c3fc298488922660cce9f9c",
- "ta_hex": "630c08e363d467fa00c19d741672d4eac8bc9676c2b52bdb9f4939d842b12686c4d27c8ab900a85a411977042a9f4e97be520d9e64eeeeb59038a0330aec8f5d",
- "tb_hex": "1eeaafd522d6884f57057475a3bde52e3e14debcd79088aae52c5aa1edb858bdb12c4fb02a5427c42c46fdec565b43fd9a1c45b8b22d91ff733d43ac14396919",
- "td_hex": "cad8b6dd3af2c1f1b78c16c6eb86fdf897bb4f1b69f5559461491722a845ac83b5332c48433b5c4228accb93b3f177e264acbef9be9f4e21b985c165cea3dc2e",
- "token": "4xGHJR0vazj3INjxHjXpkTzLvzDEtxKZ8TiQQp8QhCw",
- "messages": {
- "pair_start": {
- "type": "pair_start",
- "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",
- "v": 2,
- "nonce": "7a0eukLtEc_Yug2rp0pLyA",
- "share": "Jkn4kyW3LmRgAPpdx8QiG_hp3kk4qI_s7b2jmMvzQVA",
- "name": "Vector Mac",
- "id": ""
- },
- "pair_answer": {
- "type": "pair_answer",
- "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",
- "ok": true,
- "share": "LQ3HVLsXhlsnbDm6b_AMCVS0gENxpGdCw6IofATgE0c",
- "tag": "Huqv1SLWiE9XBXR1o73lLj4U3rzXkIiq5Sxaoe24WL2xLE-wKlQnxCxG_exWW0P9mhxFuLItkf9zPUOsFDlpGQ",
- "name": "VECTOR-PC",
- "id": ""
- },
- "pair_confirm": {
- "type": "pair_confirm",
- "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",
- "tag": "YwwI42PUZ_oAwZ10FnLU6si8lnbCtSvbn0k52EKxJobE0nyKuQCoWkEZdwQqn06XvlINnmTu7rWQOKAzCuyPXQ"
- },
- "pair_done": {
- "type": "pair_done",
- "pair": "eb6cf2ee3c1c8cbd2161b67b41be3003",
- "ok": true,
- "tag": "yti23TrywfG3jBbG64b9-Je7Txtp9VWUYUkXIqhFrIO1MyxIQztcQiisy5Oz8XfiZKy--b6fTiG5hcFlzqPcLg"
- }
- }
- },
- {
- "comment": "The wire v6 shape: a 16-byte id each side, and a name with characters outside ASCII and outside the BMP",
- "code": "007045",
- "pair_id": "d397348abeb0691c3292a1f36093d950",
- "requester": {
- "name": "Zo\u00eb\u2019s \ud835\udd39eamer Mac",
- "id_hex": "74f70aa0e96f874c9866b11545950f8b",
- "nonce_hex": "e979b12f908a2f0ad16eb37876b5f0b5",
- "scalar_hex": "85b6b2942677e61db3636c9e6faea4586cc708ac4051afc481e17810a672266a"
- },
- "host": {
- "name": "VECTOR-PC",
- "id_hex": "ee3e1ebd5eacd2c487f2403bac611cdb",
- "scalar_hex": "4ee3c8b532aca27be39b1ac34ea82bd4084684dbd0e54987b192b5cd30541dbc"
- },
- "sid_hex": "20643339373334386162656230363931633332393261316633363039336439353010e979b12f908a2f0ad16eb37876b5f0b5",
- "ada_hex": "097265717565737465721074f70aa0e96f874c9866b11545950f8b165a6fc3abe280997320f09d94b965616d6572204d6163",
- "adb_hex": "04686f737410ee3e1ebd5eacd2c487f2403bac611cdb09564543544f522d5043",
- "generator_string_hex": "084350616365323535063030373034356f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e6265616d65722d706169722d76323220643339373334386162656230363931633332393261316633363039336439353010e979b12f908a2f0ad16eb37876b5f0b5",
- "generator_hex": "73b80492ce8c3d166117a405dc4bc62d593149cda94e53f3012d102fb539c069",
- "ya_hex": "46d1977042bd7aabd494df39930b1f6efb83078fe7cf605ffcf1580c8613d005",
- "yb_hex": "5fdbb545d4175d7f1e83613994e2abfdff7f7f46fb62e5c9b3f74c08e0ab8147",
- "k_hex": "f94259fbe1b827b22fc38e9beed8c77501ceca3373fe2abcc79e03ab0b245a77",
- "isk_hex": "9010d318e53253ad83ae8c3354e7d32229b7427d144d99fdba9681482a3ca81c4edc4ef433d1c2253949288c22464ff4b61b66158e983910b9c088de2826bf30",
- "mac_key_hex": "5d539ab7dd2da83e6411669bb70f95578cc61ed2f7f55462352953e3a687edcf8ea0b08bc5737d1ed2dd285cf61968efaed83d4e5acdb9136b7056f03a9681f4",
- "ta_hex": "d084e7d4b3e4d3008f2082cfeb9f421496fd1ea514717eb6f1fabb9e951deb88f734c2806c0a7153914cf5ed37635fa40dd46295c5ff0b7e8dd942f103504a41",
- "tb_hex": "2e636a9a44c7dde48f4d2dee732bd556abf31b4ba2e97121e0af076e1eb6d8297c0d4ad517513caef69c111e46c4097b940740f38e4251c10bc0a03da9b4d556",
- "td_hex": "f3ab76e44dca6d3aad881499c4941f6b5a5cd7e95971b75d0163b1f127fbb6785e728d53863a1d5e7c7ba96c8247a629f106833397415f73eb223febc28272fd",
- "token": "RG0uipRsvpPDZlGTPq3dXODw6X-a1M5f2QnB9jPcldo",
- "messages": {
- "pair_start": {
- "type": "pair_start",
- "pair": "d397348abeb0691c3292a1f36093d950",
- "v": 2,
- "nonce": "6XmxL5CKLwrRbrN4drXwtQ",
- "share": "RtGXcEK9eqvUlN85kwsfbvuDB4_nz2Bf_PFYDIYT0AU",
- "name": "Zo\u00eb\u2019s \ud835\udd39eamer Mac",
- "id": "dPcKoOlvh0yYZrEVRZUPiw"
- },
- "pair_answer": {
- "type": "pair_answer",
- "pair": "d397348abeb0691c3292a1f36093d950",
- "ok": true,
- "share": "X9u1RdQXXX8eg2E5lOKr_f9_f0b7YuXJs_dMCOCrgUc",
- "tag": "LmNqmkTH3eSPTS3ucyvVVqvzG0ui6XEh4K8Hbh622Cl8DUrVF1E8rvacER5GxAl7lAdA845CUcELwKA9qbTVVg",
- "name": "VECTOR-PC",
- "id": "7j4evV6s0sSH8kA7rGEc2w"
- },
- "pair_confirm": {
- "type": "pair_confirm",
- "pair": "d397348abeb0691c3292a1f36093d950",
- "tag": "0ITn1LPk0wCPIILP659CFJb9HqUUcX628fq7npUd64j3NMKAbApxU5FM9e03Y1-kDdRilcX_C36N2ULxA1BKQQ"
- },
- "pair_done": {
- "type": "pair_done",
- "pair": "d397348abeb0691c3292a1f36093d950",
- "ok": true,
- "tag": "86t25E3KbTqtiBSZxJQfa1pc1-lZcbddAWOx8Sf7tnheco1ThjodXnx7qWyCR6Yp8QaDM5dBX3PrIj_rwoJy_Q"
- }
- }
- }
- ],
- "wrong_code": {
- "host_code": "482913",
- "requester_code": "482914",
- "pair_id": "6bc698c0065affb622fff9fb87cac02a",
- "requester": {
- "name": "Vector Mac",
- "id_hex": "",
- "nonce_hex": "d90bf42db9e188ff2f817cd143f514f2",
- "scalar_hex": "5318fc1f72d7f28d4053a37001e4b96339c154095161d9e3686d068e993cd2a5"
- },
- "pair_start": {
- "type": "pair_start",
- "pair": "6bc698c0065affb622fff9fb87cac02a",
- "v": 2,
- "nonce": "2Qv0LbnhiP8vgXzRQ_UU8g",
- "share": "Qq9Jel7gwUBo6te3H1ucksTPo9W9_KNE3wS6H1i8IFY",
- "name": "Vector Mac",
- "id": ""
- },
- "pair_answer": {
- "type": "pair_answer",
- "pair": "6bc698c0065affb622fff9fb87cac02a",
- "ok": true,
- "share": "CAKZVA2Yp_gG6soy4krssop3x0uLbG4BIPWF2JQLCxA",
- "tag": "EDuxWV1wqH2EdQtuQCC4DyFXZb9kibeRaxATuacSQv0hr3hVqhsBkS8bt90zJirBrkZWRSBWaRWNemqnNfu31g",
- "name": "VECTOR-PC",
- "id": ""
- },
- "requester_must": "refused",
- "pair_confirm_abort": {
- "type": "pair_confirm",
- "pair": "6bc698c0065affb622fff9fb87cac02a",
- "tag": ""
- }
- },
- "name_cut": {
- "name": "\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e",
- "code_points": 60,
- "sent": "\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e\ud835\udd39e",
- "sent_code_points": 48
- }
-}
diff --git a/win_app/tests/test_app_config.py b/win_app/tests/test_app_config.py
index 69a51ec..b535273 100644
--- a/win_app/tests/test_app_config.py
+++ b/win_app/tests/test_app_config.py
@@ -3,9 +3,13 @@ import tempfile
import unittest
from pathlib import Path
from unittest import mock
+import os
+import sys
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import app_config
-import protocol
+from core import protocol
from dataclasses import replace
from app_config import ConfigError, config_from_dict, config_to_dict, default_config
@@ -47,13 +51,13 @@ class EdgeGlowConfigTests(unittest.TestCase):
self.assertEqual((saved["glow_style"], saved["glow_colour"]), ("beam", "sunset"))
def test_colour_choices_are_the_shared_palettes_then_the_effect_packs(self):
- import effects
+ from core 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
+ from core import effects
for style in effects.EFFECT_IDS:
with self.subTest(style=style):
@@ -71,7 +75,7 @@ class EdgeGlowConfigTests(unittest.TestCase):
self.assertEqual((config.glow_style, config.glow_colour), ("discharge", "sunset"))
def test_a_colour_resolves_to_todays_palette_else_its_pack(self):
- import effects
+ from core import effects
import tokens
self.assertEqual(app_config.palette_colours("sunset"), tuple(tokens.PALETTES["sunset"]))
diff --git a/win_app/tests/test_clipboard_win.py b/win_app/tests/test_clipboard_win.py
index 9f2643d..e35327e 100644
--- a/win_app/tests/test_clipboard_win.py
+++ b/win_app/tests/test_clipboard_win.py
@@ -8,9 +8,12 @@ import struct
import sys
import unittest
from unittest import mock
+import os
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import clipboard_win
-import protocol
+from core import protocol
from clipboard_win import BI_BITFIELDS, BI_RGB, CF_DIB, CF_UNICODETEXT, bgra_to_dib, dib_to_bgra
diff --git a/win_app/tests/test_core.py b/win_app/tests/test_core.py
new file mode 100644
index 0000000..034b8ab
--- /dev/null
+++ b/win_app/tests/test_core.py
@@ -0,0 +1,18 @@
+"""core/'s own tests, run as part of this app's suite so one command still covers everything this
+app ships, under this app's interpreter and packages."""
+
+import os
+import sys
+import unittest
+
+_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+
+def load_tests(loader, tests, pattern):
+ tests.addTests(loader.discover(os.path.join(_REPO_ROOT, "core", "tests"), pattern="test*.py", top_level_dir=_REPO_ROOT))
+ # discover leaves the root first on sys.path. It goes behind the app's own folder instead: the
+ # root also holds the Mac's theme.py, which must not stand in for win_app's.
+ while _REPO_ROOT in sys.path:
+ sys.path.remove(_REPO_ROOT)
+ sys.path.append(_REPO_ROOT)
+ return tests
diff --git a/win_app/tests/test_crossing_matrix.py b/win_app/tests/test_crossing_matrix.py
index 5602ebd..a43158c 100644
--- a/win_app/tests/test_crossing_matrix.py
+++ b/win_app/tests/test_crossing_matrix.py
@@ -7,12 +7,16 @@ import logging
import time
import types
import unittest
+import os
+import sys
-import return_edge
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import return_edge
import sender
from app_config import Config, default_config
from fakes import FakeClipboard, FakeDesktop
-from return_edge import CORNERS, EDGES, OPPOSITE, Rect
+from core.return_edge import CORNERS, EDGES, OPPOSITE, Rect
MONITORS = [Rect(0, 0, 1920, 1080)]
THIRDS = {"start": 0.17, "middle": 0.5, "end": 0.83}
@@ -273,14 +277,18 @@ class ArrangementHeldByBothTests(unittest.TestCase):
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.
+ def test_the_macs_hello_leaves_an_edge_set_here(self):
+ # G1 in the report, fixed: a PC set up before pairing keeps the side chosen here, and the
+ # Mac's first hello only fills an edge the PC does not hold.
page, saved = self.page("top", stamp=5000)
self.learn(page, "left")
- self.assertEqual((page._config.mac_return_edge, page._config.arrangement_set_at), ("left", 5000))
+ self.assertEqual((page._config.mac_return_edge, page._config.arrangement_set_at), ("top", 5000))
+
+ def test_the_macs_hello_leaves_an_edge_even_a_hello_filled(self):
+ # The Mac's announced arrangement, not its next hello, is what moves it after that.
+ page, saved = self.page("left", stamp=0)
+ self.learn(page, "bottom")
+ self.assertEqual(page._config.mac_return_edge, "left")
def test_a_fresh_config_holds_no_edge_though_the_crossing_page_offers_right(self):
# Pinned known gap (G3 in the report).
diff --git a/win_app/tests/test_edge_glow.py b/win_app/tests/test_edge_glow.py
index df3bb71..4ed516c 100644
--- a/win_app/tests/test_edge_glow.py
+++ b/win_app/tests/test_edge_glow.py
@@ -59,7 +59,7 @@ class DarkColoursTest(unittest.TestCase):
def test_a_dark_pack_is_lifted_on_a_dark_appearance_only(self):
from unittest import mock
- import effects
+ from core import effects
# Indigo ink, the darkest pack, though Ink is offered nowhere for now.
def first(dark):
diff --git a/win_app/tests/test_effect_layouts.py b/win_app/tests/test_effect_layouts.py
index db83623..aa2b68e 100644
--- a/win_app/tests/test_effect_layouts.py
+++ b/win_app/tests/test_effect_layouts.py
@@ -6,8 +6,12 @@ Byte-identical in mac_app and win_app."""
import colorsys
import unittest
from types import SimpleNamespace
+import os
+import sys
-import effects
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import effects
PALETTE = ["#ff7828", "#ff3264", "#ffb43c"]
NOTCH = {"x": 771.5, "y": 0.0, "w": 185.0, "h": 32.0, "r": 10.0}
diff --git a/win_app/tests/test_effect_overlay.py b/win_app/tests/test_effect_overlay.py
index 84ace05..8ddd48d 100644
--- a/win_app/tests/test_effect_overlay.py
+++ b/win_app/tests/test_effect_overlay.py
@@ -6,9 +6,12 @@ import os
import unittest
from dataclasses import replace
from types import SimpleNamespace
+import sys
-import effects
-from return_edge import Rect
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import effects
+from core.return_edge import Rect
try:
from PySide6.QtCore import QPointF, QRect, Qt
diff --git a/win_app/tests/test_firewall_win.py b/win_app/tests/test_firewall_win.py
index 9866b05..2a5b1c8 100644
--- a/win_app/tests/test_firewall_win.py
+++ b/win_app/tests/test_firewall_win.py
@@ -5,6 +5,10 @@ the status script emits, so the decisions run on the Mac with no Windows at all.
"""
import unittest
+import os
+import sys
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import firewall_win
from firewall_win import advise, interpret
diff --git a/win_app/tests/test_gameinput_foreground.py b/win_app/tests/test_gameinput_foreground.py
index eb78da8..edb79bd 100644
--- a/win_app/tests/test_gameinput_foreground.py
+++ b/win_app/tests/test_gameinput_foreground.py
@@ -10,6 +10,10 @@ import ctypes
import subprocess
import unittest
from unittest import mock
+import os
+import sys
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import desktop_win
import input_injector
diff --git a/win_app/tests/test_hook_key_repeat.py b/win_app/tests/test_hook_key_repeat.py
index 24266e2..8753085 100644
--- a/win_app/tests/test_hook_key_repeat.py
+++ b/win_app/tests/test_hook_key_repeat.py
@@ -6,9 +6,13 @@ from `_on_hook_key`'s body."""
import time
import unittest
+import os
+import sys
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import capture_win
-import protocol
+from core import protocol
import sender
from capture_win import Trigger
from fakes import FakeDesktop
diff --git a/win_app/tests/test_ignored_inputs.py b/win_app/tests/test_ignored_inputs.py
index 637650c..6efac39 100644
--- a/win_app/tests/test_ignored_inputs.py
+++ b/win_app/tests/test_ignored_inputs.py
@@ -6,14 +6,18 @@ import tempfile
import time
import unittest
from pathlib import Path
+import os
+import sys
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import app_config
import capture_win
-import ignored
-import protocol
+from core import ignored
+from core import protocol
import sender
from fakes import FakeClipboard, FakeDesktop
-from return_edge import Rect
+from core.return_edge import Rect
VK_F13 = 0x7C
VK_A = 0x41
diff --git a/win_app/tests/test_ignored_page.py b/win_app/tests/test_ignored_page.py
index 15f77f7..47948fa 100644
--- a/win_app/tests/test_ignored_page.py
+++ b/win_app/tests/test_ignored_page.py
@@ -3,9 +3,13 @@ window: what it does when the list cannot be saved."""
import types
import unittest
+import os
+import sys
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import app_config
-import ignored
+from core import ignored
try:
import kvm_bridge_win
diff --git a/win_app/tests/test_key_up_after_switch_back.py b/win_app/tests/test_key_up_after_switch_back.py
index bd6f9e7..60aa7dd 100644
--- a/win_app/tests/test_key_up_after_switch_back.py
+++ b/win_app/tests/test_key_up_after_switch_back.py
@@ -5,11 +5,15 @@ key-down was actually forwarded."""
import time
import unittest
+import os
+import sys
-import protocol
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import protocol
import sender
from fakes import FakeClipboard, FakeDesktop
-from return_edge import Rect
+from core.return_edge import Rect
MONITORS = [Rect(0, 0, 1920, 1080)]
diff --git a/win_app/tests/test_pages_win.py b/win_app/tests/test_pages_win.py
index c8a511a..6170d19 100644
--- a/win_app/tests/test_pages_win.py
+++ b/win_app/tests/test_pages_win.py
@@ -1,9 +1,12 @@
import os
import unittest
from types import SimpleNamespace
+import sys
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import app_config
-import effects
+from core import effects
import pages_win
try:
@@ -377,6 +380,8 @@ class CrossingPageTest(unittest.TestCase):
page.sender = SimpleNamespace(update_config=lambda config: None)
page.mac_host_readout = widgets.label("", "readout")
page.edge_choice = SimpleNamespace(set_value=lambda value: None)
+ # A hello fills only an edge the PC does not hold yet (G1).
+ page._config.mac_return_edge = ""
real = kvm_bridge_win.sender.is_this_machine
kvm_bridge_win.sender.is_this_machine = lambda host: False
try:
diff --git a/win_app/tests/test_pairing.py b/win_app/tests/test_pairing.py
index 7f90516..a1c97ea 100644
--- a/win_app/tests/test_pairing.py
+++ b/win_app/tests/test_pairing.py
@@ -1,8 +1,12 @@
import json
import unittest
+import os
+import sys
-import pairing
-from pairing import PairingHost, beacon_msg, decode, encode
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import pairing
+from core.pairing import PairingHost, beacon_msg, decode, encode
class FakeClock:
diff --git a/win_app/tests/test_pairing_window.py b/win_app/tests/test_pairing_window.py
index d11b8a0..03f4bea 100644
--- a/win_app/tests/test_pairing_window.py
+++ b/win_app/tests/test_pairing_window.py
@@ -6,8 +6,11 @@ import os
import tempfile
import unittest
from pathlib import Path
+import sys
-import pairing
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import pairing
try:
from PySide6.QtWidgets import QApplication
diff --git a/win_app/tests/test_parity.py b/win_app/tests/test_parity.py
index e2d209e..e734995 100644
--- a/win_app/tests/test_parity.py
+++ b/win_app/tests/test_parity.py
@@ -5,10 +5,14 @@ while dragging, alerts, and waking the Mac."""
import time
import unittest
from dataclasses import replace
+import os
+import sys
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import app_config
import capture_win
-import protocol
+from core import protocol
from app_config import ConfigError, config_from_dict, config_to_dict, default_config
import sender as sender_module
import test_sender
@@ -63,7 +67,7 @@ class ReviewFixTests(unittest.TestCase):
self.assertIn(vk, app_config.UNRECORDABLE_TRIGGER_VKS)
def test_the_subnet_broadcast_of_a_home_address(self):
- import wol
+ from core import wol
self.assertEqual(wol.subnet_broadcast("192.168.1.10"), "192.168.1.255")
self.assertIsNone(wol.subnet_broadcast("mac.local"))
@@ -86,6 +90,13 @@ class ConfigRangeTests(unittest.TestCase):
again = config_from_dict(saved)
self.assertEqual((again.modifier_style, again.block_while_dragging), ("positional", False))
+ def test_the_full_screen_hold_defaults_on_and_round_trips(self):
+ config = config_from_dict(raw())
+ self.assertTrue(config.hold_full_screen)
+ saved = config_to_dict(replace(config, hold_full_screen=False))
+ self.assertFalse(config_from_dict(saved).hold_full_screen)
+ self.assertTrue(config_from_dict(raw()).hold_full_screen)
+
def test_an_unknown_modifier_style_is_refused(self):
with self.assertRaises(ConfigError):
config_from_dict(raw(modifier_style="sideways"))
@@ -118,6 +129,14 @@ class HeldEdgeTests(unittest.TestCase):
self.push()
self.assertFalse(self.sender.redirecting)
+ def test_with_the_hold_off_a_full_screen_app_does_not_hold_the_edge_either_way(self):
+ self.sender.update_config(make_config(hold_full_screen=False))
+ self.sender.full_screen_app = "Game"
+ self.assertIsNone(self.sender.full_screen_app)
+ self.assertFalse(self.sender.edges_held)
+ self.push()
+ self.assertTrue(self.sender.redirecting)
+
def test_a_drag_against_the_edge_does_not_cross(self):
self.sender.on_mouse(capture_win.WM_LBUTTONDOWN, 0, 500, 0)
self.push()
diff --git a/win_app/tests/test_receiver.py b/win_app/tests/test_receiver.py
index 24bca29..955d5e5 100644
--- a/win_app/tests/test_receiver.py
+++ b/win_app/tests/test_receiver.py
@@ -3,14 +3,18 @@ import threading
import time
import unittest
from unittest import mock
+import os
+import sys
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import input_injector
-import protocol
-import receiver
+from core import protocol
+from core import receiver
from app_config import Config
-from receiver import ReceiverServer, ServerState, handle_message
+from core.receiver import ReceiverServer, ServerState, handle_message
-from return_edge import Rect
+from core.return_edge import Rect
from fakes import FakeClipboard, FakeDesktop, FakeInjector, connected_socket_pair, wait_for_calls, wait_for_status
diff --git a/win_app/tests/test_replay.py b/win_app/tests/test_replay.py
index 50e5e8c..ebc2dd4 100644
--- a/win_app/tests/test_replay.py
+++ b/win_app/tests/test_replay.py
@@ -9,13 +9,17 @@ responder, and it must fail the tag rather than type what was recorded."""
import socket
import time
import unittest
+import os
+import sys
-import protocol
-import receiver
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import protocol
+from core import receiver
import sender
from app_config import Config
from fakes import FakeClipboard, FakeDesktop, FakeInjector, wait_for_calls
-from return_edge import Rect
+from core.return_edge import Rect
from test_sender import NoUnlock, free_port, make_config, wait_for
MONITORS = [Rect(0, 0, 1920, 1080)]
diff --git a/win_app/tests/test_return_edge.py b/win_app/tests/test_return_edge.py
index b162e7b..85ba94b 100644
--- a/win_app/tests/test_return_edge.py
+++ b/win_app/tests/test_return_edge.py
@@ -1,6 +1,10 @@
import unittest
+import os
+import sys
-from return_edge import CROSS, HOLD, PASS, Rect, ReturnEdge, arrival_position, edge_offset, union
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core.return_edge import CROSS, HOLD, PASS, Rect, ReturnEdge, arrival_position, edge_offset, union
class FakeClock:
@@ -123,7 +127,7 @@ class PressureTests(unittest.TestCase):
class PartEdgeTests(unittest.TestCase):
def test_only_the_chosen_thirds_cross(self):
- from return_edge import PartEdge
+ from core.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.
@@ -140,13 +144,13 @@ class PartEdgeTests(unittest.TestCase):
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
+ from core.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
+ from core.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",)))
diff --git a/win_app/tests/test_same_on_both.py b/win_app/tests/test_same_on_both.py
new file mode 100644
index 0000000..a34ac1d
--- /dev/null
+++ b/win_app/tests/test_same_on_both.py
@@ -0,0 +1,115 @@
+"""Same on both machines in the real window: the Overview switch, a Mac's settings arriving, and a
+change here going out. Built offscreen from a synthetic config as test_style_for builds it, which
+starts no receiver, hooks or announcer; the two links' sends are recorded instead."""
+
+import json
+import os
+import tempfile
+import unittest
+from pathlib import Path
+
+try:
+ from PySide6.QtWidgets import QApplication
+
+ import kvm_bridge_win
+ import pages_win
+ from core import settings_sync
+ import theme
+ from app_config import load_config
+except ImportError: # PySide6 is only in the Windows venv
+ kvm_bridge_win = None
+
+
+def mac_message(on, set_at, **values):
+ base = dict(methods=["corner"], edge_parts=["start"], corner="top_right", resistance_px=60,
+ block_while_dragging=False, trigger_key="alt_r", trigger_style="hold", double_tap_ms=400,
+ glow_style="beam", glow_colour="ocean", effect_length="long", shortcut_arrival=False,
+ shortcut_arrival_style="locator")
+ base.update(values)
+ return settings_sync.message_data(on, set_at, base)
+
+
[email protected](kvm_bridge_win is None, "needs PySide6")
+class SameOnBothTest(unittest.TestCase):
+ def setUp(self):
+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+ self.app = QApplication.instance() or QApplication([])
+ theme.init_fonts()
+ self.path = Path(tempfile.mkdtemp()) / "config.json"
+ self.path.write_text(json.dumps({
+ "host": "192.168.1.20", "port": 24820, "auth_token": "synthetic", "paired_with": "MacBook Pro",
+ "mac_host": "192.168.1.10", "mac_return_edge": "left", "edge_glow": True,
+ }))
+ self.window = kvm_bridge_win.WindowsApplication(self.path)
+ self.sent = []
+ self.window.sender.send_settings = lambda data: self.sent.append(("pc-to-mac", data)) or True
+ self.window.server.send_settings = lambda data: self.sent.append(("mac-to-pc", data)) or True
+ self.window._refresh_window()
+
+ def tearDown(self):
+ self.window.deleteLater()
+
+ def test_off_by_default_with_each_page_its_own(self):
+ self.assertFalse(self.window.same_switch.isChecked())
+ self.assertEqual(self.window.scope_labels["design"].text(), pages_win.SCOPE["design"])
+
+ def test_the_macs_settings_arrive_on_this_pcs_fields_and_controls(self):
+ self.window._on_settings(mac_message(True, 100))
+ config = self.window._config
+ self.assertTrue(config.same_on_both)
+ self.assertEqual((config.crossing_methods, config.crossing_edge_parts), (["corner"], ["start"]))
+ # The Mac is on this PC's left, so its top right is this PC's top left.
+ self.assertEqual(config.crossing_corner, "top_left")
+ self.assertEqual((config.glow_style, config.glow_colour, config.effect_length), ("beam", "ocean", "long"))
+ self.assertEqual((config.trigger_style, config.double_tap_ms, config.shortcut_arrival), ("hold", 400, False))
+ self.assertTrue(config.edge_glow)
+ self.assertEqual(load_config(self.path).glow_style, "beam")
+ self.assertEqual(self.window.resistance_slider.value(), 60)
+ self.assertFalse(self.window.landing_toggle.isChecked())
+ self.window._refresh_window()
+ self.assertTrue(self.window.same_switch.isChecked())
+ self.assertEqual(self.window.scope_labels["crossing"].text(),
+ "Kept the same as your Mac. Change it on either machine.")
+ # Applying what arrived is not a change made here, so nothing is sent back.
+ self.assertEqual(self.sent, [])
+
+ def test_an_older_message_changes_nothing(self):
+ self.window._on_settings(mac_message(True, 100))
+ self.window._on_settings(mac_message(True, 90, glow_style="glow"))
+ self.assertEqual(self.window._config.glow_style, "beam")
+
+ def test_turning_it_on_here_sends_this_pcs_values_on_both_links(self):
+ self.window.same_switch.setChecked(True)
+ self.assertEqual([link for link, _data in self.sent], ["pc-to-mac", "mac-to-pc"])
+ data = self.sent[0][1]
+ self.assertTrue(data["on"])
+ self.assertEqual(data["crossing"]["corner"], "top_right")
+
+ def test_a_change_here_while_on_is_stamped_and_sent_and_one_to_this_pcs_own_is_not(self):
+ self.window.same_switch.setChecked(True)
+ stamp = self.window._config.same_set_at
+ self.sent.clear()
+ self.window._config.same_set_at = stamp - 10
+ self.window._config.edge_glow = False
+ self.window._persist()
+ self.assertEqual(self.sent, [])
+ self.window._config.effect_length = "short"
+ self.window._persist()
+ self.assertEqual(len(self.sent), 2)
+ self.assertGreaterEqual(self.window._config.same_set_at, stamp)
+ self.assertEqual(self.sent[0][1]["design"]["effect_length"], "short")
+
+ def test_a_change_here_while_off_goes_nowhere(self):
+ self.window._config.effect_length = "short"
+ self.window._persist()
+ self.assertEqual(self.sent, [])
+
+ def test_announcing_carries_a_chosen_arrangement_but_not_a_learned_one(self):
+ self.assertEqual([m["type"] for m in self.window._announce()], ["settings"])
+ self.window._config.arrangement_set_at = 500
+ messages = self.window._announce()
+ self.assertEqual(messages[0], {"type": "arrangement", "data": {"mac_edge": "right", "set_at": 500}})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/win_app/tests/test_sender.py b/win_app/tests/test_sender.py
index 49b2f85..7f417ef 100644
--- a/win_app/tests/test_sender.py
+++ b/win_app/tests/test_sender.py
@@ -6,14 +6,18 @@ import socket
import threading
import time
import unittest
+import os
+import sys
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import capture_win
-import protocol
-import receiver
+from core import protocol
+from core import receiver
import sender
from app_config import Config
from fakes import FakeClipboard, FakeDesktop, FakeInjector, wait_for_calls
-from return_edge import Rect
+from core.return_edge import Rect
MONITORS = [Rect(0, 0, 1920, 1080)]
diff --git a/win_app/tests/test_shared_copies.py b/win_app/tests/test_shared_copies.py
deleted file mode 100644
index 6e7cd04..0000000
--- a/win_app/tests/test_shared_copies.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""The files both apps share are kept byte-identical, not merely similar.
-
-`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
-legitimate reason for the two copies to differ by a byte, and a diff is
-always drift. This test is byte-for-byte on purpose: a structural comparison
-would pass while the two sides' return-edge arithmetic or status wording
-quietly diverged.
-
-This file is itself one of those copies, and checks itself.
-"""
-
-import hashlib
-import os
-import unittest
-
-_TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
-_REPO_ROOT = os.path.dirname(os.path.dirname(_TESTS_DIR))
-
-SHARED_MODULES = (
- "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 = (
- "pairing_vectors.json", "test_ignored.py", "test_pairing_cpace.py", "test_shared_copies.py", "test_switch_arrival.py",
- "test_updates.py",
-)
-
-
-def _digest(path):
- with open(path, "rb") as handle:
- return hashlib.sha256(handle.read()).hexdigest()
-
-
-class SharedCopyTests(unittest.TestCase):
- def _assert_identical(self, mac_path, win_path, name):
- for path in (mac_path, win_path):
- self.assertTrue(os.path.isfile(path), f"{name} is missing from {os.path.dirname(path)}")
- self.assertEqual(
- _digest(mac_path),
- _digest(win_path),
- f"mac_app and win_app copies of {name} have drifted apart",
- )
-
- def test_shared_modules_are_identical(self):
- for name in SHARED_MODULES:
- with self.subTest(module=name):
- self._assert_identical(
- os.path.join(_REPO_ROOT, "mac_app", name),
- os.path.join(_REPO_ROOT, "win_app", name),
- name,
- )
-
- def test_shared_tests_are_identical(self):
- for name in SHARED_TESTS:
- with self.subTest(module=name):
- self._assert_identical(
- os.path.join(_REPO_ROOT, "mac_app", "tests", name),
- os.path.join(_REPO_ROOT, "win_app", "tests", name),
- name,
- )
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/win_app/tests/test_stuck_modifier_on_drop.py b/win_app/tests/test_stuck_modifier_on_drop.py
index eb75de5..c4e53d8 100644
--- a/win_app/tests/test_stuck_modifier_on_drop.py
+++ b/win_app/tests/test_stuck_modifier_on_drop.py
@@ -1,8 +1,11 @@
import sys
import unittest
+import os
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import input_injector
-import receiver
+from core import receiver
class FakeInjector:
diff --git a/win_app/tests/test_two_scripts.py b/win_app/tests/test_two_scripts.py
index a20ba7d..ea9ebe4 100644
--- a/win_app/tests/test_two_scripts.py
+++ b/win_app/tests/test_two_scripts.py
@@ -7,10 +7,14 @@ letter is from another script than the one typed there."""
import time
import unittest
+import os
+import sys
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import capture_win
-import protocol
-import receiver
+from core import protocol
+from core import receiver
import sender
from fakes import FakeClipboard, FakeDesktop
from input_injector import KEYEVENTF_KEYUP, KEYEVENTF_UNICODE, plan_key_inputs
diff --git a/win_app/tests/test_unlock_win.py b/win_app/tests/test_unlock_win.py
index 3f66508..2580934 100644
--- a/win_app/tests/test_unlock_win.py
+++ b/win_app/tests/test_unlock_win.py
@@ -6,11 +6,15 @@ handle_message use, so this suite runs on the Mac.
"""
import unittest
+import os
+import sys
-import protocol
-import receiver
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from core import protocol
+from core import receiver
import unlock_win
-from receiver import ReceiverServer, ServerState
+from core.receiver import ReceiverServer, ServerState
class FakeKernel32:
diff --git a/win_app/tests/test_updates.py b/win_app/tests/test_updates.py
deleted file mode 100644
index d41ddfb..0000000
--- a/win_app/tests/test_updates.py
+++ /dev/null
@@ -1,91 +0,0 @@
-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
index a72c657..6256749 100644
--- a/win_app/tests/test_way_home.py
+++ b/win_app/tests/test_way_home.py
@@ -14,14 +14,14 @@ class WayHomeFollowsThisPcTests(unittest.TestCase):
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
+ from core import return_edge
armed = self.model(["part", "shortcut"], parts=("start", "end"))
self.assertIsInstance(armed, return_edge.PartEdge)
self.assertEqual(armed.parts, frozenset({"start", "end"}))
def test_a_corner_on_that_edge_and_none_elsewhere(self):
- import return_edge
+ from core import return_edge
self.assertIsInstance(self.model(["corner"], corner="bottom_left"), return_edge.CornerPush)
self.assertIsNone(self.model(["corner"], corner="top_left"))
diff --git a/win_app/updates.py b/win_app/updates.py
deleted file mode 100644
index 21bfc57..0000000
--- a/win_app/updates.py
+++ /dev/null
@@ -1,134 +0,0 @@
-"""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/wol.py b/win_app/wol.py
deleted file mode 100644
index 670c569..0000000
--- a/win_app/wol.py
+++ /dev/null
@@ -1,108 +0,0 @@
-"""Wake-on-LAN, shared by both apps: each machine wakes the other when a switch finds it asleep.
-
-The hardware address is never typed. Each end reads it from its own ARP table whenever a
-connection succeeds -- the two machines have just exchanged packets, so the entry is fresh --
-and stores it with the rest of its settings.
-"""
-
-from __future__ import annotations
-
-import re
-import socket
-import subprocess
-import sys
-
-WOL_PORT = 9
-# Sleep answers in a few seconds; hibernate and a cold boot take most of a minute. Past this
-# the other machine is reported as not woken rather than the switch waiting forever.
-WAKE_WINDOW_SECONDS = 60.0
-
-# Six groups of one or two hex digits: Windows pads and joins with "-", macOS leaves a leading
-# zero off and joins with ":".
-_MAC_PATTERN = re.compile(r"(?<![0-9A-Fa-f])([0-9A-Fa-f]{1,2}(?:[:-][0-9A-Fa-f]{1,2}){5})(?![0-9A-Fa-f])")
-
-
-def parse_mac(text: str):
- """The address as six upper-case, zero-padded pairs joined with ":", or None."""
- match = _MAC_PATTERN.fullmatch(text.strip()) if isinstance(text, str) else None
- if match is None:
- return None
- return ":".join(part.zfill(2).upper() for part in re.split(r"[:-]", match.group(1)))
-
-
-def mac_from_arp_output(output: str, ip: str):
- """The hardware address `arp` printed for `ip`, from either platform's layout:
-
- Windows 192.168.1.3 02-1a-2b-3c-0d-4e dynamic
- macOS ? (192.168.1.3) at 2:1a:2b:3c:d:4e on en0 ifscope [ethernet]
- """
- ip_pattern = re.compile(r"(?<![\d.])" + re.escape(ip) + r"(?![\d.])")
- for line in output.splitlines():
- if not ip_pattern.search(line):
- continue
- match = _MAC_PATTERN.search(line)
- if match is not None:
- return parse_mac(match.group(1))
- return None
-
-
-def lookup_mac(host: str):
- """The hardware address this machine's ARP table holds for `host`, or None. Only useful
- right after talking to the host, which is the only time it is called. On Windows `arp` is a
- console program, so it is started with no window: Beamer there is a tray app, and a console
- flashing up on every connection is exactly what it must never do."""
- windows = sys.platform == "win32"
- try:
- ip = socket.gethostbyname(host)
- completed = subprocess.run(
- ["arp", "-a", ip] if windows else ["arp", "-n", ip],
- capture_output=True,
- text=True,
- timeout=3.0,
- check=False,
- creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0) if windows else 0,
- )
- except (OSError, subprocess.SubprocessError):
- return None
- return mac_from_arp_output(completed.stdout, ip)
-
-
-def magic_packet(mac: str) -> bytes:
- address = parse_mac(mac)
- if address is None:
- raise ValueError(f"not a hardware address: {mac!r}")
- return b"\xff" * 6 + bytes.fromhex(address.replace(":", "")) * 16
-
-
-def send_magic_packet(mac: str, host: str = None) -> None:
- """Broadcast the packet, send it to the host's own subnet, and straight at its last address.
- The limited broadcast leaves by one interface only, which on a machine with a VPN or a
- virtual adapter can be the wrong one; the subnet's broadcast is routed out of the right one;
- and the direct send is what gets through on a network that filters broadcasts."""
- packet = magic_packet(mac)
- targets = ["255.255.255.255"]
- if host:
- subnet = subnet_broadcast(host)
- if subnet:
- targets.append(subnet)
- targets.append(host)
- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- try:
- sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
- for index, target in enumerate(targets):
- try:
- sock.sendto(packet, (target, WOL_PORT))
- except OSError:
- if index == 0:
- raise
- finally:
- sock.close()
-
-
-def subnet_broadcast(host: str):
- """The /24 broadcast for a dotted IPv4 address, the size of nearly every home network, or
- None for anything else."""
- parts = host.split(".") if isinstance(host, str) else []
- if len(parts) != 4 or not all(part.isdigit() and int(part) <= 255 for part in parts):
- return None
- return ".".join(parts[:3] + ["255"])